<commit_before>/*
 * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *
 *     * Neither the name of Intel Corporation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <cstdint>
#include <string.h>
#include <mpi.h>
#include <limits.h>

#include "geopm.h"
#include "geopm_error.h"
#include "ModelApplication.hpp"
#include "ModelParse.hpp"

int main(int argc, char **argv)
{
    int err = 0;
    int rank;
    int verbosity = 0;
    uint64_t init_rid;
    char *config_path = NULL;
    const char *usage = "\n"
"%s -h | --help\n"
"    Print this help message.\n"
"\n"
"%s [--verbose] [config_file]\n"
"\n"
"    --verbose: Print output from rank zero as every region executes.\n"
"\n"
"    config_file: Path to json file containing loop count and sequence\n"
"                 of regions in each loop.\n"
"\n"
"                 Example configuration json string:\n"
"\n"
"                 {\"loop-count\": 10,\n"
"                  \"region\": [\"sleep\", \"stream\", \"dgemm\", \"stream\", \"all2all\"],\n"
"                  \"big-o\": [1.0, 1.0, 1.0, 1.0, 1.0]}\n"
"\n"
"                 The \"loop-count\" value is an integer that sets the\n"
"                 number of loops executed.  Each time through the loop\n"
"                 the regions listed in the \"region\" array are\n"
"                 executed.  The \"big-o\" array gives double precision\n"
"                 values for each region.  Region names can be one of\n"
"                 the following options:\n"
"\n"
"                 sleep: Executes clock_nanosleep() for big-o seconds.\n"
"\n"
"                 spin: Executes a spin loop for big-o seconds.\n"
"\n"
"                 stream: Executes stream \"triadd\" on a vector with\n"
"                 length proportional to big-o.\n"
"\n"
"                 dgemm: Dense matrix-matrix multiply with floating\n"
"                 point operations proportional to big-o.\n"
"\n"
"                 all2all: All processes send buffers to all other\n"
"                 processes.  The time of this operation is\n"
"                 proportional to big-o.\n"
"\n"
"                 Example configuration json string with imbalance and\n"
"                 progress:\n"
"\n"
"                 {\"loop-count\": 10,\n"
"                  \"region\": [\"sleep\", \"stream-progress\", \"dgemm-imbalance\", \"stream\", \"all2all\"],\n"
"                  \"big-o\": [1.0, 1.0, 1.0, 1.0, 1.0],\n"
"                  \"hostname\": [\"compute-node-3\", \"compute-node-15\"],\n"
"                  \"imbalance\": [0.05, 0.15]}\n"
"\n"
"                 If \"-imbalance\" is appended to any region name in\n"
"                 the configuration file and the \"hostname\" and\n"
"                 \"imbalance\" fields are provided then those\n"
"                 regions will have an injected delay on the hosts\n"
"                 listed.  In the above example a 5%% delay on\n"
"                 \"my-compute-node-3\" and a 15%% delay on\n"
"                 \"my-compute-node-15\" are injected when executing\n"
"                 the dgemm region.\n"
"\n"
"                 If \"-progress\" is appended to any region name in the\n"
"                 configuration, then progress for the region will be\n"
"                 reported through the geopm_prof_progress API.\n"
"\n"
"\n";

    const int ERROR_HELP = -4096;
    err = MPI_Init(&argc, &argv);
    if (!err) {
        err = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    }

    if (!err && argc > 1) {
        if (strncmp(argv[1], "--help", strlen("--help")) == 0 ||
            strncmp(argv[1], "-h", strlen("-h")) == 0) {
            if (!rank) {
                printf(usage, argv[0], argv[0]);
            }
            err = ERROR_HELP;
        }
        int offset = 1;
        if (strncmp(argv[1], "--verbose", strlen("--verbose")) == 0) {
            if (!rank) {
                verbosity = 1;
            }
            ++offset;
        }
        if (argc > offset) {
            config_path = argv[offset];
        }
    }

    if (!err) {
        err = geopm_prof_region("model-init", GEOPM_REGION_HINT_UNKNOWN, &init_rid);
    }
    if (!err) {
        err = geopm_prof_enter(init_rid);
    }
    if (!err) {
        // Do application initialization
        uint64_t loop_count = 0;
        std::vector<std::string> region_sequence;
        std::vector<double> big_o_sequence;
        if (config_path) {
            geopm::model_parse_config(config_path, loop_count, region_sequence, big_o_sequence);
        }
        else {
            // Default values if no configuration is specified
            loop_count = 10;
            region_sequence = {"sleep", "stream", "dgemm", "stream", "all2all"};
            big_o_sequence = {1.0, 1.0, 1.0, 1.0, 1.0};
        }
        geopm::ModelApplication app(loop_count, region_sequence, big_o_sequence, verbosity, rank);
        err = geopm_prof_exit(init_rid);
        if (!err) {
            // Run application
            app.run();
        }
    }

    if (err == ERROR_HELP) {
        err = 0;
    }

    if (err) {
        char err_msg[NAME_MAX] = {};
        geopm_error_message(err, err_msg, NAME_MAX);
        std::cerr << "ERROR: " << argv[0] << ": " << err_msg << std::endl;
    }

    int err_fin = MPI_Finalize();
    err = err ? err : err_fin;

    return err;
}
<commit_msg>Do not markup anything if all regions are 'unmarked'<commit_after>/*
 * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *
 *     * Neither the name of Intel Corporation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <cstdint>
#include <string.h>
#include <mpi.h>
#include <limits.h>
#include <algorithm>

#include "geopm.h"
#include "geopm_error.h"
#include "ModelApplication.hpp"
#include "ModelParse.hpp"

int main(int argc, char **argv)
{
    int err = 0;
    int rank;
    int verbosity = 0;
    int do_markup_init = 1;
    uint64_t init_rid;
    char *config_path = NULL;
    const char *usage = "\n"
"%s -h | --help\n"
"    Print this help message.\n"
"\n"
"%s [--verbose] [config_file]\n"
"\n"
"    --verbose: Print output from rank zero as every region executes.\n"
"\n"
"    config_file: Path to json file containing loop count and sequence\n"
"                 of regions in each loop.\n"
"\n"
"                 Example configuration json string:\n"
"\n"
"                 {\"loop-count\": 10,\n"
"                  \"region\": [\"sleep\", \"stream\", \"dgemm\", \"stream\", \"all2all\"],\n"
"                  \"big-o\": [1.0, 1.0, 1.0, 1.0, 1.0]}\n"
"\n"
"                 The \"loop-count\" value is an integer that sets the\n"
"                 number of loops executed.  Each time through the loop\n"
"                 the regions listed in the \"region\" array are\n"
"                 executed.  The \"big-o\" array gives double precision\n"
"                 values for each region.  Region names can be one of\n"
"                 the following options:\n"
"\n"
"                 sleep: Executes clock_nanosleep() for big-o seconds.\n"
"\n"
"                 spin: Executes a spin loop for big-o seconds.\n"
"\n"
"                 stream: Executes stream \"triadd\" on a vector with\n"
"                 length proportional to big-o.\n"
"\n"
"                 dgemm: Dense matrix-matrix multiply with floating\n"
"                 point operations proportional to big-o.\n"
"\n"
"                 all2all: All processes send buffers to all other\n"
"                 processes.  The time of this operation is\n"
"                 proportional to big-o.\n"
"\n"
"                 Example configuration json string with imbalance and\n"
"                 progress:\n"
"\n"
"                 {\"loop-count\": 10,\n"
"                  \"region\": [\"sleep\", \"stream-progress\", \"dgemm-imbalance\", \"stream\", \"all2all\"],\n"
"                  \"big-o\": [1.0, 1.0, 1.0, 1.0, 1.0],\n"
"                  \"hostname\": [\"compute-node-3\", \"compute-node-15\"],\n"
"                  \"imbalance\": [0.05, 0.15]}\n"
"\n"
"                 If \"-imbalance\" is appended to any region name in\n"
"                 the configuration file and the \"hostname\" and\n"
"                 \"imbalance\" fields are provided then those\n"
"                 regions will have an injected delay on the hosts\n"
"                 listed.  In the above example a 5%% delay on\n"
"                 \"my-compute-node-3\" and a 15%% delay on\n"
"                 \"my-compute-node-15\" are injected when executing\n"
"                 the dgemm region.\n"
"\n"
"                 If \"-progress\" is appended to any region name in the\n"
"                 configuration, then progress for the region will be\n"
"                 reported through the geopm_prof_progress API.\n"
"\n"
"\n";

    const int ERROR_HELP = -4096;
    err = MPI_Init(&argc, &argv);
    if (!err) {
        err = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    }

    if (!err && argc > 1) {
        if (strncmp(argv[1], "--help", strlen("--help")) == 0 ||
            strncmp(argv[1], "-h", strlen("-h")) == 0) {
            if (!rank) {
                printf(usage, argv[0], argv[0]);
            }
            err = ERROR_HELP;
        }
        int offset = 1;
        if (strncmp(argv[1], "--verbose", strlen("--verbose")) == 0) {
            if (!rank) {
                verbosity = 1;
            }
            ++offset;
        }
        if (argc > offset) {
            config_path = argv[offset];
        }
    }

    uint64_t loop_count = 0;
    std::vector<std::string> region_sequence;
    std::vector<double> big_o_sequence;

    if (!err) {
        if (config_path) {
            geopm::model_parse_config(config_path, loop_count, region_sequence, big_o_sequence);
        }
        else {
            // Default values if no configuration is specified
            loop_count = 10;
            region_sequence = {"sleep", "stream", "dgemm", "stream", "all2all"};
            big_o_sequence = {1.0, 1.0, 1.0, 1.0, 1.0};
        }

        if (region_sequence.size() > 0 &&
            std::all_of(region_sequence.cbegin(), region_sequence.cend(),
                        [](const std::string &region) {
                            return (region.find("-unmarked") != std::string::npos);
                        })) {
            do_markup_init = 0;
        }
    }

    if (!err && do_markup_init == 1) {
        err = geopm_prof_region("model-init", GEOPM_REGION_HINT_UNKNOWN, &init_rid);
    }
    if (!err && do_markup_init == 1) {
        err = geopm_prof_enter(init_rid);
    }
    if (!err) {
        // Do application initialization
        geopm::ModelApplication app(loop_count, region_sequence, big_o_sequence, verbosity, rank);
        if (do_markup_init == 1) {
            err = geopm_prof_exit(init_rid);
        }
        if (!err) {
            // Run application
            app.run();
        }
    }

    if (err == ERROR_HELP) {
        err = 0;
    }

    if (err) {
        char err_msg[NAME_MAX] = {};
        geopm_error_message(err, err_msg, NAME_MAX);
        std::cerr << "ERROR: " << argv[0] << ": " << err_msg << std::endl;
    }

    int err_fin = MPI_Finalize();
    err = err ? err : err_fin;

    return err;
}
<|endoftext|>


<commit_before>
#include "googlepush.hh"
#include <iostream>
#include <string.h>
#include "log/logmanager.hh"

using namespace std;

GooglePushNotificationRequest::GooglePushNotificationRequest(const PushInfo &pinfo)
: PushNotificationRequest(pinfo.mAppId, "google") {
	const string &deviceToken = pinfo.mDeviceToken;
	const string &apiKey = pinfo.mApiKey;
	const string &arg = pinfo.mFromName.empty() ? pinfo.mFromUri : pinfo.mFromName;
	const string &callid = pinfo.mCallId;
	ostringstream httpBody;
	time_t t = time(NULL);
	struct tm *tm = localtime(&t);
	char date[20];
	strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", tm);

	httpBody << "{\"registration_ids\":[\"" << deviceToken << "\"],\"data\":{\"loc-args\":\"" << arg
	<< "\"}"
	",\"priority\":\"high\""
	",\"call-id\":\"" << callid
	<< "\",\"uuid\":" << pinfo.mUid
	<< ",\"send-time\":\"" << date << "\"}";
	mHttpBody = httpBody.str();
	LOGD("Push notification https post body is %s", mHttpBody.c_str());

	ostringstream httpHeader;
	httpHeader << "POST /gcm/send "
	"HTTP/1.1\r\nHost:android.googleapis.com\r\nContent-Type:application/json\r\nAuthorization:key="
	<< apiKey << "\r\nContent-Length:" << httpBody.str().size() << "\r\n\r\n";
	mHttpHeader = httpHeader.str();
	SLOGD << "PNR " << this << " https post header is " << mHttpHeader;
}

void GooglePushNotificationRequest::createPushNotification() {
	int headerLength = mHttpHeader.length();
	int bodyLength = mHttpBody.length();

	mBuffer.clear();
	mBuffer.resize(headerLength + bodyLength);

	char *binaryMessageBuff = &mBuffer[0];
	char *binaryMessagePt = binaryMessageBuff;

	memcpy(binaryMessagePt, &mHttpHeader[0], headerLength);
	binaryMessagePt += headerLength;

	memcpy(binaryMessagePt, &mHttpBody[0], bodyLength);
	binaryMessagePt += bodyLength;
}

const vector<char> &GooglePushNotificationRequest::getData() {
	createPushNotification();
	return mBuffer;
}

string GooglePushNotificationRequest::isValidResponse(const string &str) {
	static const char expected[] = "HTTP/1.1 200";
	return strncmp(expected, str.c_str(), sizeof(expected) - 1) == 0 ? "" : "Unexpected HTTP response value (not 200 OK)";
}
<commit_msg>Fix JSON of Google GCM push (deprecated), uuid wasn't enclosed between quotes.<commit_after>
#include "googlepush.hh"
#include <iostream>
#include <string.h>
#include "log/logmanager.hh"

using namespace std;

GooglePushNotificationRequest::GooglePushNotificationRequest(const PushInfo &pinfo)
: PushNotificationRequest(pinfo.mAppId, "google") {
	const string &deviceToken = pinfo.mDeviceToken;
	const string &apiKey = pinfo.mApiKey;
	const string &arg = pinfo.mFromName.empty() ? pinfo.mFromUri : pinfo.mFromName;
	const string &callid = pinfo.mCallId;
	ostringstream httpBody;
	time_t t = time(NULL);
	struct tm *tm = localtime(&t);
	char date[20];
	strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", tm);

	httpBody << "{\"registration_ids\":[\"" << deviceToken << "\"],\"data\":{\"loc-args\":\"" << arg
	<< "\"}"
	",\"priority\":\"high\""
	",\"call-id\":\"" << callid
	<< "\", \"uuid\":\"" << pinfo.mUid
	<< "\", \"send-time\":\"" << date << "\"}";
	mHttpBody = httpBody.str();
	LOGD("Push notification https post body is %s", mHttpBody.c_str());

	ostringstream httpHeader;
	httpHeader << "POST /gcm/send "
	"HTTP/1.1\r\nHost:android.googleapis.com\r\nContent-Type:application/json\r\nAuthorization:key="
	<< apiKey << "\r\nContent-Length:" << httpBody.str().size() << "\r\n\r\n";
	mHttpHeader = httpHeader.str();
	SLOGD << "PNR " << this << " https post header is " << mHttpHeader;
}

void GooglePushNotificationRequest::createPushNotification() {
	int headerLength = mHttpHeader.length();
	int bodyLength = mHttpBody.length();

	mBuffer.clear();
	mBuffer.resize(headerLength + bodyLength);

	char *binaryMessageBuff = &mBuffer[0];
	char *binaryMessagePt = binaryMessageBuff;

	memcpy(binaryMessagePt, &mHttpHeader[0], headerLength);
	binaryMessagePt += headerLength;

	memcpy(binaryMessagePt, &mHttpBody[0], bodyLength);
	binaryMessagePt += bodyLength;
}

const vector<char> &GooglePushNotificationRequest::getData() {
	createPushNotification();
	return mBuffer;
}

string GooglePushNotificationRequest::isValidResponse(const string &str) {
	static const char expected[] = "HTTP/1.1 200";
	return strncmp(expected, str.c_str(), sizeof(expected) - 1) == 0 ? "" : "Unexpected HTTP response value (not 200 OK)";
}
<|endoftext|>


<commit_before>/** tutorial/Ex1
 * This example shows how to:
 * initialize a femus application;
 * define the multilevel-mesh object mlMsh;
 * read from the file ./input/square.neu the coarse-level mesh and associate it to mlMsh;
 * add in mlMsh uniform refined level-meshes;
 * define the multilevel-solution object mlSol associated to mlMsh;
 * add in mlSol different types of finite element solution variables;
 * initialize the solution varables;
 * define vtk and gmv writer objects associated to mlSol;
 * print vtk and gmv binary-format files in ./output directory.
 **/

#include "FemusInit.hpp"
#include "MultiLevelProblem.hpp"
#include "VTKWriter.hpp"
#include "GMVWriter.hpp"

using namespace femus;

double InitalValueU(const std::vector < double >& x) {
  return x[0] + x[1];
}

double InitalValueP(const std::vector < double >& x) {
  return x[0];
}

double InitalValueT(const std::vector < double >& x) {
  return x[1];
}

int main(int argc, char** args) {

  // init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);

  // define multilevel mesh
  MultiLevelMesh mlMsh;
  double scalingFactor = 1.;
  // read coarse level mesh and generate finers level meshes
  mlMsh.ReadCoarseMesh("./input/square.neu", "seventh", scalingFactor);
  /* "seventh" is the order of accuracy that is used in the gauss integration scheme
      probably in the furure it is not going to be an argument of this function   */
  unsigned numberOfUniformLevels = 3;
  unsigned numberOfSelectiveLevels = 0;
  mlMsh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);
  mlMsh.PrintInfo();

  // define the multilevel solution and attach the mlMsh object to it
  MultiLevelSolution mlSol(&mlMsh);

  // add variables to mlSol
  mlSol.AddSolution("U", LAGRANGE, FIRST);
  mlSol.AddSolution("V", LAGRANGE, SERENDIPITY);
  mlSol.AddSolution("W", LAGRANGE, SECOND);
  mlSol.AddSolution("P", DISCONTINOUS_POLYNOMIAL, ZERO);
  mlSol.AddSolution("T", DISCONTINOUS_POLYNOMIAL, FIRST);

  mlSol.Initialize("All");    // initialize all varaibles to zero

  mlSol.Initialize("U", InitalValueU);
  mlSol.Initialize("P", InitalValueP);
  mlSol.Initialize("T", InitalValueT);    // note that this initialization is the same as piecewise constant element

  // print solutions
  std::vector < std::string > variablesToBePrinted;
  variablesToBePrinted.push_back("U");
  variablesToBePrinted.push_back("P");
  variablesToBePrinted.push_back("T");

  VTKWriter vtkIO(&mlSol);
  vtkIO.write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);

  GMVWriter gmvIO(&mlSol);
  variablesToBePrinted.push_back("all");
  gmvIO.SetDebugOutput(false);
  gmvIO.write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);

  return 0;
}<commit_msg>Initialized temperature control variables<commit_after>/** tutorial/Ex1
 * This example shows how to:
 * initialize a femus application;
 * define the multilevel-mesh object mlMsh;
 * read from the file ./input/square.neu the coarse-level mesh and associate it to mlMsh;
 * add in mlMsh uniform refined level-meshes;
 * define the multilevel-solution object mlSol associated to mlMsh;
 * add in mlSol different types of finite element solution variables;
 * initialize the solution varables;
 * define vtk and gmv writer objects associated to mlSol;
 * print vtk and gmv binary-format files in ./output directory.
 **/

#include "FemusInit.hpp"
#include "MultiLevelProblem.hpp"
#include "VTKWriter.hpp"
#include "GMVWriter.hpp"

using namespace femus;

double InitalValueU(const std::vector < double >& x) {
  return x[0] + x[1];
}

double InitalValueP(const std::vector < double >& x) {
  return x[0];
}

double InitalValueT(const std::vector < double >& x) {
  return x[1];
}

int main(int argc, char** args) {

  // init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);

  // define multilevel mesh
  MultiLevelMesh mlMsh;
  double scalingFactor = 1.;
  // read coarse level mesh and generate finers level meshes
  mlMsh.ReadCoarseMesh("./input/square.neu", "seventh", scalingFactor);
  /* "seventh" is the order of accuracy that is used in the gauss integration scheme
      probably in the furure it is not going to be an argument of this function   */
  unsigned numberOfUniformLevels = 3;
  unsigned numberOfSelectiveLevels = 0;
  mlMsh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);
  mlMsh.PrintInfo();

  // define the multilevel solution and attach the mlMsh object to it
  MultiLevelSolution mlSol(&mlMsh);

  // add variables to mlSol
  mlSol.AddSolution("Thom", LAGRANGE, SECOND);
  mlSol.AddSolution("ThomAdj", LAGRANGE, SECOND);
  mlSol.AddSolution("Tcont", LAGRANGE, SECOND);

  mlSol.Initialize("All");    // initialize all varaibles to zero

  mlSol.Initialize("Thom", InitalValueU);
  mlSol.Initialize("ThomAdj", InitalValueP);
  mlSol.Initialize("Tcont", InitalValueT);    // note that this initialization is the same as piecewise constant element

  // print solutions
  std::vector < std::string > variablesToBePrinted;
  variablesToBePrinted.push_back("Thom");
  variablesToBePrinted.push_back("ThomAdj");
  variablesToBePrinted.push_back("Tcont");

  VTKWriter vtkIO(&mlSol);
  vtkIO.write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);

  GMVWriter gmvIO(&mlSol);
  variablesToBePrinted.push_back("all");
  gmvIO.SetDebugOutput(false);
  gmvIO.write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);

  return 0;
}<|endoftext|>


<commit_before>#include "PrecompiledHeader.h"
#include "SearchEngine.h"
#include "SearchWindow.h"
#include "Utilities/FontCache.h"
#include "Utilities/WindowUtilities.h"

static SearchWindow* s_Instance;
static HINSTANCE GetHInstance();

constexpr DWORD kWindowExStyle = WS_EX_APPWINDOW | WS_EX_OVERLAPPEDWINDOW;
constexpr DWORD kWindowStyle = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
constexpr int kWindowClientWidth = 409;
constexpr int kWindowClientHeight = 639;

constexpr intptr_t kBackgroundColor = COLOR_WINDOW + 1;

enum class ByteUnit : uint64_t
{
    B = 1,
    KB = 1024 * B,
    MB = 1024 * KB,
    GB = 1024 * MB,
    TB = 1024 * GB,
};

struct NamedByteUnit
{
    constexpr NamedByteUnit(ByteUnit unit, const wchar_t* name) :
        unit(unit), name(name)
    {
    }

    ByteUnit unit;
    const wchar_t* name;
};

constexpr NamedByteUnit kByteUnits[] =
{
    { ByteUnit::B, L"B" },
    { ByteUnit::KB, L"KB" },
    { ByteUnit::MB, L"MB" },
    { ByteUnit::GB, L"GB" },
    { ByteUnit::TB, L"TB" },
};

SearchWindow::SearchWindow(const FontCache& fontCache, int nCmdShow) :
    m_FontCache(fontCache)
{
    Assert(s_Instance == nullptr); // Current design dictates only one Search Window gets spawned per app instance
    s_Instance = this;

    WNDCLASSEXW classDescription = {};
    classDescription.cbSize = sizeof(classDescription);
    classDescription.style = CS_HREDRAW | CS_VREDRAW;
    classDescription.lpfnWndProc = SearchWindow::WndProc;
    classDescription.hInstance = GetHInstance();
    classDescription.hCursor = LoadCursorW(nullptr, IDC_ARROW);
    classDescription.hbrBackground = reinterpret_cast<HBRUSH>(kBackgroundColor);
    classDescription.lpszClassName = L"SearchWindow";

    m_WindowClass = RegisterClassExW(&classDescription);
    Assert(m_WindowClass != 0);

    auto hwnd = CreateWindowExW(kWindowExStyle, m_WindowClass, L"File System Search - Search", kWindowStyle, CW_USEDEFAULT, 0, 0, 0, nullptr, nullptr, GetHInstance(), nullptr);
    Assert(m_Hwnd == hwnd);

    auto wasVisible = ShowWindow(m_Hwnd, nCmdShow);
    Assert(wasVisible == FALSE);
}

SearchWindow::~SearchWindow()
{
    Assert(s_Instance == this);
    s_Instance = nullptr;
}

LRESULT SearchWindow::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
        case WM_CREATE:
        {
            s_Instance->OnCreate(hWnd);

            auto createStruct = reinterpret_cast<CREATESTRUCT*>(lParam);
            s_Instance->AdjustSearchWindowPlacement(createStruct->x, createStruct->y, GetDpiForWindow(hWnd));
            return 0;
        }

        case WM_CLOSE:
            PostQuitMessage(0);
            break;

        case WM_CTLCOLORSTATIC:
            return kBackgroundColor;

        case WM_DPICHANGED:
        {
            auto targetRect = reinterpret_cast<RECT*>(lParam);
            s_Instance->AdjustSearchWindowPlacement(targetRect->left, targetRect->top, HIWORD(wParam));

            return 0;
        }

        case WM_COMMAND:
        {
            switch (wParam)
            {
                case IDOK:
                    s_Instance->SearchButtonClicked();
                    break;

                default:
                {
                    switch (LOWORD(wParam))
                    {
                        case m_SearchButton:
                        {
                            switch (HIWORD(wParam))
                            {
                                case BN_CLICKED:
                                    s_Instance->SearchButtonClicked();
                                    break;
                            }

                            break;
                        }
                    }

                }
            }

            break;
        }
    }

    return DefWindowProcW(hWnd, msg, wParam, lParam);
}

void SearchWindow::OnCreate(HWND hWnd)
{
    m_Hwnd = hWnd;

    for (size_t i = 0; i < m_ControlCount; i++)
        m_Controls[i] = kControls[i].Create(hWnd, i);

    // Restrict to numbers only
    HWND ignoreFilesLargerThanTextBox = m_Controls[m_IgnoreFilesLargerThanTextBox];
    SetWindowLongPtrW(ignoreFilesLargerThanTextBox, GWL_STYLE, GetWindowLongPtrW(ignoreFilesLargerThanTextBox, GWL_STYLE) | ES_NUMBER);

    // Populate byteUnitComboBox
    HWND byteUnitComboBox = m_Controls[m_IgnoreFilesLargerThanUnitComboBox];
    for (size_t i = 0; i < ARRAYSIZE(kByteUnits); i++)
    {
        SendMessageW(byteUnitComboBox, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(kByteUnits[i].name));
        SendMessageW(byteUnitComboBox, CB_SETITEMDATA, i, static_cast<LPARAM>(kByteUnits[i].unit));
    }

    // Select MB by default
    SendMessageW(byteUnitComboBox, CB_SETCURSEL, 2 /* MB */, 0);

    // Enable default options
    SendMessageW(m_Controls[m_SearchForFilesCheckBox], BM_SETCHECK, BST_CHECKED, 0);
    SendMessageW(m_Controls[m_SearchInFileNameCheckBox], BM_SETCHECK, BST_CHECKED, 0);
    SendMessageW(m_Controls[m_SearchRecursivelyCheckBox], BM_SETCHECK, BST_CHECKED, 0);
    SendMessageW(m_Controls[m_IgnoreCaseCheckBox], BM_SETCHECK, BST_CHECKED, 0);
    SendMessageW(m_Controls[m_IgnoreFilesStartingWithDotCheckBox], BM_SETCHECK, BST_CHECKED, 0);
}

void SearchWindow::AdjustSearchWindowPlacement(int positionX, int positionY, uint32_t dpi)
{
    RECT adjustedWindowRect =
    {
        0,
        0,
        DipsToPixels(kWindowClientWidth, dpi),
        DipsToPixels(kWindowClientHeight, dpi),
    };

    auto result = AdjustWindowRectExForDpi(&adjustedWindowRect, kWindowStyle, FALSE, kWindowExStyle, dpi);
    Assert(result != FALSE);

    result = SetWindowPos(m_Hwnd, nullptr, positionX, positionY, adjustedWindowRect.right - adjustedWindowRect.left, adjustedWindowRect.bottom - adjustedWindowRect.top, SWP_NOACTIVATE | SWP_NOZORDER);
    Assert(result != FALSE);

    auto font = m_FontCache.GetFontForDpi(dpi);
    for (size_t i = 0; i < m_ControlCount; i++)
    {
        HWND childHwnd = m_Controls[i];
        Assert(childHwnd != nullptr);

        const auto& desc = kControls[i];
        auto x = DipsToPixels(desc.x, dpi);
        auto y = DipsToPixels(desc.y, dpi);
        auto width = DipsToPixels(desc.width, dpi);
        auto height = DipsToPixels(desc.height, dpi);

        result = SetWindowPos(childHwnd, nullptr, x, y, width, height, SWP_NOACTIVATE | SWP_NOZORDER);
        Assert(result != FALSE);

        SendMessageW(childHwnd, WM_SETFONT, reinterpret_cast<WPARAM>(font), TRUE);
    }
}

void SearchWindow::SearchButtonClicked()
{
    std::wstring searchPath = GetWindowTextW(m_Controls[m_SearchPathTextBox]);
    std::wstring searchPattern = GetWindowTextW(m_Controls[m_SearchPatternTextBox]);
    std::wstring searchString = GetWindowTextW(m_Controls[m_SearchStringTextBox]);

    std::wstring ignoreFilesLargerThan = GetWindowTextW(m_Controls[m_IgnoreFilesLargerThanTextBox]);
    auto comboBoxIndex = SendMessageW(m_Controls[m_IgnoreFilesLargerThanUnitComboBox], CB_GETCURSEL, 0, 0);
    ByteUnit ignoreFilesLargerThanUnit = static_cast<ByteUnit>(SendMessageW(m_Controls[m_IgnoreFilesLargerThanUnitComboBox], CB_GETITEMDATA, comboBoxIndex, 0));
    Assert(ignoreFilesLargerThanUnit <= ByteUnit::TB);

    bool searchForFiles = IsChecked(m_Controls[m_SearchForFilesCheckBox]);
    bool searchInFilePath = IsChecked(m_Controls[m_SearchInFilePathCheckBox]);
    bool searchInFileName = IsChecked(m_Controls[m_SearchInFileNameCheckBox]);
    bool searchInFileContents = IsChecked(m_Controls[m_SearchInFileContentsCheckBox]);
    bool searchContentsAsUtf8 = IsChecked(m_Controls[m_SearchFileContentsAsUTF8CheckBox]);
    bool searchContentsAsUtf16 = IsChecked(m_Controls[m_SearchFileContentsAsUTF16CheckBox]);

    bool searchForDirectories = IsChecked(m_Controls[m_SearchForDirectoriesCheckBox]);
    bool searchInDirectoryPath = IsChecked(m_Controls[m_SearchInDirectoryPathCheckBox]);
    bool searchInDirectoryName = IsChecked(m_Controls[m_SearchInDirectoryNameCheckBox]);

    bool searchRecursively = IsChecked(m_Controls[m_SearchRecursivelyCheckBox]);
    bool ignoreCase = IsChecked(m_Controls[m_IgnoreCaseCheckBox]);
    bool ignoreFilesStartingWithDot = IsChecked(m_Controls[m_IgnoreFilesStartingWithDotCheckBox]);

    bool useDirectStorage = IsChecked(m_Controls[m_UseDirectStorageCheckBox]);

    if (!searchForFiles && !searchForDirectories)
    {
        DisplayValidationFailure(L"Either 'Search for files', and/or 'Search for directories' must be selected.");
        return;
    }

    if (searchForFiles && !searchInFilePath && !searchInFileName && !searchInFileContents)
    {
        DisplayValidationFailure(L"At least one file search mode must be selected if searching for files.");
        return;
    }

    if (searchInFileContents && !searchContentsAsUtf8 && !searchContentsAsUtf16)
    {
        DisplayValidationFailure(L"When searching file contents, UTF8 and/or UTF16 search must be selected.");
        return;
    }

    if (searchForDirectories && !searchInDirectoryPath && !searchInDirectoryName)
    {
        DisplayValidationFailure(L"At least one directory search mode must be selected if searching for directories.");
        return;
    }

    if (searchPath.empty())
    {
        DisplayValidationFailure(L"Search path must not be empty.");
        return;
    }

    if (searchPattern.empty())
    {
        DisplayValidationFailure(L"Search pattern must not be empty.");
        return;
    }

    if (searchString.empty())
    {
        DisplayValidationFailure(L"Search string must not be empty.");
        return;
    }

    if (searchString.length() > 1 << 26)
    {
        if (searchString.length() > (1 << 30) ||
            WideCharToMultiByte(CP_UTF8, 0, searchString.c_str(), static_cast<int>(searchString.length()), nullptr, 0, nullptr, nullptr) > (1 << 30))
        {
            DisplayValidationFailure(L"Search string is too long.");
            return;
        }
    }

    if (searchInFileContents && searchContentsAsUtf8 &&
        std::find_if(searchString.begin(), searchString.end(), [](wchar_t c) { return c < 0 || c > 127; }) != searchString.end())
    {
        DisplayValidationFailure(L"Searching for file contents as UTF8 with non-ascii string is not implemented.");
        return;
    }

    SearchFlags searchFlags = {};

    if (searchForFiles)
        searchFlags |= SearchFlags::kSearchForFiles;

    if (searchInFileName)
        searchFlags |= SearchFlags::kSearchInFileName;

    if (searchInFilePath)
        searchFlags |= SearchFlags::kSearchInFilePath;

    if (searchInFileContents)
        searchFlags |= SearchFlags::kSearchInFileContents;

    if (searchContentsAsUtf8)
        searchFlags |= SearchFlags::kSearchContentsAsUtf8;

    if (searchContentsAsUtf16)
        searchFlags |= SearchFlags::kSearchContentsAsUtf16;

    if (searchForDirectories)
        searchFlags |= SearchFlags::kSearchForDirectories;

    if (searchInDirectoryPath)
        searchFlags |= SearchFlags::kSearchInDirectoryPath;

    if (searchInDirectoryName)
        searchFlags |= SearchFlags::kSearchInDirectoryName;

    if (searchRecursively)
        searchFlags |= SearchFlags::kSearchRecursively;

    if (ignoreCase)
        searchFlags |= SearchFlags::kIgnoreCase;

    if (ignoreFilesStartingWithDot)
        searchFlags |= SearchFlags::kIgnoreDotStart;

    if (useDirectStorage)
        searchFlags |= SearchFlags::kUseDirectStorage;

    uint64_t ignoreLargerThan = 0;
    for (auto c : ignoreFilesLargerThan)
    {
        Assert(c >= '0' && c <= '9');
        if (c < '0' || c > '9')
        {
            ignoreLargerThan = std::numeric_limits<uint64_t>::max();
            break;
        }

        if (ignoreLargerThan > std::numeric_limits<uint64_t>::max() / 10)
        {
            ignoreLargerThan = std::numeric_limits<uint64_t>::max();
            break;
        }

        ignoreLargerThan = ignoreLargerThan * 10;
        auto digit = (c - '0');

        if (ignoreLargerThan > std::numeric_limits<uint64_t>::max() - digit)
        {
            ignoreLargerThan = std::numeric_limits<uint64_t>::max();
            break;
        }

        ignoreLargerThan += digit;
    }

    if (ignoreLargerThan > std::numeric_limits<uint64_t>::max() / static_cast<uint64_t>(ignoreFilesLargerThanUnit))
    {
        ignoreLargerThan = std::numeric_limits<uint64_t>::max();
    }
    else
    {
        ignoreLargerThan *= static_cast<uint64_t>(ignoreFilesLargerThanUnit);
    }

    auto search = ::Search(
        [](const WIN32_FIND_DATAW* /*findData*/, const wchar_t* path) { std::wstring result = L"Path found: '"; result += path; result += L"'\r\n"; OutputDebugStringW(result.c_str()); },
        [](const SearchStatistics& /*searchStatistics*/, double /*progress*/) {},
        [](const SearchStatistics& /*searchStatistics*/) { OutputDebugStringW(L"Search done!\r\n"); },
        [](const wchar_t* errorMessage) { MessageBoxW(nullptr, errorMessage, L"Error", MB_OK | MB_ICONERROR); },
        searchPath.c_str(),
        searchPattern.c_str(),
        searchString.c_str(),
        searchFlags,
        ignoreLargerThan);

    CleanupSearchOperation(search);
}

void SearchWindow::DisplayValidationFailure(const wchar_t* message)
{
    MessageBoxW(m_Hwnd, message, L"Search is not possible", MB_OK | MB_ICONERROR);
}<commit_msg>Some code cleanup.<commit_after>#include "PrecompiledHeader.h"
#include "SearchEngine.h"
#include "SearchWindow.h"
#include "Utilities/FontCache.h"
#include "Utilities/WindowUtilities.h"

static SearchWindow* s_Instance;
static HINSTANCE GetHInstance();

constexpr DWORD kWindowExStyle = WS_EX_APPWINDOW | WS_EX_OVERLAPPEDWINDOW;
constexpr DWORD kWindowStyle = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
constexpr int kWindowClientWidth = 409;
constexpr int kWindowClientHeight = 639;

constexpr intptr_t kBackgroundColor = COLOR_WINDOW + 1;

enum class ByteUnit : uint64_t
{
    B = 1,
    KB = 1024 * B,
    MB = 1024 * KB,
    GB = 1024 * MB,
    TB = 1024 * GB,
};

struct NamedByteUnit
{
    constexpr NamedByteUnit(ByteUnit unit, const wchar_t* name) :
        unit(unit), name(name)
    {
    }

    ByteUnit unit;
    const wchar_t* name;
};

constexpr NamedByteUnit kByteUnits[] =
{
    { ByteUnit::B, L"B" },
    { ByteUnit::KB, L"KB" },
    { ByteUnit::MB, L"MB" },
    { ByteUnit::GB, L"GB" },
    { ByteUnit::TB, L"TB" },
};

SearchWindow::SearchWindow(const FontCache& fontCache, int nCmdShow) :
    m_FontCache(fontCache)
{
    Assert(s_Instance == nullptr); // Current design dictates only one Search Window gets spawned per app instance
    s_Instance = this;

    WNDCLASSEXW classDescription = {};
    classDescription.cbSize = sizeof(classDescription);
    classDescription.style = CS_HREDRAW | CS_VREDRAW;
    classDescription.lpfnWndProc = SearchWindow::WndProc;
    classDescription.hInstance = GetHInstance();
    classDescription.hCursor = LoadCursorW(nullptr, IDC_ARROW);
    classDescription.hbrBackground = reinterpret_cast<HBRUSH>(kBackgroundColor);
    classDescription.lpszClassName = L"SearchWindow";

    m_WindowClass = RegisterClassExW(&classDescription);
    Assert(m_WindowClass != 0);

    auto hwnd = CreateWindowExW(kWindowExStyle, m_WindowClass, L"File System Search - Search", kWindowStyle, CW_USEDEFAULT, 0, 0, 0, nullptr, nullptr, GetHInstance(), nullptr);
    Assert(m_Hwnd == hwnd);

    auto wasVisible = ShowWindow(m_Hwnd, nCmdShow);
    Assert(wasVisible == FALSE);
}

SearchWindow::~SearchWindow()
{
    Assert(s_Instance == this);
    s_Instance = nullptr;
}

LRESULT SearchWindow::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
        case WM_CREATE:
        {
            s_Instance->OnCreate(hWnd);

            auto createStruct = reinterpret_cast<CREATESTRUCT*>(lParam);
            s_Instance->AdjustSearchWindowPlacement(createStruct->x, createStruct->y, GetDpiForWindow(hWnd));
            return 0;
        }

        case WM_CLOSE:
            PostQuitMessage(0);
            break;

        case WM_CTLCOLORSTATIC:
            return kBackgroundColor;

        case WM_DPICHANGED:
        {
            auto targetRect = reinterpret_cast<RECT*>(lParam);
            s_Instance->AdjustSearchWindowPlacement(targetRect->left, targetRect->top, HIWORD(wParam));

            return 0;
        }

        case WM_COMMAND:
            if (wParam == IDOK || (LOWORD(wParam) == m_SearchButton && HIWORD(wParam) == BN_CLICKED))
                s_Instance->SearchButtonClicked();

            break;
    }

    return DefWindowProcW(hWnd, msg, wParam, lParam);
}

void SearchWindow::OnCreate(HWND hWnd)
{
    m_Hwnd = hWnd;

    for (size_t i = 0; i < m_ControlCount; i++)
        m_Controls[i] = kControls[i].Create(hWnd, i);

    // Restrict to numbers only
    HWND ignoreFilesLargerThanTextBox = m_Controls[m_IgnoreFilesLargerThanTextBox];
    SetWindowLongPtrW(ignoreFilesLargerThanTextBox, GWL_STYLE, GetWindowLongPtrW(ignoreFilesLargerThanTextBox, GWL_STYLE) | ES_NUMBER);

    // Populate byteUnitComboBox
    HWND byteUnitComboBox = m_Controls[m_IgnoreFilesLargerThanUnitComboBox];
    for (size_t i = 0; i < ARRAYSIZE(kByteUnits); i++)
    {
        SendMessageW(byteUnitComboBox, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(kByteUnits[i].name));
        SendMessageW(byteUnitComboBox, CB_SETITEMDATA, i, static_cast<LPARAM>(kByteUnits[i].unit));
    }

    // Select MB by default
    SendMessageW(byteUnitComboBox, CB_SETCURSEL, 2 /* MB */, 0);

    // Enable default options
    SendMessageW(m_Controls[m_SearchForFilesCheckBox], BM_SETCHECK, BST_CHECKED, 0);
    SendMessageW(m_Controls[m_SearchInFileNameCheckBox], BM_SETCHECK, BST_CHECKED, 0);
    SendMessageW(m_Controls[m_SearchRecursivelyCheckBox], BM_SETCHECK, BST_CHECKED, 0);
    SendMessageW(m_Controls[m_IgnoreCaseCheckBox], BM_SETCHECK, BST_CHECKED, 0);
    SendMessageW(m_Controls[m_IgnoreFilesStartingWithDotCheckBox], BM_SETCHECK, BST_CHECKED, 0);
}

void SearchWindow::AdjustSearchWindowPlacement(int positionX, int positionY, uint32_t dpi)
{
    RECT adjustedWindowRect =
    {
        0,
        0,
        DipsToPixels(kWindowClientWidth, dpi),
        DipsToPixels(kWindowClientHeight, dpi),
    };

    auto result = AdjustWindowRectExForDpi(&adjustedWindowRect, kWindowStyle, FALSE, kWindowExStyle, dpi);
    Assert(result != FALSE);

    result = SetWindowPos(m_Hwnd, nullptr, positionX, positionY, adjustedWindowRect.right - adjustedWindowRect.left, adjustedWindowRect.bottom - adjustedWindowRect.top, SWP_NOACTIVATE | SWP_NOZORDER);
    Assert(result != FALSE);

    auto font = m_FontCache.GetFontForDpi(dpi);
    for (size_t i = 0; i < m_ControlCount; i++)
    {
        HWND childHwnd = m_Controls[i];
        Assert(childHwnd != nullptr);

        const auto& desc = kControls[i];
        auto x = DipsToPixels(desc.x, dpi);
        auto y = DipsToPixels(desc.y, dpi);
        auto width = DipsToPixels(desc.width, dpi);
        auto height = DipsToPixels(desc.height, dpi);

        result = SetWindowPos(childHwnd, nullptr, x, y, width, height, SWP_NOACTIVATE | SWP_NOZORDER);
        Assert(result != FALSE);

        SendMessageW(childHwnd, WM_SETFONT, reinterpret_cast<WPARAM>(font), TRUE);
    }
}

void SearchWindow::SearchButtonClicked()
{
    std::wstring searchPath = GetWindowTextW(m_Controls[m_SearchPathTextBox]);
    std::wstring searchPattern = GetWindowTextW(m_Controls[m_SearchPatternTextBox]);
    std::wstring searchString = GetWindowTextW(m_Controls[m_SearchStringTextBox]);

    std::wstring ignoreFilesLargerThan = GetWindowTextW(m_Controls[m_IgnoreFilesLargerThanTextBox]);
    auto comboBoxIndex = SendMessageW(m_Controls[m_IgnoreFilesLargerThanUnitComboBox], CB_GETCURSEL, 0, 0);
    ByteUnit ignoreFilesLargerThanUnit = static_cast<ByteUnit>(SendMessageW(m_Controls[m_IgnoreFilesLargerThanUnitComboBox], CB_GETITEMDATA, comboBoxIndex, 0));
    Assert(ignoreFilesLargerThanUnit <= ByteUnit::TB);

    bool searchForFiles = IsChecked(m_Controls[m_SearchForFilesCheckBox]);
    bool searchInFilePath = IsChecked(m_Controls[m_SearchInFilePathCheckBox]);
    bool searchInFileName = IsChecked(m_Controls[m_SearchInFileNameCheckBox]);
    bool searchInFileContents = IsChecked(m_Controls[m_SearchInFileContentsCheckBox]);
    bool searchContentsAsUtf8 = IsChecked(m_Controls[m_SearchFileContentsAsUTF8CheckBox]);
    bool searchContentsAsUtf16 = IsChecked(m_Controls[m_SearchFileContentsAsUTF16CheckBox]);

    bool searchForDirectories = IsChecked(m_Controls[m_SearchForDirectoriesCheckBox]);
    bool searchInDirectoryPath = IsChecked(m_Controls[m_SearchInDirectoryPathCheckBox]);
    bool searchInDirectoryName = IsChecked(m_Controls[m_SearchInDirectoryNameCheckBox]);

    bool searchRecursively = IsChecked(m_Controls[m_SearchRecursivelyCheckBox]);
    bool ignoreCase = IsChecked(m_Controls[m_IgnoreCaseCheckBox]);
    bool ignoreFilesStartingWithDot = IsChecked(m_Controls[m_IgnoreFilesStartingWithDotCheckBox]);

    bool useDirectStorage = IsChecked(m_Controls[m_UseDirectStorageCheckBox]);

    if (!searchForFiles && !searchForDirectories)
    {
        DisplayValidationFailure(L"Either 'Search for files', and/or 'Search for directories' must be selected.");
        return;
    }

    if (searchForFiles && !searchInFilePath && !searchInFileName && !searchInFileContents)
    {
        DisplayValidationFailure(L"At least one file search mode must be selected if searching for files.");
        return;
    }

    if (searchInFileContents && !searchContentsAsUtf8 && !searchContentsAsUtf16)
    {
        DisplayValidationFailure(L"When searching file contents, UTF8 and/or UTF16 search must be selected.");
        return;
    }

    if (searchForDirectories && !searchInDirectoryPath && !searchInDirectoryName)
    {
        DisplayValidationFailure(L"At least one directory search mode must be selected if searching for directories.");
        return;
    }

    if (searchPath.empty())
    {
        DisplayValidationFailure(L"Search path must not be empty.");
        return;
    }

    if (searchPattern.empty())
    {
        DisplayValidationFailure(L"Search pattern must not be empty.");
        return;
    }

    if (searchString.empty())
    {
        DisplayValidationFailure(L"Search string must not be empty.");
        return;
    }

    if (searchString.length() > 1 << 26)
    {
        if (searchString.length() > (1 << 30) ||
            WideCharToMultiByte(CP_UTF8, 0, searchString.c_str(), static_cast<int>(searchString.length()), nullptr, 0, nullptr, nullptr) > (1 << 30))
        {
            DisplayValidationFailure(L"Search string is too long.");
            return;
        }
    }

    if (searchInFileContents && searchContentsAsUtf8 &&
        std::find_if(searchString.begin(), searchString.end(), [](wchar_t c) { return c < 0 || c > 127; }) != searchString.end())
    {
        DisplayValidationFailure(L"Searching for file contents as UTF8 with non-ascii string is not implemented.");
        return;
    }

    SearchFlags searchFlags = {};

    if (searchForFiles)
        searchFlags |= SearchFlags::kSearchForFiles;

    if (searchInFileName)
        searchFlags |= SearchFlags::kSearchInFileName;

    if (searchInFilePath)
        searchFlags |= SearchFlags::kSearchInFilePath;

    if (searchInFileContents)
        searchFlags |= SearchFlags::kSearchInFileContents;

    if (searchContentsAsUtf8)
        searchFlags |= SearchFlags::kSearchContentsAsUtf8;

    if (searchContentsAsUtf16)
        searchFlags |= SearchFlags::kSearchContentsAsUtf16;

    if (searchForDirectories)
        searchFlags |= SearchFlags::kSearchForDirectories;

    if (searchInDirectoryPath)
        searchFlags |= SearchFlags::kSearchInDirectoryPath;

    if (searchInDirectoryName)
        searchFlags |= SearchFlags::kSearchInDirectoryName;

    if (searchRecursively)
        searchFlags |= SearchFlags::kSearchRecursively;

    if (ignoreCase)
        searchFlags |= SearchFlags::kIgnoreCase;

    if (ignoreFilesStartingWithDot)
        searchFlags |= SearchFlags::kIgnoreDotStart;

    if (useDirectStorage)
        searchFlags |= SearchFlags::kUseDirectStorage;

    uint64_t ignoreLargerThan = 0;
    for (auto c : ignoreFilesLargerThan)
    {
        Assert(c >= '0' && c <= '9');
        if (c < '0' || c > '9' || ignoreLargerThan > std::numeric_limits<uint64_t>::max() / 10)
        {
            ignoreLargerThan = std::numeric_limits<uint64_t>::max();
            break;
        }

        ignoreLargerThan = ignoreLargerThan * 10;
        auto digit = c - '0';

        if (ignoreLargerThan > std::numeric_limits<uint64_t>::max() - digit)
        {
            ignoreLargerThan = std::numeric_limits<uint64_t>::max();
            break;
        }

        ignoreLargerThan += digit;
    }

    if (ignoreLargerThan > std::numeric_limits<uint64_t>::max() / static_cast<uint64_t>(ignoreFilesLargerThanUnit))
    {
        ignoreLargerThan = std::numeric_limits<uint64_t>::max();
    }
    else
    {
        ignoreLargerThan *= static_cast<uint64_t>(ignoreFilesLargerThanUnit);
    }

    auto search = ::Search(
        [](const WIN32_FIND_DATAW* /*findData*/, const wchar_t* path) { std::wstring result = L"Path found: '"; result += path; result += L"'\r\n"; OutputDebugStringW(result.c_str()); },
        [](const SearchStatistics& /*searchStatistics*/, double /*progress*/) {},
        [](const SearchStatistics& /*searchStatistics*/) { OutputDebugStringW(L"Search done!\r\n"); },
        [](const wchar_t* errorMessage) { MessageBoxW(nullptr, errorMessage, L"Error", MB_OK | MB_ICONERROR); },
        searchPath.c_str(),
        searchPattern.c_str(),
        searchString.c_str(),
        searchFlags,
        ignoreLargerThan);

    CleanupSearchOperation(search);
}

void SearchWindow::DisplayValidationFailure(const wchar_t* message)
{
    MessageBoxW(m_Hwnd, message, L"Search is not possible", MB_OK | MB_ICONERROR);
}<|endoftext|>


<commit_before>#include "DySySim.h"
#include <unittest++/UnitTest++.h>
#include <iostream>

namespace dss = dysysim;
using namespace std;

SUITE(DySySim)
{
   TEST(Attenuator) {
      cout << "-- Attenuator" << endl;
      dss::Attenuator att{1, 10.0};
      att.input(1.0);
      CHECK_EQUAL(0.1, att.output());
   }

   TEST(Gain) {
      cout << "-- Gain" << endl;
      dss::Gain gain{1, 10.0};
      gain.input(1.0);
      CHECK_EQUAL(10.0, gain.output());
   }

}

int main() {
   auto result = UnitTest::RunAllTests();
   cout << endl;
   return result;
}
<commit_msg>Added more DySySim tests.<commit_after>#include "DySySim.h"
#include "LibInfoDySySim.h"
#include <unittest++/UnitTest++.h>
#include <iostream>

namespace dss = dysysim;
using namespace std;

const double EPS {0.0001};

SUITE(DySySim)
{
   TEST(Attenuator) {
      cout << "-- Attenuator" << endl;
      dss::Attenuator att{1, 10.0};
      att.input(1.0);
      CHECK_CLOSE(0.1, att.output(), EPS);
      att.input(-1.0);
      CHECK_CLOSE(-0.1, att.output(), EPS);
   }

   TEST(Gain) {
      cout << "-- Gain" << endl;
      dss::Gain gain{1, 10.0};
      gain.input(1.0);
      CHECK_CLOSE(10.0, gain.output(), EPS);
      gain.input(-1.0);
      CHECK_CLOSE(-10.0, gain.output(), EPS);
   }

   TEST(Time) {
      cout << "-- Time" << endl;
      dss::Time time{1, 0.1};
      CHECK_CLOSE(0.0, time.output(), EPS);
      time.next();
      CHECK_CLOSE(0.1, time.output(), EPS);
      time.next();
      CHECK_CLOSE(0.2, time.output(), EPS);
      for(int  i = 0; i < 10; ++i) {
         time.next();
      }
      CHECK_CLOSE(1.2, time.output(), EPS);
   }

   TEST(Step) {
      dss::Time time{1, 0.1};
      cout << "-- Step" << endl;
      dss::Step step{2, 0.0, 1.0, 0.3};
      CHECK_CLOSE(0.0, step.output(), EPS);
      time.next();
      step.next();
      CHECK_CLOSE(0.0, step.output(), EPS);
      time.next();
      step.next();
      CHECK_CLOSE(1.0, step.output(), EPS);
      time.next();
      step.next();
      CHECK_CLOSE(1.0, step.output(), EPS);
      time.next();
      step.next();
      CHECK_CLOSE(1.0, step.output(), EPS);
      time.next();
      step.next();
      CHECK_CLOSE(1.0, step.output(), EPS);
   }
}

int main() {
   cout << "\n== Tests DySySim lib: " << dss::libVersion
        << " " << string(50, '=') << endl << endl;

   auto result = UnitTest::RunAllTests();

   cout << endl << string(80, '=') << endl;

   return result;
}
<|endoftext|>


<commit_before><commit_msg>FIX vulkan barrier for indirect buffer usage and initial data.<commit_after><|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX24T システム制御
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX24T/system.hpp"
#include "RX24T/flash.hpp"

#ifndef F_ICLK
#  error "system_io.hpp requires F_ICLK to be defined"
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  systen_io クラス
		@param[in]	base_clock	ベース・クロック周波数（標準：１０ＭＨｚ）
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t base_clock = 10000000>
	struct system_io {

		//-------------------------------------------------------------//
		/*!
			@brief  システム・クロックの設定
			@return エラーなら「false」
		*/
		//-------------------------------------------------------------//
		static bool setup_system_clock()
		{
			device::SYSTEM::PRCR = 0xA500 | 0b0111;	// クロック、低消費電力、関係書き込み許可

			// メモリーの WAIT 設定
			if(F_ICLK > 64000000) {
				device::SYSTEM::MEMWAIT = 0b10; // 64MHz 以上 wait 設定
			} else if(F_ICLK > 32000000) {
				device::SYSTEM::MEMWAIT = 0b01; // 32MHz 以上 64MHz 以下 wait 設定
			} else {
				device::SYSTEM::MEMWAIT = 0b00; // wait 無し
			}

			while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop");
			device::SYSTEM::OPCCR = 0;  // 高速モード選択
			while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop");

			device::SYSTEM::MOSCWTCR = 9;	// 4ms wait
			// メインクロック・ドライブ能力設定、内部発信
			device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1);
			device::SYSTEM::MOSCCR.MOSTP = 0;  // メインクロック発振器動作
			while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop");

			// ベースクロックからマルチプライヤを計算
			uint8_t x = F_ICLK * 2 / base_clock;
			if(x < (4 * 2) || x >= (16 * 2)) return false;
			x -= 1;
			device::SYSTEM::PLLCR.STC = x;

			uint32_t sysclk = ((static_cast<uint32_t>(x) + 1) * base_clock) / 2;

			// Max: 32MHz
			uint8_t fck = (sysclk / F_FCLK) - 1;
			if(fck > 6) return false;

			uint8_t ick = (sysclk / F_ICLK) - 1;
			if(ick > 6) return false;

			uint8_t pcka = (sysclk / F_PCLKA) - 1;
			if(pcka > 6) return false;
			uint8_t pckb = (sysclk / F_PCLKB) - 1;
			if(pckb > 6) return false;
			uint8_t pckd = (sysclk / F_PCLKD) - 1;
			if(pckd > 6) return false;

			device::SYSTEM::PLLCR2.PLLEN = 0;			// PLL 動作
			while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop");

			device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(fck)
								  | device::SYSTEM::SCKCR.ICK.b(ick)     // Max: 80MHz
								  | device::SYSTEM::SCKCR.PCKA.b(pcka)	 // Max: 80MHz
								  | device::SYSTEM::SCKCR.PCKB.b(pckb)	 // Max: 40MHz
								  | device::SYSTEM::SCKCR.PCKD.b(pckd);	 // Max: 40MHz

			device::SYSTEM::SCKCR3.CKSEL = 0b100;	// PLL 選択

			// クロック関係書き込み不許可
			device::SYSTEM::PRCR = 0xA500;

			// ROM キャッシュを有効（標準）
			device::FLASH::ROMCE = 1;

			return true;
		}
	};
}
<commit_msg>update: base clock manage<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX24T システム制御
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX24T/system.hpp"
#include "RX24T/flash.hpp"

#ifndef F_ICLK
#  error "system_io.hpp requires F_ICLK to be defined"
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  systen_io クラス
		@param[in]	BASE_CLOCK	ベース・クロック周波数（１０ＭＨｚ）
		@param[in]	INTR_CLOCK	内臓クロック周波数（８０ＭＨｚ）
		@param[in]	EXT_CLOCK	外部クロックに入力を行う場合「true」
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t BASE_CLOCK = 10000000, uint32_t INTR_CLOCK = 80000000,
		bool EXT_CLOCK = false>
	struct system_io {

		static uint8_t clock_div_(uint32_t clk) noexcept
		{
			uint8_t div = 0;
			while(clk < INTR_CLOCK) {
				++div;
				clk <<= 1;
			}
			return div;
		}

		//-------------------------------------------------------------//
		/*!
			@brief  システム・クロックの設定
			@return エラーなら「false」
		*/
		//-------------------------------------------------------------//
		static bool setup_system_clock()
		{
			device::SYSTEM::PRCR = 0xA500 | 0b0111;	// クロック、低消費電力、関係書き込み許可

			// メモリーの WAIT 設定
			if(F_ICLK > 64000000) {
				device::SYSTEM::MEMWAIT = 0b10; // 64MHz 以上 wait 設定
			} else if(F_ICLK > 32000000) {
				device::SYSTEM::MEMWAIT = 0b01; // 32MHz 以上 64MHz 以下 wait 設定
			} else {
				device::SYSTEM::MEMWAIT = 0b00; // wait 無し
			}

			while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop");
			device::SYSTEM::OPCCR = 0;  // 高速モード選択
			while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop");

			device::SYSTEM::MOSCWTCR = 9;	// 4ms wait
			// メインクロック・ドライブ能力設定、内部発信
			bool xtal = BASE_CLOCK >= 10000000;
			device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(xtal)
				| device::SYSTEM::MOFCR.MOSEL.b(EXT_CLOCK);
			device::SYSTEM::MOSCCR.MOSTP = 0;  // メインクロック発振器動作
			while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop");

			// (x10.0) 0b010011, (x10.5) 0b010100, (x11.0) 0b010101, (x11.5) 0b010110
			// ... MAX x30.0
			uint32_t n = INTR_CLOCK * 2 / BASE_CLOCK;
			if(n < 20) n = 20;
			else if(n > 60) n = 60;
			n -= 20;
			device::SYSTEM::PLLCR.STC = n + 0b010011;

			device::SYSTEM::PLLCR2.PLLEN = 0;			// PLL 動作
			while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop");

			device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(clock_div_(F_FCLK))
								  | device::SYSTEM::SCKCR.ICK.b(clock_div_(F_ICLK))
								  | device::SYSTEM::SCKCR.PCKA.b(clock_div_(F_PCLKA))
								  | device::SYSTEM::SCKCR.PCKB.b(clock_div_(F_PCLKB))
								  | device::SYSTEM::SCKCR.PCKD.b(clock_div_(F_PCLKD));

			device::SYSTEM::SCKCR3.CKSEL = 0b100;	// PLL 選択

			// クロック関係書き込み不許可
			device::SYSTEM::PRCR = 0xA500;

			// ROM キャッシュを有効（標準）
			device::FLASH::ROMCE = 1;

			return true;
		}
	};
}
<|endoftext|>


<commit_before>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

//    bitwise_and(frame, frame, frame, mask);

    erode(mask, mask, Mat(), Point(-1, -1), 5);
    medianBlur(mask, mask, 5);
    medianBlur(mask, mask, 5);
    medianBlur(mask, mask, 5);

    vector<Vec4i> lines;
    HoughLines(mask, lines, 1, CV_PI / 180.0, 10);

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      float rho = lines[i][0], theta = lines[i][1];
      Point pt1, pt2;
      double a = cos(theta), b = sin(theta);
      double x0 = a * rho, y0 = b * rho;
      pt1.x = cvRound(x0 + 1000 * (-b));
      pt1.y = cvRound(y0 + 1000 * (a));
      pt2.x = cvRound(x0 - 1000 * (-b));
      pt2.y = cvRound(y0 - 1000 * (a));
      line(frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
    }
//    if (lines.size() < 1) continue;

    imshow("edges", mask);
    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<commit_msg>messing with erode<commit_after>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

//    bitwise_and(frame, frame, frame, mask);

//    erode(mask, mask, Mat(), Point(-1, -1), 5);
//    medianBlur(mask, mask, 5);
//    medianBlur(mask, mask, 5);
//    medianBlur(mask, mask, 5);

    vector<Vec2f> lines;
    HoughLines(mask, lines, 1, CV_PI/180, 100, 0, 0 );

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      float rho = lines[i][0], theta = lines[i][1];
      Point pt1, pt2;
      double a = cos(theta), b = sin(theta);
      double x0 = a * rho, y0 = b * rho;
      pt1.x = cvRound(x0 + 1000 * (-b));
      pt1.y = cvRound(y0 + 1000 * (a));
      pt2.x = cvRound(x0 - 1000 * (-b));
      pt2.y = cvRound(y0 - 1000 * (a));
      line(frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
    }
//    if (lines.size() < 1) continue;

    imshow("edges", mask);
    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<|endoftext|>


<commit_before>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask, hsv_mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

    //    low = Scalar(30, 0, 240);
//    high = Scalar(80, 70, 255);

//    inRange(hsv, Scalar(100, 0, 0), Scalar(255, 255, 255), mask);

    bitwise_and(frame, frame, frame, mask);

//    cvtColor(mask, hsv_mask, CV_HS);

    vector <Vec4i> lines;
//    HoughLinesP(mask, lines, 1, CV_PI / 180, 100, 100, 10);

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      Vec4i l = lines[i];
      line(hsv_mask, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
    }

    imshow("edges", mask);
    if (waitKey(30) >= 0) break;
  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<commit_msg>debug mask<commit_after>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask, hsv_mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

    //    low = Scalar(30, 0, 240);
//    high = Scalar(80, 70, 255);

//    inRange(hsv, Scalar(100, 0, 0), Scalar(255, 255, 255), mask);

//    cvtColor(mask, hsv_mask, CV_HS);

    vector <Vec4i> lines;
    HoughLinesP(mask, lines, 1, CV_PI / 180, 100, 100, 10);

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      Vec4i l = lines[i];
      line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
    }

    imshow("edges", frame);
    if (waitKey(30) >= 0) break;
  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<|endoftext|>


<commit_before>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

//    bitwise_and(frame, frame, frame, mask);

    resize(mask, mask, Size(), .5, .5);

    vector <Vec4i> lines;
    HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10);

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      Vec4i l = lines[i];
      line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
      // break;
    }
//    if (lines.size() < 1) continue;

    imshow("edges", mask);
    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<commit_msg>size changes<commit_after>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

//    bitwise_and(frame, frame, frame, mask);

    resize(mask, mask, Size(), .2, .2);

    vector <Vec4i> lines;
    HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10);

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      Vec4i l = lines[i];
      line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
      // break;
    }
//    if (lines.size() < 1) continue;

    imshow("edges", mask);
    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<|endoftext|>


<commit_before>#include "syrah/FixedVector.h"
#include "syrah/CycleTimer.h"
using namespace syrah;
static const int VecWidth = 16;
static const int kDefaultNumElements = 1024;
static const int kNumWarmup = 16;
static const int kNumBench  = 1024 * 16 * 16;

float* randomFloats(int how_many, unsigned int seed) {
  float* result = new float[how_many];
  unsigned int lcg = seed;
  for (int i = 0; i < how_many; i++) {
    lcg = 1664525 * lcg + 1013904223;
    result[i] = -10.f + 20.f * (lcg / 4294967296.f);
  }
  return result;
}

void gather_scalar(const float* input, float* output, const int* permute, int num_elements) {
  for (int i = 0; i < num_elements; i++) {
    output[i] = input[permute[i]];
  }
}

void copy_scalar(const float* input, float* output, const int* permute, int num_elements) {
  for (int i = 0; i < num_elements; i++) {
    output[i] = input[i];
  }
}

void copy_scalar_unroll16(const float* input, float* output, const int* permute, int num_elements) {
  int vec_end = num_elements & (~(VecWidth-1));
  for (int i = 0; i < vec_end; i+= VecWidth) {
#if 0
    float* dst = &output[i];
    const float* src = &input[i];
    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;

    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;

    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;

    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;
#else
    output[i + 0] = input[i + 0];
    output[i + 1] = input[i + 1];
    output[i + 2] = input[i + 2];
    output[i + 3] = input[i + 3];

    output[i + 4] = input[i + 4];
    output[i + 5] = input[i + 5];
    output[i + 6] = input[i + 6];
    output[i + 7] = input[i + 7];

    output[i + 8] = input[i + 8];
    output[i + 9] = input[i + 9];
    output[i + 10] = input[i + 10];
    output[i + 11] = input[i + 11];

    output[i + 12] = input[i + 12];
    output[i + 13] = input[i + 13];
    output[i + 14] = input[i + 14];
    output[i + 15] = input[i + 15];
#endif
  }
  if (vec_end != num_elements) {
    for (int i = vec_end; i < num_elements; i++) {
      output[i] = input[i];
    }
  }
}

void memcpy_scalar(const float* input, float* output, const int* permute, int num_elements) {
  memcpy(output, input, sizeof(float) * num_elements);
}

void reverse_scalar(const float* input, float* output, const int* permute, int num_elements) {
  for (int i = 0; i < num_elements; i++) {
    output[i] = input[num_elements - 1 - i];
  }
}

void reverse_scalar_unroll16(const float* input, float* output, const int* permute, int num_elements) {
  int vec_end = num_elements & (~(VecWidth-1));
  for (int i = 0; i < vec_end; i+= VecWidth) {
    float* dst = &output[i];
    const float* src = &input[num_elements - 1 - i];
    // NOTE(boulos): This version is much faster than doing array
    // indexing while above they're similar with arrays being faster.
    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;

    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;

    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;

    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;
  }
  for (int i = vec_end; i < num_elements; i++) {
    output[i] = input[num_elements - 1 - i];
  }
}

void gather_vector(const float* input, float* output, const int* permute, int num_elements) {
  int vec_end = num_elements & (~(VecWidth-1));
  for (int i = 0; i < vec_end; i+=VecWidth) {
    FixedVector<int, VecWidth> gather_indices(&permute[i], true);
    FixedVector<float, VecWidth> gathered;
    gathered.gather(input, gather_indices, sizeof(float));
    gathered.store_aligned(&(output[i]));
  }
  if (vec_end != num_elements) {
    int i = vec_end;
    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);
    FixedVector<int, VecWidth> gather_indices(&permute[i], true);
    FixedVector<float, VecWidth> gathered;
    gathered.gather(input, gather_indices, sizeof(float), store_mask);
    gathered.store_aligned(&(output[i]), store_mask);
  }
}

void copy_vector(const float* input, float* output, const int* permute, int num_elements) {
  int vec_end = num_elements & (~(VecWidth-1));
  for (int i = 0; i < vec_end; i+=VecWidth) {
    FixedVector<float, VecWidth> gathered(&input[i], true);
    gathered.store_aligned(&(output[i]));
  }
  if (vec_end != num_elements) {
    int i = vec_end;
    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);
    FixedVector<float, VecWidth> gathered(&input[i], true);
    gathered.store_aligned(&(output[i]), store_mask);
  }
}

void reverse_vector(const float* input, float* output, const int* permute, int num_elements) {
  int vec_end = num_elements & (~(VecWidth-1));
  for (int i = 0; i < vec_end; i+=VecWidth) {
    // Load the vecwidth stuff, and then do it backwards
    FixedVector<float, VecWidth> gathered(&input[num_elements - i - VecWidth], true);
    gathered = reverse(gathered);
    gathered.store_aligned(&(output[i]));
  }
  if (vec_end != num_elements) {
    int i = vec_end;
    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);
    FixedVector<float, VecWidth> gathered(&input[num_elements - i - VecWidth], true);
    gathered = reverse(gathered);
    gathered.store_aligned(&(output[i]), store_mask);
  }
}

typedef void(*MemCpyFunc)(const float*, float*, const int*, int);

void BenchFunctions(const char* func1_name, MemCpyFunc func1,
                    const char* func2_name, MemCpyFunc func2,
                    const float* input,
                    float* func1_output, float* func2_output,
                    const int* permute, int num_elements,
                    int bench, int warmup) {
  for (int i = 0; i < warmup; i++) {
    func1(input, func1_output, permute, num_elements);
  }
  CycleTimer::SysClock start_func1 = CycleTimer::currentTicks();
  for (int i = 0; i < bench; i++) {
    func1(input, func1_output, permute, num_elements);
  }
  CycleTimer::SysClock end_func1 = CycleTimer::currentTicks();

  CycleTimer::SysClock func1_ticks = end_func1 - start_func1;
  double func1_time_avg = func1_ticks * CycleTimer::secondsPerTick() / bench;
  CycleTimer::SysClock func1_ticks_per_element = func1_ticks / (num_elements * bench);
  printf("%25s time: %lf (%4.2f million elements per second, %d %s per element)\n", func1_name, func1_time_avg, (num_elements / func1_time_avg) / 1e6f, int(func1_ticks_per_element), CycleTimer::tickUnits());

  if (func2) {
    for (int i = 0; i < warmup; i++) {
      func2(input, func2_output, permute, num_elements);
    }
    CycleTimer::SysClock start_func2 = CycleTimer::currentTicks();
    for (int i = 0; i < bench; i++) {
      func2(input, func2_output, permute, num_elements);
    }
    CycleTimer::SysClock end_func2 = CycleTimer::currentTicks();
    CycleTimer::SysClock func2_ticks = end_func2 - start_func2;
    double func2_time_avg = func2_ticks * CycleTimer::secondsPerTick() / bench;
    CycleTimer::SysClock func2_ticks_per_element = func2_ticks / (num_elements * bench);
    printf("%25s time: %lf (%4.2f million elements per second, %d %s per element)\n", func2_name, func2_time_avg, (num_elements / func2_time_avg) / 1e6f, int(func2_ticks_per_element), CycleTimer::tickUnits());
    printf("%25s vs %s speedup: %lf\n\n", func1_name, func2_name, func1_time_avg / func2_time_avg);

    for (int i = 0; i < num_elements; i++) {
      if (func1_output[i] != func2_output[i]) {
        printf("ERROR: Outputs differ %4d, %s -> %8f != %s -> %8f (input = %8f)\n", i, func1_name, func1_output[i], func2_name, func2_output[i], input[i]);
      }
    }
  }
}

int main(int argc, char** argv) {
  int num_elements = kDefaultNumElements;
  int bench = kNumBench;
  int warmup = kNumWarmup;

  if (argc > 1) num_elements = atoi(argv[1]);

  float* scalar_output = new float[num_elements];
  float* vector_output = new float[num_elements];
  float* input = randomFloats(num_elements, 0xDEADBABE);
  int* permutation = new int[num_elements];
  // Identity for now.
  for (int i = 0; i < num_elements; i++) {
    permutation[i] = i;
  }

#if 0
  BenchFunctions("gather_scalar", gather_scalar,
                 "copy_scalar", copy_scalar,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);

  BenchFunctions("copy_scalar", copy_scalar,
                 "copy_scalar_unroll16", copy_scalar_unroll16,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);
  BenchFunctions("reverse_scalar", reverse_scalar,
                 "reverse_scalar_unroll16", reverse_scalar_unroll16,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);

  BenchFunctions("copy_scalar_unroll16", copy_scalar_unroll16,
                 "copy_vector", copy_vector,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);
#endif
  BenchFunctions("reverse_scalar_unroll16", reverse_scalar_unroll16,
                 "reverse_vector", reverse_vector,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);
  return 0;
}
<commit_msg>Re-enable the other memcpy tests and remember to compare to actual memcpy<commit_after>#include "syrah/FixedVector.h"
#include "syrah/CycleTimer.h"
using namespace syrah;
static const int VecWidth = 16;
static const int kDefaultNumElements = 1024;
static const int kNumWarmup = 16;
static const int kNumBench  = 1024 * 16 * 16;

float* randomFloats(int how_many, unsigned int seed) {
  float* result = new float[how_many];
  unsigned int lcg = seed;
  for (int i = 0; i < how_many; i++) {
    lcg = 1664525 * lcg + 1013904223;
    result[i] = -10.f + 20.f * (lcg / 4294967296.f);
  }
  return result;
}

void gather_scalar(const float* input, float* output, const int* permute, int num_elements) {
  for (int i = 0; i < num_elements; i++) {
    output[i] = input[permute[i]];
  }
}

void copy_scalar(const float* input, float* output, const int* permute, int num_elements) {
  for (int i = 0; i < num_elements; i++) {
    output[i] = input[i];
  }
}

void copy_scalar_unroll16(const float* input, float* output, const int* permute, int num_elements) {
  int vec_end = num_elements & (~(VecWidth-1));
  for (int i = 0; i < vec_end; i+= VecWidth) {
#if 0
    float* dst = &output[i];
    const float* src = &input[i];
    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;

    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;

    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;

    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;
    *dst++ = *src++;
#else
    output[i + 0] = input[i + 0];
    output[i + 1] = input[i + 1];
    output[i + 2] = input[i + 2];
    output[i + 3] = input[i + 3];

    output[i + 4] = input[i + 4];
    output[i + 5] = input[i + 5];
    output[i + 6] = input[i + 6];
    output[i + 7] = input[i + 7];

    output[i + 8] = input[i + 8];
    output[i + 9] = input[i + 9];
    output[i + 10] = input[i + 10];
    output[i + 11] = input[i + 11];

    output[i + 12] = input[i + 12];
    output[i + 13] = input[i + 13];
    output[i + 14] = input[i + 14];
    output[i + 15] = input[i + 15];
#endif
  }
  if (vec_end != num_elements) {
    for (int i = vec_end; i < num_elements; i++) {
      output[i] = input[i];
    }
  }
}

void memcpy_scalar(const float* input, float* output, const int* permute, int num_elements) {
  memcpy(output, input, sizeof(float) * num_elements);
}

void reverse_scalar(const float* input, float* output, const int* permute, int num_elements) {
  for (int i = 0; i < num_elements; i++) {
    output[i] = input[num_elements - 1 - i];
  }
}

void reverse_scalar_unroll16(const float* input, float* output, const int* permute, int num_elements) {
  int vec_end = num_elements & (~(VecWidth-1));
  for (int i = 0; i < vec_end; i+= VecWidth) {
    float* dst = &output[i];
    const float* src = &input[num_elements - 1 - i];
    // NOTE(boulos): This version is much faster than doing array
    // indexing while above they're similar with arrays being faster.
    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;

    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;

    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;

    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;
    *dst++ = *src--;
  }
  for (int i = vec_end; i < num_elements; i++) {
    output[i] = input[num_elements - 1 - i];
  }
}

void gather_vector(const float* input, float* output, const int* permute, int num_elements) {
  int vec_end = num_elements & (~(VecWidth-1));
  for (int i = 0; i < vec_end; i+=VecWidth) {
    FixedVector<int, VecWidth> gather_indices(&permute[i], true);
    FixedVector<float, VecWidth> gathered;
    gathered.gather(input, gather_indices, sizeof(float));
    gathered.store_aligned(&(output[i]));
  }
  if (vec_end != num_elements) {
    int i = vec_end;
    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);
    FixedVector<int, VecWidth> gather_indices(&permute[i], true);
    FixedVector<float, VecWidth> gathered;
    gathered.gather(input, gather_indices, sizeof(float), store_mask);
    gathered.store_aligned(&(output[i]), store_mask);
  }
}

void copy_vector(const float* input, float* output, const int* permute, int num_elements) {
  int vec_end = num_elements & (~(VecWidth-1));
  for (int i = 0; i < vec_end; i+=VecWidth) {
    FixedVector<float, VecWidth> gathered(&input[i], true);
    gathered.store_aligned(&(output[i]));
  }
  if (vec_end != num_elements) {
    int i = vec_end;
    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);
    FixedVector<float, VecWidth> gathered(&input[i], true);
    gathered.store_aligned(&(output[i]), store_mask);
  }
}

void reverse_vector(const float* input, float* output, const int* permute, int num_elements) {
  int vec_end = num_elements & (~(VecWidth-1));
  for (int i = 0; i < vec_end; i+=VecWidth) {
    // Load the vecwidth stuff, and then do it backwards
    FixedVector<float, VecWidth> gathered(&input[num_elements - i - VecWidth], true);
    gathered = reverse(gathered);
    gathered.store_aligned(&(output[i]));
  }
  if (vec_end != num_elements) {
    int i = vec_end;
    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);
    FixedVector<float, VecWidth> gathered(&input[num_elements - i - VecWidth], true);
    gathered = reverse(gathered);
    gathered.store_aligned(&(output[i]), store_mask);
  }
}

typedef void(*MemCpyFunc)(const float*, float*, const int*, int);

void BenchFunctions(const char* func1_name, MemCpyFunc func1,
                    const char* func2_name, MemCpyFunc func2,
                    const float* input,
                    float* func1_output, float* func2_output,
                    const int* permute, int num_elements,
                    int bench, int warmup) {
  for (int i = 0; i < warmup; i++) {
    func1(input, func1_output, permute, num_elements);
  }
  CycleTimer::SysClock start_func1 = CycleTimer::currentTicks();
  for (int i = 0; i < bench; i++) {
    func1(input, func1_output, permute, num_elements);
  }
  CycleTimer::SysClock end_func1 = CycleTimer::currentTicks();

  CycleTimer::SysClock func1_ticks = end_func1 - start_func1;
  double func1_time_avg = func1_ticks * CycleTimer::secondsPerTick() / bench;
  CycleTimer::SysClock func1_ticks_per_element = func1_ticks / (num_elements * bench);
  printf("%25s time: %lf (%4.2f million elements per second, %d %s per element)\n", func1_name, func1_time_avg, (num_elements / func1_time_avg) / 1e6f, int(func1_ticks_per_element), CycleTimer::tickUnits());

  if (func2) {
    for (int i = 0; i < warmup; i++) {
      func2(input, func2_output, permute, num_elements);
    }
    CycleTimer::SysClock start_func2 = CycleTimer::currentTicks();
    for (int i = 0; i < bench; i++) {
      func2(input, func2_output, permute, num_elements);
    }
    CycleTimer::SysClock end_func2 = CycleTimer::currentTicks();
    CycleTimer::SysClock func2_ticks = end_func2 - start_func2;
    double func2_time_avg = func2_ticks * CycleTimer::secondsPerTick() / bench;
    CycleTimer::SysClock func2_ticks_per_element = func2_ticks / (num_elements * bench);
    printf("%25s time: %lf (%4.2f million elements per second, %d %s per element)\n", func2_name, func2_time_avg, (num_elements / func2_time_avg) / 1e6f, int(func2_ticks_per_element), CycleTimer::tickUnits());
    printf("%25s vs %s speedup: %lf\n\n", func1_name, func2_name, func1_time_avg / func2_time_avg);

    for (int i = 0; i < num_elements; i++) {
      if (func1_output[i] != func2_output[i]) {
        printf("ERROR: Outputs differ %4d, %s -> %8f != %s -> %8f (input = %8f)\n", i, func1_name, func1_output[i], func2_name, func2_output[i], input[i]);
      }
    }
  }
}

int main(int argc, char** argv) {
  int num_elements = kDefaultNumElements;
  int bench = kNumBench;
  int warmup = kNumWarmup;

  if (argc > 1) num_elements = atoi(argv[1]);

  float* scalar_output = new float[num_elements];
  float* vector_output = new float[num_elements];
  float* input = randomFloats(num_elements, 0xDEADBABE);
  int* permutation = new int[num_elements];
  // Identity for now.
  for (int i = 0; i < num_elements; i++) {
    permutation[i] = i;
  }

#if 1
  BenchFunctions("gather_scalar", gather_scalar,
                 "copy_scalar", copy_scalar,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);

  BenchFunctions("copy_scalar", copy_scalar,
                 "copy_scalar_unroll16", copy_scalar_unroll16,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);

  BenchFunctions("copy_scalar", copy_scalar,
                 "memcpy_scalar", memcpy_scalar,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);

  BenchFunctions("reverse_scalar", reverse_scalar,
                 "reverse_scalar_unroll16", reverse_scalar_unroll16,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);

  BenchFunctions("copy_scalar_unroll16", copy_scalar_unroll16,
                 "copy_vector", copy_vector,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);
#endif
  BenchFunctions("reverse_scalar_unroll16", reverse_scalar_unroll16,
                 "reverse_vector", reverse_vector,
                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);
  return 0;
}
<|endoftext|>


<commit_before>#include "engine/geospatial_query.hpp"
#include "extractor/query_node.hpp"
#include "extractor/edge_based_node.hpp"
#include "util/static_rtree.hpp"
#include "util/timing_util.hpp"
#include "util/coordinate.hpp"
#include "mocks/mock_datafacade.hpp"

#include <iostream>
#include <random>

#include <boost/filesystem/fstream.hpp>

namespace osrm
{
namespace benchmarks
{

using namespace osrm::test;

// Choosen by a fair W20 dice roll (this value is completely arbitrary)
constexpr unsigned RANDOM_SEED = 13;
constexpr int32_t WORLD_MIN_LAT = -90 * COORDINATE_PRECISION;
constexpr int32_t WORLD_MAX_LAT = 90 * COORDINATE_PRECISION;
constexpr int32_t WORLD_MIN_LON = -180 * COORDINATE_PRECISION;
constexpr int32_t WORLD_MAX_LON = 180 * COORDINATE_PRECISION;

using RTreeLeaf = extractor::EdgeBasedNode;
using CoordinateListPtr = std::shared_ptr<std::vector<util::Coordinate>>;
using BenchStaticRTree =
    util::StaticRTree<RTreeLeaf, util::ShM<util::Coordinate, false>::vector, false>;

CoordinateListPtr loadCoordinates(const boost::filesystem::path &nodes_file)
{
    boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary);

    extractor::QueryNode current_node;
    unsigned coordinate_count = 0;
    nodes_input_stream.read((char *)&coordinate_count, sizeof(unsigned));
    auto coords = std::make_shared<std::vector<Coordinate>>(coordinate_count);
    for (unsigned i = 0; i < coordinate_count; ++i)
    {
        nodes_input_stream.read((char *)&current_node, sizeof(extractor::QueryNode));
        coords->at(i) = util::Coordinate(current_node.lon, current_node.lat);
    }
    return coords;
}

template <typename QueryT>
void benchmarkQuery(const std::vector<util::Coordinate> &queries,
                    const std::string &name,
                    QueryT query)
{
    std::cout << "Running " << name << " with " << queries.size() << " coordinates: " << std::flush;

    TIMER_START(query);
    for (const auto &q : queries)
    {
        auto result = query(q);
        (void)result;
    }
    TIMER_STOP(query);

    std::cout << "Took " << TIMER_SEC(query) << " seconds "
              << "(" << TIMER_MSEC(query) << "ms"
              << ")  ->  " << TIMER_MSEC(query) / queries.size() << " ms/query "
              << "(" << TIMER_MSEC(query) << "ms"
              << ")" << std::endl;
}

void benchmark(BenchStaticRTree &rtree, unsigned num_queries)
{
    std::mt19937 mt_rand(RANDOM_SEED);
    std::uniform_int_distribution<> lat_udist(WORLD_MIN_LAT, WORLD_MAX_LAT);
    std::uniform_int_distribution<> lon_udist(WORLD_MIN_LON, WORLD_MAX_LON);
    std::vector<util::Coordinate> queries;
    for (unsigned i = 0; i < num_queries; i++)
    {
        queries.emplace_back(util::FixedLongitude{lon_udist(mt_rand)},
                             util::FixedLatitude{lat_udist(mt_rand)});
    }

    benchmarkQuery(queries, "raw RTree queries (1 result)", [&rtree](const util::Coordinate &q)
                   {
                       return rtree.Nearest(q, 1);
                   });
    benchmarkQuery(queries, "raw RTree queries (10 results)", [&rtree](const util::Coordinate &q)
                   {
                       return rtree.Nearest(q, 10);
                   });
}
}
}

int main(int argc, char **argv)
{
    if (argc < 4)
    {
        std::cout << "./rtree-bench file.ramIndex file.fileIndx file.nodes"
                  << "\n";
        return 1;
    }

    const char *ram_path = argv[1];
    const char *file_path = argv[2];
    const char *nodes_path = argv[3];

    auto coords = osrm::benchmarks::loadCoordinates(nodes_path);

    osrm::benchmarks::BenchStaticRTree rtree(ram_path, file_path, coords);

    osrm::benchmarks::benchmark(rtree, 10000);

    return 0;
}
<commit_msg>Fix rtree benchmark<commit_after>#include "engine/geospatial_query.hpp"
#include "extractor/query_node.hpp"
#include "extractor/edge_based_node.hpp"
#include "util/static_rtree.hpp"
#include "util/timing_util.hpp"
#include "util/coordinate.hpp"
#include "mocks/mock_datafacade.hpp"

#include <iostream>
#include <random>

#include <boost/filesystem/fstream.hpp>

namespace osrm
{
namespace benchmarks
{

using namespace osrm::test;

// Choosen by a fair W20 dice roll (this value is completely arbitrary)
constexpr unsigned RANDOM_SEED = 13;
constexpr int32_t WORLD_MIN_LAT = -90 * COORDINATE_PRECISION;
constexpr int32_t WORLD_MAX_LAT = 90 * COORDINATE_PRECISION;
constexpr int32_t WORLD_MIN_LON = -180 * COORDINATE_PRECISION;
constexpr int32_t WORLD_MAX_LON = 180 * COORDINATE_PRECISION;

using RTreeLeaf = extractor::EdgeBasedNode;
using BenchStaticRTree =
    util::StaticRTree<RTreeLeaf, util::ShM<util::Coordinate, false>::vector, false>;

std::vector<util::Coordinate> loadCoordinates(const boost::filesystem::path &nodes_file)
{
    boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary);

    extractor::QueryNode current_node;
    unsigned coordinate_count = 0;
    nodes_input_stream.read((char *)&coordinate_count, sizeof(unsigned));
    std::vector<util::Coordinate> coords(coordinate_count);
    for (unsigned i = 0; i < coordinate_count; ++i)
    {
        nodes_input_stream.read((char *)&current_node, sizeof(extractor::QueryNode));
        coords[i] = util::Coordinate(current_node.lon, current_node.lat);
    }
    return coords;
}

template <typename QueryT>
void benchmarkQuery(const std::vector<util::Coordinate> &queries,
                    const std::string &name,
                    QueryT query)
{
    std::cout << "Running " << name << " with " << queries.size() << " coordinates: " << std::flush;

    TIMER_START(query);
    for (const auto &q : queries)
    {
        auto result = query(q);
        (void)result;
    }
    TIMER_STOP(query);

    std::cout << "Took " << TIMER_SEC(query) << " seconds "
              << "(" << TIMER_MSEC(query) << "ms"
              << ")  ->  " << TIMER_MSEC(query) / queries.size() << " ms/query "
              << "(" << TIMER_MSEC(query) << "ms"
              << ")" << std::endl;
}

void benchmark(BenchStaticRTree &rtree, unsigned num_queries)
{
    std::mt19937 mt_rand(RANDOM_SEED);
    std::uniform_int_distribution<> lat_udist(WORLD_MIN_LAT, WORLD_MAX_LAT);
    std::uniform_int_distribution<> lon_udist(WORLD_MIN_LON, WORLD_MAX_LON);
    std::vector<util::Coordinate> queries;
    for (unsigned i = 0; i < num_queries; i++)
    {
        queries.emplace_back(util::FixedLongitude{lon_udist(mt_rand)},
                             util::FixedLatitude{lat_udist(mt_rand)});
    }

    benchmarkQuery(queries, "raw RTree queries (1 result)", [&rtree](const util::Coordinate &q)
                   {
                       return rtree.Nearest(q, 1);
                   });
    benchmarkQuery(queries, "raw RTree queries (10 results)", [&rtree](const util::Coordinate &q)
                   {
                       return rtree.Nearest(q, 10);
                   });
}
}
}

int main(int argc, char **argv)
{
    if (argc < 4)
    {
        std::cout << "./rtree-bench file.ramIndex file.fileIndx file.nodes"
                  << "\n";
        return 1;
    }

    const char *ram_path = argv[1];
    const char *file_path = argv[2];
    const char *nodes_path = argv[3];

    auto coords = osrm::benchmarks::loadCoordinates(nodes_path);

    osrm::benchmarks::BenchStaticRTree rtree(ram_path, file_path, coords);

    osrm::benchmarks::benchmark(rtree, 10000);

    return 0;
}
<|endoftext|>


<commit_before>/*

Copyright 2015-2020 Igor Petrovic

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

#include "board/Board.h"
#include "board/Internal.h"
#include "core/src/general/Reset.h"
#include "core/src/general/Interrupt.h"

namespace Board
{
    void init()
    {
        //Reset of all peripherals, Initializes the Flash interface and the Systick
        HAL_Init();

        detail::setup::clocks();
        detail::setup::io();

#ifdef FW_APP
        eeprom::init();
        detail::setup::adc();
#endif

        detail::setup::timers();

#ifdef USB_MIDI_SUPPORTED
        detail::setup::usb();
#endif
    }

    bool checkNewRevision()
    {
        return false;
    }

    void uniqueID(uniqueID_t& uid)
    {
        uint32_t id[3];

        id[0] = HAL_GetUIDw0();
        id[1] = HAL_GetUIDw1();
        id[2] = HAL_GetUIDw2();

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 4; j++)
                uid.uid[(i * 4) + j] = id[i] >> ((3 - j) * 8) & 0xFF;
        }
    }
}    // namespace Board<commit_msg>board: setup bootloader on stm32 in board init<commit_after>/*

Copyright 2015-2020 Igor Petrovic

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

#include "board/Board.h"
#include "board/Internal.h"
#include "core/src/general/Reset.h"
#include "core/src/general/Interrupt.h"

namespace Board
{
    void init()
    {
        //Reset of all peripherals, Initializes the Flash interface and the Systick
        HAL_Init();

        detail::setup::clocks();
        detail::setup::io();

#ifdef FW_APP
        eeprom::init();
        detail::setup::adc();

        detail::setup::timers();

#ifdef USB_MIDI_SUPPORTED
        detail::setup::usb();
#endif
#else
        detail::setup::bootloader();
#endif
    }

    bool checkNewRevision()
    {
        return false;
    }

    void uniqueID(uniqueID_t& uid)
    {
        uint32_t id[3];

        id[0] = HAL_GetUIDw0();
        id[1] = HAL_GetUIDw1();
        id[2] = HAL_GetUIDw2();

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 4; j++)
                uid.uid[(i * 4) + j] = id[i] >> ((3 - j) * 8) & 0xFF;
        }
    }
}    // namespace Board<|endoftext|>