<commit_before>#include <gtest/gtest.h>
#include <iostream>
#include <fstream>
#include <istream>
#include <exception>
#include <stdexcept>

#include "stan/gm/ast.hpp"
#include "stan/gm/parser.hpp"
#include <stan/gm/generator.hpp>
#include <stan/gm/grammars/program_grammar.hpp>
#include <stan/gm/grammars/whitespace_grammar.hpp>
#include <stan/gm/grammars/expression_grammar.hpp>
#include <stan/gm/grammars/statement_grammar.hpp>
#include <stan/gm/grammars/var_decls_grammar.hpp>

std::string file_name_to_model_name(const std::string& name) {
  std::string name_copy = name;
  size_t last_bk = name_copy.find_last_of('\\');
  if (last_bk != std::string::npos)
    name_copy.erase(0,last_bk + 1);
  size_t last_fwd = name_copy.find_last_of('/');
  if (last_fwd != std::string::npos)
    name_copy.erase(0,last_fwd + 1);

  size_t last_dot = name_copy.find_last_of('.');
  if (last_dot != std::string::npos)
    name_copy.erase(last_dot,name_copy.size());

  name_copy += "_model";
  return name_copy;
}

bool is_parsable(const std::string& file_name) {
  stan::gm::program prog;
  std::ifstream fs(file_name.c_str());
  std::string model_name = file_name_to_model_name(file_name);
  bool parsable = stan::gm::parse(0, fs, file_name, model_name, prog);
  return parsable;
}

TEST(gm_parser,eight_schools) {
  EXPECT_TRUE(is_parsable("src/models/misc/eight_schools/eight_schools.stan"));
}

TEST(gm_parser,bugs_1_kidney) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/kidney/kidney.stan"));
}
/*TEST(gm_parser,bugs_1_leuk) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/leuk/leuk.stan"));
  }*/
/*TEST(gm_parser,bugs_1_leukfr) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/leukfr/leukfr.stan"));
}*/
TEST(gm_parser,bugs_1_mice) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/mice/mice.stan"));
}
TEST(gm_parser,bugs_1_oxford) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/oxford/oxford.stan"));
}
TEST(gm_parser,bugs_1_rats) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/rats/rats.stan"));
}
TEST(gm_parser,bugs_1_salm) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/salm/salm.stan"));
}
TEST(gm_parser,bugs_1_seeds) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/seeds/seeds.stan"));
}
TEST(gm_parser,bugs_1_surgical) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/surgical/surgical.stan"));
}

TEST(gm_parser,bugs_2_beetles_cloglog) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_cloglog.stan"));
}
TEST(gm_parser,bugs_2_beetles_logit) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_logit.stan"));
}
TEST(gm_parser,bugs_2_beetles_probit) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_probit.stan"));
}
TEST(gm_parser,bugs_2_birats) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/birats/birats.stan"));
}
TEST(gm_parser,bugs_2_dugongs) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/dugongs/dugongs.stan"));
}
TEST(gm_parser,bugs_2_eyes) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/eyes/eyes.stan"));
}
TEST(gm_parser,bugs_2_ice) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/ice/ice.stan"));
}
/*TEST(gm_parser,bugs_2_stagnant) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/stagnant/stagnant.stan"));
  }*/

TEST(gm_parser,good_trunc) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_trunc.stan"));
}

TEST(gm_parser,good_vec_constraints) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_trunc.stan"));
}

TEST(gm_parser,good_const) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_const.stan"));
}

TEST(gm_parser,good_matrix_ops) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_matrix_ops.stan"));
}

TEST(gm_parser,good_funs) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_funs.stan"));
}

TEST(gm_parser,triangle_lp) {
  EXPECT_TRUE(is_parsable("src/models/basic_distributions/triangle.stan"));
}

TEST(gm_parser,good_vars) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_vars.stan"));
}

TEST(gm_parser,good_intercept_var) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_intercept_var.stan"));
}

TEST(gm_parser,good_cov) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_cov.stan"));
}

TEST(gm_parser,parsable_test_bad1) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad1.stan"),
               std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad2) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad2.stan"),
               std::invalid_argument);
}

TEST(gm_parser,parsable_test_bad3) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad3.stan"),
               std::invalid_argument);
}

TEST(gm_parser,parsable_test_bad4) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad4.stan"),
               std::invalid_argument);
}
// TEST(gm_parser,parsable_test_bad5) {
//    EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad5.stan"),
//                 std::invalid_argument);
// }

TEST(gm_parser,parsable_test_bad6) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad6.stan"),
               std::invalid_argument);
}

TEST(gm_parser,parsable_test_bad7) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad7.stan"),
               std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad8) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad8.stan"),
               std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad9) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad9.stan"),
               std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad10) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad10.stan"),
               std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad11) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad11.stan"),
               std::invalid_argument);
}
TEST(gmParser,parsableBadPeriods) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_data.stan"),
               std::invalid_argument);
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_tdata.stan"),
               std::invalid_argument);
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_params.stan"),
               std::invalid_argument);
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_tparams.stan"),
               std::invalid_argument);
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_gqs.stan"),
               std::invalid_argument);
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_local.stan"),
               std::invalid_argument);
}
TEST(gmParser,declareVarWithSameNameAsModel) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_model_name_var.stan"),
               std::invalid_argument);
}
TEST(gm_parser,function_signatures) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures1.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures6.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures7.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_bernoulli.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_beta.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_beta_binomial.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_binomial.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_categorical.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_cauchy.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_chi_square.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_dirichlet.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_double_exponential.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_exponential.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_gamma.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_hypergeometric.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_inv_chi_square.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_inv_gamma.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_logistic.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_lognormal.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_multinomial.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_neg_binomial.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_normal.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_ordered_logistic.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_pareto.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_poisson.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_scaled_inv_chi_square.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_student_t_0.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_student_t_1.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_student_t_2.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_student_t_3.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_uniform.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_weibull.stan"));
}
<commit_msg>changing quotes to <> for includes<commit_after>#include <gtest/gtest.h>
#include <iostream>
#include <fstream>
#include <istream>
#include <exception>
#include <stdexcept>

#include <stan/gm/ast.hpp>
#include <stan/gm/parser.hpp>
#include <stan/gm/generator.hpp>
#include <stan/gm/grammars/program_grammar.hpp>
#include <stan/gm/grammars/whitespace_grammar.hpp>
#include <stan/gm/grammars/expression_grammar.hpp>
#include <stan/gm/grammars/statement_grammar.hpp>
#include <stan/gm/grammars/var_decls_grammar.hpp>

std::string file_name_to_model_name(const std::string& name) {
  std::string name_copy = name;
  size_t last_bk = name_copy.find_last_of('\\');
  if (last_bk != std::string::npos)
    name_copy.erase(0,last_bk + 1);
  size_t last_fwd = name_copy.find_last_of('/');
  if (last_fwd != std::string::npos)
    name_copy.erase(0,last_fwd + 1);

  size_t last_dot = name_copy.find_last_of('.');
  if (last_dot != std::string::npos)
    name_copy.erase(last_dot,name_copy.size());

  name_copy += "_model";
  return name_copy;
}

bool is_parsable(const std::string& file_name) {
  stan::gm::program prog;
  std::ifstream fs(file_name.c_str());
  std::string model_name = file_name_to_model_name(file_name);
  bool parsable = stan::gm::parse(0, fs, file_name, model_name, prog);
  return parsable;
}

TEST(gm_parser,eight_schools) {
  EXPECT_TRUE(is_parsable("src/models/misc/eight_schools/eight_schools.stan"));
}

TEST(gm_parser,bugs_1_kidney) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/kidney/kidney.stan"));
}
/*TEST(gm_parser,bugs_1_leuk) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/leuk/leuk.stan"));
  }*/
/*TEST(gm_parser,bugs_1_leukfr) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/leukfr/leukfr.stan"));
}*/
TEST(gm_parser,bugs_1_mice) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/mice/mice.stan"));
}
TEST(gm_parser,bugs_1_oxford) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/oxford/oxford.stan"));
}
TEST(gm_parser,bugs_1_rats) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/rats/rats.stan"));
}
TEST(gm_parser,bugs_1_salm) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/salm/salm.stan"));
}
TEST(gm_parser,bugs_1_seeds) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/seeds/seeds.stan"));
}
TEST(gm_parser,bugs_1_surgical) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/surgical/surgical.stan"));
}

TEST(gm_parser,bugs_2_beetles_cloglog) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_cloglog.stan"));
}
TEST(gm_parser,bugs_2_beetles_logit) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_logit.stan"));
}
TEST(gm_parser,bugs_2_beetles_probit) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_probit.stan"));
}
TEST(gm_parser,bugs_2_birats) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/birats/birats.stan"));
}
TEST(gm_parser,bugs_2_dugongs) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/dugongs/dugongs.stan"));
}
TEST(gm_parser,bugs_2_eyes) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/eyes/eyes.stan"));
}
TEST(gm_parser,bugs_2_ice) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/ice/ice.stan"));
}
/*TEST(gm_parser,bugs_2_stagnant) {
  EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/stagnant/stagnant.stan"));
  }*/

TEST(gm_parser,good_trunc) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_trunc.stan"));
}

TEST(gm_parser,good_vec_constraints) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_trunc.stan"));
}

TEST(gm_parser,good_const) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_const.stan"));
}

TEST(gm_parser,good_matrix_ops) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_matrix_ops.stan"));
}

TEST(gm_parser,good_funs) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_funs.stan"));
}

TEST(gm_parser,triangle_lp) {
  EXPECT_TRUE(is_parsable("src/models/basic_distributions/triangle.stan"));
}

TEST(gm_parser,good_vars) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_vars.stan"));
}

TEST(gm_parser,good_intercept_var) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_intercept_var.stan"));
}

TEST(gm_parser,good_cov) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_cov.stan"));
}

TEST(gm_parser,parsable_test_bad1) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad1.stan"),
               std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad2) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad2.stan"),
               std::invalid_argument);
}

TEST(gm_parser,parsable_test_bad3) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad3.stan"),
               std::invalid_argument);
}

TEST(gm_parser,parsable_test_bad4) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad4.stan"),
               std::invalid_argument);
}
// TEST(gm_parser,parsable_test_bad5) {
//    EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad5.stan"),
//                 std::invalid_argument);
// }

TEST(gm_parser,parsable_test_bad6) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad6.stan"),
               std::invalid_argument);
}

TEST(gm_parser,parsable_test_bad7) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad7.stan"),
               std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad8) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad8.stan"),
               std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad9) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad9.stan"),
               std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad10) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad10.stan"),
               std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad11) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad11.stan"),
               std::invalid_argument);
}
TEST(gmParser,parsableBadPeriods) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_data.stan"),
               std::invalid_argument);
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_tdata.stan"),
               std::invalid_argument);
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_params.stan"),
               std::invalid_argument);
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_tparams.stan"),
               std::invalid_argument);
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_gqs.stan"),
               std::invalid_argument);
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_periods_local.stan"),
               std::invalid_argument);
}
TEST(gmParser,declareVarWithSameNameAsModel) {
  EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_model_name_var.stan"),
               std::invalid_argument);
}
TEST(gm_parser,function_signatures) {
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures1.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures6.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures7.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_bernoulli.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_beta.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_beta_binomial.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_binomial.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_categorical.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_cauchy.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_chi_square.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_dirichlet.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_double_exponential.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_exponential.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_gamma.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_hypergeometric.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_inv_chi_square.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_inv_gamma.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_logistic.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_lognormal.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_multinomial.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_neg_binomial.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_normal.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_ordered_logistic.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_pareto.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_poisson.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_scaled_inv_chi_square.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_student_t_0.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_student_t_1.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_student_t_2.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_student_t_3.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_uniform.stan"));
  EXPECT_TRUE(is_parsable("src/test/gm/model_specs/compiled/function_signatures_weibull.stan"));
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: 8 Oct 2016
 *      Author: muttley
 */

#include <iostream>
#include <gtkmm.h>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <regex>

#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>

#include "VDF.h"
#include "Filesystem.h"
#include "Settings.h"
#include "Utils.h"
#include "Logger.h"

#include "MainWindow.h"

#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif

using namespace std;

int main(int argc, char *argv[])
{
    //Checking parameters for --verbose or -v
    for (int i = 0; i < argc; i++)
    {
        if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0)
            LogLevel = 0;
    }

    LOG(1, "ArmA 3 Unix Launcher started");

    //~/.config/a3unixlauncher
    if (!Filesystem::DirectoryExists(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory))
    {
        bool result = Filesystem::CreateDirectory(Filesystem::HomeDirectory
                + Filesystem::LauncherSettingsDirectory);
        if (!result)
            return 1;
    }

    if (!Filesystem::FileExists(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory
            + Filesystem::LauncherSettingsFilename))
    {
        Settings::Save(Filesystem::HomeDirectory
                + Filesystem::LauncherSettingsDirectory
                + Filesystem::LauncherSettingsFilename);
    }

    Settings::Load(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory
            + Filesystem::LauncherSettingsFilename);

    if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
        Settings::ArmaPath = Filesystem::GetDirectory(DirectoryToFind::ArmaInstall);

    if (Settings::WorkshopPath == Filesystem::DIR_NOT_FOUND)
        Settings::WorkshopPath = Filesystem::GetDirectory(DirectoryToFind::WorkshopMods);

    for (int i = 0; i < argc; i++)
    {
        if (strcmp(argv[i], "--purge") == 0)
        {
            if (Settings::ArmaPath != Filesystem::DIR_NOT_FOUND)
            {
                string removeWorkshop = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirWorkshop);
                string removeCustom = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirCustom);
                system(removeWorkshop.c_str());
                system(removeCustom.c_str());
            }
            string removeConfig = "rm -rf \"" + Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + "\"";
            system(removeConfig.c_str());

            LOG(1, "Purged config file, !workshop, !custom directories");
            exit(0);
        }
    }

    //Dirty fix to Gtk::Application trying to parse arguments on its own
    argc = 0;
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "muttley.a3unixlauncher");

#ifdef __APPLE__
    //apple path is like: /Applications/arma3-unix-launcher.app/Contents/MacOS/./arma3-unix-launcher
    char* path = new char[4096];
    unsigned int pathLength = 4095;
    _NSGetExecutablePath(path, &pathLength);
    string currentPath = path;
    delete[] path;

    string MainFormPath = Utils::RemoveLastElement(currentPath, false) + "MainForm.glade";
#else
    string MainFormPath = "/usr/share/arma3-unix-launcher/MainForm.glade";
    if (!Filesystem::FileExists(MainFormPath))
        MainFormPath = "MainForm.glade";
    if (!Filesystem::FileExists(MainFormPath))
    {
        string binaryPath = Filesystem::GetSymlinkTarget("/proc/" + to_string(getpid()) + "/exe");
        MainFormPath = Utils::RemoveLastElement(binaryPath, false, 2) + "MainForm.glade";
    }
#endif

    Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file(MainFormPath);

    cout << "GTK+ version: " << gtk_major_version << "." << gtk_minor_version << "." << gtk_micro_version << endl
         << "Glib version: " << glib_major_version << "." << glib_minor_version << "." << glib_micro_version << endl;

    //if autodetection fails
    while (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
    {
        string Message = string("Launcher couldn't detect ArmA 3 installation directory") +
                "\nClick 'Yes' to select appropriate directory" +
                "\nClick 'No' to close the program";

        Gtk::MessageDialog msg(Message, false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_YES_NO);
        int result = msg.run();

        if (result == Gtk::RESPONSE_NO)
            exit(2);

        Gtk::FileChooserDialog fcDialog("Select ArmA 3 install directory", Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
        fcDialog.add_button("_Open", 1);
        result = fcDialog.run();
        if (result == 1)
        {
            string currentFolder = fcDialog.get_current_folder();
            if (Filesystem::FileExists(currentFolder + "/arma3.i386")
                    || Filesystem::FileExists(currentFolder + "/ArmA3.app")
                    || Filesystem::DirectoryExists(currentFolder + "/ArmA3.app"))
                Settings::ArmaPath = currentFolder;
            currentFolder = fcDialog.get_filename();
            if (Filesystem::FileExists(currentFolder + "/arma3.i386")
                    || Filesystem::FileExists(currentFolder + "/ArmA3.app")
                    || Filesystem::DirectoryExists(currentFolder + "/ArmA3.app"))
                Settings::ArmaPath = currentFolder;

            if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
            {
                string Message2 = string("Selected directory seems incorrect") +
                                "\n" + currentFolder + "/arma3.i386 doesn't exist"
                                 "\n" + currentFolder + "/ArmA3.app doesn't exist";

                Gtk::MessageDialog msg2(Message2);
                msg2.run();
            }
        }
    }

    MainWindow* mainWindow = NULL;

    builder->get_widget_derived("MainForm", mainWindow);

    if (mainWindow)
        app->run(*mainWindow);

    delete mainWindow;

    return 0;
}
<commit_msg>Possible workaround for situations, where auto-detection fails<commit_after>/*
 * main.cpp
 *
 *  Created on: 8 Oct 2016
 *      Author: muttley
 */

#include <iostream>
#include <gtkmm.h>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <regex>

#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>

#include "VDF.h"
#include "Filesystem.h"
#include "Settings.h"
#include "Utils.h"
#include "Logger.h"

#include "MainWindow.h"

#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif

using namespace std;

int main(int argc, char *argv[])
{
    //Checking parameters for --verbose or -v
    for (int i = 0; i < argc; i++)
    {
        if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0)
            LogLevel = 0;
    }

    LOG(1, "ArmA 3 Unix Launcher started");

    //~/.config/a3unixlauncher
    if (!Filesystem::DirectoryExists(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory))
    {
        bool result = Filesystem::CreateDirectory(Filesystem::HomeDirectory
                + Filesystem::LauncherSettingsDirectory);
        if (!result)
            return 1;
    }

    if (!Filesystem::FileExists(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory
            + Filesystem::LauncherSettingsFilename))
    {
        Settings::Save(Filesystem::HomeDirectory
                + Filesystem::LauncherSettingsDirectory
                + Filesystem::LauncherSettingsFilename);
    }

    Settings::Load(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory
            + Filesystem::LauncherSettingsFilename);

    if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
        Settings::ArmaPath = Filesystem::GetDirectory(DirectoryToFind::ArmaInstall);

    if (Settings::WorkshopPath == Filesystem::DIR_NOT_FOUND)
        Settings::WorkshopPath = Filesystem::GetDirectory(DirectoryToFind::WorkshopMods);

    for (int i = 0; i < argc; i++)
    {
        if (strcmp(argv[i], "--purge") == 0)
        {
            if (Settings::ArmaPath != Filesystem::DIR_NOT_FOUND)
            {
                string removeWorkshop = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirWorkshop);
                string removeCustom = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirCustom);
                system(removeWorkshop.c_str());
                system(removeCustom.c_str());
            }
            string removeConfig = "rm -rf \"" + Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + "\"";
            system(removeConfig.c_str());

            LOG(1, "Purged config file, !workshop, !custom directories");
            exit(0);
        }
    }

    //Dirty fix to Gtk::Application trying to parse arguments on its own
    argc = 0;
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "muttley.a3unixlauncher");

#ifdef __APPLE__
    //apple path is like: /Applications/arma3-unix-launcher.app/Contents/MacOS/./arma3-unix-launcher
    char* path = new char[4096];
    unsigned int pathLength = 4095;
    _NSGetExecutablePath(path, &pathLength);
    string currentPath = path;
    delete[] path;

    string MainFormPath = Utils::RemoveLastElement(currentPath, false) + "MainForm.glade";
#else
    string MainFormPath = "/usr/share/arma3-unix-launcher/MainForm.glade";
    if (!Filesystem::FileExists(MainFormPath))
        MainFormPath = "MainForm.glade";
    if (!Filesystem::FileExists(MainFormPath))
    {
        string binaryPath = Filesystem::GetSymlinkTarget("/proc/" + to_string(getpid()) + "/exe");
        MainFormPath = Utils::RemoveLastElement(binaryPath, false, 2) + "MainForm.glade";
    }
#endif

    Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file(MainFormPath);

    cout << "GTK+ version: " << gtk_major_version << "." << gtk_minor_version << "." << gtk_micro_version << endl
         << "Glib version: " << glib_major_version << "." << glib_minor_version << "." << glib_micro_version << endl;

    //if autodetection fails
    while (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
    {
        string Message = string("Launcher couldn't detect ArmA 3 installation directory") +
                "\nClick 'Yes' to select appropriate directory" +
                "\nClick 'No' to close the program";

        Gtk::MessageDialog msg(Message, false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_YES_NO);
        int result = msg.run();

        if (result == Gtk::RESPONSE_NO)
            exit(2);

        Gtk::FileChooserDialog fcDialog("Select ArmA 3 install directory", Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
        fcDialog.add_button("_Open", 1);
        result = fcDialog.run();
        if (result == 1)
        {
            string currentFolder = fcDialog.get_current_folder();
            if (Filesystem::FileExists(currentFolder + "/arma3.i386")
                    || Filesystem::FileExists(currentFolder + "/ArmA3.app")
                    || Filesystem::DirectoryExists(currentFolder + "/ArmA3.app"))
                Settings::ArmaPath = currentFolder;
            currentFolder = fcDialog.get_filename();
            if (Filesystem::FileExists(currentFolder + "/arma3.i386")
                    || Filesystem::FileExists(currentFolder + "/ArmA3.app")
                    || Filesystem::DirectoryExists(currentFolder + "/ArmA3.app"))
                Settings::ArmaPath = currentFolder;

            if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
            {
                string Message2 = string("Selected directory seems incorrect") +
                                "\n" + currentFolder + "/arma3.i386 doesn't exist"
                                 "\n" + currentFolder + "/ArmA3.app doesn't exist";

                Gtk::MessageDialog msg2(Message2);
                msg2.run();
            }
            else
            {
                Settings::WorkshopPath = Utils::RemoveLastElement(Settings::ArmaPath, false, 2) + "workshop/content/107410";
                LOG(1, "Workaround workshop path: " + Settings::WorkshopPath);
            }
        }
    }

    MainWindow* mainWindow = NULL;

    builder->get_widget_derived("MainForm", mainWindow);

    if (mainWindow)
        app->run(*mainWindow);

    delete mainWindow;

    return 0;
}
<|endoftext|>


<commit_before>#include "hFramework.h"
#include <stdio.h>
#include "Lego_Touch.h"

using namespace hFramework;
using namespace hSensors;
bool motorOpen(bool open) {
    int power = 100;
    if(open) {
        printf("\rOpening...\n");
        hMot1.rotAbs(0);
    } else {
        printf("\rClosing...\n");
        hMot1.rotAbs(100);
    }
    printf("\rDone!\n");
    hMot1.setPower(0);
    return open;
}
void encoder()
{
    while (true)
    {
        // Print the current rotation of hMot1 in encoder ticks
        sys.delay(100);
    }
}
void hMain(void)
{
    sys.setLogDev(&Serial);
    Lego_Touch sensor(hSens1);
    // This creates a task that will execute `encoder` concurrently
    sys.taskCreate(encoder);

    bool maindown = false;
    int counter = 10;
    bool open = false;

    while(counter > 0) {
        bool s = sensor.isPressed();

        if(s) { // Changing mode
            if(!maindown) {
                counter++;
                printf("Button down, %d times more", counter);
                maindown = true;
                if(open) {
                    motorOpen(false);
                    open = false;
                } else {
                    motorOpen(true);
                    open = true;
                }
            }
        } else {
            if(maindown) {
                maindown = false;
            }
        }
        sys.delay_ms(50);
    }
}<commit_msg>removed setpower(0)<commit_after>#include "hFramework.h"
#include <stdio.h>
#include "Lego_Touch.h"

using namespace hFramework;
using namespace hSensors;
bool motorOpen(bool open) {
    int power = 1000;
    bool block = 1;
    int angle1 = 0;
    int angle2 = 180;

    if(open) {
        printf("\rOpening...\n");
        hMot1.rotAbs(angle1, power, block);
    } else {
        printf("\rClosing...\n");
        hMot1.rotAbs(angle2, power, block);
    }
    printf("\rDone!\n");
    return open;
}
void encoder()
{
    while (true)
    {
        // Print the current rotation of hMot1 in encoder ticks
        sys.delay(100);
    }
}
void hMain(void)
{
    sys.setLogDev(&Serial);
    Lego_Touch sensor(hSens1);
    // This creates a task that will execute `encoder` concurrently
    sys.taskCreate(encoder);

    bool maindown = false;
    int counter = 10;
    bool open = false;

    while(counter > 0) {
        bool s = sensor.isPressed();

        if(s) { // Changing mode
            if(!maindown) {
                counter++;
                printf("Button down, %d times more", counter);
                maindown = true;
                if(open) {
                    motorOpen(false);
                    open = false;
                } else {
                    motorOpen(true);
                    open = true;
                }
            }
        } else {
            if(maindown) {
                maindown = false;
            }
        }
        sys.delay_ms(50);
    }
}<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#define MAXBUF 1024

#ifdef MASTER

#include <sys/time.h>
#include <vector>
#define HOSTPORT 31415
#define MAXCLIENTS 10

#else

#include <Mandelbrot.h>
#define HOSTPORT "31415"
#define HOSTADDR "10.3.14.5"

#endif

using namespace std;

int main()
{
    struct sockaddr_in addr;
    int sock;
    char buf[MAXBUF + 1];

    #ifdef MASTER

    int clients[MAXCLIENTS];
    fd_set fds;

    for (int i = 0; i < MAXCLIENTS; i++) clients[i] = 0;
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        printf("Could not create socket: %d\n", errno);
        return -1;
    }

    int opt = 1;
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int)) < 0)
    {
        printf("Could not set socket options: %d\n", errno);
        return -1;
    }

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(HOSTPORT);

    if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        printf("Could not bind port: %d\n", errno);
        return -1;
    }

    printf("Listening on port %d\n", HOSTPORT);

    if (listen(sock, 5) < 0)
    {
        printf("Could not listen: %d\n", errno);
        return -1;
    }

    int addrlen = sizeof(addr);
    printf("Waiting for connections\n");

    #else

    struct addrinfo hints, *serv;
    memset(&hints, 0, sizeof(hints));

    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    int ret = getaddrinfo(HOSTADDR, HOSTPORT, &hints, &serv);
    if (ret != 0)
    {
        printf("Could not get address info: %s\n", gai_strerror(ret));
        return -1;
    }

    struct addrinfo *i;
    for (i = serv; i != NULL; i = i->ai_next)
    {
        if ((sock = socket(i->ai_family, i->ai_socktype, i->ai_protocol)) == -1)
        {
            printf("Could not create socket: %d\n", errno);
            continue;
        }

        if (connect(sock, i->ai_addr, i->ai_addrlen) < 0)
        {
            close(sock);
            printf("Could not connect to host: %d\n", errno);
            continue;
        }

        break;
    }

    if (i == NULL)
    {
        printf("Could not connect\n");
        return -1;
    }

    printf("Connecting to %s:%d\n", inet_ntoa(((struct sockaddr_in*)i)->sin_addr), ntohs(((struct sockaddr_in*)i)->sin_port));

    freeaddrinfo(serv);

    #endif

    while (true)
    {
        #ifdef MASTER

        FD_ZERO(&fds);

        FD_SET(sock, &fds);
        int ms = sock;
        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (s > 0) FD_SET(s, &fds);
            if (s > ms) ms = s;
        }

        int activity = select(ms + 1, &fds, NULL, NULL, NULL);

        if (activity < 0 && errno != EINTR) printf("'select' error\n");

        if (FD_ISSET(sock, &fds))
        {
            int newsock = accept(sock, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
            if (newsock < 0)
            {
                printf("Could not accept client\n");
                return -1;
            }

            printf("New connection from %s:%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));

            char* msg = "You have just connected to Master Pi!\n";
            int msglen = strlen(msg);
            if (send(newsock, msg, msglen, 0) != msglen) printf("Could not send message\n");
            else printf("Greeted %s\n", inet_ntoa(addr.sin_addr));

            for (int i = 0; i < MAXCLIENTS; i++)
            {
                if (clients[i] == 0)
                {
                    clients[i] = newsock;
                    printf("Client %d added to list\n", i);
                    break;
                }
            }
        }

        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (FD_ISSET(s, &fds))
            {
                int val = read(s, buf, MAXBUF);
                getpeername(s, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
                if (val == 0)
                {
                    printf("Client %s disconnected\n", inet_ntoa(addr.sin_addr));
                    close(s);
                    clients[i] = 0;
                }
                else
                {
                    buf[val - 2] = 0;
                    printf("-> %s: \"%s\"\n", inet_ntoa(addr.sin_addr), buf);
                    char* msg = "Received message\n";
                    send(s, msg, strlen(msg), 0);
                }
            }
        }

        #else

        ret = recv(sock, buf, MAXBUF, 0);
        if (ret < 0)
        {
            printf("Error receiving message");
            return -1;
        }

        buf[ret] = 0;
        printf("Server: \"%s\"\n", buf);

        #endif
    }

    close(sock);
}
<commit_msg>Removed endline for sent messages<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#define MAXBUF 1024

#ifdef MASTER

#include <sys/time.h>
#include <vector>
#define HOSTPORT 31415
#define MAXCLIENTS 10

#else

#include <Mandelbrot.h>
#define HOSTPORT "31415"
#define HOSTADDR "10.3.14.5"

#endif

using namespace std;

int main()
{
    struct sockaddr_in addr;
    int sock;
    char buf[MAXBUF + 1];

    #ifdef MASTER

    int clients[MAXCLIENTS];
    fd_set fds;

    for (int i = 0; i < MAXCLIENTS; i++) clients[i] = 0;
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        printf("Could not create socket: %d\n", errno);
        return -1;
    }

    int opt = 1;
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int)) < 0)
    {
        printf("Could not set socket options: %d\n", errno);
        return -1;
    }

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(HOSTPORT);

    if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        printf("Could not bind port: %d\n", errno);
        return -1;
    }

    printf("Listening on port %d\n", HOSTPORT);

    if (listen(sock, 5) < 0)
    {
        printf("Could not listen: %d\n", errno);
        return -1;
    }

    int addrlen = sizeof(addr);
    printf("Waiting for connections\n");

    #else

    struct addrinfo hints, *serv;
    memset(&hints, 0, sizeof(hints));

    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    int ret = getaddrinfo(HOSTADDR, HOSTPORT, &hints, &serv);
    if (ret != 0)
    {
        printf("Could not get address info: %s\n", gai_strerror(ret));
        return -1;
    }

    struct addrinfo *i;
    for (i = serv; i != NULL; i = i->ai_next)
    {
        if ((sock = socket(i->ai_family, i->ai_socktype, i->ai_protocol)) == -1)
        {
            printf("Could not create socket: %d\n", errno);
            continue;
        }

        if (connect(sock, i->ai_addr, i->ai_addrlen) < 0)
        {
            close(sock);
            printf("Could not connect to host: %d\n", errno);
            continue;
        }

        break;
    }

    if (i == NULL)
    {
        printf("Could not connect\n");
        return -1;
    }

    printf("Connecting to %s:%d\n", inet_ntoa(((struct sockaddr_in*)i)->sin_addr), ntohs(((struct sockaddr_in*)i)->sin_port));

    freeaddrinfo(serv);

    #endif

    while (true)
    {
        #ifdef MASTER

        FD_ZERO(&fds);

        FD_SET(sock, &fds);
        int ms = sock;
        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (s > 0) FD_SET(s, &fds);
            if (s > ms) ms = s;
        }

        int activity = select(ms + 1, &fds, NULL, NULL, NULL);

        if (activity < 0 && errno != EINTR) printf("'select' error\n");

        if (FD_ISSET(sock, &fds))
        {
            int newsock = accept(sock, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
            if (newsock < 0)
            {
                printf("Could not accept client\n");
                return -1;
            }

            printf("New connection from %s:%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));

            char* msg = "You have just connected to Master Pi!";
            int msglen = strlen(msg);
            if (send(newsock, msg, msglen, 0) != msglen) printf("Could not send message\n");
            else printf("Greeted %s\n", inet_ntoa(addr.sin_addr));

            for (int i = 0; i < MAXCLIENTS; i++)
            {
                if (clients[i] == 0)
                {
                    clients[i] = newsock;
                    printf("Client %d added to list\n", i);
                    break;
                }
            }
        }

        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (FD_ISSET(s, &fds))
            {
                int val = read(s, buf, MAXBUF);
                getpeername(s, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
                if (val == 0)
                {
                    printf("Client %s disconnected\n", inet_ntoa(addr.sin_addr));
                    close(s);
                    clients[i] = 0;
                }
                else
                {
                    buf[val - 2] = 0;
                    printf("-> %s: \"%s\"\n", inet_ntoa(addr.sin_addr), buf);
                    char* msg = "Received message";
                    send(s, msg, strlen(msg), 0);
                }
            }
        }

        #else

        ret = recv(sock, buf, MAXBUF, 0);
        if (ret < 0)
        {
            printf("Error receiving message");
            return -1;
        }

        buf[ret] = 0;
        printf("Server: \"%s\"\n", buf);

        #endif
    }

    close(sock);
}
<|endoftext|>


<commit_before>83367f4f-2749-11e6-a15b-e0f84713e7b8<commit_msg>Introduced random NullPointerException bug<commit_after>83420df3-2749-11e6-a310-e0f84713e7b8<|endoftext|>


<commit_before>a8477ec0-2747-11e6-9bca-e0f84713e7b8<commit_msg>my cat is cute<commit_after>a8586e07-2747-11e6-8f45-e0f84713e7b8<|endoftext|>


<commit_before>
/** \file main.cpp
 *
 * \brief Contains main function, and possibly some small amount
 * of other code, relating to Phatbooks application.
 *
 * \author Matthew Harvey
 * \date 04 July 2012.
 *
 * Copyright (c) 2012, Matthew Harvey. All rights reserved.
 */

// TODO It looks like I can get around the issue of typedefs not working
// within templates by using the typename keyword. This will
// enable proper encapsulation of Id type within each business
// class. The direct use of sqloxx::Id within templates that
// are supposed to be instantiated across different business
// classes, can then be abolished, in favour of a locution of the form
// as T::template Id.

#include "application.hpp"
#include "graphical_session.hpp"
#include "phatbooks_text_session.hpp"
#include <tclap/CmdLine.h>
#include <cassert>
#include <iostream>
#include <string>

using phatbooks::Application;
using phatbooks::gui::GraphicalSession;
using phatbooks::tui::PhatbooksTextSession;
using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::wstring;
using TCLAP::ArgException;
using TCLAP::CmdLine;
using TCLAP::SwitchArg;
using TCLAP::UnlabeledValueArg;

// TODO High priority. I need to make Unicode supportable on both
// Linux and Windows builds.
// I should do this as follows. Have wxString throughout the business
// layer of Phatbooks, both in GUI and TUI code. In Linux, wxString
// is a UTF-8 encoded string, and on Windows, it is a UTF-16 encoded
// wide string.
// At the lowest level just before the database - i.e. in the load() and save()
// methods of the ...Impl classes - I convert from wxString to UTF-8 std::string just
// before storing to the database, and convert from
// UTF-8 std::string to wxString just after retrieving from the
// database. This ensures that strings stored on one platform can be
// read later on another platform and display properly: all strings
// are stored with the same encoding in the database.
//
// This entails a major editing operation throughout the code base.
//
// Note that Jewel currently supports std::string and std::wstring, and
// I don't think I should involve wxString in that. I may need to do
// some conversion to and from wxString and std::string and std::wstring,
// in code that involves jewel::Decimal at the presentation layer.
//
// Sqloxx currently supports std::string only; and I don't think there's any
// need for it to support anything else. All strings are ultimately going
// to be stored in the database in UTF-8 form so this narrow interface
// can be retained for Sqloxx.

int main(int argc, char** argv)
{
	try
	{
		// Process command line arguments
		CmdLine cmd("Phatbooks"); // WARNING TEMP - should use Application::application_name()
		SwitchArg gui_switch("g", "gui", "Run in graphical mode", cmd);
		UnlabeledValueArg<string> filepath_arg
		(	"FILE",
			"File to open or create",
			true,
			"",
			"string"
		);
		cmd.add(filepath_arg);
		cmd.parse(argc, argv);
		bool const is_gui = gui_switch.getValue();
		string const filename = filepath_arg.getValue();
		if (is_gui)
		{
			GraphicalSession graphical_session;
			return graphical_session.run(filename);
		}
		assert (!is_gui);
		PhatbooksTextSession text_session;
		return text_session.run(filename);
	}
	catch (ArgException& e)
	{
		cerr << "error: " << e.error() << " for arg " << e.argId() << endl;
		return 1;
	}
	// This seems pointless but is necessary to guarantee the stack is fully
	// unwound if an exception is thrown.
	catch (...)
	{
		throw;
	}
}
<commit_msg>Deleted stupid working notes from main.cpp.<commit_after>
/** \file main.cpp
 *
 * \brief Contains main function, and possibly some small amount
 * of other code, relating to Phatbooks application.
 *
 * \author Matthew Harvey
 * \date 04 July 2012.
 *
 * Copyright (c) 2012, Matthew Harvey. All rights reserved.
 */

// TODO It looks like I can get around the issue of typedefs not working
// within templates by using the typename keyword. This will
// enable proper encapsulation of Id type within each business
// class. The direct use of sqloxx::Id within templates that
// are supposed to be instantiated across different business
// classes, can then be abolished, in favour of a locution of the form
// as T::template Id.

#include "application.hpp"
#include "graphical_session.hpp"
#include "phatbooks_text_session.hpp"
#include <tclap/CmdLine.h>
#include <cassert>
#include <iostream>
#include <string>

using phatbooks::Application;
using phatbooks::gui::GraphicalSession;
using phatbooks::tui::PhatbooksTextSession;
using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::wstring;
using TCLAP::ArgException;
using TCLAP::CmdLine;
using TCLAP::SwitchArg;
using TCLAP::UnlabeledValueArg;

int main(int argc, char** argv)
{
	try
	{
		// Process command line arguments
		CmdLine cmd("Phatbooks"); // WARNING TEMP - should use Application::application_name()
		SwitchArg gui_switch("g", "gui", "Run in graphical mode", cmd);
		UnlabeledValueArg<string> filepath_arg
		(	"FILE",
			"File to open or create",
			true,
			"",
			"string"
		);
		cmd.add(filepath_arg);
		cmd.parse(argc, argv);
		bool const is_gui = gui_switch.getValue();
		string const filename = filepath_arg.getValue();
		if (is_gui)
		{
			GraphicalSession graphical_session;
			return graphical_session.run(filename);
		}
		assert (!is_gui);
		PhatbooksTextSession text_session;
		return text_session.run(filename);
	}
	catch (ArgException& e)
	{
		cerr << "error: " << e.error() << " for arg " << e.argId() << endl;
		return 1;
	}
	// This seems pointless but is necessary to guarantee the stack is fully
	// unwound if an exception is thrown.
	catch (...)
	{
		throw;
	}
}
<|endoftext|>


<commit_before>#include <iostream>
#include <arm_neon.h>
#include "rng.hpp"

inline uint16x8_t cv_vpacks_u32(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vqmovn_u32(v0), vqmovn_u32(v1));
}

inline uint8x16_t cv_vpacks_u16(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vqmovn_u16(v0), vqmovn_u16(v1));
}

inline int16x8_t cv_vpacks_s32(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vqmovn_s32(v0), vqmovn_s32(v1));
}

inline int8x16_t cv_vpacks_s16(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vqmovn_s16(v0), vqmovn_s16(v1));
}

inline uint16x8_t cv_vpack_u32(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vmovn_u32(v0), vmovn_u32(v1));
}

inline uint8x16_t cv_vpack_u16(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vmovn_u16(v0), vmovn_u16(v1));
}

inline int16x8_t cv_vpack_s32(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vmovn_s32(v0), vmovn_s32(v1));
}

inline int8x16_t cv_vpack_s16(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vmovn_s16(v0), vmovn_s16(v1));
}

void fill(uint32_t* ptr, RNG& r)
{
	for(uint32_t i = 0;i < 4;i++)
		ptr[i] = (r.next() & 0x7fff);
}

void debugPack(const uint32_t* src0, const uint32_t* src1, uint16_t* dst)
{
	for(uint32_t i = 0;i < (16/sizeof(uint32_t));i++)
	{
		dst[i*2  ] = (uint16_t)(src0[i]);
		dst[i*2+1] = (uint16_t)(src1[i]);
	}
}

template <typename ST, typename DT>
void dumpArray(const ST* src0, const ST* src1, const DT* dst)
{
	using namespace std;
	unsigned int srcLoop = 16/sizeof(ST);
	unsigned int dstLoop = 16/sizeof(DT);
	cout << "src0:";
	for(unsigned int i = 0;i < srcLoop;i++)
	{
		cout << '\t' << src0[i];
	}
	cout << endl;
	cout << "src1:";
	for(unsigned int i = 0;i < srcLoop;i++)
	{
		cout << '\t' << src1[i];
	}
	cout << endl;
	cout << "dst :";
	for(unsigned int i = 0;i < dstLoop;i++)
	{
		cout << '\t' << dst[i];
	}
	cout << endl;
}

int main(int argc, char** argv)
{
	RNG r(0x123);
	uint32_t src0[4], src1[4];
	uint16_t dst[8];
	fill(src0, r);
	fill(src1, r);
	debugPack((const uint32_t*)src0, (const uint32_t*)src1, (uint16_t*)dst);
	dumpArray(src0, src1, dst);

	return 0;
}
<commit_msg>add more templated implementation<commit_after>#include <iostream>
#include <arm_neon.h>
#include "rng.hpp"

inline uint16x8_t cv_vpacks_u32(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vqmovn_u32(v0), vqmovn_u32(v1));
}

inline uint8x16_t cv_vpacks_u16(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vqmovn_u16(v0), vqmovn_u16(v1));
}

inline int16x8_t cv_vpacks_s32(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vqmovn_s32(v0), vqmovn_s32(v1));
}

inline int8x16_t cv_vpacks_s16(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vqmovn_s16(v0), vqmovn_s16(v1));
}

inline uint16x8_t cv_vpack_u32(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vmovn_u32(v0), vmovn_u32(v1));
}

inline uint8x16_t cv_vpack_u16(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vmovn_u16(v0), vmovn_u16(v1));
}

inline int16x8_t cv_vpack_s32(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vmovn_s32(v0), vmovn_s32(v1));
}

inline int8x16_t cv_vpack_s16(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vmovn_s16(v0), vmovn_s16(v1));
}

template <typename ST>
void fill(ST* ptr, RNG& r)
{
	unsigned int cLoop = 16/sizeof(ST);
	for(unsigned int i = 0;i < cLoop;i++)
		ptr[i] = (r.next() & 0x7f);
}

template <typename ST, typename DT>
void debugPack(const ST* src0, const ST* src1, DT* dst)
{
	for(uint32_t i = 0;i < (16/sizeof(ST));i++)
	{
		dst[i*2  ] = (DT)(src0[i]);
		dst[i*2+1] = (DT)(src1[i]);
	}
}

template <typename ST, typename DT>
void dumpArray(const ST* src0, const ST* src1, const DT* dst)
{
	using namespace std;
	unsigned int srcLoop = 16/sizeof(ST);
	unsigned int dstLoop = 16/sizeof(DT);
	cout << "src0:";
	for(unsigned int i = 0;i < srcLoop;i++)
	{
		cout << '\t' << src0[i];
	}
	cout << endl;
	cout << "src1:";
	for(unsigned int i = 0;i < srcLoop;i++)
	{
		cout << '\t' << src1[i];
	}
	cout << endl;
	cout << "dst :";
	for(unsigned int i = 0;i < dstLoop;i++)
	{
		cout << '\t' << dst[i];
	}
	cout << endl;
}

template <typename ST, typename DT>
void verifyArray(ST* src0, ST* src1, DT* dst, RNG& r)
{
	fill(src0, r);
	fill(src1, r);
	debugPack((const ST*)src0, (const ST*)src1, (DT*)dst);
	dumpArray(src0, src1, dst);
}

int main(int argc, char** argv)
{
	RNG r(0x123);
	uint32_t src0[4], src1[4];
	uint16_t dst[8];
	verifyArray(src0, src1, dst, r);

	return 0;
}
<|endoftext|>


<commit_before>#include "hFramework.h"
#include <stdio.h>
#include "Lego_Touch.h"

using namespace hFramework;
using namespace hSensors;
bool motorOpen(bool open) {
    if(open) {
        printf("\rOpening...\n");
        hMot1.setPower(500);
        sys.delay_ms(10000);
    } else {
        printf("\rClosing...\n");
        hMot1.setPower(-500);
        sys.delay_ms(10000);
    }
    printf("\rDone!\n");
    hMot1.setPower(0);
    return open;
}
void encoder()
{
    while (true)
    {
        // Print the current rotation of hMot1 in encoder ticks
        sys.delay(100);
    }
}
void hMain(void)
{
    sys.setLogDev(&Serial);
    Lego_Touch sensor(hSens1);
    // This creates a task that will execute `encoder` concurrently
    sys.taskCreate(encoder);

    bool maindown = false;
    int counter = 10;
    bool open = false;

    while(counter > 0) {
        bool s = sensor.isPressed();

        if(s) { // Changing mode
            if(!maindown) {
                counter++;
                printf("Button down, %d times more", counter);
                maindown = true;
                if(open) {
                    motorOpen(false);
                    open = false;
                } else {
                    motorOpen(true);
                    open = true;
                }
            }
        } else {
            if(maindown) {
                maindown = false;
            }
        }
        sys.delay_ms(50);
    }
}<commit_msg>encoder<commit_after>#include "hFramework.h"
#include <stdio.h>
#include "Lego_Touch.h"

using namespace hFramework;
using namespace hSensors;
bool motorOpen(bool open) {
    int power = 500;
    if(open) {
        printf("\rOpening...\n");
        hMot1.setPower(power);
    } else {
        printf("\rClosing...\n");
        hMot1.setPower(-1 * power);
    }
    hMot1.resetEncoderCnt();
    int toAngle = 180;
    int currentAngle = 0;
    do {
        currentAngle = hMot1.getEncoderCnt()
        printf("\r%d\n",hMot1.getEncoderCnt());
    } while (toAngle > currentAngle || (toAngle * -1 < currentAngle));
    printf("\rDone!\n");
    hMot1.setPower(0);
    return open;
}
void encoder()
{
    while (true)
    {
        // Print the current rotation of hMot1 in encoder ticks
        sys.delay(100);
    }
}
void hMain(void)
{
    sys.setLogDev(&Serial);
    Lego_Touch sensor(hSens1);
    // This creates a task that will execute `encoder` concurrently
    sys.taskCreate(encoder);

    bool maindown = false;
    int counter = 10;
    bool open = false;

    while(counter > 0) {
        bool s = sensor.isPressed();

        if(s) { // Changing mode
            if(!maindown) {
                counter++;
                printf("Button down, %d times more", counter);
                maindown = true;
                if(open) {
                    motorOpen(false);
                    open = false;
                } else {
                    motorOpen(true);
                    open = true;
                }
            }
        } else {
            if(maindown) {
                maindown = false;
            }
        }
        sys.delay_ms(50);
    }
}<|endoftext|>


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

#include <iostream>
#include <stdint.h>

#include "DDBooster.h"

using namespace std;

int main()
{
    // booster object
    DDBooster booster;

    // init
    booster.init(64);
    booster.clearAll();
    booster.show();

    // set white with low brightness
    booster.setRGB(0x40, 0x40, 0x40);
    booster.setAll();
    booster.show();
}
<commit_msg>Setup working example application that uses the shared library<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Richard Guenther
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <iostream>
#include <cstdlib>
#include <stdint.h>
#include <unistd.h>

#include "DDBooster.h"

using namespace std;

int main()
{
    int i;

    DDBooster booster;

    // init
    booster.reset();
    booster.init(64);
    booster.configurePins(2);

    booster.clearAll();
    booster.show();
    usleep(500);

    while(1) {

		// set white
        booster.setRGB(40, 40, 40);
        for(i=0; i<64; i++) {
            booster.setLED(i);
            booster.show();
            usleep(50000);
        }

		// clear LEDs
		booster.setRGB(0, 0, 0);
		for(i=0; i<64; i++) {
            booster.setLED(i);
            booster.show();
            usleep(50000);
        }
    }
}

<|endoftext|>


<commit_before>252179d4-2748-11e6-9dfc-e0f84713e7b8<commit_msg>Deal with it<commit_after>252ce223-2748-11e6-bb7e-e0f84713e7b8<|endoftext|>


<commit_before>#include "UEPyEdGraphPin.h"

#if WITH_EDITOR

#include "Runtime/Engine/Classes/EdGraph/EdGraphPin.h"
#include "Editor/UnrealEd/Public/Kismet2/BlueprintEditorUtils.h"

static PyObject *py_ue_edgraphpin_make_link_to(ue_PyEdGraphPin *self, PyObject * args)
{
	PyObject *other_pin;
	if (!PyArg_ParseTuple(args, "O:make_link_to", &other_pin))
	{
		return NULL;
	}

	ue_PyEdGraphPin *py_other_pin = py_ue_is_edgraphpin(other_pin);
	if (!py_other_pin)
	{
		return PyErr_Format(PyExc_Exception, "argument is not a UEdGraphPin");
	}

	self->pin->MakeLinkTo(py_other_pin->pin);

	if (UBlueprint *bp = Cast<UBlueprint>(self->pin->GetOwningNode()->GetGraph()->GetOuter()))
	{
		FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(bp);
	}

	Py_RETURN_NONE;
}

static PyObject *py_ue_edgraphpin_connect(ue_PyEdGraphPin *self, PyObject * args)
{
	PyObject *other_pin;
	if (!PyArg_ParseTuple(args, "O:connect", &other_pin))
	{
		return NULL;
	}

	ue_PyEdGraphPin *py_other_pin = py_ue_is_edgraphpin(other_pin);
	if (!py_other_pin)
	{
		return PyErr_Format(PyExc_Exception, "argument is not a UEdGraphPin");
	}

	if (!self->pin->GetSchema()->TryCreateConnection(self->pin, py_other_pin->pin))
	{
		return PyErr_Format(PyExc_Exception, "unable to connect pins");
	}

	if (UBlueprint *bp = Cast<UBlueprint>(self->pin->GetOwningNode()->GetGraph()->GetOuter()))
	{
		FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(bp);
	}

	Py_RETURN_NONE;
}

static PyObject *py_ue_edgraphpin_break_link_to(ue_PyEdGraphPin *self, PyObject * args)
{
	PyObject *other_pin;
	if (!PyArg_ParseTuple(args, "O:break_link_to", &other_pin))
	{
		return NULL;
	}

	ue_PyEdGraphPin *py_other_pin = py_ue_is_edgraphpin(other_pin);
	if (!py_other_pin)
	{
		return PyErr_Format(PyExc_Exception, "argument is not a UEdGraphPin");
	}

	self->pin->BreakLinkTo(py_other_pin->pin);

	if (UBlueprint *bp = Cast<UBlueprint>(self->pin->GetOwningNode()->GetGraph()->GetOuter()))
	{
		FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(bp);
	}

	Py_RETURN_NONE;
}

static PyMethodDef ue_PyEdGraphPin_methods[] = {
	{ "make_link_to", (PyCFunction)py_ue_edgraphpin_make_link_to, METH_VARARGS, "" },
	{ "break_link_to", (PyCFunction)py_ue_edgraphpin_break_link_to, METH_VARARGS, "" },
	{ "connect", (PyCFunction)py_ue_edgraphpin_connect, METH_VARARGS, "" },
	{ NULL }  /* Sentinel */
};

static PyObject *py_ue_edgraphpin_get_name(ue_PyEdGraphPin *self, void *closure)
{
#if ENGINE_MINOR_VERSION > 18
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinName.ToString())));
#else
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinName)));
#endif
}

static PyObject *py_ue_edgraphpin_get_category(ue_PyEdGraphPin *self, void *closure)
{
#if ENGINE_MINOR_VERSION > 18
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinType.PinCategory.ToString())));
#else
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinType.PinCategory)));
#endif
}

static PyObject *py_ue_edgraphpin_get_sub_category(ue_PyEdGraphPin *self, void *closure)
{
#if ENGINE_MINOR_VERSION > 18
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinType.PinSubCategory.ToString())));
#else
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinType.PinSubCategory)));
#endif
}

static PyObject *py_ue_edgraphpin_get_default_value(ue_PyEdGraphPin *self, void *closure)
{
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->DefaultValue)));
}

static int py_ue_edgraphpin_set_default_value(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value && PyUnicodeOrString_Check(value))
	{
		const char *str = UEPyUnicode_AsUTF8(value);
		self->pin->DefaultValue = UTF8_TO_TCHAR(str);
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a string");
	return -1;
}

static PyObject *py_ue_edgraphpin_get_default_text_value(ue_PyEdGraphPin *self, void *closure)
{
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->DefaultTextValue.ToString())));
}

static int py_ue_edgraphpin_set_default_text_value(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value && PyUnicodeOrString_Check(value))
	{
		const char *str = UEPyUnicode_AsUTF8(value);
		self->pin->DefaultTextValue = FText::FromString(UTF8_TO_TCHAR(str));
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a string");
	return -1;
}

static PyObject *py_ue_edgraphpin_get_default_object(ue_PyEdGraphPin *self, void *closure)
{
	UObject *u_object = self->pin->DefaultObject;
	if (!u_object)
	{
		Py_RETURN_NONE;
	}
	Py_RETURN_UOBJECT(u_object);
}

static int py_ue_edgraphpin_set_default_object(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value && ue_is_pyuobject(value))
	{
		ue_PyUObject *py_obj = (ue_PyUObject *)value;
		self->pin->DefaultObject = py_obj->ue_object;
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a UObject");
	return -1;
}

static int py_ue_edgraphpin_set_category(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value && PyUnicodeOrString_Check(value))
	{
		const char *str = UEPyUnicode_AsUTF8(value);
#if ENGINE_MINOR_VERSION > 18
		self->pin->PinType.PinCategory = FName(UTF8_TO_TCHAR(str));
#else
		self->pin->PinType.PinCategory = FString(UTF8_TO_TCHAR(str));
#endif
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a string");
	return -1;
}

static int py_ue_edgraphpin_set_sub_category(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value)
	{
		if (ue_is_pyuobject(value))
		{
			ue_PyUObject *py_obj = (ue_PyUObject *)value;
			self->pin->PinType.PinSubCategoryObject = py_obj->ue_object;
			return 0;
		}
		if (PyUnicodeOrString_Check(value))
		{
			const char *str = UEPyUnicode_AsUTF8(value);
#if ENGINE_MINOR_VERSION > 18
			self->pin->PinType.PinSubCategory = FName(UTF8_TO_TCHAR(str));
#else
			self->pin->PinType.PinSubCategory = FString(UTF8_TO_TCHAR(str));
#endif
			return 0;
		}
	}
	PyErr_SetString(PyExc_TypeError, "value is not a UObject");
	return -1;
}

static PyGetSetDef ue_PyEdGraphPin_getseters[] = {
	{ (char*)"name", (getter)py_ue_edgraphpin_get_name, NULL, (char *)"", NULL },
	{ (char*)"category", (getter)py_ue_edgraphpin_get_category, (setter)py_ue_edgraphpin_set_category, (char *)"", NULL },
	{ (char*)"sub_category", (getter)py_ue_edgraphpin_get_sub_category, (setter)py_ue_edgraphpin_set_sub_category, (char *)"", NULL },
	{ (char*)"default_value", (getter)py_ue_edgraphpin_get_default_value, (setter)py_ue_edgraphpin_set_default_value, (char *)"", NULL },
	{ (char*)"default_text_value", (getter)py_ue_edgraphpin_get_default_text_value, (setter)py_ue_edgraphpin_set_default_text_value, (char *)"", NULL },
	{ (char*)"default_object", (getter)py_ue_edgraphpin_get_default_object, (setter)py_ue_edgraphpin_set_default_object, (char *)"", NULL },
	{ NULL }  /* Sentinel */
};

static PyObject *ue_PyEdGraphPin_str(ue_PyEdGraphPin *self)
{
	return PyUnicode_FromFormat("<unreal_engine.EdGraphPin {'name': '%s', 'type': '%s'}>",
#if ENGINE_MINOR_VERSION > 18
		TCHAR_TO_UTF8(*self->pin->PinName.ToString()), TCHAR_TO_UTF8(*self->pin->PinType.PinCategory.ToString()));
#else
		TCHAR_TO_UTF8(*self->pin->PinName), TCHAR_TO_UTF8(*self->pin->PinType.PinCategory));
#endif
}

static PyTypeObject ue_PyEdGraphPinType = {
	PyVarObject_HEAD_INIT(NULL, 0)
	"unreal_engine.EdGraphPin", /* tp_name */
	sizeof(ue_PyEdGraphPin), /* tp_basicsize */
	0,                         /* tp_itemsize */
	0,       /* tp_dealloc */
	0,                         /* tp_print */
	0,                         /* tp_getattr */
	0,                         /* tp_setattr */
	0,                         /* tp_reserved */
	0,                         /* tp_repr */
	0,                         /* tp_as_number */
	0,                         /* tp_as_sequence */
	0,                         /* tp_as_mapping */
	0,                         /* tp_hash  */
	0,                         /* tp_call */
	(reprfunc)ue_PyEdGraphPin_str,                         /* tp_str */
	0,                         /* tp_getattro */
	0,                         /* tp_setattro */
	0,                         /* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,        /* tp_flags */
	"Unreal Engine Editor GraphPin",           /* tp_doc */
	0,                         /* tp_traverse */
	0,                         /* tp_clear */
	0,                         /* tp_richcompare */
	0,                         /* tp_weaklistoffset */
	0,                         /* tp_iter */
	0,                         /* tp_iternext */
	ue_PyEdGraphPin_methods,             /* tp_methods */
	0,
	ue_PyEdGraphPin_getseters,
};

void ue_python_init_edgraphpin(PyObject *ue_module)
{
	ue_PyEdGraphPinType.tp_new = PyType_GenericNew;

	if (PyType_Ready(&ue_PyEdGraphPinType) < 0)
		return;

	Py_INCREF(&ue_PyEdGraphPinType);
	PyModule_AddObject(ue_module, "EdGraphPin", (PyObject *)&ue_PyEdGraphPinType);
}

PyObject *py_ue_new_edgraphpin(UEdGraphPin *pin)
{
	ue_PyEdGraphPin *ret = (ue_PyEdGraphPin *)PyObject_New(ue_PyEdGraphPin, &ue_PyEdGraphPinType);
	ret->pin = pin;
	return (PyObject *)ret;
}

ue_PyEdGraphPin *py_ue_is_edgraphpin(PyObject *obj)
{
	if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyEdGraphPinType))
		return nullptr;
	return (ue_PyEdGraphPin *)obj;
}

#endif
<commit_msg>Add break_all_links() and get_linked_to()<commit_after>#include "UEPyEdGraphPin.h"

#if WITH_EDITOR

#include "Runtime/Engine/Classes/EdGraph/EdGraphPin.h"
#include "Editor/UnrealEd/Public/Kismet2/BlueprintEditorUtils.h"

static PyObject *py_ue_edgraphpin_make_link_to(ue_PyEdGraphPin *self, PyObject * args)
{
	PyObject *other_pin;
	if (!PyArg_ParseTuple(args, "O:make_link_to", &other_pin))
	{
		return NULL;
	}

	ue_PyEdGraphPin *py_other_pin = py_ue_is_edgraphpin(other_pin);
	if (!py_other_pin)
	{
		return PyErr_Format(PyExc_Exception, "argument is not a UEdGraphPin");
	}

	self->pin->MakeLinkTo(py_other_pin->pin);

	if (UBlueprint *bp = Cast<UBlueprint>(self->pin->GetOwningNode()->GetGraph()->GetOuter()))
	{
		FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(bp);
	}

	Py_RETURN_NONE;
}

static PyObject *py_ue_edgraphpin_connect(ue_PyEdGraphPin *self, PyObject * args)
{
	PyObject *other_pin;
	if (!PyArg_ParseTuple(args, "O:connect", &other_pin))
	{
		return NULL;
	}

	ue_PyEdGraphPin *py_other_pin = py_ue_is_edgraphpin(other_pin);
	if (!py_other_pin)
	{
		return PyErr_Format(PyExc_Exception, "argument is not a UEdGraphPin");
	}

	if (!self->pin->GetSchema()->TryCreateConnection(self->pin, py_other_pin->pin))
	{
		return PyErr_Format(PyExc_Exception, "unable to connect pins");
	}

	if (UBlueprint *bp = Cast<UBlueprint>(self->pin->GetOwningNode()->GetGraph()->GetOuter()))
	{
		FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(bp);
	}

	Py_RETURN_NONE;
}

static PyObject *py_ue_edgraphpin_break_link_to(ue_PyEdGraphPin *self, PyObject * args)
{
	PyObject *other_pin;
	if (!PyArg_ParseTuple(args, "O:break_link_to", &other_pin))
	{
		return NULL;
	}

	ue_PyEdGraphPin *py_other_pin = py_ue_is_edgraphpin(other_pin);
	if (!py_other_pin)
	{
		return PyErr_Format(PyExc_Exception, "argument is not a UEdGraphPin");
	}

	self->pin->BreakLinkTo(py_other_pin->pin);

	if (UBlueprint *bp = Cast<UBlueprint>(self->pin->GetOwningNode()->GetGraph()->GetOuter()))
	{
		FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(bp);
	}

	Py_RETURN_NONE;
}

static PyObject *py_ue_edgraphpin_break_all_pin_links(ue_PyEdGraphPin *self, PyObject * args)
{
	PyObject *py_notify_nodes = nullptr;
	if (!PyArg_ParseTuple(args, "O:break_all_pin_links", &py_notify_nodes))
	{
		return NULL;
	}

	bool notify_nodes = true;
	if (py_notify_nodes && !PyObject_IsTrue(py_notify_nodes))
		notify_nodes = false;

	self->pin->BreakAllPinLinks(notify_nodes);

	if (UBlueprint *bp = Cast<UBlueprint>(self->pin->GetOwningNode()->GetGraph()->GetOuter()))
	{
		FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(bp);
	}

	Py_RETURN_NONE;
}

static PyObject *py_ue_edgraphpin_get_linked_to(ue_PyEdGraphPin * self, PyObject * args)
{
	PyObject *pins = PyList_New(0);

	TArray<UEdGraphPin*> Links = self->pin->LinkedTo;

	for (int32 i = 0; i < Links.Num(); i++)
	{
		UEdGraphPin *pin = Links[i];
		ue_PyUObject *item = (ue_PyUObject *)py_ue_new_edgraphpin(pin);
		if (item)
			PyList_Append(pins, (PyObject *)item);
	}
	return pins;
}

static PyMethodDef ue_PyEdGraphPin_methods[] = {
	{ "make_link_to", (PyCFunction)py_ue_edgraphpin_make_link_to, METH_VARARGS, "" },
	{ "break_link_to", (PyCFunction)py_ue_edgraphpin_break_link_to, METH_VARARGS, "" },
	{ "break_all_pin_links", (PyCFunction)py_ue_edgraphpin_break_all_pin_links, METH_VARARGS, "" },
	{ "get_linked_to", (PyCFunction)py_ue_edgraphpin_get_linked_to, METH_VARARGS, "" },
	{ "connect", (PyCFunction)py_ue_edgraphpin_connect, METH_VARARGS, "" },
	{ NULL }  /* Sentinel */
};

static PyObject *py_ue_edgraphpin_get_name(ue_PyEdGraphPin *self, void *closure)
{
#if ENGINE_MINOR_VERSION > 18
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinName.ToString())));
#else
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinName)));
#endif
}

static PyObject *py_ue_edgraphpin_get_category(ue_PyEdGraphPin *self, void *closure)
{
#if ENGINE_MINOR_VERSION > 18
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinType.PinCategory.ToString())));
#else
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinType.PinCategory)));
#endif
}

static PyObject *py_ue_edgraphpin_get_sub_category(ue_PyEdGraphPin *self, void *closure)
{
#if ENGINE_MINOR_VERSION > 18
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinType.PinSubCategory.ToString())));
#else
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinType.PinSubCategory)));
#endif
}

static PyObject *py_ue_edgraphpin_get_default_value(ue_PyEdGraphPin *self, void *closure)
{
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->DefaultValue)));
}

static int py_ue_edgraphpin_set_default_value(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value && PyUnicodeOrString_Check(value))
	{
		const char *str = UEPyUnicode_AsUTF8(value);
		self->pin->DefaultValue = UTF8_TO_TCHAR(str);
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a string");
	return -1;
}

static PyObject *py_ue_edgraphpin_get_default_text_value(ue_PyEdGraphPin *self, void *closure)
{
	return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->DefaultTextValue.ToString())));
}

static int py_ue_edgraphpin_set_default_text_value(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value && PyUnicodeOrString_Check(value))
	{
		const char *str = UEPyUnicode_AsUTF8(value);
		self->pin->DefaultTextValue = FText::FromString(UTF8_TO_TCHAR(str));
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a string");
	return -1;
}

static PyObject *py_ue_edgraphpin_get_default_object(ue_PyEdGraphPin *self, void *closure)
{
	UObject *u_object = self->pin->DefaultObject;
	if (!u_object)
	{
		Py_RETURN_NONE;
	}
	Py_RETURN_UOBJECT(u_object);
}

static int py_ue_edgraphpin_set_default_object(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value && ue_is_pyuobject(value))
	{
		ue_PyUObject *py_obj = (ue_PyUObject *)value;
		self->pin->DefaultObject = py_obj->ue_object;
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a UObject");
	return -1;
}

static int py_ue_edgraphpin_set_category(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value && PyUnicodeOrString_Check(value))
	{
		const char *str = UEPyUnicode_AsUTF8(value);
#if ENGINE_MINOR_VERSION > 18
		self->pin->PinType.PinCategory = FName(UTF8_TO_TCHAR(str));
#else
		self->pin->PinType.PinCategory = FString(UTF8_TO_TCHAR(str));
#endif
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a string");
	return -1;
}

static int py_ue_edgraphpin_set_sub_category(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value)
	{
		if (ue_is_pyuobject(value))
		{
			ue_PyUObject *py_obj = (ue_PyUObject *)value;
			self->pin->PinType.PinSubCategoryObject = py_obj->ue_object;
			return 0;
		}
		if (PyUnicodeOrString_Check(value))
		{
			const char *str = UEPyUnicode_AsUTF8(value);
#if ENGINE_MINOR_VERSION > 18
			self->pin->PinType.PinSubCategory = FName(UTF8_TO_TCHAR(str));
#else
			self->pin->PinType.PinSubCategory = FString(UTF8_TO_TCHAR(str));
#endif
			return 0;
		}
	}
	PyErr_SetString(PyExc_TypeError, "value is not a UObject");
	return -1;
}

static PyGetSetDef ue_PyEdGraphPin_getseters[] = {
	{ (char*)"name", (getter)py_ue_edgraphpin_get_name, NULL, (char *)"", NULL },
	{ (char*)"category", (getter)py_ue_edgraphpin_get_category, (setter)py_ue_edgraphpin_set_category, (char *)"", NULL },
	{ (char*)"sub_category", (getter)py_ue_edgraphpin_get_sub_category, (setter)py_ue_edgraphpin_set_sub_category, (char *)"", NULL },
	{ (char*)"default_value", (getter)py_ue_edgraphpin_get_default_value, (setter)py_ue_edgraphpin_set_default_value, (char *)"", NULL },
	{ (char*)"default_text_value", (getter)py_ue_edgraphpin_get_default_text_value, (setter)py_ue_edgraphpin_set_default_text_value, (char *)"", NULL },
	{ (char*)"default_object", (getter)py_ue_edgraphpin_get_default_object, (setter)py_ue_edgraphpin_set_default_object, (char *)"", NULL },
	{ NULL }  /* Sentinel */
};

static PyObject *ue_PyEdGraphPin_str(ue_PyEdGraphPin *self)
{
	return PyUnicode_FromFormat("<unreal_engine.EdGraphPin {'name': '%s', 'type': '%s'}>",
#if ENGINE_MINOR_VERSION > 18
		TCHAR_TO_UTF8(*self->pin->PinName.ToString()), TCHAR_TO_UTF8(*self->pin->PinType.PinCategory.ToString()));
#else
		TCHAR_TO_UTF8(*self->pin->PinName), TCHAR_TO_UTF8(*self->pin->PinType.PinCategory));
#endif
}

static PyTypeObject ue_PyEdGraphPinType = {
	PyVarObject_HEAD_INIT(NULL, 0)
	"unreal_engine.EdGraphPin", /* tp_name */
	sizeof(ue_PyEdGraphPin), /* tp_basicsize */
	0,                         /* tp_itemsize */
	0,       /* tp_dealloc */
	0,                         /* tp_print */
	0,                         /* tp_getattr */
	0,                         /* tp_setattr */
	0,                         /* tp_reserved */
	0,                         /* tp_repr */
	0,                         /* tp_as_number */
	0,                         /* tp_as_sequence */
	0,                         /* tp_as_mapping */
	0,                         /* tp_hash  */
	0,                         /* tp_call */
	(reprfunc)ue_PyEdGraphPin_str,                         /* tp_str */
	0,                         /* tp_getattro */
	0,                         /* tp_setattro */
	0,                         /* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,        /* tp_flags */
	"Unreal Engine Editor GraphPin",           /* tp_doc */
	0,                         /* tp_traverse */
	0,                         /* tp_clear */
	0,                         /* tp_richcompare */
	0,                         /* tp_weaklistoffset */
	0,                         /* tp_iter */
	0,                         /* tp_iternext */
	ue_PyEdGraphPin_methods,             /* tp_methods */
	0,
	ue_PyEdGraphPin_getseters,
};

void ue_python_init_edgraphpin(PyObject *ue_module)
{
	ue_PyEdGraphPinType.tp_new = PyType_GenericNew;

	if (PyType_Ready(&ue_PyEdGraphPinType) < 0)
		return;

	Py_INCREF(&ue_PyEdGraphPinType);
	PyModule_AddObject(ue_module, "EdGraphPin", (PyObject *)&ue_PyEdGraphPinType);
}

PyObject *py_ue_new_edgraphpin(UEdGraphPin *pin)
{
	ue_PyEdGraphPin *ret = (ue_PyEdGraphPin *)PyObject_New(ue_PyEdGraphPin, &ue_PyEdGraphPinType);
	ret->pin = pin;
	return (PyObject *)ret;
}

ue_PyEdGraphPin *py_ue_is_edgraphpin(PyObject *obj)
{
	if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyEdGraphPinType))
		return nullptr;
	return (ue_PyEdGraphPin *)obj;
}

#endif
<|endoftext|>


<commit_before>
#include "UnrealEnginePythonPrivatePCH.h"

#include "UEPySHorizontalBox.h"

#define GET_s_horizontal_box SHorizontalBox *s_horizontal_box = (SHorizontalBox *)self->s_box_panel.s_panel.s_widget.s_widget

static PyObject *ue_PySHorizontalBox_str(ue_PySHorizontalBox *self)
{
	return PyUnicode_FromFormat("<unreal_engine.SHorizontalBox '%p'>",
		self->s_box_panel.s_panel.s_widget.s_widget);
}

static PyObject *py_ue_shorizontal_box_add_slot(ue_PySHorizontalBox *self, PyObject * args, PyObject *kwargs) {
	PyObject *py_content;
	int h_align = 0;
	float max_width = 0;
	float padding = 0;
	int v_align = 0;

	char *kwlist[] = { (char *)"widget", (char *)"h_align", (char *)"max_width", (char *)"padding", (char *)"v_align", nullptr };

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iffi:add_slot", kwlist,
		&py_content,
		&h_align,
		&max_width,
		&padding,
		&v_align)) {
		return NULL;
	}

	ue_PySWidget *py_swidget = py_ue_is_swidget(py_content);
	if (!py_swidget) {
		return PyErr_Format(PyExc_Exception, "argument is not a SWidget");
	}
	// TODO: decrement reference when destroying parent
	Py_INCREF(py_swidget);

	GET_s_horizontal_box;

	SHorizontalBox::FSlot &fslot = s_horizontal_box->AddSlot();
	fslot.AttachWidget(py_swidget->s_widget->AsShared());
	fslot.HAlign((EHorizontalAlignment)h_align);
	if (max_width != 0)
		fslot.MaxWidth(max_width);
	fslot.Padding(padding);
	fslot.VAlign((EVerticalAlignment)v_align);

	Py_INCREF(self);
	return (PyObject *)self;
}

static PyObject *py_ue_shorizontal_box_num_slots(ue_PySHorizontalBox *self, PyObject * args) {
	GET_s_horizontal_box;
	return PyLong_FromLong(s_horizontal_box->NumSlots());
}

static PyMethodDef ue_PySHorizontalBox_methods[] = {
#pragma warning(suppress: 4191)
	{ "add_slot", (PyCFunction)py_ue_shorizontal_box_add_slot, METH_VARARGS | METH_KEYWORDS, "" },
	{ "num_slots", (PyCFunction)py_ue_shorizontal_box_num_slots, METH_VARARGS, "" },
	{ NULL }  /* Sentinel */
};

PyTypeObject ue_PySHorizontalBoxType = {
	PyVarObject_HEAD_INIT(NULL, 0)
	"unreal_engine.SHorizontalBox", /* tp_name */
	sizeof(ue_PySHorizontalBox), /* tp_basicsize */
	0,                         /* tp_itemsize */
	0,       /* tp_dealloc */
	0,                         /* tp_print */
	0,                         /* tp_getattr */
	0,                         /* tp_setattr */
	0,                         /* tp_reserved */
	0,                         /* tp_repr */
	0,                         /* tp_as_number */
	0,                         /* tp_as_sequence */
	0,                         /* tp_as_mapping */
	0,                         /* tp_hash  */
	0,                         /* tp_call */
	(reprfunc)ue_PySHorizontalBox_str,                         /* tp_str */
	0,                         /* tp_getattro */
	0,                         /* tp_setattro */
	0,                         /* tp_as_buffer */
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,        /* tp_flags */
	"Unreal Engine SHorizontalBox",           /* tp_doc */
	0,                         /* tp_traverse */
	0,                         /* tp_clear */
	0,                         /* tp_richcompare */
	0,                         /* tp_weaklistoffset */
	0,                         /* tp_iter */
	0,                         /* tp_iternext */
	ue_PySHorizontalBox_methods,             /* tp_methods */
};

static int ue_py_shorizontal_box_init(ue_PySHorizontalBox *self, PyObject *args, PyObject *kwargs) {
	ue_py_snew(SHorizontalBox, s_box_panel.s_panel.s_widget);
	return 0;
}

void ue_python_init_shorizontal_box(PyObject *ue_module) {
	ue_PySHorizontalBoxType.tp_new = PyType_GenericNew;

	ue_PySHorizontalBoxType.tp_init = (initproc)ue_py_shorizontal_box_init;

	ue_PySHorizontalBoxType.tp_base = &ue_PySBoxPanelType;

	if (PyType_Ready(&ue_PySHorizontalBoxType) < 0)
		return;

	Py_INCREF(&ue_PySHorizontalBoxType);
	PyModule_AddObject(ue_module, "SHorizontalBox", (PyObject *)&ue_PySHorizontalBoxType);
}
<commit_msg>improved SHorizontalBox<commit_after>
#include "UnrealEnginePythonPrivatePCH.h"

#include "UEPySHorizontalBox.h"

#define GET_s_horizontal_box SHorizontalBox *s_horizontal_box = (SHorizontalBox *)self->s_box_panel.s_panel.s_widget.s_widget

static PyObject *ue_PySHorizontalBox_str(ue_PySHorizontalBox *self)
{
	return PyUnicode_FromFormat("<unreal_engine.SHorizontalBox '%p'>",
		self->s_box_panel.s_panel.s_widget.s_widget);
}

static PyObject *py_ue_shorizontal_box_add_slot(ue_PySHorizontalBox *self, PyObject * args, PyObject *kwargs) {
	PyObject *py_content;
	int h_align = 0;
	float max_width = 0;
	float padding = 0;
	int v_align = 0;
	float fill_width = 0;
	PyObject *py_auto_width = nullptr;

	char *kwlist[] = { (char *)"widget",
		(char *)"h_align",
		(char *)"max_width",
		(char *)"padding",
		(char *)"v_align",
		(char *)"fill_width",
		(char *)"auto_width",
		nullptr };

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iffifO:add_slot", kwlist,
		&py_content,
		&h_align,
		&max_width,
		&padding,
		&v_align,
		&fill_width,
		&py_auto_width)) {
		return NULL;
	}

	ue_PySWidget *py_swidget = py_ue_is_swidget(py_content);
	if (!py_swidget) {
		return PyErr_Format(PyExc_Exception, "argument is not a SWidget");
	}
	// TODO: decrement reference when destroying parent
	Py_INCREF(py_swidget);

	GET_s_horizontal_box;

	SHorizontalBox::FSlot &fslot = s_horizontal_box->AddSlot();
	fslot.AttachWidget(py_swidget->s_widget->AsShared());
	fslot.HAlign((EHorizontalAlignment)h_align);
	if (max_width != 0)
		fslot.MaxWidth(max_width);
	if (fill_width)
		fslot.FillWidth(fill_width);
	fslot.Padding(padding);
	fslot.VAlign((EVerticalAlignment)v_align);
	if (py_auto_width && PyObject_IsTrue(py_auto_width))
		fslot.AutoWidth();

	Py_INCREF(self);
	return (PyObject *)self;
}

static PyObject *py_ue_shorizontal_box_num_slots(ue_PySHorizontalBox *self, PyObject * args) {
	GET_s_horizontal_box;
	return PyLong_FromLong(s_horizontal_box->NumSlots());
}

static PyMethodDef ue_PySHorizontalBox_methods[] = {
#pragma warning(suppress: 4191)
	{ "add_slot", (PyCFunction)py_ue_shorizontal_box_add_slot, METH_VARARGS | METH_KEYWORDS, "" },
	{ "num_slots", (PyCFunction)py_ue_shorizontal_box_num_slots, METH_VARARGS, "" },
	{ NULL }  /* Sentinel */
};

PyTypeObject ue_PySHorizontalBoxType = {
	PyVarObject_HEAD_INIT(NULL, 0)
	"unreal_engine.SHorizontalBox", /* tp_name */
	sizeof(ue_PySHorizontalBox), /* tp_basicsize */
	0,                         /* tp_itemsize */
	0,       /* tp_dealloc */
	0,                         /* tp_print */
	0,                         /* tp_getattr */
	0,                         /* tp_setattr */
	0,                         /* tp_reserved */
	0,                         /* tp_repr */
	0,                         /* tp_as_number */
	0,                         /* tp_as_sequence */
	0,                         /* tp_as_mapping */
	0,                         /* tp_hash  */
	0,                         /* tp_call */
	(reprfunc)ue_PySHorizontalBox_str,                         /* tp_str */
	0,                         /* tp_getattro */
	0,                         /* tp_setattro */
	0,                         /* tp_as_buffer */
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,        /* tp_flags */
	"Unreal Engine SHorizontalBox",           /* tp_doc */
	0,                         /* tp_traverse */
	0,                         /* tp_clear */
	0,                         /* tp_richcompare */
	0,                         /* tp_weaklistoffset */
	0,                         /* tp_iter */
	0,                         /* tp_iternext */
	ue_PySHorizontalBox_methods,             /* tp_methods */
};

static int ue_py_shorizontal_box_init(ue_PySHorizontalBox *self, PyObject *args, PyObject *kwargs) {
	ue_py_snew(SHorizontalBox, s_box_panel.s_panel.s_widget);
	return 0;
}

void ue_python_init_shorizontal_box(PyObject *ue_module) {
	ue_PySHorizontalBoxType.tp_new = PyType_GenericNew;

	ue_PySHorizontalBoxType.tp_init = (initproc)ue_py_shorizontal_box_init;

	ue_PySHorizontalBoxType.tp_base = &ue_PySBoxPanelType;

	if (PyType_Ready(&ue_PySHorizontalBoxType) < 0)
		return;

	Py_INCREF(&ue_PySHorizontalBoxType);
	PyModule_AddObject(ue_module, "SHorizontalBox", (PyObject *)&ue_PySHorizontalBoxType);
}
<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.c
 * Author: peterharrison
 *
 * Created on 07 February 2016, 23:47
 */

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "maze.h"
#include "mazeprinter.h"
#include "mazesearcher.h"
#include <glob.h>

uint8_t wallData[1024];

int ReadRealWallsFromFile(char *filename) {
  FILE *fp;
  if ((fp = fopen(filename, "rb")) == NULL) {
    return 1;
  }
  if (fread(wallData, 1, 256, fp) < 256) {
    fclose(fp);
    return 2;
  };
  fclose(fp);
  return 0;
}

static char *strpad(const char *string, char pad, size_t fieldSize);

char *strpad(const char *string, char pad, size_t fieldSize) {
  size_t ssize = strlen(string);
  size_t padSize = fieldSize - ssize;
  assert(padSize > 0);
  char padding[128];
  memset(padding, pad, 126);
  padding[127] = 0;
  char *padded = (char *) malloc(fieldSize + 1);
  strncpy(padded, string, fieldSize);
  strncat(padded, padding, padSize);
//  memset(padded, pad, fieldSize);
  padded[fieldSize] = 0;
//  strcpy(padded , string);
  return padded;
}

/*
 *
 */
int main(int argc, char **argv) {
  MazeSearcher barney;
  glob_t glob_result;
  glob("./mazefiles/*", GLOB_TILDE, NULL, &glob_result);
  if (argc > 1) {
    Maze maze(16);
    int onePassCount = 0;
    int chancerCount = 0;
    printf("   FULL  MODOPEN   MODALL\n");
    maze.setFloodType(Maze::RUNLENGTH_FLOOD);
    barney.setSearchMethod(MazeSearcher::SEARCH_NORMAL);
    for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) {
      std::cout << "";
      ReadRealWallsFromFile(glob_result.gl_pathv[i]);
      maze.load(wallData);
      maze.copyMazeFromFileData(wallData, 256);
      maze.flood(0x77);
      barney.setRealMaze(&maze);
      barney.map()->resetToEmptyMaze();
      barney.setLocation(0x00);
      int steps = barney.searchTo(0x77);
      steps += barney.searchTo(0x00);
      steps += barney.searchTo(0x77);
      steps += barney.searchTo(0x00);
      barney.map()->testForSolution();
      int costDifference = barney.map()->costDifference();
      int openCost = barney.map()->openMazeCost();
      int residual = (100 * costDifference) / openCost;

      if (residual > 5) {
        MazePrinter::printVisitedDirs(barney.map());
      }
      char *name = strpad(glob_result.gl_pathv[i], ' ', 50);
      std::cout << name;
      delete name;
      std::cout.width(6);
      std::cout << std::right;
      std::cout << steps << " steps";
      std::cout << " delta " << costDifference << " (" << residual << "%)";
      if (costDifference == 0) {
        onePassCount++;
        std::cout << " <---- ";
      } else if (residual < 5 && residual >= 0) {
        chancerCount++;
        std::cout << " ***** ";
      }
        std::cout << std::endl;

    }

    printf("\n%d mazes:\n", glob_result.gl_pathc);
    printf(" one Pass mazes: %3d\n", onePassCount);
    printf(" Possible chancer  mazes: %3d\n", chancerCount);

  } else {
    printf(" you should provide the name of at least one maze file on the command line\n");
  }
  return (EXIT_SUCCESS);
}

<commit_msg>tidy the main function a little<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.c
 * Author: peterharrison
 *
 * Created on 07 February 2016, 23:47
 */

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "maze.h"
#include "mazeprinter.h"
#include "mazesearcher.h"
#include <glob.h>

uint8_t wallData[1024];

enum {
  E_FILE_NOT_FOUND = 1,
  E_FILE_READ_ERROR = 2,
};

int ReadRealWallsFromFile(char *filename) {
  FILE *fp;
  if ((fp = fopen(filename, "rb")) == NULL) {
    return E_FILE_NOT_FOUND;
  }
  if (fread(wallData, 1, 256, fp) < 256) {
    fclose(fp);
    return E_FILE_READ_ERROR;
  };
  fclose(fp);
  return 0;
}

static char *strpad(const char *string, char pad, size_t fieldSize);

char *strpad(const char *string, char pad, size_t fieldSize) {
  size_t ssize = strlen(string);
  size_t padSize = fieldSize - ssize;
  assert(padSize > 0);
  char padding[128];
  memset(padding, pad, 126);
  padding[127] = 0;
  char *padded = (char *) malloc(fieldSize + 1);
  strncpy(padded, string, fieldSize);
  strncat(padded, padding, padSize);
//  memset(padded, pad, fieldSize);
  padded[fieldSize] = 0;
//  strcpy(padded , string);
  return padded;
}

/*
 *
 */
int main(int argc, char **argv) {
  MazeSearcher barney;
  glob_t glob_result;
  glob("./mazefiles/*", GLOB_TILDE, NULL, &glob_result);
  if (argc > 1) {
    Maze maze(16);
    int onePassCount = 0;
    int chancerCount = 0;
    printf("   FULL  MODOPEN   MODALL\n");
    maze.setFloodType(Maze::RUNLENGTH_FLOOD);
    for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) {
      std::cout << "";
      if (0 !=  ReadRealWallsFromFile(glob_result.gl_pathv[i])){
        continue;
      };
      maze.load(wallData);
      maze.copyMazeFromFileData(wallData, 256);
      maze.flood(0x77);
      barney.setRealMaze(&maze);
      barney.map()->resetToEmptyMaze();
      barney.setLocation(0x00);
      int steps = barney.searchTo(0x77);
      steps += barney.searchTo(0x00);
      steps += barney.searchTo(0x77);
      steps += barney.searchTo(0x00);
      barney.map()->testForSolution();
      int costDifference = barney.map()->costDifference();
      int openCost = barney.map()->openMazeCost();
      int residual = (100 * costDifference) / openCost;

      if (residual > 5) {
        MazePrinter::printVisitedDirs(barney.map());
      }
      char *name = strpad(glob_result.gl_pathv[i], ' ', 50);
      std::cout << name;
      delete name;
      std::cout.width(6);
      std::cout << std::right;
      std::cout << steps << " steps";
      std::cout << " delta " << costDifference << " (" << residual << "%)";
      if (costDifference == 0) {
        onePassCount++;
        std::cout << " <---- ";
      } else if (residual < 5 && residual >= 0) {
        chancerCount++;
        std::cout << " ***** ";
      }
        std::cout << std::endl;

    }

    printf("\n%d mazes:\n", glob_result.gl_pathc);
    printf(" one Pass mazes: %3d\n", onePassCount);
    printf(" Possible chancer  mazes: %3d\n", chancerCount);

  } else {
    printf(" you should provide the name of at least one maze file on the command line\n");
  }
  return (EXIT_SUCCESS);
}

<|endoftext|>


<commit_before>e4910ce1-2747-11e6-9f03-e0f84713e7b8<commit_msg>Initial commit.13<commit_after>e4eefa30-2747-11e6-a310-e0f84713e7b8<|endoftext|>