text
stringlengths
54
60.6k
<commit_before>e9c1a9eb-2e4e-11e5-a993-28cfe91dbc4b<commit_msg>e9c89387-2e4e-11e5-91fd-28cfe91dbc4b<commit_after>e9c89387-2e4e-11e5-91fd-28cfe91dbc4b<|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10MODEL2_HH #define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10MODEL2_HH #include <memory> #include <dune/stuff/common/memory.hh> #include <dune/stuff/common/type_utils.hh> #include <dune/stuff/functions/constant.hh> #include <dune/stuff/functions/combined.hh> #include <dune/stuff/playground/functions/indicator.hh> #include <dune/stuff/functions/spe10model2.hh> #include <dune/pymor/functions/default.hh> #include "default.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace Problems { namespace Spe10 { template< class E, class D, int d, class R, int r = 1 > class Model2 : public ProblemInterface< E, D, d, R, r > { Model2() { static_assert(AlwaysFalse< E >::value, "Not available for dimDomain != 3!"); } }; template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class Model2< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > : public Default< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > { typedef Default< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > BaseType; typedef Model2< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > ThisType; typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > ScalarConstantFunctionType; typedef Stuff::Functions::Indicator< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > ScalarIndicatorFunctionType; typedef typename ScalarConstantFunctionType::DomainType DomainType; typedef Stuff::Functions::Spe10::Model2< EntityImp, DomainFieldImp, 3, RangeFieldImp, 3, 3 > Spe10FunctionType; using typename BaseType::DiffusionFactorWrapperType; using typename BaseType::DiffusionTensorWrapperType; using typename BaseType::FunctionWrapperType; public: using typename BaseType::DomainFieldType; using typename BaseType::DiffusionTensorType; static const bool available = true; static std::string static_id() { return BaseType::BaseType::static_id() + ".spe10.model2"; } static Stuff::Common::Configuration default_config(const std::string sub_name = "") { Stuff::Common::Configuration config; config["type"] = static_id(); config["filename"] = Spe10FunctionType::default_config().get< std::string >("filename"); config["upper_right"] = Spe10FunctionType::default_config().get< std::string >("upper_right"); config["channel_width"] = "0"; if (sub_name.empty()) return config; else { Stuff::Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(), const std::string sub_name = static_id()) { const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; return Stuff::Common::make_unique< ThisType >( cfg.get("filename", default_config().get< std::string >("filename")), cfg.get("upper_right", default_config().get< DomainType >("upper_right")), cfg.get("channel_width", default_config().get< DomainFieldType >("channel_width"))); } // ... create(...) Model2(const std::string& filename, const DomainType& upper_right, const DomainFieldType& channel_width) : BaseType(std::make_shared<DiffusionFactorWrapperType>(std::make_shared< ScalarConstantFunctionType >(1, "diffusion_factor")), make_diffusion_tensor(filename, upper_right, channel_width), std::make_shared<FunctionWrapperType>(std::make_shared< ScalarConstantFunctionType >(0, "force")), std::make_shared<FunctionWrapperType>(std::make_shared< ScalarConstantFunctionType >(0, "dirichlet")), std::make_shared<FunctionWrapperType>(make_neumann(upper_right))) {} virtual std::string type() const override { return BaseType::BaseType::static_id() + ".spe10.model2"; } private: static std::shared_ptr< DiffusionTensorType > make_diffusion_tensor(const std::string& filename, const DomainType& upper_right, const DomainFieldType& channel_width) { typedef Pymor::Functions::AffinelyDecomposableDefault< EntityImp, DomainFieldType, 3, RangeFieldImp, 3, 3 > ParametricTensorType; auto diffusion_tensor = std::make_shared<ParametricTensorType>("diffusion_tensor"); auto spe10 = std::shared_ptr<Spe10FunctionType>(new Spe10FunctionType( filename, "spe10", {0., 0., 0.}, upper_right)); diffusion_tensor->register_affine_part(spe10); if (channel_width > 0) { typedef Stuff::Functions::Indicator< EntityImp, DomainFieldImp, 3, RangeFieldImp, 3, 3 > TensorIndicatorFunctionType; auto one = std::make_shared<ScalarConstantFunctionType>(1, "one"); auto channel_x = std::shared_ptr<ScalarIndicatorFunctionType>(new ScalarIndicatorFunctionType( {{{{0., upper_right[1]/2. - channel_width/2., 0.}, {upper_right[0], upper_right[1]/2. + channel_width/2., upper_right[2]/2.}}, 1.}})); typename TensorIndicatorFunctionType::RangeType channel_x_scaled_value(0.); channel_x_scaled_value[0][0] = channel_x_scaled_value[1][1] = channel_x_scaled_value[2][2] = Spe10FunctionType::default_config().get< RangeFieldImp >("max"); auto channel_x_scaled = std::shared_ptr<TensorIndicatorFunctionType>(new TensorIndicatorFunctionType( {{{{0., upper_right[1]/2. - channel_width/2., 0.}, {upper_right[0], upper_right[1]/2. + channel_width/2., upper_right[2]/2.}}, channel_x_scaled_value}})); auto channel_x_remover = Stuff::Functions::make_difference(one, channel_x, "channel_x_remover"); auto spe10_wo_channel_x = Stuff::Functions::make_product(channel_x_remover, spe10, "spe10_wo_channel_x"); auto spe10_w_scaled_channel_x = Stuff::Functions::make_sum(spe10_wo_channel_x, channel_x_scaled, "spe10_w_scaled_channel_x"); diffusion_tensor->register_component(spe10_w_scaled_channel_x, new Pymor::ParameterFunctional("channel", 2, "channel[0]")); auto channel_y = std::shared_ptr<ScalarIndicatorFunctionType>(new ScalarIndicatorFunctionType( {{{{upper_right[0]/2. - channel_width/2., 0., upper_right[2]/2.}, {upper_right[0]/2. + channel_width/2., upper_right[1], upper_right[2]}}, 1.}})); typename TensorIndicatorFunctionType::RangeType channel_y_scaled_value(0.); channel_y_scaled_value[0][0] = channel_y_scaled_value[1][1] = channel_y_scaled_value[2][2] = Spe10FunctionType::default_config().get< RangeFieldImp >("max"); auto channel_y_scaled = std::shared_ptr<TensorIndicatorFunctionType>(new TensorIndicatorFunctionType( {{{{upper_right[0]/2. - channel_width/2., 0., upper_right[2]/2.}, {upper_right[0]/2. + channel_width/2., upper_right[1], upper_right[2]}}, channel_y_scaled_value}})); auto channel_y_remover = Stuff::Functions::make_difference(one, channel_y, "channel_y_remover"); auto spe10_wo_channel_y = Stuff::Functions::make_product(channel_y_remover, spe10, "spe10_wo_channel_y"); auto spe10_w_scaled_channel_y = Stuff::Functions::make_sum(spe10_wo_channel_y, channel_y_scaled, "spe10_w_scaled_channel_y"); diffusion_tensor->register_component(spe10_w_scaled_channel_y, new Pymor::ParameterFunctional("channel", 2, "channel[1]")); } return diffusion_tensor; } // ... make_diffusion_tensor(...) static std::shared_ptr< ScalarIndicatorFunctionType > make_neumann(const DomainType& upper_right) { return std::shared_ptr<ScalarIndicatorFunctionType>(new ScalarIndicatorFunctionType( {{{{0., 0., 0.}, {upper_right[0], upper_right[1]/440., upper_right[2]}}, 1.}}, "neumann")); } }; // class Model2< ..., 3, 3 > } // namespace Spe10 } // namespace Problems } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10MODEL2_HH <commit_msg>[...spe10.model2] make clang happy<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10MODEL2_HH #define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10MODEL2_HH #include <memory> #include <dune/stuff/common/memory.hh> #include <dune/stuff/common/type_utils.hh> #include <dune/stuff/functions/constant.hh> #include <dune/stuff/functions/combined.hh> #include <dune/stuff/playground/functions/indicator.hh> #include <dune/stuff/functions/spe10model2.hh> #include <dune/pymor/functions/default.hh> #include "default.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace Problems { namespace Spe10 { template< class E, class D, int d, class R, int r = 1 > class Model2 : public ProblemInterface< E, D, d, R, r > { Model2() { static_assert(AlwaysFalse< E >::value, "Not available for dimDomain != 3!"); } }; template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class Model2< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > : public Default< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > { typedef Default< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > BaseType; typedef Model2< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > ThisType; typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > ScalarConstantFunctionType; typedef Stuff::Functions::Indicator< EntityImp, DomainFieldImp, 3, RangeFieldImp, 1 > ScalarIndicatorFunctionType; typedef typename ScalarConstantFunctionType::DomainType DomainType; typedef Stuff::Functions::Spe10::Model2< EntityImp, DomainFieldImp, 3, RangeFieldImp, 3, 3 > Spe10FunctionType; using typename BaseType::DiffusionFactorWrapperType; using typename BaseType::DiffusionTensorWrapperType; using typename BaseType::FunctionWrapperType; public: using typename BaseType::DomainFieldType; using typename BaseType::DiffusionTensorType; static const bool available = true; static std::string static_id() { return BaseType::BaseType::static_id() + ".spe10.model2"; } static Stuff::Common::Configuration default_config(const std::string sub_name = "") { Stuff::Common::Configuration config; config["type"] = static_id(); config["filename"] = Spe10FunctionType::default_config().template get< std::string >("filename"); config["upper_right"] = Spe10FunctionType::default_config().template get< std::string >("upper_right"); config["channel_width"] = "0"; if (sub_name.empty()) return config; else { Stuff::Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(), const std::string sub_name = static_id()) { const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; return Stuff::Common::make_unique< ThisType >( cfg.get("filename", default_config().get< std::string >("filename")), cfg.get("upper_right", default_config().get< DomainType >("upper_right")), cfg.get("channel_width", default_config().get< DomainFieldType >("channel_width"))); } // ... create(...) Model2(const std::string& filename, const DomainType& upper_right, const DomainFieldType& channel_width) : BaseType(std::make_shared<DiffusionFactorWrapperType>(std::make_shared< ScalarConstantFunctionType >(1, "diffusion_factor")), make_diffusion_tensor(filename, upper_right, channel_width), std::make_shared<FunctionWrapperType>(std::make_shared< ScalarConstantFunctionType >(0, "force")), std::make_shared<FunctionWrapperType>(std::make_shared< ScalarConstantFunctionType >(0, "dirichlet")), std::make_shared<FunctionWrapperType>(make_neumann(upper_right))) {} virtual std::string type() const override { return BaseType::BaseType::static_id() + ".spe10.model2"; } private: static std::shared_ptr< DiffusionTensorType > make_diffusion_tensor(const std::string& filename, const DomainType& upper_right, const DomainFieldType& channel_width) { typedef Pymor::Functions::AffinelyDecomposableDefault< EntityImp, DomainFieldType, 3, RangeFieldImp, 3, 3 > ParametricTensorType; auto diffusion_tensor = std::make_shared<ParametricTensorType>("diffusion_tensor"); auto spe10 = std::shared_ptr<Spe10FunctionType>(new Spe10FunctionType( filename, "spe10", {0., 0., 0.}, upper_right)); diffusion_tensor->register_affine_part(spe10); if (channel_width > 0) { typedef Stuff::Functions::Indicator< EntityImp, DomainFieldImp, 3, RangeFieldImp, 3, 3 > TensorIndicatorFunctionType; auto one = std::make_shared<ScalarConstantFunctionType>(1, "one"); auto channel_x = std::shared_ptr<ScalarIndicatorFunctionType>(new ScalarIndicatorFunctionType( {{{{0., upper_right[1]/2. - channel_width/2., 0.}, {upper_right[0], upper_right[1]/2. + channel_width/2., upper_right[2]/2.}}, 1.}})); typename TensorIndicatorFunctionType::RangeType channel_x_scaled_value(0.); channel_x_scaled_value[0][0] = channel_x_scaled_value[1][1] = channel_x_scaled_value[2][2] = Spe10FunctionType::default_config().template get< RangeFieldImp >("max"); auto channel_x_scaled = std::shared_ptr<TensorIndicatorFunctionType>(new TensorIndicatorFunctionType( {{{{0., upper_right[1]/2. - channel_width/2., 0.}, {upper_right[0], upper_right[1]/2. + channel_width/2., upper_right[2]/2.}}, channel_x_scaled_value}})); auto channel_x_remover = Stuff::Functions::make_difference(one, channel_x, "channel_x_remover"); auto spe10_wo_channel_x = Stuff::Functions::make_product(channel_x_remover, spe10, "spe10_wo_channel_x"); auto spe10_w_scaled_channel_x = Stuff::Functions::make_sum(spe10_wo_channel_x, channel_x_scaled, "spe10_w_scaled_channel_x"); diffusion_tensor->register_component(spe10_w_scaled_channel_x, new Pymor::ParameterFunctional("channel", 2, "channel[0]")); auto channel_y = std::shared_ptr<ScalarIndicatorFunctionType>(new ScalarIndicatorFunctionType( {{{{upper_right[0]/2. - channel_width/2., 0., upper_right[2]/2.}, {upper_right[0]/2. + channel_width/2., upper_right[1], upper_right[2]}}, 1.}})); typename TensorIndicatorFunctionType::RangeType channel_y_scaled_value(0.); channel_y_scaled_value[0][0] = channel_y_scaled_value[1][1] = channel_y_scaled_value[2][2] = Spe10FunctionType::default_config().template get< RangeFieldImp >("max"); auto channel_y_scaled = std::shared_ptr<TensorIndicatorFunctionType>(new TensorIndicatorFunctionType( {{{{upper_right[0]/2. - channel_width/2., 0., upper_right[2]/2.}, {upper_right[0]/2. + channel_width/2., upper_right[1], upper_right[2]}}, channel_y_scaled_value}})); auto channel_y_remover = Stuff::Functions::make_difference(one, channel_y, "channel_y_remover"); auto spe10_wo_channel_y = Stuff::Functions::make_product(channel_y_remover, spe10, "spe10_wo_channel_y"); auto spe10_w_scaled_channel_y = Stuff::Functions::make_sum(spe10_wo_channel_y, channel_y_scaled, "spe10_w_scaled_channel_y"); diffusion_tensor->register_component(spe10_w_scaled_channel_y, new Pymor::ParameterFunctional("channel", 2, "channel[1]")); } return diffusion_tensor; } // ... make_diffusion_tensor(...) static std::shared_ptr< ScalarIndicatorFunctionType > make_neumann(const DomainType& upper_right) { return std::shared_ptr<ScalarIndicatorFunctionType>(new ScalarIndicatorFunctionType( {{{{0., 0., 0.}, {upper_right[0], upper_right[1]/440., upper_right[2]}}, 1.}}, "neumann")); } }; // class Model2< ..., 3, 3 > } // namespace Spe10 } // namespace Problems } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10MODEL2_HH <|endoftext|>
<commit_before>77f716ea-2d53-11e5-baeb-247703a38240<commit_msg>77f79a34-2d53-11e5-baeb-247703a38240<commit_after>77f79a34-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>0af81c66-2e4f-11e5-a087-28cfe91dbc4b<commit_msg>0b036e73-2e4f-11e5-9e47-28cfe91dbc4b<commit_after>0b036e73-2e4f-11e5-9e47-28cfe91dbc4b<|endoftext|>
<commit_before>5bf6738b-2d16-11e5-af21-0401358ea401<commit_msg>5bf6738c-2d16-11e5-af21-0401358ea401<commit_after>5bf6738c-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>ebff8da6-585a-11e5-b5b8-6c40088e03e4<commit_msg>ec0a8328-585a-11e5-a591-6c40088e03e4<commit_after>ec0a8328-585a-11e5-a591-6c40088e03e4<|endoftext|>
<commit_before>// // main.cpp // fxtract // // Created by Connor Skennerton on 30/07/13. // Copyright (c) 2013 Connor Skennerton. All rights reserved. // #include <unistd.h> #include <cstdio> #include <cassert> #include "util.h" #include "fileManager.h" #include "Fx.h" extern "C" { #include "util/ssearch.h" #include "util/bpsearch.h" #include "util/msutil.h" } #define VERSION "1.0-alpha" struct Options { bool H_flag; bool Q_flag; bool G_flag; bool E_flag; bool x_flag; bool r_flag; bool I_flag; char * f_flag; Options() : H_flag(false), Q_flag(false), G_flag(false), E_flag(false), x_flag(false), r_flag(false), I_flag(false), f_flag(NULL) {} }; void printSingle(Fx * mate1, FILE * out ) { mate1->puts(out); } void printPair(Fx* mate1, Fx* mate2, FILE * out) { // match in the first read print out pair printSingle(mate1, out); printSingle(mate2, out); } //void usage() { static const char usage_msg[] =\ "[-hHv] {-f pattern_file | pattern} <read1.fx> [<read2.fx>]\n" "\t-H Evaluate patterns in the context of headers (default: sequences)\n" "\t-Q Evaluate patterns in the context of quality scores (default: sequences)\n" "\t-G pattern is a posix basic regular expression (default: literal substring)\n" "\t-E pattern is a posix extended regular expression (default: literal substring)\n" "\t-P pattern is a perl compatable regular expression (default: literal substring)\n" "\t-x pattern exactly matches the whole string (default: literal substring)\n" "\t-I The read file is interleaved (both pairs in a single file)\n" "\t-f <file> File containing patterns, one per line\n" "\t-h Print this help\n" "\t-V Print version\n"; // exit(1); //} int parseOptions(int argc, char * argv[], Options& opts) { int c; while ((c = getopt(argc, argv, "HhIf:zjqVrQGEPx")) != -1 ) { switch (c) { case 'f': opts.f_flag = optarg; break; case 'I': opts.I_flag = true; break; case 'Q': opts.Q_flag = true; break; case 'e': opts.r_flag = true; break; case 'x': opts.x_flag = true; break; case 'V': puts(VERSION); exit(1); break; case 'H': opts.H_flag = true; break; case 'r': opts.r_flag = true; break; case 'h': default: usage(usage_msg); break; } } return optind; } void split( std::vector<std::string> & theStringVector, /* Altered/returned value */ std::string theString, const std::string theDelimiter) { assert(theDelimiter.size() > 0); // My own ASSERT macro. size_t start = 0, end = 0; while ( end != std::string::npos) { end = theString.find( theDelimiter, start); // If at end, use length=maxLength. Else use length=end-start. theStringVector.push_back( theString.substr( start, (end == std::string::npos) ? std::string::npos : end - start)); // If at end, use start=maxSize. Else use start=end+delimiter. start = ( ( end > (std::string::npos - theDelimiter.size()) ) ? std::string::npos : end + theDelimiter.size()); } } void tokenizePatternFile(FILE * in, FileManager& fmanager) { // tokenize a line from the pattern file. The first part will be the pattern and the second // part is the file to write to. char * lineptr = NULL; size_t n; while(getline(&lineptr, &n, in) != -1) { std::vector<std::string> fields; split(fields, lineptr, "\t"); switch(fields.size()) { case 0: break; case 1: fmanager.add(fields[0]); break; default: fmanager.add(fields[0], fields[1]); break; } } free(lineptr); } static int on_match(int strnum, const char *textp, void const * context) { Fx * read = (Fx *) context; read->puts(stdout); return 1; } int main(int argc, char * argv[]) { //kvec_t(sds) pattern_list; FileManager manager; Options opts; int opt_idx = parseOptions(argc, argv, opts); if(opts.f_flag == NULL) { if( opt_idx >= argc) { puts("Please provide a pattern (or pattern file) and at least one input file"); usage(usage_msg); } else if (opt_idx >= argc - 1) { puts("Please provide an input file (or two)"); usage(usage_msg); } std::string pattern = argv[opt_idx]; ++opt_idx; manager.add(pattern); if(opts.r_flag) { std::string rcpattern = pattern; reverseComplement(rcpattern); manager.add(rcpattern); } } else { if (opt_idx > argc - 1) { puts("Please provide an input file (or two)"); usage(usage_msg); } FILE * in = fopen(opts.f_flag, "r"); tokenizePatternFile(in, manager); } Fxstream stream; if(opt_idx == argc - 2) { // two read files stream.open(argv[opt_idx], argv[opt_idx+1], opts.I_flag); } else if (opt_idx == argc - 1) { // one read file stream.open(argv[opt_idx], NULL, opts.I_flag); } Fx * mate1 = new Fx(); Fx * mate2 = new Fx(); std::string conc; std::map<std::string, int>::iterator iter; for (iter = manager.patternMapping.begin(); iter != manager.patternMapping.end() ; ++iter ) { conc += iter->first + "\n"; } char * concstr = (char *) malloc(conc.size() * sizeof(char *)); strncpy(concstr, conc.c_str(), conc.size()); concstr[conc.size()-1] = '\0'; int npatts; MEMREF *pattv = refsplit(concstr, '\n', &npatts); SSEARCH *ssp = ssearch_create(pattv, npatts); while(stream.read(&mate1, &mate2) >= 0) { MEMREF data = {mate1->seq, strlen(mate1->seq)}; int ret = ssearch_scan(ssp, data, (SSEARCH_CB)on_match, (void *)mate1); if(ret == 0){ // read one did not have a match check read 2 if it exists if(mate2 != NULL) { MEMREF data2 = {mate2->seq, strlen(mate2->seq)}; ssearch_scan(ssp, data2, (SSEARCH_CB)on_match, (void *)mate2); } } } free(concstr); delete mate1; delete mate2; stream.close(); free(pattv); return 0; } <commit_msg>Add in options H & Q for different searching patterns<commit_after>// // main.cpp // fxtract // // Created by Connor Skennerton on 30/07/13. // Copyright (c) 2013 Connor Skennerton. All rights reserved. // #include <unistd.h> #include <cstdio> #include <cassert> #include "util.h" #include "fileManager.h" #include "Fx.h" extern "C" { #include "util/ssearch.h" #include "util/bpsearch.h" #include "util/msutil.h" } #define VERSION "1.0-alpha" struct Options { bool H_flag; bool Q_flag; bool G_flag; bool E_flag; bool x_flag; bool r_flag; bool I_flag; char * f_flag; Options() : H_flag(false), Q_flag(false), G_flag(false), E_flag(false), x_flag(false), r_flag(false), I_flag(false), f_flag(NULL) {} }; void printSingle(Fx * mate1, FILE * out ) { mate1->puts(out); } void printPair(Fx* mate1, Fx* mate2, FILE * out) { // match in the first read print out pair printSingle(mate1, out); printSingle(mate2, out); } //void usage() { static const char usage_msg[] =\ "[-hHv] {-f pattern_file | pattern} <read1.fx> [<read2.fx>]\n" "\t-H Evaluate patterns in the context of headers (default: sequences)\n" "\t-Q Evaluate patterns in the context of quality scores (default: sequences)\n" "\t-G pattern is a posix basic regular expression (default: literal substring)\n" "\t-E pattern is a posix extended regular expression (default: literal substring)\n" "\t-P pattern is a perl compatable regular expression (default: literal substring)\n" "\t-x pattern exactly matches the whole string (default: literal substring)\n" "\t-I The read file is interleaved (both pairs in a single file)\n" "\t-f <file> File containing patterns, one per line\n" "\t-h Print this help\n" "\t-V Print version\n"; // exit(1); //} int parseOptions(int argc, char * argv[], Options& opts) { int c; while ((c = getopt(argc, argv, "HhIf:zjqVrQGEPx")) != -1 ) { switch (c) { case 'f': opts.f_flag = optarg; break; case 'I': opts.I_flag = true; break; case 'Q': opts.Q_flag = true; break; case 'e': opts.r_flag = true; break; case 'x': opts.x_flag = true; break; case 'V': puts(VERSION); exit(1); break; case 'H': opts.H_flag = true; break; case 'r': opts.r_flag = true; break; case 'h': default: usage(usage_msg); break; } } return optind; } void split( std::vector<std::string> & theStringVector, /* Altered/returned value */ std::string theString, const std::string theDelimiter) { assert(theDelimiter.size() > 0); // My own ASSERT macro. size_t start = 0, end = 0; while ( end != std::string::npos) { end = theString.find( theDelimiter, start); // If at end, use length=maxLength. Else use length=end-start. theStringVector.push_back( theString.substr( start, (end == std::string::npos) ? std::string::npos : end - start)); // If at end, use start=maxSize. Else use start=end+delimiter. start = ( ( end > (std::string::npos - theDelimiter.size()) ) ? std::string::npos : end + theDelimiter.size()); } } void tokenizePatternFile(FILE * in, FileManager& fmanager) { // tokenize a line from the pattern file. The first part will be the pattern and the second // part is the file to write to. char * lineptr = NULL; size_t n; while(getline(&lineptr, &n, in) != -1) { std::vector<std::string> fields; split(fields, lineptr, "\t"); switch(fields.size()) { case 0: break; case 1: fmanager.add(fields[0]); break; default: fmanager.add(fields[0], fields[1]); break; } } free(lineptr); } static int on_match(int strnum, const char *textp, void const * context) { Fx * read = (Fx *) context; read->puts(stdout); return 1; } int main(int argc, char * argv[]) { //kvec_t(sds) pattern_list; FileManager manager; Options opts; int opt_idx = parseOptions(argc, argv, opts); if(opts.f_flag == NULL) { if( opt_idx >= argc) { puts("Please provide a pattern (or pattern file) and at least one input file"); usage(usage_msg); } else if (opt_idx >= argc - 1) { puts("Please provide an input file (or two)"); usage(usage_msg); } std::string pattern = argv[opt_idx]; ++opt_idx; manager.add(pattern); if(opts.r_flag) { std::string rcpattern = pattern; reverseComplement(rcpattern); manager.add(rcpattern); } } else { if (opt_idx > argc - 1) { puts("Please provide an input file (or two)"); usage(usage_msg); } FILE * in = fopen(opts.f_flag, "r"); tokenizePatternFile(in, manager); } Fxstream stream; if(opt_idx == argc - 2) { // two read files stream.open(argv[opt_idx], argv[opt_idx+1], opts.I_flag); } else if (opt_idx == argc - 1) { // one read file stream.open(argv[opt_idx], NULL, opts.I_flag); } Fx * mate1 = new Fx(); Fx * mate2 = new Fx(); std::string conc; std::map<std::string, int>::iterator iter; for (iter = manager.patternMapping.begin(); iter != manager.patternMapping.end() ; ++iter ) { conc += iter->first + "\n"; } char * concstr = (char *) malloc(conc.size() * sizeof(char *)); strncpy(concstr, conc.c_str(), conc.size()); concstr[conc.size()-1] = '\0'; int npatts; MEMREF *pattv = refsplit(concstr, '\n', &npatts); SSEARCH *ssp = ssearch_create(pattv, npatts); while(stream.read(&mate1, &mate2) >= 0) { MEMREF data; if(opts.H_flag) { data.ptr = mate1->name; data.len = strlen(mate1->name); } else if(opts.Q_flag){ if(!mate1->isFasta()) { data.ptr = mate1->qual; data.len = (size_t)mate1->len; } } else { data.ptr = mate1->seq; data.len = (size_t)mate1->len; } int ret = ssearch_scan(ssp, data, (SSEARCH_CB)on_match, (void *)mate1); if(ret == 0){ // read one did not have a match check read 2 if it exists if(mate2 != NULL) { if(opts.H_flag) { data.ptr = mate2->name; data.len = strlen(mate2->name); } else if(opts.Q_flag){ if(!mate2->isFasta()) { data.ptr = mate2->seq; data.len = (size_t)mate2->len; } } else { data.ptr = mate2->seq; data.len = (size_t)mate2->len; } ssearch_scan(ssp, data, (SSEARCH_CB)on_match, (void *)mate2); } } } free(concstr); delete mate1; delete mate2; stream.close(); free(pattv); return 0; } <|endoftext|>
<commit_before>8c3d211c-2d14-11e5-af21-0401358ea401<commit_msg>8c3d211d-2d14-11e5-af21-0401358ea401<commit_after>8c3d211d-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>15e76f34-2f67-11e5-b808-6c40088e03e4<commit_msg>15edf854-2f67-11e5-af22-6c40088e03e4<commit_after>15edf854-2f67-11e5-af22-6c40088e03e4<|endoftext|>
<commit_before>ad5ffe57-4b02-11e5-8a57-28cfe9171a43<commit_msg>Really doesn't crash if X, now<commit_after>ad7517b3-4b02-11e5-9188-28cfe9171a43<|endoftext|>
<commit_before>353f4757-ad5a-11e7-9412-ac87a332f658<commit_msg>I hope I am done<commit_after>35d39d68-ad5a-11e7-add0-ac87a332f658<|endoftext|>
<commit_before>ed6ca39c-585a-11e5-8fa4-6c40088e03e4<commit_msg>ed7434e8-585a-11e5-ada8-6c40088e03e4<commit_after>ed7434e8-585a-11e5-ada8-6c40088e03e4<|endoftext|>
<commit_before>7c8d5ce3-2e4f-11e5-9241-28cfe91dbc4b<commit_msg>7c941430-2e4f-11e5-b466-28cfe91dbc4b<commit_after>7c941430-2e4f-11e5-b466-28cfe91dbc4b<|endoftext|>
<commit_before>afe62326-4b02-11e5-aedf-28cfe9171a43<commit_msg>Did a thing<commit_after>aff8fb19-4b02-11e5-ac11-28cfe9171a43<|endoftext|>
<commit_before>//======================================================== // Hazi feladat keret. // A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorokon beluli reszben celszeru garazdalkodni, mert // a tobbit ugyis toroljuk. // A Hazi feladat csak ebben a fajlban lehet // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni //======================================================== #include <math.h> #include <stdlib.h> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) // MsWindows-on ez is kell #include <windows.h> #endif // Win32 platform #include <GL/gl.h> #include <GL/glu.h> // A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/ #include <GL/glut.h> #include <stdio.h> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Innentol modosithatod... //-------------------------------------------------------- // Nev: // Neptun: //-------------------------------------------------------- #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) class Vector { public: float x, y; Vector(float x0, float y0) { x = x0; y = y0; } Vector operator+(const Vector& v) { return Vector(x + v.x, y + v.y); } Vector operator*(float f) { return Vector(x * f, y * f); } }; Vector* points[4]; void onInitialization( ) { points[0] = new Vector(10, 10); points[1] = new Vector(10, 20); points[2] = new Vector(20, 10); points[3] = new Vector(20, 20); } void onDisplay( ) { glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); gluOrtho2D(0., 100., 0., 100.); glColor4d(0.9f, 0.8f, 0.7f, 1.0f); glBegin(GL_LINE_LOOP); for (int i = 0; i < ARRAY_SIZE(points); i++) glVertex2d(points[i]->x, points[i]->y); glEnd(); // Buffercsere: rajzolas vege glFinish(); glutSwapBuffers(); } void onMouse(int button, int state, int x, int y) { // A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON // ill. a GLUT_DOWN / GLUT_UP makrokat hasznald. } void onIdle( ) { } void onKeyboard(unsigned char key, int x, int y) { } // ...Idaig modosithatod //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Grafika hazi feladat"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); onInitialization(); glutDisplayFunc(onDisplay); glutMouseFunc(onMouse); glutIdleFunc(onIdle); glutKeyboardFunc(onKeyboard); glutMainLoop(); return 0; } <commit_msg>vizonto alakzat<commit_after>//======================================================== // Hazi feladat keret. // A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorokon beluli reszben celszeru garazdalkodni, mert // a tobbit ugyis toroljuk. // A Hazi feladat csak ebben a fajlban lehet // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni //======================================================== #include <math.h> #include <stdlib.h> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) // MsWindows-on ez is kell #include <windows.h> #endif // Win32 platform #include <GL/gl.h> #include <GL/glu.h> // A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/ #include <GL/glut.h> #include <stdio.h> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Innentol modosithatod... //-------------------------------------------------------- // Nev: // Neptun: //-------------------------------------------------------- #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) class Vector { public: float x, y; Vector(float x0, float y0) { x = x0; y = y0; } Vector operator+(const Vector& v) { return Vector(x + v.x, y + v.y); } Vector operator*(float f) { return Vector(x * f, y * f); } }; Vector* points[2][7]; void onInitialization( ) { points[0][0] = new Vector(10, 20); points[0][1] = new Vector(100, 80); points[0][2] = new Vector(120, 20); points[0][3] = new Vector(210, 80); points[0][4] = new Vector(230, 20); points[0][5] = new Vector(320, 80); points[0][6] = new Vector(340, 20); points[1][0] = new Vector(10, 120); points[1][1] = new Vector(100, 180); points[1][2] = new Vector(120, 120); points[1][3] = new Vector(210, 180); points[1][4] = new Vector(230, 120); points[1][5] = new Vector(320, 180); points[1][6] = new Vector(340, 120); gluOrtho2D(0., 500., 0., 500.); } void onDisplay( ) { glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor4d(0.9f, 0.8f, 0.7f, 1.0f); for (int i = 0; i < ARRAY_SIZE(points); i++) { glBegin(GL_LINE_STRIP); for (int j = 0; j < ARRAY_SIZE(points[i]); j++) glVertex2d(points[i][j]->x, points[i][j]->y); glEnd(); } // Buffercsere: rajzolas vege glFinish(); glutSwapBuffers(); } void onMouse(int button, int state, int x, int y) { // A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON // ill. a GLUT_DOWN / GLUT_UP makrokat hasznald. } void onIdle( ) { } void onKeyboard(unsigned char key, int x, int y) { } // ...Idaig modosithatod //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Grafika hazi feladat"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); onInitialization(); glutDisplayFunc(onDisplay); glutMouseFunc(onMouse); glutIdleFunc(onIdle); glutKeyboardFunc(onKeyboard); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>251e5e0a-2e3a-11e5-8ed5-c03896053bdd<commit_msg>252da31a-2e3a-11e5-ab68-c03896053bdd<commit_after>252da31a-2e3a-11e5-ab68-c03896053bdd<|endoftext|>
<commit_before>13fe7c8a-2e4f-11e5-ab6e-28cfe91dbc4b<commit_msg>14055594-2e4f-11e5-9bf6-28cfe91dbc4b<commit_after>14055594-2e4f-11e5-9bf6-28cfe91dbc4b<|endoftext|>
<commit_before>d75c7cd1-327f-11e5-96b6-9cf387a8033e<commit_msg>d762b2b5-327f-11e5-8e58-9cf387a8033e<commit_after>d762b2b5-327f-11e5-8e58-9cf387a8033e<|endoftext|>
<commit_before>/* * main.cpp * * Created on: Sep 21, 2013 * Author: tomas */ #include <stdlib.h> #include <stdio.h> #include <GL/glut.h> #include <iostream> // TODO unused? #include <math.h> /* fabs */ #include <sys/time.h> #include <unistd.h> using namespace std; #define GRID_SIZE 32 #define KEY_SPACE 32 #define RAND_SEED 1 int windowSizeH = 600; int windowSizeV = 600; bool shouldDrawUserLine = false; bool shouldDrawBresenhamLine = false; bool snapToGrid = true; bool showHelp = false; float beginX = 0; float beginY = 0; float endX = 0; float endY = 0; // TODO better titles int gridBeginX = 0; int gridBeginY = 0; int gridEndX = 0; int gridEndY = 0; void transformScreenToWorldCoordinates(int screenX, int screenY, float &worldX, float &worldY) { worldX = ((float)screenX / (float)windowSizeH) * 2 - 1; worldY = ((float)screenY / (float)windowSizeV) * -2 + 1; } void transformWorldToGridCoordinates(float worldX, float worldY, int &gridX, int &gridY){ gridX = (int)( ( ( worldX+1)/2 ) * GRID_SIZE ); gridY = (int)( ( (-worldY+1)/2 ) * GRID_SIZE ); } void transformGridToWorldCoordinates(int gridX, int gridY, float &worldX, float &worldY){ float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize worldX = ( ( (float)gridX / GRID_SIZE) * 2 ) - 1 + (cornerLength/2); worldY = ( ( (float)gridY / GRID_SIZE) * -2 ) + 1 - (cornerLength/2); } void colorGridCell(int x, int y) { float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize float topLeftX = (cornerLength * x) - 1; float topLeftY = ((cornerLength * y) - 1) * -1; glColor3f(0, 0.5, 0.5); glBegin(GL_QUADS); glVertex2f(topLeftX, topLeftY); glVertex2f(topLeftX + cornerLength, topLeftY); glVertex2f(topLeftX + cornerLength, topLeftY - cornerLength); glVertex2f(topLeftX, topLeftY - cornerLength); glEnd(); } void drawBresenhamLine(int gridBeginX, int gridBeginY, int gridEndX, int gridEndY, bool useInts, bool draw) { bool steep = abs(gridEndY - gridBeginY) > abs(gridEndX - gridBeginX); if (steep) { swap(gridBeginX, gridBeginY); swap(gridEndX, gridEndY); } if (gridBeginX > gridEndX) { swap(gridBeginX, gridEndX); swap(gridBeginY, gridEndY); } if (useInts) { int deltaX = gridEndX - gridBeginX; int deltay = abs(gridEndY - gridBeginY); int error = deltaX / 2; int currentY = gridBeginY; int yStep = 1; if (gridBeginY >= gridEndY) { yStep = -1; } for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) { if (draw) { if (steep) { colorGridCell(currentY, currentX); } else { colorGridCell(currentX, currentY); } } error = error - deltay; if (error < 0) { currentY = currentY + yStep; error = error + deltaX; } } } else { int deltaX = gridEndX - gridBeginX; int deltay = abs(gridEndY - gridBeginY); float error = 0; float deltaError = fabs((float) deltay / (float) deltaX); int currentY = gridBeginY; int yStep = 1; if (gridBeginY >= gridEndY) { yStep = -1; } for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) { if (draw){ if (steep) { colorGridCell(currentY, currentX); } else { colorGridCell(currentX, currentY); } } error = error + deltaError; if (error >= 0.5) { currentY = currentY + yStep; error = error - 1.0; } } } } void mouseClickCallback (int button, int state, int x, int y){ if (button == GLUT_LEFT_BUTTON){ if ((state == GLUT_DOWN)){ transformScreenToWorldCoordinates(x, y, beginX, beginY); endX = beginX; endY = beginY; shouldDrawUserLine = true; transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY); gridEndX = gridBeginX; gridEndY = gridBeginY; shouldDrawBresenhamLine = true; } // else if (state == GLUT_UP) { // transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY); // transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY); // // } glutPostRedisplay(); } } void mouseDragCallback(int x, int y){ transformScreenToWorldCoordinates(x, y, endX, endY); transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY); glutPostRedisplay(); } void keyboardCallback(unsigned char key, int x, int y){ switch (key) { case KEY_SPACE: showHelp = !showHelp; glutPostRedisplay(); break; } } void drawUserLine(){ float lineBeginX = 0; float lineBeginY = 0; float lineEndX = 0; float lineEndY = 0; if (snapToGrid) { transformGridToWorldCoordinates(gridBeginX, gridBeginY, lineBeginX, lineBeginY); transformGridToWorldCoordinates(gridEndX, gridEndY, lineEndX, lineEndY); } else { lineBeginX = beginX; lineBeginY = beginY; lineEndX = endX; lineEndY = endY; } glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINES); glVertex2f(lineBeginX, lineBeginY); glVertex2f(lineEndX, lineEndY); glEnd(); } void drawGrid(){ glColor3f(0.5, 0.5, 0.5); int i; glBegin(GL_LINES); for (i = -(GRID_SIZE / 2); i <= (GRID_SIZE / 2); i++) { //TODO optimize float x = i / (float) (GRID_SIZE / 2); glVertex2f(x, -1.0); glVertex2f(x, 1.0); glVertex2f(-1.0, x); glVertex2f(1.0, x); } glEnd(); } //TODO do not forget to reset colors void drawHelpOverlay(){ glColor3f(0.1, 0.1, 0.1); glBegin(GL_QUADS); glVertex2f(-1.0, 1.0); glVertex2f(1.0, 1.0); glVertex2f(1.0, 0); glVertex2f(-1.0, 0); glEnd(); glColor3f(1.0, 1.0, 1.0); glRasterPos2f(-0.9, 0.9); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); drawGrid(); if (shouldDrawBresenhamLine){ drawBresenhamLine(gridBeginX, gridBeginY, gridEndX, gridEndY, false, true); } if (shouldDrawUserLine) { drawUserLine(); } if (showHelp) { drawHelpOverlay(); } glFlush(); } int getRandomIntInRange(int min, int max) { return min + (rand() % (int)(max - min + 1)); // TODO review algorithm // TODO make random seed always the same } long getLineDrawingExecutionSpeedMicroseconds(bool useInts, long lineDraws){ int min = 0; int max = GRID_SIZE - 1; int randBeginX; int randBeginY; int randEndX; int randEndY; srand(RAND_SEED); struct timeval start, end; gettimeofday(&start, NULL); for (long i = 0; i < lineDraws; i++) { randBeginX = getRandomIntInRange(min, max); randBeginY = getRandomIntInRange(min, max); randEndX = getRandomIntInRange(min, max); randEndY = getRandomIntInRange(min, max); drawBresenhamLine(randBeginX, randBeginY, randEndX, randEndY, useInts, false); // cout << randBeginX << " " << randBeginX << " to " << randEndX << " " << randEndY << endl; } gettimeofday(&end, NULL); return end.tv_usec - start.tv_usec; } void testBresenhamLineAlgorithmExecutionSpeed(long numberOfCalls){ long execTimeUsingInt = getLineDrawingExecutionSpeedMicroseconds(true, numberOfCalls); long execTimeUsingFloat = getLineDrawingExecutionSpeedMicroseconds(false, numberOfCalls); cout << execTimeUsingInt << " " << execTimeUsingFloat << endl; } void init(void) { } int main(int argc, char *argv[]) { // testBresenhamLineAlgorithmExecutionSpeed(10000); // return 0; glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutInitWindowSize(windowSizeH, windowSizeV); glutInitWindowPosition(100, 50); glutCreateWindow("Bresenham's line algorithm demo - press \"ENTER\" for help"); init(); glutDisplayFunc(display); glutMouseFunc(mouseClickCallback); glutMotionFunc(mouseDragCallback); glutKeyboardFunc(keyboardCallback); glutMainLoop(); return 0; } <commit_msg>Drawing grid after filling the cells for better visibility<commit_after>/* * main.cpp * * Created on: Sep 21, 2013 * Author: tomas */ #include <stdlib.h> #include <stdio.h> #include <GL/glut.h> #include <iostream> // TODO unused? #include <math.h> /* fabs */ #include <sys/time.h> #include <unistd.h> using namespace std; #define GRID_SIZE 32 #define KEY_SPACE 32 #define RAND_SEED 1 int windowSizeH = 600; int windowSizeV = 600; bool shouldDrawUserLine = false; bool shouldDrawBresenhamLine = false; bool snapToGrid = true; bool showHelp = false; float beginX = 0; float beginY = 0; float endX = 0; float endY = 0; // TODO better titles int gridBeginX = 0; int gridBeginY = 0; int gridEndX = 0; int gridEndY = 0; void transformScreenToWorldCoordinates(int screenX, int screenY, float &worldX, float &worldY) { worldX = ((float)screenX / (float)windowSizeH) * 2 - 1; worldY = ((float)screenY / (float)windowSizeV) * -2 + 1; } void transformWorldToGridCoordinates(float worldX, float worldY, int &gridX, int &gridY){ gridX = (int)( ( ( worldX+1)/2 ) * GRID_SIZE ); gridY = (int)( ( (-worldY+1)/2 ) * GRID_SIZE ); } void transformGridToWorldCoordinates(int gridX, int gridY, float &worldX, float &worldY){ float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize worldX = ( ( (float)gridX / GRID_SIZE) * 2 ) - 1 + (cornerLength/2); worldY = ( ( (float)gridY / GRID_SIZE) * -2 ) + 1 - (cornerLength/2); } void colorGridCell(int x, int y) { float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize float topLeftX = (cornerLength * x) - 1; float topLeftY = ((cornerLength * y) - 1) * -1; glColor3f(0, 0.5, 0.5); glBegin(GL_QUADS); glVertex2f(topLeftX, topLeftY); glVertex2f(topLeftX + cornerLength, topLeftY); glVertex2f(topLeftX + cornerLength, topLeftY - cornerLength); glVertex2f(topLeftX, topLeftY - cornerLength); glEnd(); } void drawBresenhamLine(int gridBeginX, int gridBeginY, int gridEndX, int gridEndY, bool useInts, bool draw) { bool steep = abs(gridEndY - gridBeginY) > abs(gridEndX - gridBeginX); if (steep) { swap(gridBeginX, gridBeginY); swap(gridEndX, gridEndY); } if (gridBeginX > gridEndX) { swap(gridBeginX, gridEndX); swap(gridBeginY, gridEndY); } if (useInts) { int deltaX = gridEndX - gridBeginX; int deltay = abs(gridEndY - gridBeginY); int error = deltaX / 2; int currentY = gridBeginY; int yStep = 1; if (gridBeginY >= gridEndY) { yStep = -1; } for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) { if (draw) { if (steep) { colorGridCell(currentY, currentX); } else { colorGridCell(currentX, currentY); } } error = error - deltay; if (error < 0) { currentY = currentY + yStep; error = error + deltaX; } } } else { int deltaX = gridEndX - gridBeginX; int deltay = abs(gridEndY - gridBeginY); float error = 0; float deltaError = fabs((float) deltay / (float) deltaX); int currentY = gridBeginY; int yStep = 1; if (gridBeginY >= gridEndY) { yStep = -1; } for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) { if (draw){ if (steep) { colorGridCell(currentY, currentX); } else { colorGridCell(currentX, currentY); } } error = error + deltaError; if (error >= 0.5) { currentY = currentY + yStep; error = error - 1.0; } } } } void mouseClickCallback (int button, int state, int x, int y){ if (button == GLUT_LEFT_BUTTON){ if ((state == GLUT_DOWN)){ transformScreenToWorldCoordinates(x, y, beginX, beginY); endX = beginX; endY = beginY; shouldDrawUserLine = true; transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY); gridEndX = gridBeginX; gridEndY = gridBeginY; shouldDrawBresenhamLine = true; } // else if (state == GLUT_UP) { // transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY); // transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY); // // } glutPostRedisplay(); } } void mouseDragCallback(int x, int y){ transformScreenToWorldCoordinates(x, y, endX, endY); transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY); glutPostRedisplay(); } void keyboardCallback(unsigned char key, int x, int y){ switch (key) { case KEY_SPACE: showHelp = !showHelp; glutPostRedisplay(); break; } } void drawUserLine(){ float lineBeginX = 0; float lineBeginY = 0; float lineEndX = 0; float lineEndY = 0; if (snapToGrid) { transformGridToWorldCoordinates(gridBeginX, gridBeginY, lineBeginX, lineBeginY); transformGridToWorldCoordinates(gridEndX, gridEndY, lineEndX, lineEndY); } else { lineBeginX = beginX; lineBeginY = beginY; lineEndX = endX; lineEndY = endY; } glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINES); glVertex2f(lineBeginX, lineBeginY); glVertex2f(lineEndX, lineEndY); glEnd(); } void drawGrid(){ glColor3f(0.5, 0.5, 0.5); int i; glBegin(GL_LINES); for (i = -(GRID_SIZE / 2); i <= (GRID_SIZE / 2); i++) { //TODO optimize float x = i / (float) (GRID_SIZE / 2); glVertex2f(x, -1.0); glVertex2f(x, 1.0); glVertex2f(-1.0, x); glVertex2f(1.0, x); } glEnd(); } //TODO do not forget to reset colors void drawHelpOverlay(){ glColor3f(0.1, 0.1, 0.1); glBegin(GL_QUADS); glVertex2f(-1.0, 1.0); glVertex2f(1.0, 1.0); glVertex2f(1.0, 0); glVertex2f(-1.0, 0); glEnd(); glColor3f(1.0, 1.0, 1.0); glRasterPos2f(-0.9, 0.9); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); if (shouldDrawBresenhamLine){ drawBresenhamLine(gridBeginX, gridBeginY, gridEndX, gridEndY, false, true); } drawGrid(); if (shouldDrawUserLine) { drawUserLine(); } if (showHelp) { drawHelpOverlay(); } glFlush(); } int getRandomIntInRange(int min, int max) { return min + (rand() % (int)(max - min + 1)); // TODO review algorithm // TODO make random seed always the same } long getLineDrawingExecutionSpeedMicroseconds(bool useInts, long lineDraws){ int min = 0; int max = GRID_SIZE - 1; int randBeginX; int randBeginY; int randEndX; int randEndY; srand(RAND_SEED); struct timeval start, end; gettimeofday(&start, NULL); for (long i = 0; i < lineDraws; i++) { randBeginX = getRandomIntInRange(min, max); randBeginY = getRandomIntInRange(min, max); randEndX = getRandomIntInRange(min, max); randEndY = getRandomIntInRange(min, max); drawBresenhamLine(randBeginX, randBeginY, randEndX, randEndY, useInts, false); // cout << randBeginX << " " << randBeginX << " to " << randEndX << " " << randEndY << endl; } gettimeofday(&end, NULL); return end.tv_usec - start.tv_usec; } void testBresenhamLineAlgorithmExecutionSpeed(long numberOfCalls){ long execTimeUsingInt = getLineDrawingExecutionSpeedMicroseconds(true, numberOfCalls); long execTimeUsingFloat = getLineDrawingExecutionSpeedMicroseconds(false, numberOfCalls); cout << execTimeUsingInt << " " << execTimeUsingFloat << endl; } void init(void) { } int main(int argc, char *argv[]) { // testBresenhamLineAlgorithmExecutionSpeed(10000); // return 0; glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutInitWindowSize(windowSizeH, windowSizeV); glutInitWindowPosition(100, 50); glutCreateWindow("Bresenham's line algorithm demo - press \"ENTER\" for help"); init(); glutDisplayFunc(display); glutMouseFunc(mouseClickCallback); glutMotionFunc(mouseDragCallback); glutKeyboardFunc(keyboardCallback); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>#include "ACS712.h" #include <Arduino.h> // Measured using 3.3v logic using namespace Knobs; static const float _MV_PER_DIV = 5000.0/2048.0; static const float _ACS_SENS[] = { 0.185, 0.100, 0.066 }; //mV/mA s. datasheet static const float _ACS_MUL[] = { _MV_PER_DIV/_ACS_SENS[ x05B ], _MV_PER_DIV/_ACS_SENS[ x20A ], _MV_PER_DIV/_ACS_SENS[ x30A ] }; ACS712::ACS712( const char *name, pin_t pin, ACS_VERSION version, knob_value_t max, knob_value_t samples ) : Lever( name, pin, 0, max ) , _scale( _ACS_MUL[ version ] ) , _samples( samples ) { _div_avg = 0; _val_avg = 0; _count = 0; } void ACS712::loop(){ knob_value_t in, val; float div; in = _read(); _count++; if( _count == 1 ) { _val_avg = in; return; } _val_avg = ( _val_avg * (_samples-1) + in ) / _samples; if( _count < _samples ) return; div = fabs( _val_avg - in ); if( _count == _samples ) { _div_avg = div; } _div_avg = ( _div_avg * (_samples-1) + div ) / _samples; if( _count < _samples*2 ) return; _count = _samples*2; //prevent overflow val = (knob_value_t) ( _div_avg * _ACS_MUL[ 1 ] ); if( modify( &val ) ) { activate( val ); } } <commit_msg>debugging output<commit_after>#include "ACS712.h" #include <Arduino.h> // Measured using 3.3v logic using namespace Knobs; static const float _MV_PER_DIV = 5000.0/2048.0; static const float _ACS_SENS[] = { 0.185, 0.100, 0.066 }; //mV/mA s. datasheet static const float _ACS_MUL[] = { _MV_PER_DIV/_ACS_SENS[ x05B ], _MV_PER_DIV/_ACS_SENS[ x20A ], _MV_PER_DIV/_ACS_SENS[ x30A ] }; ACS712::ACS712( const char *name, pin_t pin, ACS_VERSION version, knob_value_t max, knob_value_t samples ) : Lever( name, pin, 0, max ) , _scale( _ACS_MUL[ version ] ) , _samples( samples ) { _div_avg = 0; _val_avg = 0; _count = 0; } void ACS712::loop(){ //static int i; knob_value_t in, val; float div; in = _read(); /* i++; if( i%100 == 0 ){ Serial.print( "[" ); Serial.print( in ); Serial.println( "]" ); } */ _count++; if( _count == 1 ) { _val_avg = in; return; } _val_avg = ( _val_avg * (_samples-1) + in ) / _samples; if( _count < _samples ) return; div = fabs( _val_avg - in ); if( _count == _samples ) { _div_avg = div; } _div_avg = ( _div_avg * (_samples-1) + div ) / _samples; if( _count < _samples*2 ) return; _count = _samples*2; //prevent overflow val = (knob_value_t) ( _div_avg * _ACS_MUL[ 1 ] ); if( modify( &val ) ) { activate( val ); } } <|endoftext|>
<commit_before>acd2ed21-327f-11e5-aaff-9cf387a8033e<commit_msg>acd90c66-327f-11e5-abfe-9cf387a8033e<commit_after>acd90c66-327f-11e5-abfe-9cf387a8033e<|endoftext|>
<commit_before>9ff41c8c-327f-11e5-922c-9cf387a8033e<commit_msg>9ffa0dae-327f-11e5-beec-9cf387a8033e<commit_after>9ffa0dae-327f-11e5-beec-9cf387a8033e<|endoftext|>
<commit_before>86936f8a-2d15-11e5-af21-0401358ea401<commit_msg>86936f8b-2d15-11e5-af21-0401358ea401<commit_after>86936f8b-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>64574b24-2fa5-11e5-94e5-00012e3d3f12<commit_msg>64591fe4-2fa5-11e5-97c4-00012e3d3f12<commit_after>64591fe4-2fa5-11e5-97c4-00012e3d3f12<|endoftext|>
<commit_before>4b3479b5-2e4f-11e5-a239-28cfe91dbc4b<commit_msg>4b3b7073-2e4f-11e5-a7a5-28cfe91dbc4b<commit_after>4b3b7073-2e4f-11e5-a7a5-28cfe91dbc4b<|endoftext|>
<commit_before>03ed9fca-585b-11e5-8da5-6c40088e03e4<commit_msg>03f4836c-585b-11e5-8127-6c40088e03e4<commit_after>03f4836c-585b-11e5-8127-6c40088e03e4<|endoftext|>
<commit_before>8431fc1b-2d15-11e5-af21-0401358ea401<commit_msg>8431fc1c-2d15-11e5-af21-0401358ea401<commit_after>8431fc1c-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>68465fa6-2fa5-11e5-8d2c-00012e3d3f12<commit_msg>68483464-2fa5-11e5-8602-00012e3d3f12<commit_after>68483464-2fa5-11e5-8602-00012e3d3f12<|endoftext|>
<commit_before>63ddf218-5216-11e5-970a-6c40088e03e4<commit_msg>63e47c00-5216-11e5-a7fb-6c40088e03e4<commit_after>63e47c00-5216-11e5-a7fb-6c40088e03e4<|endoftext|>
<commit_before>// // main.cpp // CRAM // // Created by Marc Martinez on 5/11/14. // Copyright (c) 2014 the universal framework. All rights reserved. // #include <iostream> int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; } <commit_msg>somewhat working<commit_after>// // main.cpp // CRAM // // Created by Marc Martinez on 5/11/14. // Copyright (c) 2014 the universal framework. All rights reserved. // #include <iostream> #include <boost/asio.hpp> #include <boost/array.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/program_options.hpp> boost::asio::io_service _ioService; boost::asio::ip::tcp::resolver _resolver(_ioService); boost::asio::ip::tcp::socket _socket(_ioService); boost::array<char, 8192> buffer; std::string queuePath = ""; boost::program_options::options_description description("CRAM Utility"); void readHandler(const boost::system::error_code &error, std::size_t bytes_transferred){ if (!error){ std::cout << "Read Begin" << std::endl; std::cout << std::string(buffer.data(), bytes_transferred) << std::endl; std::cout << "Read End" << std::endl; _socket.async_read_some(boost::asio::buffer(buffer), readHandler); } else{ std::cout << "Could not read!" << std::endl; } } void loadSession(std::string sessionPath){ std::string session = ""; std::cout << "Loading Session: " << sessionPath << std::endl; if(boost::filesystem::exists(sessionPath)){ boost::filesystem::ifstream fileStream(sessionPath); while(fileStream){ std::string fileLine = ""; std::getline(fileStream, fileLine); //session += fileLine + "\r"; std::cout << "Session Line: " << fileLine << std::endl; } //session = "subject: oiwefwnefiewnfion\r\njust a test\r\n.\r\n"; //boost::asio::write(_socket, boost::asio::buffer("HELO miowenfoinwf.com\r\nMAIL FROM: ioenwfoiwenf.com\r\nRCPT TO:darks1de11@hotmail.com\r\nDATA\r\n")); //boost::asio::write(_socket, boost::asio::buffer("from:ytftyfftyf@ytcuuyfv.com\nto:darks1de11@hotmail.com\nsubject: oiwefwnefiewnfion\njust a test\r\n.\r\n")); } } void loadQueue(std::string queuePath){ std::string queueData = ""; std::cout << "Loading Queue: " << queuePath << std::endl; if(boost::filesystem::exists(queuePath) && boost::filesystem::is_directory(queuePath)){ boost::filesystem::directory_iterator queuePathIterator(queuePath); boost::filesystem::directory_iterator endQueuePathIterator; //boost::asio::write(_socket, boost::asio::buffer("HELO miowenfoinwf.com\r\nMAIL FROM: ioenwfoiwenf.com\r\nRCPT TO:darks1de11@hotmail.com\r\nDATA\r\n")); while(queuePathIterator != endQueuePathIterator){ std::string sessionPath = queuePath + "/" + queuePathIterator->path().filename().string(); loadSession(sessionPath); queuePathIterator++; } boost::asio::write(_socket, boost::asio::buffer("HELO miowe1nfoinwf.com\r\nMAIL FROM: ioenwfo1iwenf.com\r\nRCPT TO:darks1de11@hotmail.com\r\nDATA\r\nfrom:ytftyfftyf@ytcuuyfv.com\nto:darks1de11@hotmail.com\nsubject: oiwefwnefiewnfion\njust a test\r\n.\r\n")); //boost::asio::write(_socket, boost::asio::buffer("from:ytftyfftyf@ytcuuyfv.com\nto:darks1de11@hotmail.com\nsubject: oiwefwnefiewnfion\njust a test\r\n.\r\n")); boost::asio::write(_socket, boost::asio::buffer("HELO miowen2foinwf.com\r\nMAIL FROM: ioenwfo2iwenf.com\r\nRCPT TO:darks1de11@hotmail.com\r\nDATA\r\nfrom:ytftyfftyf@ytcuuyfv.com\nto:darks1de11@hotmail.com\nsubject: oiwefwnefiewnfion\njust a test\r\n.\r\n")); //boost::asio::write(_socket, boost::asio::buffer("from:ytftyfftyf@ytcuuyfv.com\nto:darks1de11@hotmail.com\nsubject: oiwefwnefiewnfion\njust a test\r\n.\r\n")); //boost::asio::write(_socket, boost::asio::buffer(queueData)); } //return queueData; } void connectHandler(const boost::system::error_code &error){ if(!error){ std::cout << "Connected!" << std::endl; loadQueue(queuePath); //boost::asio::write(_socket, boost::asio::buffer("\r\n.\r\n")); _socket.async_read_some(boost::asio::buffer(buffer), readHandler); } else{ std::cout << "Could not connect!" << std::endl; } } void resolveHandler(const boost::system::error_code &error, boost::asio::ip::tcp::resolver::iterator iterator){ if (!error){ _socket.async_connect(*iterator, connectHandler); } else{ std::cout << "Could not resolve!" << std::endl; } } int main(int argc, const char * argv[]){ std::string receivingServer = "mx1.hotmail.com"; std::cout << "Resolving: " << receivingServer << std::endl; description.add_options() ("queue,q", boost::program_options::value<std::string>(), "Queue path.") ("help,h", "Help"); boost::program_options::variables_map optionMap; boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(description).run(), optionMap); boost::program_options::notify(optionMap); if(optionMap.count("help")){ std::cout << description << std::endl; return 0; } if(optionMap.count("queue")){ queuePath = optionMap["queue"].as<std::string>(); boost::asio::ip::tcp::resolver::query query(receivingServer, "smtp"); _resolver.async_resolve(query, resolveHandler); _ioService.run(); } // insert code here... //std::cout << "Hello, World!\n"; //_socket.open(boost::asio::ip::tcp::v4()); //_socket.bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(clientAddress), 0)); //_socket.async_connect(*endpointIterator++, boost::bind(&TCPClient::handleConnect, this, boost::asio::placeholders::error)); return 0; } <|endoftext|>
<commit_before>188fe68c-2d3f-11e5-9e1a-c82a142b6f9b<commit_msg>18e8e930-2d3f-11e5-960c-c82a142b6f9b<commit_after>18e8e930-2d3f-11e5-960c-c82a142b6f9b<|endoftext|>
<commit_before>2e7686ab-2e4f-11e5-9d53-28cfe91dbc4b<commit_msg>2e7f5782-2e4f-11e5-a998-28cfe91dbc4b<commit_after>2e7f5782-2e4f-11e5-a998-28cfe91dbc4b<|endoftext|>
<commit_before>3dfff48a-2e4f-11e5-b311-28cfe91dbc4b<commit_msg>3e057e3d-2e4f-11e5-8cae-28cfe91dbc4b<commit_after>3e057e3d-2e4f-11e5-8cae-28cfe91dbc4b<|endoftext|>
<commit_before>#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <stdio.h> #include <string> #include "include/logging/enumCvType.hpp" #include "include/filters/selectMode.hpp" #include "include/filters/gaussianBlurWindows.hpp" #include "include/filters/hsvColorThresholdWindows.hpp" #include "include/filters/dilateErodeWindows.hpp" #include "include/filters/cannyEdgeDetectWindows.hpp" #include "include/filters/laplacianSharpenWindows.hpp" #include "include/filters/houghLinesWindows.hpp" #include "include/filters/mergeFinalWindows.hpp" #include "include/filters/depthDistanceWindows.hpp" void drawBoundedRects(cv::Mat& src, int thresh) { cv::Mat threshold_output; std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; // Convert src to gray format cv::cvtColor(src, threshold_output, CV_BGR2GRAY); // Detect edges using Threshold cv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY); // Find contours cv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0)); // Get the moments std::vector<cv::Moments> mu(contours.size() ); for( int i = 0; i < contours.size(); i++ ) { mu[i] = moments( contours[i], false ); } // Get the mass centers: cv::vector<cv::Point2f> mc( contours.size() ); for( int i = 0; i < contours.size(); i++ ) { mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); } // Approximate contours to rotated rectangles and ellipses std::vector<cv::RotatedRect> minRect( contours.size()); for(int i = 0; i < contours.size(); i++) { minRect[i] = cv::minAreaRect(cv::Mat(contours[i])); } // Draw polygonal contour + bounding rects cv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3); for(int i = 0; i < contours.size(); i++) { cv::Scalar color = cv::Scalar(0, 0, 255); cv::drawContours(drawing, contours, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point()); cv::Point2f rect_points[4]; minRect[i].points(rect_points); for(int j = 0; j < 4; j++) { cv::line(drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8); } } // Calculate the area with the moments 00 and compare with the result of the OpenCV function printf("\t Info: Area and Contour Length \n"); for( int i = 0; i< contours.size(); i++ ) { printf(" * Contour[%2d] - Area (M_00) = %4.2f - Area OpenCV: %4.2f - Length: %4.2f\n", i, mu[i].m00, contourArea(contours[i]), arcLength( contours[i], true ) ); cv::Scalar color = cv::Scalar(0, 255, 0); cv::drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() ); } // Show in a window cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE); cv::imshow("Contours", drawing); } int main( int argc, char *argv[]) { // Parameters for selecting which filters to apply int blur = 0; int color = 0; int dilate_erode = 0; int edge = 0; int laplacian = 0; int hough = 0; int depth_dist = 0; int merge = 0; // Parameters for applying filters even if windows are closed int apply_blur = 1; int apply_color = 1; int apply_dilate_erode = 0; int apply_edge = 1; int apply_laplacian = 0; int apply_hough = 0; int apply_depth_dist = 0; int apply_merge = 1; // gaussianBlur parameters int blur_ksize = 7; int sigmaX = 10; int sigmaY = 10; // hsvColorThreshold parameters int hMin = 130; int hMax = 190; int sMin = 10; int sMax = 30; int vMin = 85; int vMax = 100; int debugMode = 0; // 0 is none, 1 is debug mode int bitAnd = 1; // 0 is none, 1 is bitAnd between h, s, and v // dilateErode parameters int holes = 0; int noise = 0; int size = 1; cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS, cv::Size(2 * size + 1, 2 * size + 1), cv::Point(size, size) ); // cannyEdgeDetect parameters int threshLow = 100; int threshHigh = 300; // laplacianSharpen parameters int laplacian_ksize = 3; int scale = 1; // optional scale value added to image int delta = 0; // optional delta value added to image int ddepth = CV_16S; // houghLines parameters int rho = 1; int theta = 180; int threshold = 50; int lineMin = 50; int maxGap = 10; // mergeFinal parameters int weight1 = 100; // decide weighted sums of original rgb feed to filtered rgb feed; values = out of 100 int weight2 = 100; std::cout << "\n"; std::cout << " =========== FILTER LIST =========== " << "\n"; std::cout << "| |" << "\n"; std::cout << "| (0) No Filter |" << "\n"; std::cout << "| (1) Gaussian Blur Filter |" << "\n"; std::cout << "| (2) HSV Color Filter |" << "\n"; std::cout << "| (3) Dilate and Erode Filter |" << "\n"; std::cout << "| (4) Canny Edge Detection Filter |" << "\n"; std::cout << "| (5) Laplacian Sharpen Filter |" << "\n"; std::cout << "| (6) Hough Lines Filter |" << "\n"; std::cout << "| (7) Merge Final Outputs |" << "\n"; std::cout << "| |" << "\n"; std::cout << " =================================== " << "\n"; std::cout << "\n"; std::cout << "\n"; std::cout << " ============== NOTICE ============= " << "\n"; std::cout << "| |" << "\n"; std::cout << "| Press 'q' to quit without saving |" << "\n"; std::cout << "| Press ' ' to pause |" << "\n"; std::cout << "| |" << "\n"; std::cout << " =================================== " << "\n"; std::cout << "\n"; cv::VideoCapture camera(0); if( !camera.isOpened() && (argc < 2) ) { std::cout << "Error - Unable to open Camera at Port 0" << std::endl; return -1; } // Matrices for holding image data cv::Mat rgb, rgb_orig; cv::Mat image; char kill = ' '; // Press q to quit the program int thresh = 120; while ((kill != 'q') && (kill != 's')) { if (kill == ' ') // Press space to pause program, then any key to resume { cv::waitKey(0); } selectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge); if (argc > 2) // Use images { rgb = cv::imread(argv[1]); rgb_orig = rgb.clone(); // Clone rgb input in order to merge at end if (!rgb.data || !rgb_orig.data) // No data { std::cout << "No image data" << std::endl; return -1; } } else { camera >> rgb; rgb_orig = rgb.clone(); } cv::imshow("BGR Feed", rgb); rgb.copyTo(image); cv::namedWindow("Source", CV_WINDOW_AUTOSIZE); cv::createTrackbar("Threshold:", "Source", &thresh, 255); // Filters are only applied if last parameter is true, otherwise their windows are destroyed gaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur); hsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color); dilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode); drawBoundedRects(image, thresh); cannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge); laplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian); #if 0 // List sizes of image cv::Size imageSize = image.size(); std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n"; #endif houghLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough); #if 0 // List sizes of image imageSize = image.size(); std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n"; #endif mergeFinalWindows(rgb_orig, image, weight1, weight2, apply_merge, merge); kill = cv::waitKey(5); } return 0; } <commit_msg>Fix compile errors<commit_after>#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <stdio.h> #include <string> #include "include/logging/enumCvType.hpp" #include "include/filters/selectMode.hpp" #include "include/filters/gaussianBlurWindows.hpp" #include "include/filters/hsvColorThresholdWindows.hpp" #include "include/filters/dilateErodeWindows.hpp" #include "include/filters/cannyEdgeDetectWindows.hpp" #include "include/filters/laplacianSharpenWindows.hpp" #include "include/filters/houghLinesWindows.hpp" #include "include/filters/mergeFinalWindows.hpp" #include "include/filters/depthDistanceWindows.hpp" void drawBoundedRects(cv::Mat& src, int thresh) { cv::Mat threshold_output; std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; // Convert src to gray format cv::cvtColor(src, threshold_output, CV_BGR2GRAY); // Detect edges using Threshold cv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY); // Find contours cv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0)); // Get the moments std::vector<cv::Moments> mu(contours.size() ); for( int i = 0; i < contours.size(); i++ ) { mu[i] = moments( contours[i], false ); } // Get the mass centers: std::vector<cv::Point2f> mc( contours.size() ); for( int i = 0; i < contours.size(); i++ ) { mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); } // Approximate contours to rotated rectangles and ellipses std::vector<cv::RotatedRect> minRect( contours.size()); for(int i = 0; i < contours.size(); i++) { minRect[i] = cv::minAreaRect(cv::Mat(contours[i])); } // Draw polygonal contour + bounding rects cv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3); for(int i = 0; i < contours.size(); i++) { cv::Scalar color = cv::Scalar(0, 0, 255); cv::drawContours(drawing, contours, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point()); cv::Point2f rect_points[4]; minRect[i].points(rect_points); for(int j = 0; j < 4; j++) { cv::line(drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8); } } // Calculate the area with the moments 00 and compare with the result of the OpenCV function printf("\t Info: Area and Contour Length \n"); for( int i = 0; i< contours.size(); i++ ) { printf(" * Contour[%2d] - Area (M_00) = %4.2f - Area OpenCV: %4.2f - Length: %4.2f\n", i, mu[i].m00, contourArea(contours[i]), arcLength( contours[i], true ) ); cv::Scalar color = cv::Scalar(0, 255, 0); cv::drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() ); } // Show in a window cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE); cv::imshow("Contours", drawing); } int main( int argc, char *argv[]) { // Parameters for selecting which filters to apply int blur = 0; int color = 0; int dilate_erode = 0; int edge = 0; int laplacian = 0; int hough = 0; int depth_dist = 0; int merge = 0; // Parameters for applying filters even if windows are closed int apply_blur = 1; int apply_color = 1; int apply_dilate_erode = 0; int apply_edge = 1; int apply_laplacian = 0; int apply_hough = 0; int apply_depth_dist = 0; int apply_merge = 1; // gaussianBlur parameters int blur_ksize = 7; int sigmaX = 10; int sigmaY = 10; // hsvColorThreshold parameters int hMin = 130; int hMax = 190; int sMin = 10; int sMax = 30; int vMin = 85; int vMax = 100; int debugMode = 0; // 0 is none, 1 is debug mode int bitAnd = 1; // 0 is none, 1 is bitAnd between h, s, and v // dilateErode parameters int holes = 0; int noise = 0; int size = 1; cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS, cv::Size(2 * size + 1, 2 * size + 1), cv::Point(size, size) ); // cannyEdgeDetect parameters int threshLow = 100; int threshHigh = 300; // laplacianSharpen parameters int laplacian_ksize = 3; int scale = 1; // optional scale value added to image int delta = 0; // optional delta value added to image int ddepth = CV_16S; // houghLines parameters int rho = 1; int theta = 180; int threshold = 50; int lineMin = 50; int maxGap = 10; // mergeFinal parameters int weight1 = 100; // decide weighted sums of original rgb feed to filtered rgb feed; values = out of 100 int weight2 = 100; std::cout << "\n"; std::cout << " =========== FILTER LIST =========== " << "\n"; std::cout << "| |" << "\n"; std::cout << "| (0) No Filter |" << "\n"; std::cout << "| (1) Gaussian Blur Filter |" << "\n"; std::cout << "| (2) HSV Color Filter |" << "\n"; std::cout << "| (3) Dilate and Erode Filter |" << "\n"; std::cout << "| (4) Canny Edge Detection Filter |" << "\n"; std::cout << "| (5) Laplacian Sharpen Filter |" << "\n"; std::cout << "| (6) Hough Lines Filter |" << "\n"; std::cout << "| (7) Merge Final Outputs |" << "\n"; std::cout << "| |" << "\n"; std::cout << " =================================== " << "\n"; std::cout << "\n"; std::cout << "\n"; std::cout << " ============== NOTICE ============= " << "\n"; std::cout << "| |" << "\n"; std::cout << "| Press 'q' to quit without saving |" << "\n"; std::cout << "| Press ' ' to pause |" << "\n"; std::cout << "| |" << "\n"; std::cout << " =================================== " << "\n"; std::cout << "\n"; cv::VideoCapture camera(0); if( !camera.isOpened() && (argc < 2) ) { std::cout << "Error - Unable to open Camera at Port 0" << std::endl; return -1; } // Matrices for holding image data cv::Mat rgb, rgb_orig; cv::Mat image; char kill = ' '; // Press q to quit the program int thresh = 120; while ((kill != 'q') && (kill != 's')) { if (kill == ' ') // Press space to pause program, then any key to resume { cv::waitKey(0); } selectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge); if (argc > 2) // Use images { rgb = cv::imread(argv[1]); rgb_orig = rgb.clone(); // Clone rgb input in order to merge at end if (!rgb.data || !rgb_orig.data) // No data { std::cout << "No image data" << std::endl; return -1; } } else { camera >> rgb; rgb_orig = rgb.clone(); } cv::imshow("BGR Feed", rgb); rgb.copyTo(image); cv::namedWindow("Source", CV_WINDOW_AUTOSIZE); cv::createTrackbar("Threshold:", "Source", &thresh, 255); // Filters are only applied if last parameter is true, otherwise their windows are destroyed gaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur); hsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color); dilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode); drawBoundedRects(image, thresh); cannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge); laplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian); #if 0 // List sizes of image cv::Size imageSize = image.size(); std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n"; #endif houghLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough); #if 0 // List sizes of image imageSize = image.size(); std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n"; #endif mergeFinalWindows(rgb_orig, image, weight1, weight2, apply_merge, merge); kill = cv::waitKey(5); } return 0; } <|endoftext|>
<commit_before>990ab057-2e4f-11e5-b303-28cfe91dbc4b<commit_msg>9912b47d-2e4f-11e5-9d80-28cfe91dbc4b<commit_after>9912b47d-2e4f-11e5-9d80-28cfe91dbc4b<|endoftext|>
<commit_before>5bf67428-2d16-11e5-af21-0401358ea401<commit_msg>5bf67429-2d16-11e5-af21-0401358ea401<commit_after>5bf67429-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>6eb49f5c-5216-11e5-81c2-6c40088e03e4<commit_msg>6ebb50de-5216-11e5-b0ff-6c40088e03e4<commit_after>6ebb50de-5216-11e5-b0ff-6c40088e03e4<|endoftext|>
<commit_before>1d00af80-2e4f-11e5-96f0-28cfe91dbc4b<commit_msg>1d0afb00-2e4f-11e5-8a6d-28cfe91dbc4b<commit_after>1d0afb00-2e4f-11e5-8a6d-28cfe91dbc4b<|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <sstream> #include <iomanip> #include "DbfTable.h" #include "Version.h" using namespace std; typedef enum Mode { kVersion, kSummary, kCsv } Mode; void print_usage() { cout << "usage: dbf2csv [-h|-v|-s|-c|-k] filename" << endl; cout << " -h = print this message" << endl; cout << " -v = print the program version" << endl; cout << " -s = print summary information" << endl; cout << " -c = create a CSV file" << endl; cout << " -k = skip deleted records (default: true)" << endl; cout << " -l = output csv header names in lowercase (default: false)" << endl; } int main(int argc, char *argv[]) { Mode mode = kVersion; bool skip_deleted = true; bool lowercase_header_names = false; int opt; while ((opt = getopt(argc, argv, "hvsck:l:")) != -1) { switch (opt) { case 'v': mode = kVersion; break; case 's': mode = kSummary; break; case 'c': mode = kCsv; break; case 'k': skip_deleted = (optarg[0] == 'Y' || optarg[0] == 'y'); break; case 'l': lowercase_header_names = (optarg[0] == 'Y' || optarg[0] == 'y'); break; case 'h': print_usage(); return 0; default: cerr << "Unrecognized option: '" << optopt << "'" << endl; print_usage(); return 1; } } if (mode == kVersion) { cout << "dbf2csv version: " << Version << endl; print_usage(); return 0; } string dbf_filename = argv[optind]; DbfTablePtr dbf_table = DbfTablePtr(new DbfTable(dbf_filename, skip_deleted)); if (!dbf_table->good()) { cerr << "Unable to open file: " << dbf_filename << endl; return 1; } if (mode == kSummary) { cout << "Database: " << dbf_filename << endl; const DbfHeaderPtr header = dbf_table->header(); cout << "Type: (" << hex << header->version() << dec << ") " << header->version_description() << endl; cout << "Memo File: " << (dbf_table->has_memo_file() ? "true" : "false") << endl; cout << "Records: " << header->record_count() << endl; cout << "Last updated at: " << header->updated_at() << endl; cout << endl; cout << "Fields:" << endl; cout << "Name Type Length Decimal" << endl; cout << "------------------------------------------------------------------------------" << endl; std::vector<DbfColumnPtr> columns = dbf_table->columns(); for (auto it = std::begin(columns); it != std::end(columns); ++it) { DbfColumnPtr column(*it); cout << left << setw(17) << column->name(); cout << left << setw(11) << (char)column->type(); cout << left << setw(11) << column->length(); cout << left << column->decimal(); cout << endl; } } else { dbf_table->to_csv(cout, lowercase_header_names); } return 0; } <commit_msg>Allows specifying relative filepath in command line<commit_after>#include <iostream> #include <vector> #include <sstream> #include <iomanip> #include <boost/filesystem/operations.hpp> #include "DbfTable.h" #include "Version.h" using namespace std; typedef enum Mode { kVersion, kSummary, kCsv } Mode; void print_usage() { cout << "usage: dbf2csv [-h|-v|-s|-c|-k] filename" << endl; cout << " -h = print this message" << endl; cout << " -v = print the program version" << endl; cout << " -s = print summary information" << endl; cout << " -c = create a CSV file" << endl; cout << " -k = skip deleted records (default: true)" << endl; cout << " -l = output csv header names in lowercase (default: false)" << endl; } int main(int argc, char *argv[]) { Mode mode = kVersion; bool skip_deleted = true; bool lowercase_header_names = false; int opt; while ((opt = getopt(argc, argv, "hvsck:l:")) != -1) { switch (opt) { case 'v': mode = kVersion; break; case 's': mode = kSummary; break; case 'c': mode = kCsv; break; case 'k': skip_deleted = (optarg[0] == 'Y' || optarg[0] == 'y'); break; case 'l': lowercase_header_names = (optarg[0] == 'Y' || optarg[0] == 'y'); break; case 'h': print_usage(); return 0; default: cerr << "Unrecognized option: '" << optopt << "'" << endl; print_usage(); return 1; } } if (mode == kVersion) { cout << "dbf2csv version: " << Version << endl; print_usage(); return 0; } string dbf_filename = boost::filesystem::absolute(argv[optind]).string(); DbfTablePtr dbf_table = DbfTablePtr(new DbfTable(dbf_filename, skip_deleted)); if (!dbf_table->good()) { cerr << "Unable to open file: " << dbf_filename << endl; return 1; } if (mode == kSummary) { cout << "Database: " << dbf_filename << endl; const DbfHeaderPtr header = dbf_table->header(); cout << "Type: (" << hex << header->version() << dec << ") " << header->version_description() << endl; cout << "Memo File: " << (dbf_table->has_memo_file() ? "true" : "false") << endl; cout << "Records: " << header->record_count() << endl; cout << "Last updated at: " << header->updated_at() << endl; cout << endl; cout << "Fields:" << endl; cout << "Name Type Length Decimal" << endl; cout << "------------------------------------------------------------------------------" << endl; std::vector<DbfColumnPtr> columns = dbf_table->columns(); for (auto it = std::begin(columns); it != std::end(columns); ++it) { DbfColumnPtr column(*it); cout << left << setw(17) << column->name(); cout << left << setw(11) << (char)column->type(); cout << left << setw(11) << column->length(); cout << left << column->decimal(); cout << endl; } } else { dbf_table->to_csv(cout, lowercase_header_names); } return 0; } <|endoftext|>
<commit_before>5f8949b7-2d16-11e5-af21-0401358ea401<commit_msg>5f8949b8-2d16-11e5-af21-0401358ea401<commit_after>5f8949b8-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>3ba64bd8-5216-11e5-a35d-6c40088e03e4<commit_msg>3bad3ee8-5216-11e5-ad9f-6c40088e03e4<commit_after>3bad3ee8-5216-11e5-ad9f-6c40088e03e4<|endoftext|>
<commit_before>907a10d0-35ca-11e5-9761-6c40088e03e4<commit_msg>9080710a-35ca-11e5-aadc-6c40088e03e4<commit_after>9080710a-35ca-11e5-aadc-6c40088e03e4<|endoftext|>
<commit_before>78eab502-2d53-11e5-baeb-247703a38240<commit_msg>78eb3612-2d53-11e5-baeb-247703a38240<commit_after>78eb3612-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>8101ede3-2e4f-11e5-b5bc-28cfe91dbc4b<commit_msg>81076d47-2e4f-11e5-96cf-28cfe91dbc4b<commit_after>81076d47-2e4f-11e5-96cf-28cfe91dbc4b<|endoftext|>
<commit_before>abd32e5e-2747-11e6-8b00-e0f84713e7b8<commit_msg>Typical bobby<commit_after>abeaad87-2747-11e6-b2cc-e0f84713e7b8<|endoftext|>
<commit_before>8cb7189c-4b02-11e5-8dcc-28cfe9171a43<commit_msg>Too poor for Dropbox<commit_after>8cc2bf9e-4b02-11e5-85a7-28cfe9171a43<|endoftext|>
<commit_before>cbc348eb-2e4e-11e5-99b8-28cfe91dbc4b<commit_msg>cbca9230-2e4e-11e5-84e1-28cfe91dbc4b<commit_after>cbca9230-2e4e-11e5-84e1-28cfe91dbc4b<|endoftext|>
<commit_before>a54cd580-2e4f-11e5-853d-28cfe91dbc4b<commit_msg>a55436ca-2e4f-11e5-8089-28cfe91dbc4b<commit_after>a55436ca-2e4f-11e5-8089-28cfe91dbc4b<|endoftext|>
<commit_before>071ac51c-2f67-11e5-9118-6c40088e03e4<commit_msg>07218278-2f67-11e5-b540-6c40088e03e4<commit_after>07218278-2f67-11e5-b540-6c40088e03e4<|endoftext|>
<commit_before>d65e47ca-2e4e-11e5-8925-28cfe91dbc4b<commit_msg>d664be82-2e4e-11e5-8196-28cfe91dbc4b<commit_after>d664be82-2e4e-11e5-8196-28cfe91dbc4b<|endoftext|>
<commit_before>65546fd2-2fa5-11e5-9f1b-00012e3d3f12<commit_msg>65564494-2fa5-11e5-b531-00012e3d3f12<commit_after>65564494-2fa5-11e5-b531-00012e3d3f12<|endoftext|>
<commit_before>999f3f78-2e4f-11e5-897b-28cfe91dbc4b<commit_msg>99a5dc7a-2e4f-11e5-8f38-28cfe91dbc4b<commit_after>99a5dc7a-2e4f-11e5-8f38-28cfe91dbc4b<|endoftext|>
<commit_before>eb99ae14-585a-11e5-85b3-6c40088e03e4<commit_msg>eba4dd90-585a-11e5-9caf-6c40088e03e4<commit_after>eba4dd90-585a-11e5-9caf-6c40088e03e4<|endoftext|>
<commit_before>#include "opencv2/opencv.hpp" #include <stdio.h> /* defines FILENAME_MAX */ #ifdef WINDOWS #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif using namespace cv; void clampRectangleToVideoDemensions(Rect &searchFrame,const Size &videoDimensions) { if(searchFrame.x <= 0) searchFrame.x = 0; if(searchFrame.x >= videoDimensions.width-searchFrame.width) searchFrame.x = videoDimensions.width-searchFrame.width; if(searchFrame.y <= 0) searchFrame.y = 0; if(searchFrame.y >= videoDimensions.height-searchFrame.height) searchFrame.y = videoDimensions.height-searchFrame.height; } Rect crateSearchFrameFromRegionOfInterest(const Rect &regionOfInterest,const Size &videoDimensions) { Rect searchFrame( regionOfInterest.x-(regionOfInterest.width/2), regionOfInterest.y-(regionOfInterest.height/2), 2*regionOfInterest.width, 2*regionOfInterest.height); clampRectangleToVideoDemensions(searchFrame, videoDimensions); return searchFrame; } void DrawPoint( Mat &img,const Point &center,const Scalar &Color) { int thickness = -1; int lineType = 1; double radius = 0.5; circle( img, center, radius, Color, thickness, lineType ); } void drawRectangle(const Rect &rectangleToDraw,Mat &matrixToDrawTheRectangleIn,const Scalar &color) { line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x,rectangleToDraw.y), Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y), Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height), Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height), Point(rectangleToDraw.x,rectangleToDraw.y), color, 0,1); } Point match(const Mat &SearchFrameMatrix,const Mat &RegionOfInterestMatrix, Mat &result) { int match_method = CV_TM_CCOEFF; int resultCols = SearchFrameMatrix.cols - RegionOfInterestMatrix.cols + 1; int resultRows = SearchFrameMatrix.rows - RegionOfInterestMatrix.rows + 1; result = Mat(resultCols,resultRows,CV_32FC1); /// Do the Matching and Normalize matchTemplate( SearchFrameMatrix, RegionOfInterestMatrix, result, match_method ); normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat()); double minVal, maxVal; Point minLoc, maxLoc, matchLoc; minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc); /// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED ) { matchLoc = minLoc; rectangle( result, Point( matchLoc.x - result.cols/10 , matchLoc.y - result.rows/10 ), Point( matchLoc.x + result.cols/10 , matchLoc.y + result.rows/10 ), Scalar::all(255), 1, 1, 0 ); } else { matchLoc = maxLoc; rectangle( result, Point( matchLoc.x - result.cols/10 , matchLoc.y - result.rows/10 ), Point( matchLoc.x + result.cols/10 , matchLoc.y + result.rows/10 ), Scalar::all(0), 1, 1, 0 ); } //printf("matchLoc: = (%d,%d)",matchLoc.x,matchLoc.y); //printf("matchLoc: = (%f,%f)",double(SearchFrameMatrix.cols - result.cols)/2.0,double(SearchFrameMatrix.rows-result.rows)/2.0); Point diff((SearchFrameMatrix.cols - result.cols)/2 + 1 ,(SearchFrameMatrix.rows-result.rows)/2 + 1); Point retVal(matchLoc + diff); return retVal; } Point match_2(const Mat &InnerFrame,const Mat &OuterFrame) { int outerX = OuterFrame.cols; int outerY = OuterFrame.rows; int innerX = InnerFrame.cols; int innerY = InnerFrame.rows; int resultCols = OuterFrame.cols - InnerFrame.cols + 1; int resultRows = OuterFrame.rows - InnerFrame.rows + 1; float result[resultCols * resultRows]; float minDifference = FLT_MAX; Point posMinDifferenceInOuterFrame; for(int leftUpperY = 0; leftUpperY < outerY - innerY; leftUpperY++) { for(int leftUpperX = 0; leftUpperX < outerX - innerX; leftUpperX++) { float difference = 0; for(int offsetX = 0; offsetX <= innerX; offsetX++) { for(int offsetY = 0; offsetY <= innerY; offsetY++) { Point posInOuterFrame = Point(leftUpperX + offsetX, leftUpperY + offsetY); Point posInInnerFrame = Point(offsetX, offsetY); difference += OuterFrame.at<int>(posInOuterFrame) - InnerFrame.at<int>(posInInnerFrame); } } if(difference < minDifference) { minDifference = difference; // get the mid-Point of the innerFrame in outerFrame-Coordinates posMinDifferenceInOuterFrame = Point(leftUpperX + innerX/2, leftUpperY + innerY/2); } result[leftUpperX + leftUpperY * resultCols]; } } //minDifference, result hold additional information return posMinDifferenceInOuterFrame; } void createNewRegionOfInterestFromMatchLocation(const Point &matchLoc,Rect &regionOfInterest,const Size &videoDimensions) { regionOfInterest = Rect( matchLoc.x-regionOfInterest.width/2, matchLoc.y-regionOfInterest.height/2, regionOfInterest.width, regionOfInterest.height); clampRectangleToVideoDemensions(regionOfInterest,videoDimensions); } int main(int, char**) { //diable printf() buffering setbuf(stdout, NULL); printf("press 'c' to close\n"); char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { return -1; } cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */ std::string videoFileName = "videos/trafficInChina.mp4"; VideoCapture videoHandle(videoFileName); // open the default camera if(!videoHandle.isOpened()) // check if we succeeded { printf ("Could not find File: %s/%s\n", cCurrentPath,videoFileName.c_str()); return -1; } Size videoDimensions = Size((int) videoHandle.get(CV_CAP_PROP_FRAME_WIDTH), (int) videoHandle.get(CV_CAP_PROP_FRAME_HEIGHT)); printf("VideoWidth: %d,VideoHeight: %d\n",videoDimensions.width,videoDimensions.height); unsigned int numberOfVideoFrames = videoHandle.get(CV_CAP_PROP_FRAME_COUNT); printf("number of Frames: %d\n",numberOfVideoFrames); std::string drawFrameWindowName("DrawFrame"),ROIWindowName("ROIWindow"),matchingWindowName("ResultOfMatching"); namedWindow(drawFrameWindowName,CV_WINDOW_AUTOSIZE); // namedWindow(ROIWindowName,CV_WINDOW_AUTOSIZE); // namedWindow(matchingWindowName,CV_WINDOW_AUTOSIZE); // define location of sub matrices in image Rect regionOfInterest( videoDimensions.width/2-100, videoDimensions.height/2-50, 50, 50 ); Scalar regionOfInterestColor(255,0,0); Rect searchFrame; Scalar searchFrameColor(0,255,0); cv::Point *bestMatchPositionsByFrame = new cv::Point[numberOfVideoFrames]; // Mat edges; double oldMinVal, oldMaxVal; Point oldMinLoc, oldMaxLoc, oldMatchLoc; bool stopTheProgramm = false; for(unsigned int i = 0; i < numberOfVideoFrames; ++i) { Mat frame; // get a new frame from camera videoHandle >> frame; // create Matrix we can draw into without overwriting data of the original image Mat drawFrame; frame.copyTo(drawFrame); DrawPoint(drawFrame,oldMatchLoc,Scalar(0,255,255)); drawRectangle(regionOfInterest,drawFrame,regionOfInterestColor); Mat RegionOfInterestMatrix(frame,regionOfInterest); searchFrame = crateSearchFrameFromRegionOfInterest(regionOfInterest,videoDimensions); drawRectangle(searchFrame,drawFrame,searchFrameColor); Mat SearchFrameMatrix(frame,searchFrame); Mat result; Point matchLoc = match(SearchFrameMatrix,RegionOfInterestMatrix, result); // the returned matchLocation is in the wrong Coordinate System, we need to transform it back matchLoc.x += searchFrame.x; matchLoc.y += searchFrame.y; oldMatchLoc = matchLoc; DrawPoint(drawFrame,matchLoc,Scalar(0,0,255)); // createNewRegionOfInterestFromMatchLocation(matchLoc, regionOfInterest, videoDimensions); imshow(drawFrameWindowName,drawFrame); int key = waitKey(100000); switch(key) { case ' ': continue; break; case 'c': stopTheProgramm = true; break; } if(stopTheProgramm) break; } delete[] bestMatchPositionsByFrame; // the camera will be deinitialized automatically in VideoCapture destructor return 0; } <commit_msg>added additional debug windows<commit_after>#include "opencv2/opencv.hpp" #include <stdio.h> /* defines FILENAME_MAX */ #ifdef WINDOWS #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif using namespace cv; void clampRectangleToVideoDemensions(Rect &searchFrame,const Size &videoDimensions) { if(searchFrame.x <= 0) searchFrame.x = 0; if(searchFrame.x >= videoDimensions.width-searchFrame.width) searchFrame.x = videoDimensions.width-searchFrame.width; if(searchFrame.y <= 0) searchFrame.y = 0; if(searchFrame.y >= videoDimensions.height-searchFrame.height) searchFrame.y = videoDimensions.height-searchFrame.height; } Rect crateSearchFrameFromRegionOfInterest(const Rect &regionOfInterest,const Size &videoDimensions) { Rect searchFrame( regionOfInterest.x-(regionOfInterest.width/2), regionOfInterest.y-(regionOfInterest.height/2), 2*regionOfInterest.width, 2*regionOfInterest.height); clampRectangleToVideoDemensions(searchFrame, videoDimensions); return searchFrame; } void DrawPoint( Mat &img,const Point &center,const Scalar &Color) { int thickness = -1; int lineType = 1; double radius = 0.5; circle( img, center, radius, Color, thickness, lineType ); } void drawRectangle(const Rect &rectangleToDraw,Mat &matrixToDrawTheRectangleIn,const Scalar &color) { line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x,rectangleToDraw.y), Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y), Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height), Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height), Point(rectangleToDraw.x,rectangleToDraw.y), color, 0,1); } Point match(const Mat &SearchFrameMatrix,const Mat &RegionOfInterestMatrix, Mat &result) { int match_method = CV_TM_CCOEFF; int resultCols = SearchFrameMatrix.cols - RegionOfInterestMatrix.cols + 1; int resultRows = SearchFrameMatrix.rows - RegionOfInterestMatrix.rows + 1; result = Mat(resultCols,resultRows,CV_32FC1); /// Do the Matching and Normalize matchTemplate( SearchFrameMatrix, RegionOfInterestMatrix, result, match_method ); normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat()); double minVal, maxVal; Point minLoc, maxLoc, matchLoc; minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc); /// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED ) { matchLoc = minLoc; rectangle( result, Point( matchLoc.x - result.cols/10 , matchLoc.y - result.rows/10 ), Point( matchLoc.x + result.cols/10 , matchLoc.y + result.rows/10 ), Scalar::all(255), 1, 1, 0 ); } else { matchLoc = maxLoc; rectangle( result, Point( matchLoc.x - result.cols/10 , matchLoc.y - result.rows/10 ), Point( matchLoc.x + result.cols/10 , matchLoc.y + result.rows/10 ), Scalar::all(0), 1, 1, 0 ); } //printf("matchLoc: = (%d,%d)",matchLoc.x,matchLoc.y); //printf("matchLoc: = (%f,%f)",double(SearchFrameMatrix.cols - result.cols)/2.0,double(SearchFrameMatrix.rows-result.rows)/2.0); Point diff((SearchFrameMatrix.cols - result.cols)/2 + 1 ,(SearchFrameMatrix.rows-result.rows)/2 + 1); Point retVal(matchLoc + diff); return retVal; } Point match_2(const Mat &InnerFrame,const Mat &OuterFrame) { int outerX = OuterFrame.cols; int outerY = OuterFrame.rows; int innerX = InnerFrame.cols; int innerY = InnerFrame.rows; int resultCols = OuterFrame.cols - InnerFrame.cols + 1; int resultRows = OuterFrame.rows - InnerFrame.rows + 1; float result[resultCols * resultRows]; float minDifference = FLT_MAX; Point posMinDifferenceInOuterFrame; for(int leftUpperY = 0; leftUpperY < outerY - innerY; leftUpperY++) { for(int leftUpperX = 0; leftUpperX < outerX - innerX; leftUpperX++) { float difference = 0; for(int offsetX = 0; offsetX <= innerX; offsetX++) { for(int offsetY = 0; offsetY <= innerY; offsetY++) { Point posInOuterFrame = Point(leftUpperX + offsetX, leftUpperY + offsetY); Point posInInnerFrame = Point(offsetX, offsetY); difference += OuterFrame.at<int>(posInOuterFrame) - InnerFrame.at<int>(posInInnerFrame); } } if(difference < minDifference) { minDifference = difference; // get the mid-Point of the innerFrame in outerFrame-Coordinates posMinDifferenceInOuterFrame = Point(leftUpperX + innerX/2, leftUpperY + innerY/2); } result[leftUpperX + leftUpperY * resultCols]; } } //minDifference, result hold additional information return posMinDifferenceInOuterFrame; } void createNewRegionOfInterestFromMatchLocation(const Point &matchLoc,Rect &regionOfInterest,const Size &videoDimensions) { regionOfInterest = Rect( matchLoc.x-regionOfInterest.width/2, matchLoc.y-regionOfInterest.height/2, regionOfInterest.width, regionOfInterest.height); clampRectangleToVideoDemensions(regionOfInterest,videoDimensions); } int main(int, char**) { //diable printf() buffering setbuf(stdout, NULL); printf("press 'c' to close\n"); char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { return -1; } cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */ std::string videoFileName = "videos/trafficInChina.mp4"; VideoCapture videoHandle(videoFileName); // open the default camera if(!videoHandle.isOpened()) // check if we succeeded { printf ("Could not find File: %s/%s\n", cCurrentPath,videoFileName.c_str()); return -1; } Size videoDimensions = Size((int) videoHandle.get(CV_CAP_PROP_FRAME_WIDTH), (int) videoHandle.get(CV_CAP_PROP_FRAME_HEIGHT)); printf("VideoWidth: %d,VideoHeight: %d\n",videoDimensions.width,videoDimensions.height); unsigned int numberOfVideoFrames = videoHandle.get(CV_CAP_PROP_FRAME_COUNT); printf("number of Frames: %d\n",numberOfVideoFrames); std::string drawFrameWindowName("DrawFrame"),ROIWindowName("ROIWindow"),matchingWindowName("ResultOfMatching"); namedWindow(drawFrameWindowName,CV_WINDOW_AUTOSIZE); namedWindow(ROIWindowName,CV_WINDOW_AUTOSIZE); namedWindow(matchingWindowName,CV_WINDOW_AUTOSIZE); // define location of sub matrices in image Rect regionOfInterest( videoDimensions.width/2-100, videoDimensions.height/2-50, 50, 50 ); Scalar regionOfInterestColor(255,0,0); Rect searchFrame; Scalar searchFrameColor(0,255,0); cv::Point *bestMatchPositionsByFrame = new cv::Point[numberOfVideoFrames]; // Mat edges; double oldMinVal, oldMaxVal; Point oldMinLoc, oldMaxLoc, oldMatchLoc; bool stopTheProgramm = false; for(unsigned int i = 0; i < numberOfVideoFrames; ++i) { Mat frame; // get a new frame from camera videoHandle >> frame; // create Matrix we can draw into without overwriting data of the original image Mat drawFrame; frame.copyTo(drawFrame); DrawPoint(drawFrame,oldMatchLoc,Scalar(0,255,255)); drawRectangle(regionOfInterest,drawFrame,regionOfInterestColor); Mat RegionOfInterestMatrix(frame,regionOfInterest); searchFrame = crateSearchFrameFromRegionOfInterest(regionOfInterest,videoDimensions); drawRectangle(searchFrame,drawFrame,searchFrameColor); Mat SearchFrameMatrix(frame,searchFrame); Mat result; Point matchLoc = match(SearchFrameMatrix,RegionOfInterestMatrix, result); // the returned matchLocation is in the wrong Coordinate System, we need to transform it back matchLoc.x += searchFrame.x; matchLoc.y += searchFrame.y; oldMatchLoc = matchLoc; DrawPoint(drawFrame,matchLoc,Scalar(0,0,255)); // createNewRegionOfInterestFromMatchLocation(matchLoc, regionOfInterest, videoDimensions); Mat searchFrameZoomed(Point(256,256)); resize(Mat(drawFrame,searchFrame),searchFrameZoomed,Size(256,256)); imshow(ROIWindowName,searchFrameZoomed); Mat resultZoomed(Point(256,256)); resize(result,resultZoomed,Size(256,256)); imshow(matchingWindowName,resultZoomed); imshow(drawFrameWindowName,drawFrame); int key = waitKey(100000); switch(key) { case ' ': continue; break; case 'c': stopTheProgramm = true; break; } if(stopTheProgramm) break; } delete[] bestMatchPositionsByFrame; // the camera will be deinitialized automatically in VideoCapture destructor return 0; } <|endoftext|>
<commit_before>dcf4fda6-313a-11e5-af62-3c15c2e10482<commit_msg>dcfaf94a-313a-11e5-a911-3c15c2e10482<commit_after>dcfaf94a-313a-11e5-a911-3c15c2e10482<|endoftext|>
<commit_before>8d6dfd19-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd1a-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd1a-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>658f61c8-2e3a-11e5-b41a-c03896053bdd<commit_msg>65a8e1ca-2e3a-11e5-8b1d-c03896053bdd<commit_after>65a8e1ca-2e3a-11e5-8b1d-c03896053bdd<|endoftext|>
<commit_before>c6343dc0-327f-11e5-80de-9cf387a8033e<commit_msg>c63a3fe1-327f-11e5-ac54-9cf387a8033e<commit_after>c63a3fe1-327f-11e5-ac54-9cf387a8033e<|endoftext|>
<commit_before>c21b45f8-327f-11e5-ae08-9cf387a8033e<commit_msg>c2213df8-327f-11e5-9486-9cf387a8033e<commit_after>c2213df8-327f-11e5-9486-9cf387a8033e<|endoftext|>
<commit_before>c3177fbe-35ca-11e5-9611-6c40088e03e4<commit_msg>c31e242c-35ca-11e5-9533-6c40088e03e4<commit_after>c31e242c-35ca-11e5-9533-6c40088e03e4<|endoftext|>
<commit_before>a61d5b23-2e4f-11e5-99e6-28cfe91dbc4b<commit_msg>a62770c5-2e4f-11e5-a00a-28cfe91dbc4b<commit_after>a62770c5-2e4f-11e5-a00a-28cfe91dbc4b<|endoftext|>
<commit_before>92323b95-2d14-11e5-af21-0401358ea401<commit_msg>92323b96-2d14-11e5-af21-0401358ea401<commit_after>92323b96-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>0ffbe370-2e4f-11e5-9f7a-28cfe91dbc4b<commit_msg>100255fd-2e4f-11e5-b021-28cfe91dbc4b<commit_after>100255fd-2e4f-11e5-b021-28cfe91dbc4b<|endoftext|>
<commit_before>ae1fbd26-ad5b-11e7-aa55-ac87a332f658<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>ae94c511-ad5b-11e7-bae1-ac87a332f658<|endoftext|>
<commit_before>b7661c1e-327f-11e5-8778-9cf387a8033e<commit_msg>b76d6a45-327f-11e5-9da5-9cf387a8033e<commit_after>b76d6a45-327f-11e5-9da5-9cf387a8033e<|endoftext|>
<commit_before>86936f8b-2d15-11e5-af21-0401358ea401<commit_msg>86936f8c-2d15-11e5-af21-0401358ea401<commit_after>86936f8c-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>a62770c5-2e4f-11e5-a00a-28cfe91dbc4b<commit_msg>a62fe8d1-2e4f-11e5-a82c-28cfe91dbc4b<commit_after>a62fe8d1-2e4f-11e5-a82c-28cfe91dbc4b<|endoftext|>
<commit_before>08d0084a-585b-11e5-a4c9-6c40088e03e4<commit_msg>08d74a88-585b-11e5-9d6f-6c40088e03e4<commit_after>08d74a88-585b-11e5-9d6f-6c40088e03e4<|endoftext|>
<commit_before>79a7b3be-2d53-11e5-baeb-247703a38240<commit_msg>79a83492-2d53-11e5-baeb-247703a38240<commit_after>79a83492-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>#include "html5viewer/html5viewer.h" #include "ClientWrapper.hpp" #include "Utilities.hpp" #include "MainWindow.hpp" #include <boost/thread.hpp> #include <bts/blockchain/config.hpp> #include <bts/wallet/url.hpp> #include <signal.h> #include <QApplication> #include <QSettings> #include <QPixmap> #include <QErrorMessage> #include <QSplashScreen> #include <QDir> #include <QWebSettings> #include <QWebPage> #include <QWebFrame> #include <QJsonDocument> #include <QGraphicsWebView> #include <QTimer> #include <QAuthenticator> #include <QNetworkReply> #include <QResource> #include <QGraphicsWidget> #include <QMainWindow> #include <QMenuBar> #include <QLayout> #include <QLocalSocket> #include <QLocalServer> #include <QMessageBox> #include <QProxyStyle> #include <QComboBox> #include <boost/program_options.hpp> #include <bts/client/client.hpp> #include <bts/net/upnp.hpp> #include <bts/blockchain/chain_database.hpp> #include <bts/rpc/rpc_server.hpp> #include <bts/cli/cli.hpp> #include <bts/utilities/git_revision.hpp> #include <fc/filesystem.hpp> #include <fc/thread/thread.hpp> #include <fc/log/file_appender.hpp> #include <fc/log/logger_config.hpp> #include <fc/io/json.hpp> #include <fc/reflect/variant.hpp> #include <fc/git_revision.hpp> #include <fc/io/json.hpp> #include <fc/log/logger_config.hpp> #include <fc/signals.hpp> #include <boost/iostreams/tee.hpp> #include <boost/iostreams/stream.hpp> #include <fstream> #include <iostream> #include <iomanip> void setupMenus(ClientWrapper* client, MainWindow* mainWindow) { auto accountMenu = mainWindow->accountMenu(); accountMenu->addAction("Go to My Accounts", mainWindow, SLOT(goToMyAccounts()), QKeySequence(QObject::tr("Ctrl+Shift+A"))); accountMenu->addAction("Create Account", mainWindow, SLOT(goToCreateAccount()), QKeySequence(QObject::tr("Ctrl+Shift+C"))); accountMenu->addAction("Import Account")->setEnabled(false); accountMenu->addAction("New Contact", mainWindow, SLOT(goToAddContact()), QKeySequence(QObject::tr("Ctrl+Shift+N"))); } void prepareStartupSequence(ClientWrapper* client, Html5Viewer* viewer, MainWindow* mainWindow, QSplashScreen* splash) { viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("bitshares", client); viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("magic_unicorn", new Utilities, QWebFrame::ScriptOwnership); QObject::connect(viewer->webView()->page()->networkAccessManager(), &QNetworkAccessManager::authenticationRequired, [client](QNetworkReply*, QAuthenticator *auth) { auth->setUser(client->http_url().userName()); auth->setPassword(client->http_url().password()); }); client->connect(client, &ClientWrapper::initialized, [viewer,client,mainWindow]() { ilog( "Client initialized; loading web interface from ${url}", ("url", client->http_url().toString().toStdString()) ); client->status_update("Calculating last 3 digits of pi"); viewer->webView()->load(client->http_url()); //Now we know the URL of the app, so we can create the items in the Accounts menu setupMenus(client, mainWindow); }); auto loadFinishedConnection = std::make_shared<QMetaObject::Connection>(); *loadFinishedConnection = viewer->connect(viewer->webView(), &QGraphicsWebView::loadFinished, [mainWindow,splash,viewer,loadFinishedConnection](bool ok) { ilog( "Webview loaded: ${status}", ("status", ok) ); viewer->disconnect(*loadFinishedConnection); mainWindow->show(); splash->finish(mainWindow); mainWindow->setupTrayIcon(); mainWindow->processDeferredUrl(); }); client->connect(client, &ClientWrapper::error, [=](QString errorString) { splash->hide(); QMessageBox::critical(nullptr, QObject::tr("Error"), errorString); exit(1); }); client->connect(client, &ClientWrapper::status_update, [=](QString messageString) { splash->showMessage(messageString, Qt::AlignCenter | Qt::AlignBottom, Qt::white); }); } QLocalServer* startSingleInstanceServer(MainWindow* mainWindow) { QLocalServer* singleInstanceServer = new QLocalServer(); if( !singleInstanceServer->listen(BTS_BLOCKCHAIN_NAME) ) { std::cerr << "Could not start new instance listener. Attempting to remove defunct listener... "; QLocalServer::removeServer(BTS_BLOCKCHAIN_NAME); if( !singleInstanceServer->listen(BTS_BLOCKCHAIN_NAME) ) { std::cerr << "Failed to start new instance listener: " << singleInstanceServer->errorString().toStdString() << std::endl; exit(1); } std::cerr << "Success.\n"; } std::cout << "Listening for new instances on " << singleInstanceServer->fullServerName().toStdString() << std::endl; singleInstanceServer->connect(singleInstanceServer, &QLocalServer::newConnection, [singleInstanceServer,mainWindow](){ QLocalSocket* zygote = singleInstanceServer->nextPendingConnection(); QEventLoop waitLoop; zygote->connect(zygote, &QLocalSocket::readyRead, &waitLoop, &QEventLoop::quit); QTimer::singleShot(1000, &waitLoop, SLOT(quit())); waitLoop.exec(); mainWindow->raise(); mainWindow->activateWindow(); if( zygote->bytesAvailable() ) { QByteArray message = zygote->readLine(); ilog("Got message from new instance: ${msg}", ("msg",message.data())); mainWindow->processCustomUrl(message); } zygote->close(); delete zygote; }); return singleInstanceServer; } int main( int argc, char** argv ) { QCoreApplication::setOrganizationName( "BitShares" ); QCoreApplication::setOrganizationDomain( "bitshares.org" ); QCoreApplication::setApplicationName( BTS_BLOCKCHAIN_NAME ); QApplication app(argc, argv); app.setWindowIcon(QIcon(":/images/qtapp.ico")); //This works around Qt bug 22410, which causes a crash when repeatedly clicking a QComboBox class CrashWorkaroundStyle : public QProxyStyle { public: virtual int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0, QStyleHintReturn *returnData = 0) const{ if( hint == QStyle::SH_Menu_FlashTriggeredItem ) return 0; return QProxyStyle::styleHint(hint, option, widget, returnData); } }; app.setStyle(new CrashWorkaroundStyle); MainWindow mainWindow; app.installEventFilter(&mainWindow); //We'll go ahead and leave Win/Lin URL handling available in OSX too QLocalSocket* sock = new QLocalSocket(); sock->connectToServer(BTS_BLOCKCHAIN_NAME); if( sock->waitForConnected(100) ) { if( argc > 1 && app.arguments()[1].startsWith(QString(CUSTOM_URL_SCHEME) + ":") ) { //Need to open a custom URL. Pass it to pre-existing instance. std::cout << "Found instance already running. Sending message and exiting." << std::endl; sock->write(argv[1]); sock->waitForBytesWritten(); sock->close(); } //Note that we connected, but may not have sent anything. This means that another instance is already //running. The fact that we connected prompted it to request focus; we will just exit now. delete sock; return 0; } else { if( argc > 1 && app.arguments()[1].startsWith(QString(CUSTOM_URL_SCHEME) + ":") ) { //No other instance running. Handle URL when we get started up. mainWindow.deferCustomUrl(app.arguments()[1]); } //Could not connect to already-running instance. Start a server so future instances connect to us QLocalServer* singleInstanceServer = startSingleInstanceServer(&mainWindow); app.connect(&app, &QApplication::aboutToQuit, singleInstanceServer, &QLocalServer::deleteLater); } delete sock; auto viewer = new Html5Viewer; ClientWrapper* client = new ClientWrapper; app.connect(&app, &QApplication::aboutToQuit, client, &ClientWrapper::close); mainWindow.setCentralWidget(viewer); mainWindow.setClientWrapper(client); QTimer fc_tasks; fc_tasks.connect( &fc_tasks, &QTimer::timeout, [](){ fc::usleep( fc::microseconds( 1000 ) ); } ); fc_tasks.start(33); QPixmap pixmap(":/images/splash_screen.jpg"); QSplashScreen splash(pixmap); splash.showMessage(QObject::tr("Loading configuration..."), Qt::AlignCenter | Qt::AlignBottom, Qt::white); splash.show(); prepareStartupSequence(client, viewer, &mainWindow, &splash); QWebSettings::globalSettings()->setAttribute( QWebSettings::PluginsEnabled, false ); try { client->initialize(); return app.exec(); } catch ( const fc::exception& e) { elog( "${e}", ("e",e.to_detail_string() ) ); QErrorMessage::qtHandler()->showMessage( e.to_string().c_str() ); } } <commit_msg>Add workaround for wallet_get_info RPC call failure at launch<commit_after>#include "html5viewer/html5viewer.h" #include "ClientWrapper.hpp" #include "Utilities.hpp" #include "MainWindow.hpp" #include <boost/thread.hpp> #include <bts/blockchain/config.hpp> #include <bts/wallet/url.hpp> #include <signal.h> #include <QApplication> #include <QSettings> #include <QPixmap> #include <QErrorMessage> #include <QSplashScreen> #include <QDir> #include <QWebSettings> #include <QWebPage> #include <QWebFrame> #include <QJsonDocument> #include <QGraphicsWebView> #include <QTimer> #include <QAuthenticator> #include <QNetworkReply> #include <QResource> #include <QGraphicsWidget> #include <QMainWindow> #include <QMenuBar> #include <QLayout> #include <QLocalSocket> #include <QLocalServer> #include <QMessageBox> #include <QProxyStyle> #include <QComboBox> #include <boost/program_options.hpp> #include <bts/client/client.hpp> #include <bts/net/upnp.hpp> #include <bts/blockchain/chain_database.hpp> #include <bts/rpc/rpc_server.hpp> #include <bts/cli/cli.hpp> #include <bts/utilities/git_revision.hpp> #include <fc/filesystem.hpp> #include <fc/thread/thread.hpp> #include <fc/log/file_appender.hpp> #include <fc/log/logger_config.hpp> #include <fc/io/json.hpp> #include <fc/reflect/variant.hpp> #include <fc/git_revision.hpp> #include <fc/io/json.hpp> #include <fc/log/logger_config.hpp> #include <fc/signals.hpp> #include <boost/iostreams/tee.hpp> #include <boost/iostreams/stream.hpp> #include <fstream> #include <iostream> #include <iomanip> void setupMenus(ClientWrapper* client, MainWindow* mainWindow) { auto accountMenu = mainWindow->accountMenu(); accountMenu->addAction("Go to My Accounts", mainWindow, SLOT(goToMyAccounts()), QKeySequence(QObject::tr("Ctrl+Shift+A"))); accountMenu->addAction("Create Account", mainWindow, SLOT(goToCreateAccount()), QKeySequence(QObject::tr("Ctrl+Shift+C"))); accountMenu->addAction("Import Account")->setEnabled(false); accountMenu->addAction("New Contact", mainWindow, SLOT(goToAddContact()), QKeySequence(QObject::tr("Ctrl+Shift+N"))); } void prepareStartupSequence(ClientWrapper* client, Html5Viewer* viewer, MainWindow* mainWindow, QSplashScreen* splash) { viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("bitshares", client); viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("magic_unicorn", new Utilities, QWebFrame::ScriptOwnership); QObject::connect(viewer->webView()->page()->networkAccessManager(), &QNetworkAccessManager::authenticationRequired, [client](QNetworkReply*, QAuthenticator *auth) { auth->setUser(client->http_url().userName()); auth->setPassword(client->http_url().password()); }); client->connect(client, &ClientWrapper::initialized, [viewer,client,mainWindow]() { ilog( "Client initialized; loading web interface from ${url}", ("url", client->http_url().toString().toStdString()) ); client->status_update("Calculating last 3 digits of pi"); viewer->webView()->load(client->http_url()); //Now we know the URL of the app, so we can create the items in the Accounts menu setupMenus(client, mainWindow); }); auto loadFinishedConnection = std::make_shared<QMetaObject::Connection>(); *loadFinishedConnection = viewer->connect(viewer->webView(), &QGraphicsWebView::loadFinished, [mainWindow,splash,viewer,loadFinishedConnection](bool ok) { //Workaround for wallet_get_info RPC call failure in web_wallet viewer->webView()->reload(); ilog( "Webview loaded: ${status}", ("status", ok) ); viewer->disconnect(*loadFinishedConnection); mainWindow->show(); splash->finish(mainWindow); mainWindow->setupTrayIcon(); mainWindow->processDeferredUrl(); }); client->connect(client, &ClientWrapper::error, [=](QString errorString) { splash->hide(); QMessageBox::critical(nullptr, QObject::tr("Error"), errorString); exit(1); }); client->connect(client, &ClientWrapper::status_update, [=](QString messageString) { splash->showMessage(messageString, Qt::AlignCenter | Qt::AlignBottom, Qt::white); }); } QLocalServer* startSingleInstanceServer(MainWindow* mainWindow) { QLocalServer* singleInstanceServer = new QLocalServer(); if( !singleInstanceServer->listen(BTS_BLOCKCHAIN_NAME) ) { std::cerr << "Could not start new instance listener. Attempting to remove defunct listener... "; QLocalServer::removeServer(BTS_BLOCKCHAIN_NAME); if( !singleInstanceServer->listen(BTS_BLOCKCHAIN_NAME) ) { std::cerr << "Failed to start new instance listener: " << singleInstanceServer->errorString().toStdString() << std::endl; exit(1); } std::cerr << "Success.\n"; } std::cout << "Listening for new instances on " << singleInstanceServer->fullServerName().toStdString() << std::endl; singleInstanceServer->connect(singleInstanceServer, &QLocalServer::newConnection, [singleInstanceServer,mainWindow](){ QLocalSocket* zygote = singleInstanceServer->nextPendingConnection(); QEventLoop waitLoop; zygote->connect(zygote, &QLocalSocket::readyRead, &waitLoop, &QEventLoop::quit); QTimer::singleShot(1000, &waitLoop, SLOT(quit())); waitLoop.exec(); mainWindow->raise(); mainWindow->activateWindow(); if( zygote->bytesAvailable() ) { QByteArray message = zygote->readLine(); ilog("Got message from new instance: ${msg}", ("msg",message.data())); mainWindow->processCustomUrl(message); } zygote->close(); delete zygote; }); return singleInstanceServer; } int main( int argc, char** argv ) { QCoreApplication::setOrganizationName( "BitShares" ); QCoreApplication::setOrganizationDomain( "bitshares.org" ); QCoreApplication::setApplicationName( BTS_BLOCKCHAIN_NAME ); QApplication app(argc, argv); app.setWindowIcon(QIcon(":/images/qtapp.ico")); //This works around Qt bug 22410, which causes a crash when repeatedly clicking a QComboBox class CrashWorkaroundStyle : public QProxyStyle { public: virtual int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0, QStyleHintReturn *returnData = 0) const{ if( hint == QStyle::SH_Menu_FlashTriggeredItem ) return 0; return QProxyStyle::styleHint(hint, option, widget, returnData); } }; app.setStyle(new CrashWorkaroundStyle); MainWindow mainWindow; app.installEventFilter(&mainWindow); //We'll go ahead and leave Win/Lin URL handling available in OSX too QLocalSocket* sock = new QLocalSocket(); sock->connectToServer(BTS_BLOCKCHAIN_NAME); if( sock->waitForConnected(100) ) { if( argc > 1 && app.arguments()[1].startsWith(QString(CUSTOM_URL_SCHEME) + ":") ) { //Need to open a custom URL. Pass it to pre-existing instance. std::cout << "Found instance already running. Sending message and exiting." << std::endl; sock->write(argv[1]); sock->waitForBytesWritten(); sock->close(); } //Note that we connected, but may not have sent anything. This means that another instance is already //running. The fact that we connected prompted it to request focus; we will just exit now. delete sock; return 0; } else { if( argc > 1 && app.arguments()[1].startsWith(QString(CUSTOM_URL_SCHEME) + ":") ) { //No other instance running. Handle URL when we get started up. mainWindow.deferCustomUrl(app.arguments()[1]); } //Could not connect to already-running instance. Start a server so future instances connect to us QLocalServer* singleInstanceServer = startSingleInstanceServer(&mainWindow); app.connect(&app, &QApplication::aboutToQuit, singleInstanceServer, &QLocalServer::deleteLater); } delete sock; auto viewer = new Html5Viewer; ClientWrapper* client = new ClientWrapper; app.connect(&app, &QApplication::aboutToQuit, client, &ClientWrapper::close); mainWindow.setCentralWidget(viewer); mainWindow.setClientWrapper(client); QTimer fc_tasks; fc_tasks.connect( &fc_tasks, &QTimer::timeout, [](){ fc::usleep( fc::microseconds( 1000 ) ); } ); fc_tasks.start(33); QPixmap pixmap(":/images/splash_screen.jpg"); QSplashScreen splash(pixmap); splash.showMessage(QObject::tr("Loading configuration..."), Qt::AlignCenter | Qt::AlignBottom, Qt::white); splash.show(); prepareStartupSequence(client, viewer, &mainWindow, &splash); QWebSettings::globalSettings()->setAttribute( QWebSettings::PluginsEnabled, false ); try { client->initialize(); return app.exec(); } catch ( const fc::exception& e) { elog( "${e}", ("e",e.to_detail_string() ) ); QErrorMessage::qtHandler()->showMessage( e.to_string().c_str() ); } } <|endoftext|>
<commit_before>9692fd7a-327f-11e5-8973-9cf387a8033e<commit_msg>9699693d-327f-11e5-b824-9cf387a8033e<commit_after>9699693d-327f-11e5-b824-9cf387a8033e<|endoftext|>
<commit_before>5bf673fe-2d16-11e5-af21-0401358ea401<commit_msg>5bf673ff-2d16-11e5-af21-0401358ea401<commit_after>5bf673ff-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>785d3466-2d53-11e5-baeb-247703a38240<commit_msg>785db454-2d53-11e5-baeb-247703a38240<commit_after>785db454-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>c56271d1-327f-11e5-a041-9cf387a8033e<commit_msg>c5685885-327f-11e5-af1e-9cf387a8033e<commit_after>c5685885-327f-11e5-af1e-9cf387a8033e<|endoftext|>
<commit_before>cb31fd3a-35ca-11e5-96ec-6c40088e03e4<commit_msg>cb3887d0-35ca-11e5-9662-6c40088e03e4<commit_after>cb3887d0-35ca-11e5-9662-6c40088e03e4<|endoftext|>
<commit_before>7b7a21a3-2749-11e6-9ff6-e0f84713e7b8<commit_msg>compiles now<commit_after>7b89058f-2749-11e6-b1c1-e0f84713e7b8<|endoftext|>
<commit_before>d421ef68-313a-11e5-baaf-3c15c2e10482<commit_msg>d428167d-313a-11e5-92bb-3c15c2e10482<commit_after>d428167d-313a-11e5-92bb-3c15c2e10482<|endoftext|>
<commit_before>1bf96951-ad59-11e7-a204-ac87a332f658<commit_msg>add file<commit_after>1c65396e-ad59-11e7-9299-ac87a332f658<|endoftext|>
<commit_before>575b8997-2e4f-11e5-bddf-28cfe91dbc4b<commit_msg>576294b5-2e4f-11e5-9adf-28cfe91dbc4b<commit_after>576294b5-2e4f-11e5-9adf-28cfe91dbc4b<|endoftext|>
<commit_before>8d6dfcd6-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfcd7-2d14-11e5-af21-0401358ea401<commit_after>8d6dfcd7-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>531e044a-5216-11e5-b525-6c40088e03e4<commit_msg>5324e44a-5216-11e5-8827-6c40088e03e4<commit_after>5324e44a-5216-11e5-8827-6c40088e03e4<|endoftext|>
<commit_before>1e323a80-2e3a-11e5-badc-c03896053bdd<commit_msg>1e40bc10-2e3a-11e5-a4d7-c03896053bdd<commit_after>1e40bc10-2e3a-11e5-a4d7-c03896053bdd<|endoftext|>
<commit_before>eabafccc-2e4e-11e5-8e17-28cfe91dbc4b<commit_msg>eac71426-2e4e-11e5-a114-28cfe91dbc4b<commit_after>eac71426-2e4e-11e5-a114-28cfe91dbc4b<|endoftext|>
<commit_before>63961d8c-2e4f-11e5-bccc-28cfe91dbc4b<commit_msg>639c80ab-2e4f-11e5-bc44-28cfe91dbc4b<commit_after>639c80ab-2e4f-11e5-bc44-28cfe91dbc4b<|endoftext|>
<commit_before>cd6bc4ae-ad58-11e7-be95-ac87a332f658<commit_msg>Adding stuff<commit_after>cdd4db19-ad58-11e7-91db-ac87a332f658<|endoftext|>
<commit_before>/* main.cpp * * Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Implement robot_class to provide functionality for robot. */ #include "612.h" #include "main.h" #include "ports.h" #include "update.h" #include "vision/vision_processing.h" #include "state_tracker.h" #include "visionalg.h" //constructor - initialize drive robot_class::robot_class() { //do nothing GetWatchdog().SetEnabled(false); //we don't want Watchdog } void robot_class::RobotInit() { //Run-Time INIT //set necessary inversions drive.SetInvertedMotor(left_front_motor.type, left_front_motor.reverse); drive.SetInvertedMotor(left_rear_motor.type, left_rear_motor.reverse); drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse); drive.SetInvertedMotor(right_rear_motor.type, right_rear_motor.reverse); init_camera(); } void robot_class::DisabledInit() { //do nothing } void robot_class::AutonomousInit() { //do nothing } void robot_class::TeleopInit() { //do nothing } void robot_class::DisabledPeriodic() { //do nothing } void robot_class::AutonomousPeriodic() { update_sensors(); } void robot_class::TeleopPeriodic() { update_sensors(); } void robot_class::DisabledContinuous() { //do nothing } void robot_class::AutonomousContinuous() { //do nothing } void robot_class::TeleopContinuous() { if(global_state.get_state() == STATE_DRIVING) { if (left_joystick.GetRawButton(1)) { //arcade drive drive.ArcadeDrive(left_joystick); //arcade drive on left joystick } else { //tank drive float left = left_joystick.GetY(); float right = right_joystick.GetY(); //explicitly state drive power is based on Y axis of that side joy drive.TankDrive(left, right); } if (left_joystick.GetRawButton(11)) { right_servo_shift.Set(0.7); left_servo_shift.Set(0.7); // set servo to high gear } else if (left_joystick.GetRawButton(10)) { right_servo_shift.Set(0.3); left_servo_shift.Set(0.3); //Sets servo to low gear } } else if(global_state.get_state() == STATE_AIMING) { // disable motor safety check to stop wasting netconsole space drive.SetSafetyEnabled(false); ColorImage* camera_image = vision_processing::get_image(); vector<double> target_degrees = vision_processing::get_degrees_from_image(camera_image); vector<double> target_distances = vision_processing::get_distance_from_image(camera_image); // printf("Angle (degrees) of camera: %f", target_degrees[vision_processing::determine_aim_target_from_image(vision_processing::get_image())]); if(target_degrees.size() >= 1) { printf("Angle (degrees) of camera: %f\n", target_degrees[0]); } else { printf("No target detected\n"); } if(target_distances.size() >= 1) { printf("Distance of target: %f\n", target_distances[0]); } if(!left_joystick.GetRawButton(3)) { global_state.set_state(STATE_DRIVING); drive.SetSafetyEnabled(true); } } if(global_state.get_state() != STATE_AIMING) { Wait(0.005); //let the CPU rest a little - 5 ms isn't too long } } void robot_class::update_sensors() { //run functions in update registry registry().update(); } //the following macro tells the library that we want to generate code //for our class robot_class START_ROBOT_CLASS(robot_class); <commit_msg>testing different RPMs and angles for a ratio that we will put in the final code<commit_after>/* main.cpp * * Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Implement robot_class to provide functionality for robot. */ #include "612.h" #include "main.h" #include "ports.h" #include "update.h" #include "vision/vision_processing.h" #include "state_tracker.h" #include "visionalg.h" //constructor - initialize drive robot_class::robot_class() { //do nothing GetWatchdog().SetEnabled(false); //we don't want Watchdog } void robot_class::RobotInit() { //Run-Time INIT //set necessary inversions drive.SetInvertedMotor(left_front_motor.type, left_front_motor.reverse); drive.SetInvertedMotor(left_rear_motor.type, left_rear_motor.reverse); drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse); drive.SetInvertedMotor(right_rear_motor.type, right_rear_motor.reverse); init_camera(); } void robot_class::DisabledInit() { //do nothing } void robot_class::AutonomousInit() { //do nothing } void robot_class::TeleopInit() { //do nothing } void robot_class::DisabledPeriodic() { //do nothing } void robot_class::AutonomousPeriodic() { update_sensors(); } void robot_class::TeleopPeriodic() { update_sensors(); } void robot_class::DisabledContinuous() { //do nothing } void robot_class::AutonomousContinuous() { //do nothing } void robot_class::TeleopContinuous() { if(global_state.get_state() == STATE_DRIVING) { if (left_joystick.GetRawButton(1)) { //arcade drive drive.ArcadeDrive(left_joystick); //arcade drive on left joystick } else { //tank drive float left = left_joystick.GetY(); float right = right_joystick.GetY(); //explicitly state drive power is based on Y axis of that side joy drive.TankDrive(left, right); } if (left_joystick.GetRawButton(11)) { right_servo_shift.Set(0.7); left_servo_shift.Set(0.7); // set servo to high gear } else if (left_joystick.GetRawButton(10)) { right_servo_shift.Set(0.3); left_servo_shift.Set(0.3); //Sets servo to low gear } } //stuff goes under if (left_joystick.GetRawButton(3){ left_launcher_jag.set(0.1); right_launcher_jag.set(0.1); } //stuff goes over else if(global_state.get_state() == STATE_AIMING) { // disable motor safety check to stop wasting netconsole space drive.SetSafetyEnabled(false); ColorImage* camera_image = vision_processing::get_image(); vector<double> target_degrees = vision_processing::get_degrees_from_image(camera_image); vector<double> target_distances = vision_processing::get_distance_from_image(camera_image); // printf("Angle (degrees) of camera: %f", target_degrees[vision_processing::determine_aim_target_from_image(vision_processing::get_image())]); if(target_degrees.size() >= 1) { printf("Angle (degrees) of camera: %f\n", target_degrees[0]); } else { printf("No target detected\n"); } if(target_distances.size() >= 1) { printf("Distance of target: %f\n", target_distances[0]); } if(!left_joystick.GetRawButton(3)) { global_state.set_state(STATE_DRIVING); drive.SetSafetyEnabled(true); } } if(global_state.get_state() != STATE_AIMING) { Wait(0.005); //let the CPU rest a little - 5 ms isn't too long } } void robot_class::update_sensors() { //run functions in update registry registry().update(); } //the following macro tells the library that we want to generate code //for our class robot_class START_ROBOT_CLASS(robot_class); <|endoftext|>
<commit_before>5f89497b-2d16-11e5-af21-0401358ea401<commit_msg>5f89497c-2d16-11e5-af21-0401358ea401<commit_after>5f89497c-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include "Bingot.h" #include <cryptlib.h> #include <osrng.h> #include <eccrypto.h> #include <oids.h> #include <QDebug> #include <QCryptographicHash> const unsigned int protocol_version = 1; Bingot::Bingot(QObject *parent) : QObject(parent), m_candidateBlock(0) { } void Bingot::initialize() { generateECDSAKeyPair(); generateWalletAddress(); } void Bingot::generateECDSAKeyPair() { CryptoPP::AutoSeededRandomPool autoSeededRandomPool; CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PrivateKey privateKey; privateKey.Initialize(autoSeededRandomPool, CryptoPP::ASN1::secp160r1()); bool result = privateKey.Validate( autoSeededRandomPool, 3 ); if( !result ) { qDebug() << "private key is not valid!"; return; } const CryptoPP::Integer &privateKeyInteger = privateKey.GetPrivateExponent(); QByteArray privateKeyByteArray((int)privateKeyInteger.ByteCount(), 0); privateKeyInteger.Encode((byte*)privateKeyByteArray.data(), privateKeyInteger.ByteCount()); m_privateKey = privateKeyByteArray; qDebug() << "private key:" << m_privateKey.size() << m_privateKey.toHex(); // Generating matching public key CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PublicKey publicKey; privateKey.MakePublicKey(publicKey); result = publicKey.Validate( autoSeededRandomPool, 3 ); if( !result ) { qDebug() << "public key is not valid!"; return; } const CryptoPP::ECP::Point& point = publicKey.GetPublicElement(); QByteArray publicKeyXByteArray((int)point.x.ByteCount(), 0); point.x.Encode((byte*)publicKeyXByteArray.data(), point.x.ByteCount()); QByteArray publicKeyYByteArray((int)point.y.ByteCount(), 0); point.y.Encode((byte*)publicKeyYByteArray.data(), point.y.ByteCount()); m_publicKey.clear(); m_publicKey.append(publicKeyXByteArray); m_publicKey.append(publicKeyYByteArray); qDebug() << "public key:" << m_publicKey.size() << m_publicKey.toHex(); } void Bingot::generateWalletAddress() { QCryptographicHash hasher1(QCryptographicHash::Sha3_512); hasher1.addData(m_publicKey); QByteArray a1 = hasher1.result(); a1.prepend((const char*)&protocol_version, sizeof(protocol_version)); qDebug() << "hash result:" << a1.toHex(); QCryptographicHash hasher2(QCryptographicHash::Sha256); hasher2.addData(a1); QByteArray a2 = hasher2.result(); qDebug() << "hash result:" << a2.toHex(); QCryptographicHash hasher3(QCryptographicHash::Sha3_256); hasher3.addData(a2); QByteArray a3 = hasher3.result(); qDebug() << "cehcksum:" << a3.toHex(); a1.append(a3.mid(0,4)); qDebug() << "with checksum" << a1.toHex(); m_address = a1.toBase64(); qDebug() << "final address" << m_address; } void Bingot::Transfer(const QByteArray &toAddress, unsigned int amount) { Transaction t(address(), toAddress, amount); t.signTransaction(privateKey(), publicKey()); //verify you actually has this much money; m_suggestedTransactions.insert(t.getSignature(), t); } void Bingot::startNewMiningRound() { Block newCandidateBlock(m_blockChain.size(), m_suggestedTransactions, m_blockChain.getLastBlockHash()); m_candidateBlock = newCandidateBlock; m_candidateBlock.addTransaction(Transaction(address())); m_suggestedTransactions.clear(); const unsigned int workerThreadCount = QThread::idealThreadCount(); quint64 value = Q_UINT64_C(932838457459459); quint64 chunk = value/workerThreadCount; for(unsigned int i = 0; i < workerThreadCount; ++i) { Miner *miner = new Miner(m_candidateBlock, chunk*i, chunk*(1+i)); miner->moveToThread(miner); m_miners.push_back(miner); miner->start(); } } void Bingot::newBlockReceived(Block b) { if (b.isValid()) { if (b.getIndex() == m_blockChain.size()) { if( m_blockChain.add(b)) { //recycle m_candidateBlock to m_suggestedTransactions; const QHash<QByteArray, Transaction> &transactions = m_candidateBlock.getTransactions(); for(QHash<QByteArray, Transaction>::const_iterator t = transactions.begin(); t != transactions.end(); ++t) { m_suggestedTransactions.insert(t.key(), t.value()); } //remove m_suggestedTransactions that are in blockChain already startNewMiningRound(); } } else if(b.getIndex() < m_blockChain.size()) { m_blockChain.add(b); } } } void Bingot::newBlockSolved(Block b) { m_blockChain.add(b); } <commit_msg>check transaction<commit_after>#include "Bingot.h" #include <cryptlib.h> #include <osrng.h> #include <eccrypto.h> #include <oids.h> #include <QDebug> #include <QCryptographicHash> const unsigned int protocol_version = 1; Bingot::Bingot(QObject *parent) : QObject(parent), m_candidateBlock(0) { } void Bingot::initialize() { generateECDSAKeyPair(); generateWalletAddress(); } void Bingot::generateECDSAKeyPair() { CryptoPP::AutoSeededRandomPool autoSeededRandomPool; CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PrivateKey privateKey; privateKey.Initialize(autoSeededRandomPool, CryptoPP::ASN1::secp160r1()); bool result = privateKey.Validate( autoSeededRandomPool, 3 ); if( !result ) { qDebug() << "private key is not valid!"; return; } const CryptoPP::Integer &privateKeyInteger = privateKey.GetPrivateExponent(); QByteArray privateKeyByteArray((int)privateKeyInteger.ByteCount(), 0); privateKeyInteger.Encode((byte*)privateKeyByteArray.data(), privateKeyInteger.ByteCount()); m_privateKey = privateKeyByteArray; qDebug() << "private key:" << m_privateKey.size() << m_privateKey.toHex(); // Generating matching public key CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PublicKey publicKey; privateKey.MakePublicKey(publicKey); result = publicKey.Validate( autoSeededRandomPool, 3 ); if( !result ) { qDebug() << "public key is not valid!"; return; } const CryptoPP::ECP::Point& point = publicKey.GetPublicElement(); QByteArray publicKeyXByteArray((int)point.x.ByteCount(), 0); point.x.Encode((byte*)publicKeyXByteArray.data(), point.x.ByteCount()); QByteArray publicKeyYByteArray((int)point.y.ByteCount(), 0); point.y.Encode((byte*)publicKeyYByteArray.data(), point.y.ByteCount()); m_publicKey.clear(); m_publicKey.append(publicKeyXByteArray); m_publicKey.append(publicKeyYByteArray); qDebug() << "public key:" << m_publicKey.size() << m_publicKey.toHex(); } void Bingot::generateWalletAddress() { QCryptographicHash hasher1(QCryptographicHash::Sha3_512); hasher1.addData(m_publicKey); QByteArray a1 = hasher1.result(); a1.prepend((const char*)&protocol_version, sizeof(protocol_version)); qDebug() << "hash result:" << a1.toHex(); QCryptographicHash hasher2(QCryptographicHash::Sha256); hasher2.addData(a1); QByteArray a2 = hasher2.result(); qDebug() << "hash result:" << a2.toHex(); QCryptographicHash hasher3(QCryptographicHash::Sha3_256); hasher3.addData(a2); QByteArray a3 = hasher3.result(); qDebug() << "cehcksum:" << a3.toHex(); a1.append(a3.mid(0,4)); qDebug() << "with checksum" << a1.toHex(); m_address = a1.toBase64(); qDebug() << "final address" << m_address; } void Bingot::Transfer(const QByteArray &toAddress, unsigned int amount) { int total = m_blockChain.getAccountAmount(m_address); foreach(const Transaction &t, m_suggestedTransactions) { if ((t.getType() != Transaction::REWARD) && (t.getFromAddress() == m_address)) { total -= t.getAmount(); } } const QHash<QByteArray, Transaction> &candidateTransactions = m_candidateBlock.getTransactions(); for(QHash<QByteArray, Transaction>::const_iterator iter = candidateTransactions.begin(); iter != candidateTransactions.end(); ++iter) { if ((iter->getType() != Transaction::REWARD && (iter->getFromAddress() == m_address))) { total -= iter->getAmount(); } } if (amount <= total) { Transaction t(address(), toAddress, amount); t.signTransaction(privateKey(), publicKey()); m_suggestedTransactions.insert(t.getSignature(), t); } } void Bingot::startNewMiningRound() { Block newCandidateBlock(m_blockChain.size(), m_suggestedTransactions, m_blockChain.getLastBlockHash()); m_candidateBlock = newCandidateBlock; m_candidateBlock.addTransaction(Transaction(address())); m_suggestedTransactions.clear(); const unsigned int workerThreadCount = QThread::idealThreadCount(); quint64 value = Q_UINT64_C(932838457459459); quint64 chunk = value/workerThreadCount; for(unsigned int i = 0; i < workerThreadCount; ++i) { Miner *miner = new Miner(m_candidateBlock, chunk*i, chunk*(1+i)); miner->moveToThread(miner); m_miners.push_back(miner); miner->start(); } } void Bingot::newBlockReceived(Block b) { if (b.isValid()) { if (b.getIndex() == m_blockChain.size()) { if( m_blockChain.add(b)) { //recycle m_candidateBlock to m_suggestedTransactions; const QHash<QByteArray, Transaction> &transactions = m_candidateBlock.getTransactions(); for(QHash<QByteArray, Transaction>::const_iterator t = transactions.begin(); t != transactions.end(); ++t) { m_suggestedTransactions.insert(t.key(), t.value()); } //remove m_suggestedTransactions that are in blockChain already startNewMiningRound(); } } else if(b.getIndex() < m_blockChain.size()) { m_blockChain.add(b); } } } void Bingot::newBlockSolved(Block b) { m_blockChain.add(b); } <|endoftext|>
<commit_before>98b5b645-327f-11e5-9c36-9cf387a8033e<commit_msg>98bbc73d-327f-11e5-9abd-9cf387a8033e<commit_after>98bbc73d-327f-11e5-9abd-9cf387a8033e<|endoftext|>
<commit_before>809e9200-2d15-11e5-af21-0401358ea401<commit_msg>809e9201-2d15-11e5-af21-0401358ea401<commit_after>809e9201-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <sys/mman.h> #include "asmtest.h" #include "x86_64/Operand.h" #include "x86_64/Assembler.h" #include "CompiledCode.h" #include "Linker.h" #include "lib/IncrementalAlloc.h" #include "Util.h" #include <iostream> using namespace std; #include "lib/Runtime.h" #include "lib/Object.h" #define __ masm. using namespace snot; using namespace snot::x86_64; void say_hello() { printf("HELLO WORLD! %lx\n", (void*)say_hello); } CompiledCode define_function(const std::string& name) { x86_64::Assembler masm; __ define_symbol(name); __ enter(16); __ bin_xor(rdi, rdi); // NULL prototype __ call("snot_create_object"); __ mov(rax, Address(rbp, -8)); __ mov(Address(rbp, -8), rdi); __ clear(rax); __ call("snot_call"); __ mov(rax, Address(rbp, -8)); __ mov(Address(rbp, -8), rdi); __ mov("initialize", rsi); __ mov(3, rdx); __ clear(rax); __ call("snot_send"); __ clear(rax); __ add(56, rax); __ debug_break(); __ leave(); __ ret(); return masm.compile(); } int main (int argc, char const *argv[]) { SymbolTable table; table["say_hello"] = (void*)say_hello; table["snot_create_object"] = (void*)snot::create_object; table["snot_send"] = (void*)snot::send; table["snot_call"] = (void*)snot::call; CompiledCode code = define_function("hejsa"); Linker::register_symbols(code, table); Linker::link(code, table); code.make_executable(); print_mem(code.code(), &code.code()[code.size()]); print_mem(simple_ret, simple_loop); printf("code is at 0x%lx\n", code.code()); int(*func)() = (int(*)())code.code(); printf("add: %d\n", func()); return 0; } <commit_msg>Test codegen<commit_after>#include <sys/mman.h> #include "asmtest.h" #include "x86_64/Operand.h" #include "x86_64/Assembler.h" #include "x86_64/Codegen.h" #include "CompiledCode.h" #include "Linker.h" #include "lib/IncrementalAlloc.h" #include "Util.h" #include <iostream> using namespace std; #include "lib/Runtime.h" #include "lib/Object.h" #define __ masm. using namespace snot; using namespace snot::x86_64; void say_hello() { printf("HELLO WORLD! %lx\n", (void*)say_hello); } void val_to_int(x86_64::Assembler& masm, const Register& reg) { __ shr(reg); } void int_to_val(x86_64::Assembler& masm, const Register& reg) { __ shl(reg); __ inc(reg); } void if_int(x86_64::Assembler& masm, const Register& reg, Label& no) { __ clear(rax); __ incb(rax); __ bin_and(reg, rax); __ j(CC_ZERO, no); } VALUE object_initialize(VALUE self, uint64_t num_args, VALUE* args) { printf("initializing 0x%lx, with %lu args\n", self, num_args); char c = ((char*)NULL)[0]; return self; } VALUE object_real_object(VALUE self, uint64_t num_args, VALUE* args) { printf("THIS IS A REAL OBJECT: 0x%lx\n", self); return self; } int main (int argc, char const *argv[]) { SymbolTable table; table["say_hello"] = (void*)say_hello; table["snot_create_object"] = (void*)snot::create_object; table["snot_send"] = (void*)snot::send; table["snot_call"] = (void*)snot::call; x86_64::Codegen masm; __ function_entry(4); Local l1 = __ local("hejsa"); __ get_argument(0, l1); Local l2 = __ local("hej2"); __ get_argument(1, l2); __ set_argument(0, l1); __ set_argument(1, "+"); __ set_argument(2, 1); __ set_argument(3, l2); Local retval = __ local("retval"); __ call("snot_send", retval); __ set_return(retval); __ function_return(); CompiledCode code = __ compile(); Linker::register_symbols(code, table); Linker::link(code, table); code.make_executable(); print_mem(code.code(), &code.code()[code.size()]); printf("code is at 0x%lx\n", code.code()); Object* obj = new Object; VALUE func = snot::create_function(object_initialize); obj->set("initialize", func); obj->set("real_object", snot::create_function(object_real_object)); VALUE(*entry)(VALUE a, VALUE b) = (VALUE(*)(VALUE, VALUE))code.code(); printf("add: %d\n", integer(entry(value(-67LL), value(-45LL)))); return 0; } <|endoftext|>
<commit_before>f196a588-585a-11e5-8fc5-6c40088e03e4<commit_msg>f19d56c8-585a-11e5-a315-6c40088e03e4<commit_after>f19d56c8-585a-11e5-a315-6c40088e03e4<|endoftext|>
<commit_before>16aeacf8-585b-11e5-91da-6c40088e03e4<commit_msg>16b64064-585b-11e5-a9ef-6c40088e03e4<commit_after>16b64064-585b-11e5-a9ef-6c40088e03e4<|endoftext|>
<commit_before>be04fef4-35ca-11e5-941f-6c40088e03e4<commit_msg>be0bd19e-35ca-11e5-8125-6c40088e03e4<commit_after>be0bd19e-35ca-11e5-8125-6c40088e03e4<|endoftext|>
<commit_before>06587cf0-2e4f-11e5-af8b-28cfe91dbc4b<commit_msg>0663c88a-2e4f-11e5-a20d-28cfe91dbc4b<commit_after>0663c88a-2e4f-11e5-a20d-28cfe91dbc4b<|endoftext|>
<commit_before>5bf673d7-2d16-11e5-af21-0401358ea401<commit_msg>5bf673d8-2d16-11e5-af21-0401358ea401<commit_after>5bf673d8-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>643f2f42-2fa5-11e5-9978-00012e3d3f12<commit_msg>6441a046-2fa5-11e5-966d-00012e3d3f12<commit_after>6441a046-2fa5-11e5-966d-00012e3d3f12<|endoftext|>
<commit_before>93187e80-2e4f-11e5-82cb-28cfe91dbc4b<commit_msg>931f3fd4-2e4f-11e5-8b7b-28cfe91dbc4b<commit_after>931f3fd4-2e4f-11e5-8b7b-28cfe91dbc4b<|endoftext|>
<commit_before>5d2865d5-2d16-11e5-af21-0401358ea401<commit_msg>5d2865d6-2d16-11e5-af21-0401358ea401<commit_after>5d2865d6-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>66f8d106-2fa5-11e5-82ca-00012e3d3f12<commit_msg>66fb6914-2fa5-11e5-b8bb-00012e3d3f12<commit_after>66fb6914-2fa5-11e5-b8bb-00012e3d3f12<|endoftext|>