<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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 "arrow/dataset/file_orc.h"

#include <memory>
#include <utility>

#include "arrow/adapters/orc/adapter.h"
#include "arrow/dataset/dataset_internal.h"
#include "arrow/dataset/discovery.h"
#include "arrow/dataset/file_base.h"
#include "arrow/dataset/partition.h"
#include "arrow/dataset/scanner_internal.h"
#include "arrow/dataset/test_util.h"
#include "arrow/io/memory.h"
#include "arrow/record_batch.h"
#include "arrow/table.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/util.h"

namespace arrow {
namespace dataset {

class OrcFormatHelper {
 public:
  using FormatType = OrcFileFormat;
  static Result<std::shared_ptr<Buffer>> Write(RecordBatchReader* reader) {
    ARROW_ASSIGN_OR_RAISE(auto sink, io::BufferOutputStream::Create());
    ARROW_ASSIGN_OR_RAISE(auto writer, adapters::orc::ORCFileWriter::Open(sink.get()));
    std::shared_ptr<Table> table;
    RETURN_NOT_OK(reader->ReadAll(&table));
    writer->Write(*table);
    RETURN_NOT_OK(writer->Close());
    return sink->Finish();
  }

  static std::shared_ptr<OrcFileFormat> MakeFormat() {
    return std::make_shared<OrcFileFormat>();
  }
};

class TestOrcFileFormat : public FileFormatFixtureMixin<OrcFormatHelper> {};

// TEST_F(TestOrcFileFormat, WriteRecordBatchReader) { TestWrite(); }

TEST_F(TestOrcFileFormat, InspectFailureWithRelevantError) {
  TestInspectFailureWithRelevantError(StatusCode::IOError, "ORC");
}
TEST_F(TestOrcFileFormat, Inspect) { TestInspect(); }
TEST_F(TestOrcFileFormat, IsSupported) { TestIsSupported(); }
TEST_F(TestOrcFileFormat, CountRows) { TestCountRows(); }

// TODO add TestOrcFileSystemDataset if write support is added

class TestOrcFileFormatScan : public FileFormatScanMixin<OrcFormatHelper> {};

TEST_P(TestOrcFileFormatScan, ScanRecordBatchReader) { TestScan(); }
TEST_P(TestOrcFileFormatScan, ScanRecordBatchReaderWithVirtualColumn) {
  TestScanWithVirtualColumn();
}
TEST_P(TestOrcFileFormatScan, ScanRecordBatchReaderProjected) { TestScanProjected(); }
TEST_P(TestOrcFileFormatScan, ScanRecordBatchReaderProjectedMissingCols) {
  TestScanProjectedMissingCols();
}
INSTANTIATE_TEST_SUITE_P(TestScan, TestOrcFileFormatScan,
                         ::testing::ValuesIn(TestFormatParams::Values()),
                         TestFormatParams::ToTestNameString);

}  // namespace dataset
}  // namespace arrow
<commit_msg>ARROW-14788: [C++] Fix warning in dataset/file_orc_test.cc<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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 "arrow/dataset/file_orc.h"

#include <memory>
#include <utility>

#include "arrow/adapters/orc/adapter.h"
#include "arrow/dataset/dataset_internal.h"
#include "arrow/dataset/discovery.h"
#include "arrow/dataset/file_base.h"
#include "arrow/dataset/partition.h"
#include "arrow/dataset/scanner_internal.h"
#include "arrow/dataset/test_util.h"
#include "arrow/io/memory.h"
#include "arrow/record_batch.h"
#include "arrow/table.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/util.h"

namespace arrow {
namespace dataset {

class OrcFormatHelper {
 public:
  using FormatType = OrcFileFormat;
  static Result<std::shared_ptr<Buffer>> Write(RecordBatchReader* reader) {
    ARROW_ASSIGN_OR_RAISE(auto sink, io::BufferOutputStream::Create());
    ARROW_ASSIGN_OR_RAISE(auto writer, adapters::orc::ORCFileWriter::Open(sink.get()));
    std::shared_ptr<Table> table;
    RETURN_NOT_OK(reader->ReadAll(&table));
    RETURN_NOT_OK(writer->Write(*table));
    RETURN_NOT_OK(writer->Close());
    return sink->Finish();
  }

  static std::shared_ptr<OrcFileFormat> MakeFormat() {
    return std::make_shared<OrcFileFormat>();
  }
};

class TestOrcFileFormat : public FileFormatFixtureMixin<OrcFormatHelper> {};

// TEST_F(TestOrcFileFormat, WriteRecordBatchReader) { TestWrite(); }

TEST_F(TestOrcFileFormat, InspectFailureWithRelevantError) {
  TestInspectFailureWithRelevantError(StatusCode::IOError, "ORC");
}
TEST_F(TestOrcFileFormat, Inspect) { TestInspect(); }
TEST_F(TestOrcFileFormat, IsSupported) { TestIsSupported(); }
TEST_F(TestOrcFileFormat, CountRows) { TestCountRows(); }

// TODO add TestOrcFileSystemDataset if write support is added

class TestOrcFileFormatScan : public FileFormatScanMixin<OrcFormatHelper> {};

TEST_P(TestOrcFileFormatScan, ScanRecordBatchReader) { TestScan(); }
TEST_P(TestOrcFileFormatScan, ScanRecordBatchReaderWithVirtualColumn) {
  TestScanWithVirtualColumn();
}
TEST_P(TestOrcFileFormatScan, ScanRecordBatchReaderProjected) { TestScanProjected(); }
TEST_P(TestOrcFileFormatScan, ScanRecordBatchReaderProjectedMissingCols) {
  TestScanProjectedMissingCols();
}
INSTANTIATE_TEST_SUITE_P(TestScan, TestOrcFileFormatScan,
                         ::testing::ValuesIn(TestFormatParams::Values()),
                         TestFormatParams::ToTestNameString);

}  // namespace dataset
}  // namespace arrow
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

/*
 * Copyright 2016 ScyllaDB
 *
 * Modified by ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/range/adaptor/map.hpp>

#include "drop_user_statement.hh"
#include "auth/auth.hh"
#include "auth/authenticator.hh"

cql3::statements::drop_user_statement::drop_user_statement(sstring username, bool if_exists)
    : _username(std::move(username))
    , _if_exists(if_exists)
{}

void cql3::statements::drop_user_statement::validate(distributed<service::storage_proxy>& proxy, const service::client_state& state) {
    // validate login here before checkAccess to avoid leaking user existence to anonymous users.
    state.ensure_not_anonymous();

    // cannot validate user existence here, because
    // we need to query -> continuation, and this is not a continuation method

    if (state.user()->name() == _username) {
        throw exceptions::invalid_request_exception("Users aren't allowed to DROP themselves");
    }
}

future<::shared_ptr<transport::messages::result_message>>
cql3::statements::drop_user_statement::execute(distributed<service::storage_proxy>& proxy, service::query_state& state, const query_options& options) {
    return state.get_client_state().user()->is_super().then([this](bool is_super) {
        if (!is_super) {
            throw exceptions::unauthorized_exception("Only superusers are allowed to perform DROP USER queries");
        }

        return auth::auth::is_existing_user(_username).then([this](bool exists) {
            if (!_if_exists && !exists) {
                throw exceptions::invalid_request_exception(sprint("User %s doesn't exist", _username));
            }
            if (_if_exists && !exists) {
                return  make_ready_future<::shared_ptr<transport::messages::result_message>>();
            }

            // clean up permissions after the dropped user.
            // TODO: authorizer
            //DatabaseDescriptor.getAuthorizer().revokeAll(username);
            auth::auth::delete_user(_username);
            auth::authenticator::get().drop(_username);
            return make_ready_future<::shared_ptr<transport::messages::result_message>>();
        });
    });
}

<commit_msg>cql3::statements::drop_user_statement: Drop all permissions for user<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

/*
 * Copyright 2016 ScyllaDB
 *
 * Modified by ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/range/adaptor/map.hpp>

#include "drop_user_statement.hh"
#include "auth/auth.hh"
#include "auth/authenticator.hh"
#include "auth/authorizer.hh"

cql3::statements::drop_user_statement::drop_user_statement(sstring username, bool if_exists)
    : _username(std::move(username))
    , _if_exists(if_exists)
{}

void cql3::statements::drop_user_statement::validate(distributed<service::storage_proxy>& proxy, const service::client_state& state) {
    // validate login here before checkAccess to avoid leaking user existence to anonymous users.
    state.ensure_not_anonymous();

    // cannot validate user existence here, because
    // we need to query -> continuation, and this is not a continuation method

    if (state.user()->name() == _username) {
        throw exceptions::invalid_request_exception("Users aren't allowed to DROP themselves");
    }
}

future<::shared_ptr<transport::messages::result_message>>
cql3::statements::drop_user_statement::execute(distributed<service::storage_proxy>& proxy, service::query_state& state, const query_options& options) {
    return state.get_client_state().user()->is_super().then([this](bool is_super) {
        if (!is_super) {
            throw exceptions::unauthorized_exception("Only superusers are allowed to perform DROP USER queries");
        }

        return auth::auth::is_existing_user(_username).then([this](bool exists) {
            if (!_if_exists && !exists) {
                throw exceptions::invalid_request_exception(sprint("User %s doesn't exist", _username));
            }
            if (_if_exists && !exists) {
                return  make_ready_future<::shared_ptr<transport::messages::result_message>>();
            }

            // clean up permissions after the dropped user.
            return auth::authorizer::get().revoke_all(_username).then([this] {
                return auth::auth::delete_user(_username).then([this] {
                    return auth::authenticator::get().drop(_username);
                });
            }).then([] {
                return make_ready_future<::shared_ptr<transport::messages::result_message>>();
            });
        });
    });
}

<|endoftext|>


<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_GSLIB
#define MFEM_GSLIB

#include "../config/config.hpp"
#include "gridfunc.hpp"

#ifdef MFEM_USE_GSLIB

struct comm;
struct findpts_data_2;
struct findpts_data_3;
struct array;
struct crystal;

namespace mfem
{

/** \brief FindPointsGSLIB can robustly evaluate a GridFunction on an arbitrary
 *  collection of points. There are three key functions in FindPointsGSLIB:
 *
 *  1. Setup - constructs the internal data structures of gslib.
 *
 *  2. FindPoints - for any given arbitrary set of points in physical space,
 *     gslib finds the element number, MPI rank, and the reference space
 *     coordinates inside the element that each point is located in. gslib also
 *     returns a code that indicates  wether the point was found inside an
 *     element, on element border, or not found in the domain.
 *
 *  3. Interpolate - Interpolates any gridfunction at the points found using 2.
 *
 *  FindPointsGSLIB provides interface to use these functions individually or using
 *  a single call.
 */
class FindPointsGSLIB
{
protected:
   Mesh *mesh, *meshsplit;
   IntegrationRule *ir_simplex; // IntegrationRule to split quads/hex -> simplex
   struct findpts_data_2 *fdata2D; // pointer to gslib's
   struct findpts_data_3 *fdata3D; // internal data
   int dim, points_cnt;
   Array<unsigned int> gsl_code, gsl_proc, gsl_elem, gsl_mfem_elem;
   Vector gsl_mesh, gsl_ref, gsl_dist, gsl_mfem_ref;
   bool setupflag;
   struct crystal *cr;
   struct comm *gsl_comm;
   double default_interp_value;

   GridFunction::AvgType avgtype;

   /// Get GridFunction from MFEM format to GSLIB format
   void GetNodeValues(const GridFunction &gf_in, Vector &node_vals);
   /// Get nodal coordinates from mesh to the format expected by GSLIB for quads
   /// and hexes
   void GetQuadHexNodalCoordinates();
   /// Convert simplices to quad/hexes and then get nodal coordinates for each
   /// split element into format expected by GSLIB
   void GetSimplexNodalCoordinates();

   /// Use GSLIB for communication and interpolation
   void InterpolateH1(const GridFunction &field_in, Vector &field_out);
   /// Uses GSLIB Crystal Router for communication followed by MFEM's
   /// interpolation functions
   void InterpolateGeneral(const GridFunction &field_in, Vector &field_out);
   /// Map {r,s,t} coordinates from [-1,1] to [0,1] for MFEM. For simplices mesh
   /// find the original element number (that was split into micro quads/hexes
   /// by GetSimplexNodalCoordinates())
   void MapRefPosAndElemIndices();

public:
   FindPointsGSLIB();

#ifdef MFEM_USE_MPI
   FindPointsGSLIB(MPI_Comm _comm);
#endif

   ~FindPointsGSLIB();

   /** Initializes the internal mesh in gslib, by sending the positions of the
       Gauss-Lobatto nodes of the input Mesh object @a m.
       Note: not tested with periodic (DG meshes).
       Note: the input mesh @a m must have Nodes set.

       @param[in] m         Input mesh.
       @param[in] bb_t      Relative size of bounding box around each element.
       @param[in] newt_tol  Newton tolerance for the gslib search methods.
       @param[in] npt_max   Number of points for simultaneous iteration. This
                            alters performance and memory footprint. */
   void Setup(Mesh &m, const double bb_t = 0.1, const double newt_tol = 1.0e-12,
              const int npt_max = 256);

   /** Searches positions given in physical space by @a point_pos. All output
       Arrays and Vectors are expected to have the correct size.
       @param[in]  point_pos       Positions to be found. Must by ordered by nodes
                                   (XXX...,YYY...,ZZZ).
       @param[out] gsl_codes       Return codes for each point: inside element (0),
                                   element boundary (1), not found (2).
       @param[out] gsl_proc        MPI proc ids where the points were found.
       @param[out] gsl_elem        Element ids where the points were found.
                                   Defaults to 0 for points that were not found.
       @param[out] gsl_mfem_elem   Element ids corresponding to MFEM-mesh
                                   where the points were found.
                                   @a gsl_mfem_elem != @a gsl_elem for simplices
                                   Defaults to 0 for points that were not found.
       @param[out] gsl_ref         Reference coordinates of the found point.
                                   Ordered by vdim (XYZ,XYZ,XYZ...).
                                   Note: the gslib reference frame is [-1,1].
                                   Defaults to -1 for points that were not found.
       @param[out] gsl_mfem_ref    Reference coordinates @a gsl_ref mapped to [0,1].
                                   Defaults to 0 for points that were not found.
       @param[out] gsl_dist        Distance between the sought and the found point
                                   in physical space. */
   void FindPoints(const Vector &point_pos);
   /// Setup FindPoints and search positions
   void FindPoints(Mesh &m, const Vector &point_pos, const double bb_t = 0.1,
                   const double newt_tol = 1.0e-12,  const int npt_max = 256);

   /** Interpolation of field values at prescribed reference space positions.
       @param[in] field_in    Function values that will be interpolated on the
                              reference positions. Note: it is assumed that
                              @a field_in is in H1 and in the same space as the
                              mesh that was given to Setup().
       @param[out] field_out  Interpolated values. For points that are not found
                              the value is set to #default_interp_value. */
   void Interpolate(const GridFunction &field_in, Vector &field_out);
   /** Search positions and interpolate */
   void Interpolate(const Vector &point_pos, const GridFunction &field_in,
                    Vector &field_out);
   /** Setup FindPoints, search positions and interpolate */
   void Interpolate(Mesh &m, const Vector &point_pos,
                    const GridFunction &field_in, Vector &field_out);

   /// Average type to be used for L2 functions in-case a point is located at
   /// an element boundary where the function might not have a unique value.
   void SetL2AvgType(GridFunction::AvgType avgtype_) { avgtype = avgtype_; }

   /// Set the default interpolation value for points that are not found in the
   /// mesh.
   void SetDefaultInterpolationValue(double interp_value_)
   {
      default_interp_value = interp_value_;
   }

   /** Cleans up memory allocated internally by gslib.
       Note that in parallel, this must be called before MPI_Finalize(), as
       it calls MPI_Comm_free() for internal gslib communicators. */
   void FreeData();

   /// Return code for each point searched by FindPoints: inside element (0), on
   /// element boundary (1), or not found (2).
   const Array<unsigned int> &GetCode() const { return gsl_code; }
   /// Return element number for each point found by FindPoints.
   const Array<unsigned int> &GetElem() const { return gsl_mfem_elem; }
   /// Return MPI rank on which each point was found by FindPoints.
   const Array<unsigned int> &GetProc() const { return gsl_proc; }
   /// Return reference coordinates for each point found by FindPoints.
   const Vector &GetReferencePosition() const { return gsl_mfem_ref;  }
   /// Return distance Distance between the sought and the found point
   /// in physical space, for each point found by FindPoints.
   const Vector &GetDist()              const { return gsl_dist; }

   /// Return element number for each point found by FindPoints corresponding to
   /// GSLIB mesh. gsl_mfem_elem != gsl_elem for mesh with simplices.
   const Array<unsigned int> &GetGSLIBElem() const { return gsl_elem; }
   /// Return reference coordinates in [-1,1] (internal range in GSLIB) for each
   /// point found by FindPoints.
   const Vector &GetGSLIBReferencePosition() const { return gsl_ref; }

};

} // namespace mfem

#endif //MFEM_USE_GSLIB

#endif //MFEM_GSLIB guard
<commit_msg>remove extra lines<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_GSLIB
#define MFEM_GSLIB

#include "../config/config.hpp"
#include "gridfunc.hpp"

#ifdef MFEM_USE_GSLIB

struct comm;
struct findpts_data_2;
struct findpts_data_3;
struct array;
struct crystal;

namespace mfem
{

/** \brief FindPointsGSLIB can robustly evaluate a GridFunction on an arbitrary
 *  collection of points. There are three key functions in FindPointsGSLIB:
 *
 *  1. Setup - constructs the internal data structures of gslib.
 *
 *  2. FindPoints - for any given arbitrary set of points in physical space,
 *     gslib finds the element number, MPI rank, and the reference space
 *     coordinates inside the element that each point is located in. gslib also
 *     returns a code that indicates  wether the point was found inside an
 *     element, on element border, or not found in the domain.
 *
 *  3. Interpolate - Interpolates any gridfunction at the points found using 2.
 *
 *  FindPointsGSLIB provides interface to use these functions individually or using
 *  a single call.
 */
class FindPointsGSLIB
{
protected:
   Mesh *mesh, *meshsplit;
   IntegrationRule *ir_simplex; // IntegrationRule to split quads/hex -> simplex
   struct findpts_data_2 *fdata2D; // pointer to gslib's
   struct findpts_data_3 *fdata3D; // internal data
   int dim, points_cnt;
   Array<unsigned int> gsl_code, gsl_proc, gsl_elem, gsl_mfem_elem;
   Vector gsl_mesh, gsl_ref, gsl_dist, gsl_mfem_ref;
   bool setupflag;
   struct crystal *cr;
   struct comm *gsl_comm;
   double default_interp_value;

   GridFunction::AvgType avgtype;

   /// Get GridFunction from MFEM format to GSLIB format
   void GetNodeValues(const GridFunction &gf_in, Vector &node_vals);
   /// Get nodal coordinates from mesh to the format expected by GSLIB for quads
   /// and hexes
   void GetQuadHexNodalCoordinates();
   /// Convert simplices to quad/hexes and then get nodal coordinates for each
   /// split element into format expected by GSLIB
   void GetSimplexNodalCoordinates();

   /// Use GSLIB for communication and interpolation
   void InterpolateH1(const GridFunction &field_in, Vector &field_out);
   /// Uses GSLIB Crystal Router for communication followed by MFEM's
   /// interpolation functions
   void InterpolateGeneral(const GridFunction &field_in, Vector &field_out);
   /// Map {r,s,t} coordinates from [-1,1] to [0,1] for MFEM. For simplices mesh
   /// find the original element number (that was split into micro quads/hexes
   /// by GetSimplexNodalCoordinates())
   void MapRefPosAndElemIndices();

public:
   FindPointsGSLIB();

#ifdef MFEM_USE_MPI
   FindPointsGSLIB(MPI_Comm _comm);
#endif

   ~FindPointsGSLIB();

   /** Initializes the internal mesh in gslib, by sending the positions of the
       Gauss-Lobatto nodes of the input Mesh object @a m.
       Note: not tested with periodic (DG meshes).
       Note: the input mesh @a m must have Nodes set.

       @param[in] m         Input mesh.
       @param[in] bb_t      Relative size of bounding box around each element.
       @param[in] newt_tol  Newton tolerance for the gslib search methods.
       @param[in] npt_max   Number of points for simultaneous iteration. This
                            alters performance and memory footprint. */
   void Setup(Mesh &m, const double bb_t = 0.1, const double newt_tol = 1.0e-12,
              const int npt_max = 256);

   /** Searches positions given in physical space by @a point_pos. All output
       Arrays and Vectors are expected to have the correct size.
       @param[in]  point_pos       Positions to be found. Must by ordered by nodes
                                   (XXX...,YYY...,ZZZ).
       @param[out] gsl_codes       Return codes for each point: inside element (0),
                                   element boundary (1), not found (2).
       @param[out] gsl_proc        MPI proc ids where the points were found.
       @param[out] gsl_elem        Element ids where the points were found.
                                   Defaults to 0 for points that were not found.
       @param[out] gsl_mfem_elem   Element ids corresponding to MFEM-mesh
                                   where the points were found.
                                   @a gsl_mfem_elem != @a gsl_elem for simplices
                                   Defaults to 0 for points that were not found.
       @param[out] gsl_ref         Reference coordinates of the found point.
                                   Ordered by vdim (XYZ,XYZ,XYZ...).
                                   Note: the gslib reference frame is [-1,1].
                                   Defaults to -1 for points that were not found.
       @param[out] gsl_mfem_ref    Reference coordinates @a gsl_ref mapped to [0,1].
                                   Defaults to 0 for points that were not found.
       @param[out] gsl_dist        Distance between the sought and the found point
                                   in physical space. */
   void FindPoints(const Vector &point_pos);
   /// Setup FindPoints and search positions
   void FindPoints(Mesh &m, const Vector &point_pos, const double bb_t = 0.1,
                   const double newt_tol = 1.0e-12,  const int npt_max = 256);

   /** Interpolation of field values at prescribed reference space positions.
       @param[in] field_in    Function values that will be interpolated on the
                              reference positions. Note: it is assumed that
                              @a field_in is in H1 and in the same space as the
                              mesh that was given to Setup().
       @param[out] field_out  Interpolated values. For points that are not found
                              the value is set to #default_interp_value. */
   void Interpolate(const GridFunction &field_in, Vector &field_out);
   /** Search positions and interpolate */
   void Interpolate(const Vector &point_pos, const GridFunction &field_in,
                    Vector &field_out);
   /** Setup FindPoints, search positions and interpolate */
   void Interpolate(Mesh &m, const Vector &point_pos,
                    const GridFunction &field_in, Vector &field_out);

   /// Average type to be used for L2 functions in-case a point is located at
   /// an element boundary where the function might not have a unique value.
   void SetL2AvgType(GridFunction::AvgType avgtype_) { avgtype = avgtype_; }

   /// Set the default interpolation value for points that are not found in the
   /// mesh.
   void SetDefaultInterpolationValue(double interp_value_)
   {
      default_interp_value = interp_value_;
   }

   /** Cleans up memory allocated internally by gslib.
       Note that in parallel, this must be called before MPI_Finalize(), as
       it calls MPI_Comm_free() for internal gslib communicators. */
   void FreeData();

   /// Return code for each point searched by FindPoints: inside element (0), on
   /// element boundary (1), or not found (2).
   const Array<unsigned int> &GetCode() const { return gsl_code; }
   /// Return element number for each point found by FindPoints.
   const Array<unsigned int> &GetElem() const { return gsl_mfem_elem; }
   /// Return MPI rank on which each point was found by FindPoints.
   const Array<unsigned int> &GetProc() const { return gsl_proc; }
   /// Return reference coordinates for each point found by FindPoints.
   const Vector &GetReferencePosition() const { return gsl_mfem_ref;  }
   /// Return distance Distance between the sought and the found point
   /// in physical space, for each point found by FindPoints.
   const Vector &GetDist()              const { return gsl_dist; }

   /// Return element number for each point found by FindPoints corresponding to
   /// GSLIB mesh. gsl_mfem_elem != gsl_elem for mesh with simplices.
   const Array<unsigned int> &GetGSLIBElem() const { return gsl_elem; }
   /// Return reference coordinates in [-1,1] (internal range in GSLIB) for each
   /// point found by FindPoints.
   const Vector &GetGSLIBReferencePosition() const { return gsl_ref; }
};

} // namespace mfem

#endif //MFEM_USE_GSLIB

#endif //MFEM_GSLIB guard
<|endoftext|>


<commit_before>//==================================================
// Copyright (c) 2015 Deividas Kazlauskas
//
// See the file license.txt for copying permission.
//==================================================

/*
 * =====================================================================================
 *
 *       Filename:  Filter.hpp
 *
 *    Description:  Filter class
 *
 *        Version:  1.0
 *        Created:  08/04/2014 07:37:01 PM
 *       Compiler:  gcc
 *
 *         Author:  David Kazlauskas (dk), david@templatious.org
 *
 * =====================================================================================
 */

#ifndef FILTER_O8Y22ICC
#define FILTER_O8Y22ICC

#include <utility>

#include <templatious/util/Exceptions.hpp>
#include <templatious/CollectionAdapter.hpp>
#include <templatious/proxy/Picker.hpp>

namespace templatious {

TEMPLATIOUS_BOILERPLATE_EXCEPTION( FilterPastEndIterationException,
    "Trying to iterate past end of filter.");

template <class T,class Fn,template <class> class StoragePolicy>
struct Filter {

    template <class I,class Fun>
    struct PIterator;

    typedef typename adapters::CollectionAdapter<T> Ad;
    typedef PIterator<typename Ad::Iterator,Fn> Iterator;
    typedef PIterator<typename Ad::ConstIterator,Fn> ConstIterator;
    typedef detail::IsProxy<T> ProxUtil;
    typedef typename ProxUtil::ICollection ICollection;
    typedef Filter<T,Fn,StoragePolicy> ThisFilter;

    static const bool proxy_inside = ProxUtil::val;
    static const bool floating_iterator = Ad::floating_iterator;
    static const bool random_access_iterator = false;

    static_assert(Ad::is_valid,"Adapter is invalid.");

    typedef typename StoragePolicy<T>::Container Ref;
    typedef typename StoragePolicy<Fn>::Container Fun;

#ifndef TEMPLATIOUS_TESTING
private:
#endif

    Ref _c;
    Fun _fn;
    Iterator _b;
    Iterator _e;
    bool _cleared;

    void assertUncleared() const {
        if (_cleared) {
            throw detail::ProxyClearedUsageException();
        }
    }

    void tagCleared() {
        _cleared = true;
    }

#ifndef TEMPLATIOUS_TESTING
public:
#endif

    template <class V,class FnRef>
    Filter(V&& v,FnRef&& fn) :
        _c(std::forward<V>(v)),
        _fn(std::forward<FnRef>(fn)),
        _b(Ad::begin(_c.getRef()),
            Ad::end(_c.getRef()),
            std::forward<FnRef>(fn)),
        _e(Ad::end(_c.getRef()),
            Ad::end(_c.getRef()),
            std::forward<FnRef>(fn)),
        _cleared(false)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Filter(ThisFilter&& other)
        : _c(other._c.cpy()),
          _fn(other._fn.cpy()),
          _b(Ad::begin(_c.getRef()),
              Ad::end(_c.getRef()),
              _fn.getRef()),
          _e(Ad::end(_c.getRef()),
              Ad::end(_c.getRef()),
              _fn.cpy()),
          _cleared(other._cleared)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Iterator begin() {
        assertUncleared();
        return _b;
    }

    Iterator end() {
        assertUncleared();
        return _e;
    }

    ConstIterator cbegin() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_b._i),
            ProxUtil::const_iter_cast(_b._e),
            _b._fn
        );
    }

    ConstIterator cend() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_e._i),
            ProxUtil::const_iter_cast(_e._e),
            _e._fn
        );
    }

    Iterator iterAt(size_t i) {
        assertUncleared();
        auto res(_b);
        detail::naiveIterAdvance(res,_e,i);
        return res;
    }

    long size() const {
        if (!_cleared) {
            return -1;
        } else {
            return 0;
        }
    }

    template <class I,class Fun>
    struct PIterator {
    private:
        I _i;
        I _e;
        typedef typename StoragePolicy<Fn>::Container Func;
        Func _fn;

        friend struct Filter<T,Fun,StoragePolicy>;

        template <class V>
        friend struct detail::IsProxy;
    public:

        typedef PIterator<I,Fun> ThisIter;
        typedef decltype(*_i) IVal;

        template <class V>
        PIterator(const I& i,const I& e,V&& fn) :
            _i(i), _e(e), _fn(std::forward<V>(fn)) {}

        PIterator& operator=(const PIterator& rhs) {
            _i = rhs._i;
            _e = rhs._e;
            return *this;
        }

        ThisIter& operator++() {
            if (_e == _i) {
                throw FilterPastEndIterationException();
            }

            do {
                ++_i;
            } while (_e != _i && !_fn.getRef()(*_i));
            return *this;
        }

        bool operator==(const ThisIter& rhs) const {
            return _i == rhs._i;
        }

        bool operator!=(const ThisIter& rhs) const {
            return !(*this == rhs);
        }

        auto operator*() -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        auto operator*() const -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        auto operator->()
            -> decltype(&(this->_i))
        const {
            return &(this->_i);
        }

        auto getInternal()
            -> decltype(ProxUtil::iter_unwrap(_i))&
        {
            return ProxUtil::iter_unwrap(_i);
        }

    };

    void clear() {
        detail::clearRoutine<floating_iterator>(*this);
        tagCleared();
        ProxUtil::tag_cleared(_c.getRef());
        _b._i = _e._i;
    }

    auto getInternal()
        -> decltype(ProxUtil::unwrap(_c.getRef()))&
    {
        return ProxUtil::unwrap(_c.getRef());
    }

    template <class V>
    static auto iterUnwrap(V&& v)
        -> decltype(ProxUtil::iter_unwrap(
            std::forward<V>(v)))&
    {
        return ProxUtil::iter_unwrap(
            std::forward<V>(v)
        );
    }

};

namespace detail {

template <class T,class Fn,template <class> class StoragePolicy>
struct IsProxy< Filter< T,Fn,StoragePolicy > > {
    typedef IsProxy<T> Internal;
    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef typename ThisCol::ConstIterator ConstIterator;
    static const bool val = true;
    static const bool random_access_iterator = false;

    typedef adapters::CollectionAdapter<T> Ad;
    typedef typename Ad::ThisCol ICollection;
    typedef typename
        adapters::CollectionAdapter<ICollection> IAdapter;

    template <class C>
    static auto unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static auto iter_unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static void iter_advance(C& i,C& e,size_t s) {
        naiveIterAdvance(i,e,s);
    }

    template <class C>
    static long get_mul(C&& a) {
        return -1;
    }

    template <class U>
    static void tag_cleared(U& u) {
        u.tagCleared();
    }

    template <class Iter>
    static auto const_iter_cast(Iter&& i)
     -> decltype(
        ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        )
     )
    {
        return ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        );
    }
};

}

namespace adapters {

template <class T,class Fn,template <class> class StoragePolicy>
struct CollectionAdapter< Filter<T,Fn,StoragePolicy> > {

    static const bool is_valid = true;

    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef const ThisCol ConstCol;
    typedef typename ThisCol::Iterator Iterator;
    typedef typename ThisCol::ConstIterator ConstIterator;
    typedef typename ThisCol::Ad::ValueType ValueType;
    typedef typename ThisCol::Ad::ConstValueType ConstValueType;

    static const bool floating_iterator = ThisCol::Ad::floating_iterator;

    template <class C>
    static Iterator begin(C&& c) {
        return c.begin();
    }

    template <class C>
    static Iterator end(C&& c) {
        return c.end();
    }

    static ConstIterator cbegin(ConstCol& c) {
        return c.cbegin();
    }

    static ConstIterator cend(ConstCol& c) {
        return c.cend();
    }

    template <class C>
    static Iterator iterAt(C&& c,size_t i) {
        return c.iterAt(i);
    }

    template <class C,class V>
    static void insertAt(C&& c,Iterator i,V&& v) {
        c.insert(i,std::forward<V>(v));
    }

    template <class C>
    static void erase(C&& c, Iterator i) {
        c.erase(i);
    }

    template <class C>
    static void erase(C&& c, Iterator beg, Iterator end) {
        c.erase(beg,end);
    }

    template <class C>
    static void clear(C&& c) {
        c.clear();
    }

    template <class C>
    static long size(C&& c) {
        return c.size();
    }

};

}

}

#endif /* end of include guard: FILTER_O8Y22ICC */

<commit_msg>moar correct<commit_after>//==================================================
// Copyright (c) 2015 Deividas Kazlauskas
//
// See the file license.txt for copying permission.
//==================================================

/*
 * =====================================================================================
 *
 *       Filename:  Filter.hpp
 *
 *    Description:  Filter class
 *
 *        Version:  1.0
 *        Created:  08/04/2014 07:37:01 PM
 *       Compiler:  gcc
 *
 *         Author:  David Kazlauskas (dk), david@templatious.org
 *
 * =====================================================================================
 */

#ifndef FILTER_O8Y22ICC
#define FILTER_O8Y22ICC

#include <utility>

#include <templatious/util/Exceptions.hpp>
#include <templatious/CollectionAdapter.hpp>
#include <templatious/proxy/Picker.hpp>

namespace templatious {

TEMPLATIOUS_BOILERPLATE_EXCEPTION( FilterPastEndIterationException,
    "Trying to iterate past end of filter.");

template <class T,class Fn,template <class> class StoragePolicy>
struct Filter {

    template <class I,class Fun>
    struct PIterator;

    typedef typename adapters::CollectionAdapter<T> Ad;
    typedef PIterator<typename Ad::Iterator,Fn> Iterator;
    typedef PIterator<typename Ad::ConstIterator,Fn> ConstIterator;
    typedef detail::IsProxy<T> ProxUtil;
    typedef typename ProxUtil::ICollection ICollection;
    typedef Filter<T,Fn,StoragePolicy> ThisFilter;

    static const bool proxy_inside = ProxUtil::val;
    static const bool floating_iterator = Ad::floating_iterator;
    static const bool random_access_iterator = false;

    static_assert(Ad::is_valid,"Adapter is invalid.");

    typedef typename StoragePolicy<T>::Container Ref;
    typedef typename StoragePolicy<Fn>::Container Fun;

#ifndef TEMPLATIOUS_TESTING
private:
#endif

    Ref _c;
    Fun _fn;
    Iterator _b;
    Iterator _e;
    bool _cleared;

    void assertUncleared() const {
        if (_cleared) {
            throw detail::ProxyClearedUsageException();
        }
    }

    void tagCleared() {
        _cleared = true;
    }

#ifndef TEMPLATIOUS_TESTING
public:
#endif

    template <class V,class FnRef>
    Filter(V&& v,FnRef&& fn) :
        _c(std::forward<V>(v)),
        _fn(std::forward<FnRef>(fn)),
        _b(Ad::begin(_c.getRef()),
           Ad::end(_c.getRef()),
           _fn.getRef()),
        _e(Ad::end(_c.getRef()),
           Ad::end(_c.getRef()),
           _fn.getRef()),
        _cleared(false)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Filter(ThisFilter&& other)
        : _c(other._c.cpy()),
          _fn(other._fn.cpy()),
          _b(Ad::begin(_c.getRef()),
             Ad::end(_c.getRef()),
             _fn.getRef()),
          _e(Ad::end(_c.getRef()),
              Ad::end(_c.getRef()),
              _fn.getRef()),
          _cleared(other._cleared)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Iterator begin() {
        assertUncleared();
        return _b;
    }

    Iterator end() {
        assertUncleared();
        return _e;
    }

    ConstIterator cbegin() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_b._i),
            ProxUtil::const_iter_cast(_b._e),
            _b._fn
        );
    }

    ConstIterator cend() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_e._i),
            ProxUtil::const_iter_cast(_e._e),
            _e._fn
        );
    }

    Iterator iterAt(size_t i) {
        assertUncleared();
        auto res(_b);
        detail::naiveIterAdvance(res,_e,i);
        return res;
    }

    long size() const {
        if (!_cleared) {
            return -1;
        } else {
            return 0;
        }
    }

    template <class I,class Fun>
    struct PIterator {
    private:
        I _i;
        I _e;
        typedef typename StoragePolicy<Fn>::Container Func;
        Func _fn;

        friend struct Filter<T,Fun,StoragePolicy>;

        template <class V>
        friend struct detail::IsProxy;
    public:

        typedef PIterator<I,Fun> ThisIter;
        typedef decltype(*_i) IVal;

        template <class V>
        PIterator(const I& i,const I& e,V&& fn) :
            _i(i), _e(e), _fn(std::forward<V>(fn)) {}

        PIterator& operator=(const PIterator& rhs) {
            _i = rhs._i;
            _e = rhs._e;
            return *this;
        }

        ThisIter& operator++() {
            if (_e == _i) {
                throw FilterPastEndIterationException();
            }

            do {
                ++_i;
            } while (_e != _i && !_fn.getRef()(*_i));
            return *this;
        }

        bool operator==(const ThisIter& rhs) const {
            return _i == rhs._i;
        }

        bool operator!=(const ThisIter& rhs) const {
            return !(*this == rhs);
        }

        auto operator*() -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        auto operator*() const -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        auto operator->()
            -> decltype(&(this->_i))
        const {
            return &(this->_i);
        }

        auto getInternal()
            -> decltype(ProxUtil::iter_unwrap(_i))&
        {
            return ProxUtil::iter_unwrap(_i);
        }

    };

    void clear() {
        detail::clearRoutine<floating_iterator>(*this);
        tagCleared();
        ProxUtil::tag_cleared(_c.getRef());
        _b._i = _e._i;
    }

    auto getInternal()
        -> decltype(ProxUtil::unwrap(_c.getRef()))&
    {
        return ProxUtil::unwrap(_c.getRef());
    }

    template <class V>
    static auto iterUnwrap(V&& v)
        -> decltype(ProxUtil::iter_unwrap(
            std::forward<V>(v)))&
    {
        return ProxUtil::iter_unwrap(
            std::forward<V>(v)
        );
    }

};

namespace detail {

template <class T,class Fn,template <class> class StoragePolicy>
struct IsProxy< Filter< T,Fn,StoragePolicy > > {
    typedef IsProxy<T> Internal;
    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef typename ThisCol::ConstIterator ConstIterator;
    static const bool val = true;
    static const bool random_access_iterator = false;

    typedef adapters::CollectionAdapter<T> Ad;
    typedef typename Ad::ThisCol ICollection;
    typedef typename
        adapters::CollectionAdapter<ICollection> IAdapter;

    template <class C>
    static auto unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static auto iter_unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static void iter_advance(C& i,C& e,size_t s) {
        naiveIterAdvance(i,e,s);
    }

    template <class C>
    static long get_mul(C&& a) {
        return -1;
    }

    template <class U>
    static void tag_cleared(U& u) {
        u.tagCleared();
    }

    template <class Iter>
    static auto const_iter_cast(Iter&& i)
     -> decltype(
        ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        )
     )
    {
        return ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        );
    }
};

}

namespace adapters {

template <class T,class Fn,template <class> class StoragePolicy>
struct CollectionAdapter< Filter<T,Fn,StoragePolicy> > {

    static const bool is_valid = true;

    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef const ThisCol ConstCol;
    typedef typename ThisCol::Iterator Iterator;
    typedef typename ThisCol::ConstIterator ConstIterator;
    typedef typename ThisCol::Ad::ValueType ValueType;
    typedef typename ThisCol::Ad::ConstValueType ConstValueType;

    static const bool floating_iterator = ThisCol::Ad::floating_iterator;

    template <class C>
    static Iterator begin(C&& c) {
        return c.begin();
    }

    template <class C>
    static Iterator end(C&& c) {
        return c.end();
    }

    static ConstIterator cbegin(ConstCol& c) {
        return c.cbegin();
    }

    static ConstIterator cend(ConstCol& c) {
        return c.cend();
    }

    template <class C>
    static Iterator iterAt(C&& c,size_t i) {
        return c.iterAt(i);
    }

    template <class C,class V>
    static void insertAt(C&& c,Iterator i,V&& v) {
        c.insert(i,std::forward<V>(v));
    }

    template <class C>
    static void erase(C&& c, Iterator i) {
        c.erase(i);
    }

    template <class C>
    static void erase(C&& c, Iterator beg, Iterator end) {
        c.erase(beg,end);
    }

    template <class C>
    static void clear(C&& c) {
        c.clear();
    }

    template <class C>
    static long size(C&& c) {
        return c.size();
    }

};

}

}

#endif /* end of include guard: FILTER_O8Y22ICC */

<|endoftext|>


<commit_before>//==================================================
// Copyright (c) 2015 Deividas Kazlauskas
//
// See the file license.txt for copying permission.
//==================================================

/*
 * =====================================================================================
 *
 *       Filename:  Filter.hpp
 *
 *    Description:  Filter class
 *
 *        Version:  1.0
 *        Created:  08/04/2014 07:37:01 PM
 *       Compiler:  gcc
 *
 *         Author:  David Kazlauskas (dk), david@templatious.org
 *
 * =====================================================================================
 */

#ifndef FILTER_O8Y22ICC
#define FILTER_O8Y22ICC

#include <utility>

#include <templatious/util/Exceptions.hpp>
#include <templatious/CollectionAdapter.hpp>
#include <templatious/proxy/Picker.hpp>

namespace templatious {

TEMPLATIOUS_BOILERPLATE_EXCEPTION( FilterPastEndIterationException,
    "Trying to iterate past end of filter.");

template <class T,class Fn,template <class> class StoragePolicy>
struct Filter {

    template <class I,class Fun>
    struct PIterator;

    typedef typename adapters::CollectionAdapter<T> Ad;
    typedef PIterator<typename Ad::Iterator,Fn> Iterator;
    typedef PIterator<typename Ad::ConstIterator,Fn> ConstIterator;
    typedef detail::IsProxy<T> ProxUtil;
    typedef typename ProxUtil::ICollection ICollection;
    typedef Filter<T,Fn,StoragePolicy> ThisFilter;

    static const bool proxy_inside = ProxUtil::val;
    static const bool floating_iterator = Ad::floating_iterator;
    static const bool random_access_iterator = false;

    static_assert(Ad::is_valid,"Adapter is invalid.");

    typedef typename StoragePolicy<T>::Container Ref;
    typedef typename StoragePolicy<Fn>::Container Fun;

#ifndef TEMPLATIOUS_TESTING
private:
#endif

    Ref _c;
    Fun _fn;
    Iterator _b;
    Iterator _e;
    bool _cleared;

    void assertUncleared() const {
        if (_cleared) {
            throw detail::ProxyClearedUsageException();
        }
    }

    void tagCleared() {
        _cleared = true;
    }

#ifndef TEMPLATIOUS_TESTING
public:
#endif

    template <class V,class FnRef>
    Filter(V&& v,FnRef&& fn) :
        _c(std::forward<V>(v)),
        _fn(std::forward<FnRef>(fn)),
        _b(Ad::begin(_c.getRef()),
           Ad::end(_c.getRef()),
           _fn.getRef()),
        _e(Ad::end(_c.getRef()),
           Ad::end(_c.getRef()),
           _fn.getRef()),
        _cleared(false)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Filter(ThisFilter&& other)
        : _c(other._c.cpy()),
          _fn(other._fn.cpy()),
          _b(Ad::begin(_c.getRef()),
             Ad::end(_c.getRef()),
             _fn.getRef()),
          _e(Ad::end(_c.getRef()),
              Ad::end(_c.getRef()),
              _fn.getRef()),
          _cleared(other._cleared)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Iterator begin() {
        assertUncleared();
        return _b;
    }

    Iterator end() {
        assertUncleared();
        return _e;
    }

    ConstIterator cbegin() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_b._i),
            ProxUtil::const_iter_cast(_b._e),
            _b._fn
        );
    }

    ConstIterator cend() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_e._i),
            ProxUtil::const_iter_cast(_e._e),
            _e._fn
        );
    }

    Iterator iterAt(long i) {
        assertUncleared();
        auto res(_b);
        detail::naiveIterAdvance(res,_e,i);
        return res;
    }

    long size() const {
        if (!_cleared) {
            return -1;
        } else {
            return 0;
        }
    }

    template <class I,class Fun>
    struct PIterator {
    private:
        I _i;
        I _e;
        typedef typename StoragePolicy<Fn>::Container Func;
        Func _fn;

        friend struct Filter<T,Fun,StoragePolicy>;

        template <class V>
        friend struct detail::IsProxy;
    public:

        typedef PIterator<I,Fun> ThisIter;
        typedef decltype(*_i) IVal;
        static const bool is_rvalue = std::is_rvalue_reference<IVal>::value;

        template <class V>
        PIterator(const I& i,const I& e,V&& fn) :
            _i(i), _e(e), _fn(std::forward<V>(fn)) {}

        PIterator& operator=(const PIterator& rhs) {
            _i = rhs._i;
            _e = rhs._e;
            return *this;
        }

        ThisIter& operator++() {
            if (_e == _i) {
                throw FilterPastEndIterationException();
            }

            do {
                ++_i;
            } while (_e != _i && !_fn.getRef()(*_i));
            return *this;
        }

        bool operator==(const ThisIter& rhs) const {
            return _i == rhs._i;
        }

        bool operator!=(const ThisIter& rhs) const {
            return !(*this == rhs);
        }

        auto operator*() -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        auto operator*() const -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        template <bool Rval = is_rvalue>
        auto operator->()
            -> typename std::enable_if<
                !Rval,decltype(std::addressof(
                    *(std::declval<ThisIter>()._i)))
            >::type
        const {
            return std::addressof(*(this->_i));
        }

        auto getInternal()
            -> decltype(ProxUtil::iter_unwrap(_i))&
        {
            return ProxUtil::iter_unwrap(_i);
        }

    };

    void clear() {
        detail::clearRoutine<floating_iterator>(*this);
        tagCleared();
        ProxUtil::tag_cleared(_c.getRef());
        _b._i = _e._i;
    }

    auto getInternal()
        -> decltype(ProxUtil::unwrap(_c.getRef()))&
    {
        return ProxUtil::unwrap(_c.getRef());
    }

    template <class V>
    static auto iterUnwrap(V&& v)
        -> decltype(ProxUtil::iter_unwrap(
            std::forward<V>(v)))&
    {
        return ProxUtil::iter_unwrap(
            std::forward<V>(v)
        );
    }

};

namespace detail {

template <class T,class Fn,template <class> class StoragePolicy>
struct IsProxy< Filter< T,Fn,StoragePolicy > > {
    typedef IsProxy<T> Internal;
    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef typename ThisCol::ConstIterator ConstIterator;
    static const bool val = true;
    static const bool random_access_iterator = false;

    typedef adapters::CollectionAdapter<T> Ad;
    typedef typename Ad::ThisCol ICollection;
    typedef typename
        adapters::CollectionAdapter<ICollection> IAdapter;

    template <class C>
    static auto unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static auto iter_unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static void iter_advance(C& i,C& e,long s) {
        naiveIterAdvance(i,e,s);
    }

    template <class C>
    static long get_mul(C&& a) {
        return -1;
    }

    template <class U>
    static void tag_cleared(U& u) {
        u.tagCleared();
    }

    template <class Iter>
    static auto const_iter_cast(Iter&& i)
     -> decltype(
        ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        )
     )
    {
        return ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        );
    }
};

}

namespace adapters {

template <class T,class Fn,template <class> class StoragePolicy>
struct CollectionAdapter< Filter<T,Fn,StoragePolicy> > {

    static const bool is_valid = true;

    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef const ThisCol ConstCol;
    typedef typename ThisCol::Iterator Iterator;
    typedef typename ThisCol::ConstIterator ConstIterator;
    typedef typename ThisCol::Ad::ValueType ValueType;
    typedef typename ThisCol::Ad::ConstValueType ConstValueType;

    static const bool floating_iterator = ThisCol::Ad::floating_iterator;

    template <class C>
    static Iterator begin(C&& c) {
        return c.begin();
    }

    template <class C>
    static Iterator end(C&& c) {
        return c.end();
    }

    static ConstIterator cbegin(ConstCol& c) {
        return c.cbegin();
    }

    static ConstIterator cend(ConstCol& c) {
        return c.cend();
    }

    template <class C>
    static Iterator iterAt(C&& c,long i) {
        return c.iterAt(i);
    }

    template <class C,class V>
    static void insertAt(C&& c,Iterator i,V&& v) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void erase(C&& c, Iterator i) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void erase(C&& c, Iterator beg, Iterator end) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void clear(C&& c) {
        c.clear();
    }

    template <class C>
    static long size(C&& c) {
        return c.size();
    }

};

}

}

#endif /* end of include guard: FILTER_O8Y22ICC */

<commit_msg>Scott Meyers trick<commit_after>//==================================================
// Copyright (c) 2015 Deividas Kazlauskas
//
// See the file license.txt for copying permission.
//==================================================

/*
 * =====================================================================================
 *
 *       Filename:  Filter.hpp
 *
 *    Description:  Filter class
 *
 *        Version:  1.0
 *        Created:  08/04/2014 07:37:01 PM
 *       Compiler:  gcc
 *
 *         Author:  David Kazlauskas (dk), david@templatious.org
 *
 * =====================================================================================
 */

#ifndef FILTER_O8Y22ICC
#define FILTER_O8Y22ICC

#include <utility>

#include <templatious/util/Exceptions.hpp>
#include <templatious/CollectionAdapter.hpp>
#include <templatious/proxy/Picker.hpp>

namespace templatious {

TEMPLATIOUS_BOILERPLATE_EXCEPTION( FilterPastEndIterationException,
    "Trying to iterate past end of filter.");

template <class T,class Fn,template <class> class StoragePolicy>
struct Filter {

    template <class I,class Fun>
    struct PIterator;

    typedef typename adapters::CollectionAdapter<T> Ad;
    typedef PIterator<typename Ad::Iterator,Fn> Iterator;
    typedef PIterator<typename Ad::ConstIterator,Fn> ConstIterator;
    typedef detail::IsProxy<T> ProxUtil;
    typedef typename ProxUtil::ICollection ICollection;
    typedef Filter<T,Fn,StoragePolicy> ThisFilter;

    static const bool proxy_inside = ProxUtil::val;
    static const bool floating_iterator = Ad::floating_iterator;
    static const bool random_access_iterator = false;

    static_assert(Ad::is_valid,"Adapter is invalid.");

    typedef typename StoragePolicy<T>::Container Ref;
    typedef typename StoragePolicy<Fn>::Container Fun;

#ifndef TEMPLATIOUS_TESTING
private:
#endif

    Ref _c;
    Fun _fn;
    Iterator _b;
    Iterator _e;
    bool _cleared;

    void assertUncleared() const {
        if (_cleared) {
            throw detail::ProxyClearedUsageException();
        }
    }

    void tagCleared() {
        _cleared = true;
    }

#ifndef TEMPLATIOUS_TESTING
public:
#endif

    template <class V,class FnRef>
    Filter(V&& v,FnRef&& fn) :
        _c(std::forward<V>(v)),
        _fn(std::forward<FnRef>(fn)),
        _b(Ad::begin(_c.getRef()),
           Ad::end(_c.getRef()),
           _fn.getRef()),
        _e(Ad::end(_c.getRef()),
           Ad::end(_c.getRef()),
           _fn.getRef()),
        _cleared(false)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Filter(ThisFilter&& other)
        : _c(other._c.cpy()),
          _fn(other._fn.cpy()),
          _b(Ad::begin(_c.getRef()),
             Ad::end(_c.getRef()),
             _fn.getRef()),
          _e(Ad::end(_c.getRef()),
              Ad::end(_c.getRef()),
              _fn.getRef()),
          _cleared(other._cleared)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Iterator begin() {
        assertUncleared();
        return _b;
    }

    Iterator end() {
        assertUncleared();
        return _e;
    }

    ConstIterator cbegin() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_b._i),
            ProxUtil::const_iter_cast(_b._e),
            _b._fn
        );
    }

    ConstIterator cend() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_e._i),
            ProxUtil::const_iter_cast(_e._e),
            _e._fn
        );
    }

    Iterator iterAt(long i) {
        assertUncleared();
        auto res(_b);
        detail::naiveIterAdvance(res,_e,i);
        return res;
    }

    long size() const {
        if (!_cleared) {
            return -1;
        } else {
            return 0;
        }
    }

    template <class I,class Fun>
    struct PIterator {
    private:
        I _i;
        I _e;
        typedef typename StoragePolicy<Fn>::Container Func;
        Func _fn;

        friend struct Filter<T,Fun,StoragePolicy>;

        template <class V>
        friend struct detail::IsProxy;
    public:

        typedef PIterator<I,Fun> ThisIter;
        typedef decltype(*_i)&& IVal;
        static const bool is_rvalue = std::is_rvalue_reference<IVal>::value;

        template <class V>
        PIterator(const I& i,const I& e,V&& fn) :
            _i(i), _e(e), _fn(std::forward<V>(fn)) {}

        PIterator& operator=(const PIterator& rhs) {
            _i = rhs._i;
            _e = rhs._e;
            return *this;
        }

        ThisIter& operator++() {
            if (_e == _i) {
                throw FilterPastEndIterationException();
            }

            do {
                ++_i;
            } while (_e != _i && !_fn.getRef()(*_i));
            return *this;
        }

        bool operator==(const ThisIter& rhs) const {
            return _i == rhs._i;
        }

        bool operator!=(const ThisIter& rhs) const {
            return !(*this == rhs);
        }

        auto operator*() -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        auto operator*() const -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        template <bool Rval = is_rvalue>
        auto operator->()
            -> typename std::enable_if<
                !Rval,decltype(std::addressof(
                    *(std::declval<ThisIter>()._i)))
            >::type
        const {
            return std::addressof(*(this->_i));
        }

        auto getInternal()
            -> decltype(ProxUtil::iter_unwrap(_i))&
        {
            return ProxUtil::iter_unwrap(_i);
        }

    };

    void clear() {
        detail::clearRoutine<floating_iterator>(*this);
        tagCleared();
        ProxUtil::tag_cleared(_c.getRef());
        _b._i = _e._i;
    }

    auto getInternal()
        -> decltype(ProxUtil::unwrap(_c.getRef()))&
    {
        return ProxUtil::unwrap(_c.getRef());
    }

    template <class V>
    static auto iterUnwrap(V&& v)
        -> decltype(ProxUtil::iter_unwrap(
            std::forward<V>(v)))&
    {
        return ProxUtil::iter_unwrap(
            std::forward<V>(v)
        );
    }

};

namespace detail {

template <class T,class Fn,template <class> class StoragePolicy>
struct IsProxy< Filter< T,Fn,StoragePolicy > > {
    typedef IsProxy<T> Internal;
    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef typename ThisCol::ConstIterator ConstIterator;
    static const bool val = true;
    static const bool random_access_iterator = false;

    typedef adapters::CollectionAdapter<T> Ad;
    typedef typename Ad::ThisCol ICollection;
    typedef typename
        adapters::CollectionAdapter<ICollection> IAdapter;

    template <class C>
    static auto unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static auto iter_unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static void iter_advance(C& i,C& e,long s) {
        naiveIterAdvance(i,e,s);
    }

    template <class C>
    static long get_mul(C&& a) {
        return -1;
    }

    template <class U>
    static void tag_cleared(U& u) {
        u.tagCleared();
    }

    template <class Iter>
    static auto const_iter_cast(Iter&& i)
     -> decltype(
        ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        )
     )
    {
        return ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        );
    }
};

}

namespace adapters {

template <class T,class Fn,template <class> class StoragePolicy>
struct CollectionAdapter< Filter<T,Fn,StoragePolicy> > {

    static const bool is_valid = true;

    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef const ThisCol ConstCol;
    typedef typename ThisCol::Iterator Iterator;
    typedef typename ThisCol::ConstIterator ConstIterator;
    typedef typename ThisCol::Ad::ValueType ValueType;
    typedef typename ThisCol::Ad::ConstValueType ConstValueType;

    static const bool floating_iterator = ThisCol::Ad::floating_iterator;

    template <class C>
    static Iterator begin(C&& c) {
        return c.begin();
    }

    template <class C>
    static Iterator end(C&& c) {
        return c.end();
    }

    static ConstIterator cbegin(ConstCol& c) {
        return c.cbegin();
    }

    static ConstIterator cend(ConstCol& c) {
        return c.cend();
    }

    template <class C>
    static Iterator iterAt(C&& c,long i) {
        return c.iterAt(i);
    }

    template <class C,class V>
    static void insertAt(C&& c,Iterator i,V&& v) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void erase(C&& c, Iterator i) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void erase(C&& c, Iterator beg, Iterator end) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void clear(C&& c) {
        c.clear();
    }

    template <class C>
    static long size(C&& c) {
        return c.size();
    }

};

}

}

#endif /* end of include guard: FILTER_O8Y22ICC */

<|endoftext|>


<commit_before>#define _WIN32_WINNT 0x0400
#pragma comment( lib, "user32.lib" )

#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <shellapi.h>
#include "resource.h"

#define WM_MYMESSAGE (WM_USER + 1)

#if _DEBUG
#define SHOW_WINDOW 1
#else
#define SHOW_WINDOW 0
#endif

HHOOK hKeyboardHook;

__declspec(dllexport) LRESULT CALLBACK KeyboardEvent(int nCode, WPARAM wParam, LPARAM lParam)
{
	DWORD SHIFT_key = 0;
	DWORD CTRL_key = 0;
	DWORD ALT_key = 0;

	if ((nCode == HC_ACTION) && ((wParam == WM_SYSKEYDOWN) || (wParam == WM_KEYDOWN)))
	{
		KBDLLHOOKSTRUCT hooked_key = *((KBDLLHOOKSTRUCT*)lParam);
		DWORD dwMsg = 1;
		dwMsg += hooked_key.scanCode << 16;
		dwMsg += hooked_key.flags << 24;
		char lpszKeyName[1024] = { 0 };

		int i = GetKeyNameText(dwMsg, (lpszKeyName + 1), 0xFF) + 1;

		int key = hooked_key.vkCode;

		if (hooked_key.vkCode == VK_CAPITAL) {
			if ((GetKeyState(VK_CAPITAL) & 0x0001) == 0) {
				keybd_event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
				keybd_event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
			}
		}

		SHIFT_key = GetAsyncKeyState(VK_SHIFT);
		CTRL_key = GetAsyncKeyState(VK_CONTROL);
		ALT_key = GetAsyncKeyState(VK_MENU);

		if (key >= 'A' && key <= 'Z')
		{

			if (GetAsyncKeyState(VK_SHIFT) >= 0) key += 32;

			// Lets you quit the program lmao
			if (CTRL_key != 0 && ALT_key != 0 && SHIFT_key != 0 && key == 'Q')
			{
				PostQuitMessage(0);
			}

			SHIFT_key = 0;
			CTRL_key = 0;
			ALT_key = 0;
		}

	}

	return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}

void MessageLoop()
{
	MSG message;
	while (GetMessage(&message, NULL, 0, 0))
	{
		TranslateMessage(&message);
		DispatchMessage(&message);
	}
}

DWORD WINAPI CapsLockKillerHook(LPVOID lpParm)
{
	HINSTANCE hInstance = GetModuleHandle(NULL);
	if (!hInstance) hInstance = LoadLibrary((LPCSTR)lpParm);
	if (!hInstance) return 1;

	hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)KeyboardEvent, hInstance, NULL);
	MessageLoop();
	UnhookWindowsHookEx(hKeyboardHook);
	return 0;
}

LRESULT OnMessageCallback(WPARAM wParam, LPARAM lParam)
{
	if (lParam == WM_RBUTTONDOWN)
	{	// Popup
		printf("right click was pressed\n");
		return -1;
	}

	return 0; // 0=not handled 1=handled
}

void TaskbarNotify() {

	NOTIFYICONDATA Tray;
	HWND hWnd;
	hWnd = FindWindow("ConsoleWindowClass", NULL);
	ShowWindow(hWnd, SHOW_WINDOW);
	Tray.cbSize = sizeof(Tray);

	//Custom icons one day D:
	Tray.hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));

	Tray.hWnd = hWnd;
	strcpy_s(Tray.szTip, "NoCapLock - Running");
	Tray.uCallbackMessage = WM_MYMESSAGE;
	Tray.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
	Tray.uID = 1;
	Shell_NotifyIcon(NIM_ADD, &Tray);
}

int main(int argc, char** argv)
{
	HANDLE hThread;
	DWORD dwThread;
	printf("Simple tool created by Toyz which allows you to kill capslock\n");
	printf("Source code at: https://github.com/Toyz/NoCapsLock\n");
	printf("LICENSED UNDER APACHE 2.0\n");

	hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CapsLockKillerHook, (LPVOID)argv[0], NULL, &dwThread);

#ifndef _DEBUG
	ShowWindow(FindWindowA("ConsoleWindowClass", NULL), false);
#endif // !DEBUG

	TaskbarNotify();
	if (hThread) return WaitForSingleObject(hThread, INFINITE);
	else return 1;

}
<commit_msg>Changes to the code to allow closing and showing its running<commit_after>#define _WIN32_WINNT 0x0400
#pragma comment( lib, "user32.lib" )

#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <shellapi.h>
#include "resource.h"

#define WM_MYMESSAGE (WM_USER + 1)

#if _DEBUG
#define SHOW_WINDOW 1
#else
#define SHOW_WINDOW 0
#endif

HHOOK hKeyboardHook;

HWND GetConsoleWindow() {
	return FindWindow("ConsoleWindowClass", NULL);
}

__declspec(dllexport) LRESULT CALLBACK KeyboardEvent(int nCode, WPARAM wParam, LPARAM lParam)
{
	DWORD SHIFT_key = 0;
	DWORD CTRL_key = 0;
	DWORD ALT_key = 0;

	if ((nCode == HC_ACTION) && ((wParam == WM_SYSKEYDOWN) || (wParam == WM_KEYDOWN)))
	{
		KBDLLHOOKSTRUCT hooked_key = *((KBDLLHOOKSTRUCT*)lParam);
		DWORD dwMsg = 1;
		dwMsg += hooked_key.scanCode << 16;
		dwMsg += hooked_key.flags << 24;
		char lpszKeyName[1024] = { 0 };

		int i = GetKeyNameText(dwMsg, (lpszKeyName + 1), 0xFF) + 1;

		int key = hooked_key.vkCode;

		if (hooked_key.vkCode == VK_CAPITAL) {
			if ((GetKeyState(VK_CAPITAL) & 0x0001) == 0) {
				keybd_event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
				keybd_event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
			}
		}

		SHIFT_key = GetAsyncKeyState(VK_SHIFT);
		CTRL_key = GetAsyncKeyState(VK_CONTROL);
		ALT_key = GetAsyncKeyState(VK_MENU);

		if (key >= 'A' && key <= 'Z')
		{

			if (GetAsyncKeyState(VK_SHIFT) >= 0) key += 32;

			// Lets you quit the program lmao
			if (CTRL_key != 0 && ALT_key != 0 && SHIFT_key != 0 && key == 'Q')
			{
				PostQuitMessage(0);
			}

			SHIFT_key = 0;
			CTRL_key = 0;
			ALT_key = 0;
		}

	}

	return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}

void MessageLoop()
{
	MSG message;
	while (GetMessage(&message, NULL, 0, 0))
	{
		TranslateMessage(&message);
		DispatchMessage(&message);
	}
}

DWORD WINAPI CapsLockKillerHook(LPVOID lpParm)
{
	HINSTANCE hInstance = GetModuleHandle(NULL);
	if (!hInstance) hInstance = LoadLibrary((LPCSTR)lpParm);
	if (!hInstance) return 1;

	hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)KeyboardEvent, hInstance, NULL);
	MessageLoop();
	UnhookWindowsHookEx(hKeyboardHook);
	return 0;
}

void TaskbarNotify() {
	HWND hWnd = GetConsoleWindow();

	NOTIFYICONDATA Tray;
	ShowWindow(hWnd, SHOW_WINDOW);
	Tray.cbSize = sizeof(Tray);
	Tray.hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));
	Tray.hWnd = hWnd;
	strcpy_s(Tray.szTip, "NoCapsLock - Running");
	Tray.uCallbackMessage = WM_MYMESSAGE;
	Tray.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
	Tray.uID = 1;
	Shell_NotifyIcon(NIM_ADD, &Tray);
}

int main(int argc, char** argv)
{
	HANDLE hThread;
	DWORD dwThread;
	printf("Simple tool created by Toyz which allows you to kill capslock\n");
	printf("Source code at: https://github.com/Toyz/NoCapsLock\n");
	printf("LICENSED UNDER APACHE 2.0\n");

	hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CapsLockKillerHook, (LPVOID)argv[0], NULL, &dwThread);

	TaskbarNotify();
	if (hThread) return WaitForSingleObject(hThread, INFINITE);
	else return 1;
}
<|endoftext|>


<commit_before>#include "SwiftExtractor.h"

#include <iostream>
#include <memory>
#include <unordered_set>
#include <queue>

#include <swift/AST/SourceFile.h>
#include <swift/AST/Builtins.h>
#include <swift/Basic/FileTypes.h>
#include <llvm/ADT/SmallString.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Path.h>

#include "swift/extractor/trap/generated/TrapClasses.h"
#include "swift/extractor/trap/TrapDomain.h"
#include "swift/extractor/visitors/SwiftVisitor.h"
#include "swift/extractor/TargetTrapFile.h"

using namespace codeql;
using namespace std::string_literals;

static void archiveFile(const SwiftExtractorConfiguration& config, swift::SourceFile& file) {
  if (std::error_code ec = llvm::sys::fs::create_directories(config.trapDir)) {
    std::cerr << "Cannot create TRAP directory: " << ec.message() << "\n";
    return;
  }

  if (std::error_code ec = llvm::sys::fs::create_directories(config.sourceArchiveDir)) {
    std::cerr << "Cannot create source archive directory: " << ec.message() << "\n";
    return;
  }

  llvm::SmallString<PATH_MAX> srcFilePath(file.getFilename());
  llvm::sys::fs::make_absolute(srcFilePath);

  llvm::SmallString<PATH_MAX> dstFilePath(config.sourceArchiveDir);
  llvm::sys::path::append(dstFilePath, srcFilePath);

  llvm::StringRef parent = llvm::sys::path::parent_path(dstFilePath);
  if (std::error_code ec = llvm::sys::fs::create_directories(parent)) {
    std::cerr << "Cannot create source archive destination directory '" << parent.str()
              << "': " << ec.message() << "\n";
    return;
  }

  if (std::error_code ec = llvm::sys::fs::copy_file(srcFilePath, dstFilePath)) {
    std::cerr << "Cannot archive source file '" << srcFilePath.str().str() << "' -> '"
              << dstFilePath.str().str() << "': " << ec.message() << "\n";
    return;
  }
}

static std::string getFilename(swift::ModuleDecl& module, swift::SourceFile* primaryFile) {
  if (primaryFile) {
    return primaryFile->getFilename().str();
  }
  // PCM clang module
  if (module.isNonSwiftModule()) {
    // Several modules with different names might come from .pcm (clang module) files
    // In this case we want to differentiate them
    // Moreover, pcm files may come from caches located in different directories, but are
    // unambiguously identified by the base file name, so we can discard the absolute directory
    std::string filename = "/pcms/"s + llvm::sys::path::filename(module.getModuleFilename()).str();
    filename += "-";
    filename += module.getName().str();
    return filename;
  }
  return module.getModuleFilename().str();
}

/* The builtin module is special, as it does not publish any top-level declaration
 * It creates (and caches) declarations on demand when a lookup is carried out
 * (see BuiltinUnit in swift/AST/FileUnit.h for the cache details, and getBuiltinValueDecl in
 * swift/AST/Builtins.h for the creation details)
 * As we want to create the Builtin trap file once and for all so that it works for other
 * extraction runs, rather than collecting what we need we pre-populate the builtin trap with
 * what we expect. This list might need thus to be expanded.
 * Notice, that while swift/AST/Builtins.def has a list of builtin symbols, it does not contain
 * all information required to instantiate builtin variants.
 * Other possible approaches:
 * * create one trap per builtin declaration when encountered
 * * expand the list to all possible builtins (of which there are a lot)
 */
static void getBuiltinDecls(swift::ModuleDecl& builtinModule,
                            llvm::SmallVector<swift::Decl*>& decls) {
  llvm::SmallVector<swift::ValueDecl*> values;
  for (auto symbol : {
           "zeroInitializer", "BridgeObject",   "Word",           "NativeObject",
           "RawPointer",      "Int1",           "Int8",           "Int16",
           "Int32",           "Int64",          "IntLiteral",     "FPIEEE16",
           "FPIEEE32",        "FPIEEE64",       "FPIEEE80",       "Vec2xInt8",
           "Vec4xInt8",       "Vec8xInt8",      "Vec16xInt8",     "Vec32xInt8",
           "Vec64xInt8",      "Vec2xInt16",     "Vec4xInt16",     "Vec8xInt16",
           "Vec16xInt16",     "Vec32xInt16",    "Vec64xInt16",    "Vec2xInt32",
           "Vec4xInt32",      "Vec8xInt32",     "Vec16xInt32",    "Vec32xInt32",
           "Vec64xInt32",     "Vec2xInt64",     "Vec4xInt64",     "Vec8xInt64",
           "Vec16xInt64",     "Vec32xInt64",    "Vec64xInt64",    "Vec2xFPIEEE16",
           "Vec4xFPIEEE16",   "Vec8xFPIEEE16",  "Vec16xFPIEEE16", "Vec32xFPIEEE16",
           "Vec64xFPIEEE16",  "Vec2xFPIEEE32",  "Vec4xFPIEEE32",  "Vec8xFPIEEE32",
           "Vec16xFPIEEE32",  "Vec32xFPIEEE32", "Vec64xFPIEEE32", "Vec2xFPIEEE64",
           "Vec4xFPIEEE64",   "Vec8xFPIEEE64",  "Vec16xFPIEEE64", "Vec32xFPIEEE64",
           "Vec64xFPIEEE64",
       }) {
    builtinModule.lookupValue(builtinModule.getASTContext().getIdentifier(symbol),
                              swift::NLKind::QualifiedLookup, values);
  }
  decls.insert(decls.end(), values.begin(), values.end());
}

static llvm::SmallVector<swift::Decl*> getTopLevelDecls(swift::ModuleDecl& module,
                                                        swift::SourceFile* primaryFile = nullptr) {
  llvm::SmallVector<swift::Decl*> ret;
  ret.push_back(&module);
  if (primaryFile) {
    primaryFile->getTopLevelDecls(ret);
  } else if (module.isBuiltinModule()) {
    getBuiltinDecls(module, ret);
  } else {
    module.getTopLevelDecls(ret);
  }
  return ret;
}

static std::unordered_set<swift::ModuleDecl*> extractDeclarations(
    const SwiftExtractorConfiguration& config,
    swift::CompilerInstance& compiler,
    swift::ModuleDecl& module,
    swift::SourceFile* primaryFile = nullptr) {
  auto filename = getFilename(module, primaryFile);

  // The extractor can be called several times from different processes with
  // the same input file(s). Using `TargetFile` the first process will win, and the following
  // will just skip the work
  auto trapTarget = createTargetTrapFile(config, filename);
  if (!trapTarget) {
    // another process arrived first, nothing to do for us
    return {};
  }
  TrapDomain trap{*trapTarget};

  std::vector<swift::Token> comments;
  if (primaryFile && primaryFile->getBufferID().hasValue()) {
    auto& sourceManager = compiler.getSourceMgr();
    auto tokens = swift::tokenize(compiler.getInvocation().getLangOptions(), sourceManager,
                                  primaryFile->getBufferID().getValue());
    for (auto& token : tokens) {
      if (token.getKind() == swift::tok::comment) {
        comments.push_back(token);
      }
    }
  }

  SwiftVisitor visitor(compiler.getSourceMgr(), trap, module, primaryFile);
  auto topLevelDecls = getTopLevelDecls(module, primaryFile);
  for (auto decl : topLevelDecls) {
    visitor.extract(decl);
  }
  for (auto& comment : comments) {
    visitor.extract(comment);
  }
  return std::move(visitor).getEncounteredModules();
}

static std::unordered_set<std::string> collectInputFilenames(swift::CompilerInstance& compiler) {
  // The frontend can be called in many different ways.
  // At each invocation we only extract system and builtin modules and any input source files that
  // have an output associated with them.
  std::unordered_set<std::string> sourceFiles;
  auto inputFiles = compiler.getInvocation().getFrontendOptions().InputsAndOutputs.getAllInputs();
  for (auto& input : inputFiles) {
    if (input.getType() == swift::file_types::TY_Swift && !input.outputFilename().empty()) {
      sourceFiles.insert(input.getFileName());
    }
  }
  return sourceFiles;
}

void codeql::extractSwiftFiles(const SwiftExtractorConfiguration& config,
                               swift::CompilerInstance& compiler) {
  auto inputFiles = collectInputFilenames(compiler);
  std::vector<swift::ModuleDecl*> todo = {compiler.getMainModule()};
  std::unordered_set<swift::ModuleDecl*> seen = {compiler.getMainModule()};

  while (!todo.empty()) {
    auto module = todo.back();
    todo.pop_back();
    llvm::errs() << "processing module " << module->getName() << '\n';
    bool isFromSourceFile = false;
    std::unordered_set<swift::ModuleDecl*> encounteredModules;
    for (auto file : module->getFiles()) {
      auto sourceFile = llvm::dyn_cast<swift::SourceFile>(file);
      if (!sourceFile) {
        continue;
      }
      isFromSourceFile = true;
      if (inputFiles.count(sourceFile->getFilename().str()) == 0) {
        continue;
      }
      archiveFile(config, *sourceFile);
      encounteredModules = extractDeclarations(config, compiler, *module, sourceFile);
    }
    if (!isFromSourceFile) {
      encounteredModules = extractDeclarations(config, compiler, *module);
    }
    for (auto encountered : encounteredModules) {
      if (seen.count(encountered) == 0) {
        todo.push_back(encountered);
        seen.insert(encountered);
      }
    }
  }
}
<commit_msg>Swift: emit `<Builtin>.trap` instead of `.trap`<commit_after>#include "SwiftExtractor.h"

#include <iostream>
#include <memory>
#include <unordered_set>
#include <queue>

#include <swift/AST/SourceFile.h>
#include <swift/AST/Builtins.h>
#include <swift/Basic/FileTypes.h>
#include <llvm/ADT/SmallString.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Path.h>

#include "swift/extractor/trap/generated/TrapClasses.h"
#include "swift/extractor/trap/TrapDomain.h"
#include "swift/extractor/visitors/SwiftVisitor.h"
#include "swift/extractor/TargetTrapFile.h"

using namespace codeql;
using namespace std::string_literals;

static void archiveFile(const SwiftExtractorConfiguration& config, swift::SourceFile& file) {
  if (std::error_code ec = llvm::sys::fs::create_directories(config.trapDir)) {
    std::cerr << "Cannot create TRAP directory: " << ec.message() << "\n";
    return;
  }

  if (std::error_code ec = llvm::sys::fs::create_directories(config.sourceArchiveDir)) {
    std::cerr << "Cannot create source archive directory: " << ec.message() << "\n";
    return;
  }

  llvm::SmallString<PATH_MAX> srcFilePath(file.getFilename());
  llvm::sys::fs::make_absolute(srcFilePath);

  llvm::SmallString<PATH_MAX> dstFilePath(config.sourceArchiveDir);
  llvm::sys::path::append(dstFilePath, srcFilePath);

  llvm::StringRef parent = llvm::sys::path::parent_path(dstFilePath);
  if (std::error_code ec = llvm::sys::fs::create_directories(parent)) {
    std::cerr << "Cannot create source archive destination directory '" << parent.str()
              << "': " << ec.message() << "\n";
    return;
  }

  if (std::error_code ec = llvm::sys::fs::copy_file(srcFilePath, dstFilePath)) {
    std::cerr << "Cannot archive source file '" << srcFilePath.str().str() << "' -> '"
              << dstFilePath.str().str() << "': " << ec.message() << "\n";
    return;
  }
}

static std::string getFilename(swift::ModuleDecl& module, swift::SourceFile* primaryFile) {
  if (primaryFile) {
    return primaryFile->getFilename().str();
  }
  // PCM clang module
  if (module.isNonSwiftModule()) {
    // Several modules with different names might come from .pcm (clang module) files
    // In this case we want to differentiate them
    // Moreover, pcm files may come from caches located in different directories, but are
    // unambiguously identified by the base file name, so we can discard the absolute directory
    std::string filename = "/pcms/"s + llvm::sys::path::filename(module.getModuleFilename()).str();
    filename += "-";
    filename += module.getName().str();
    return filename;
  }
  if (module.isBuiltinModule()) {
    // The Builtin module has an empty filename, let's fix that
    return "/<Builtin>";
  }
  return module.getModuleFilename().str();
}

/* The builtin module is special, as it does not publish any top-level declaration
 * It creates (and caches) declarations on demand when a lookup is carried out
 * (see BuiltinUnit in swift/AST/FileUnit.h for the cache details, and getBuiltinValueDecl in
 * swift/AST/Builtins.h for the creation details)
 * As we want to create the Builtin trap file once and for all so that it works for other
 * extraction runs, rather than collecting what we need we pre-populate the builtin trap with
 * what we expect. This list might need thus to be expanded.
 * Notice, that while swift/AST/Builtins.def has a list of builtin symbols, it does not contain
 * all information required to instantiate builtin variants.
 * Other possible approaches:
 * * create one trap per builtin declaration when encountered
 * * expand the list to all possible builtins (of which there are a lot)
 */
static void getBuiltinDecls(swift::ModuleDecl& builtinModule,
                            llvm::SmallVector<swift::Decl*>& decls) {
  llvm::SmallVector<swift::ValueDecl*> values;
  for (auto symbol : {
           "zeroInitializer", "BridgeObject",   "Word",           "NativeObject",
           "RawPointer",      "Int1",           "Int8",           "Int16",
           "Int32",           "Int64",          "IntLiteral",     "FPIEEE16",
           "FPIEEE32",        "FPIEEE64",       "FPIEEE80",       "Vec2xInt8",
           "Vec4xInt8",       "Vec8xInt8",      "Vec16xInt8",     "Vec32xInt8",
           "Vec64xInt8",      "Vec2xInt16",     "Vec4xInt16",     "Vec8xInt16",
           "Vec16xInt16",     "Vec32xInt16",    "Vec64xInt16",    "Vec2xInt32",
           "Vec4xInt32",      "Vec8xInt32",     "Vec16xInt32",    "Vec32xInt32",
           "Vec64xInt32",     "Vec2xInt64",     "Vec4xInt64",     "Vec8xInt64",
           "Vec16xInt64",     "Vec32xInt64",    "Vec64xInt64",    "Vec2xFPIEEE16",
           "Vec4xFPIEEE16",   "Vec8xFPIEEE16",  "Vec16xFPIEEE16", "Vec32xFPIEEE16",
           "Vec64xFPIEEE16",  "Vec2xFPIEEE32",  "Vec4xFPIEEE32",  "Vec8xFPIEEE32",
           "Vec16xFPIEEE32",  "Vec32xFPIEEE32", "Vec64xFPIEEE32", "Vec2xFPIEEE64",
           "Vec4xFPIEEE64",   "Vec8xFPIEEE64",  "Vec16xFPIEEE64", "Vec32xFPIEEE64",
           "Vec64xFPIEEE64",
       }) {
    builtinModule.lookupValue(builtinModule.getASTContext().getIdentifier(symbol),
                              swift::NLKind::QualifiedLookup, values);
  }
  decls.insert(decls.end(), values.begin(), values.end());
}

static llvm::SmallVector<swift::Decl*> getTopLevelDecls(swift::ModuleDecl& module,
                                                        swift::SourceFile* primaryFile = nullptr) {
  llvm::SmallVector<swift::Decl*> ret;
  ret.push_back(&module);
  if (primaryFile) {
    primaryFile->getTopLevelDecls(ret);
  } else if (module.isBuiltinModule()) {
    getBuiltinDecls(module, ret);
  } else {
    module.getTopLevelDecls(ret);
  }
  return ret;
}

static std::unordered_set<swift::ModuleDecl*> extractDeclarations(
    const SwiftExtractorConfiguration& config,
    swift::CompilerInstance& compiler,
    swift::ModuleDecl& module,
    swift::SourceFile* primaryFile = nullptr) {
  auto filename = getFilename(module, primaryFile);

  // The extractor can be called several times from different processes with
  // the same input file(s). Using `TargetFile` the first process will win, and the following
  // will just skip the work
  auto trapTarget = createTargetTrapFile(config, filename);
  if (!trapTarget) {
    // another process arrived first, nothing to do for us
    return {};
  }
  TrapDomain trap{*trapTarget};

  std::vector<swift::Token> comments;
  if (primaryFile && primaryFile->getBufferID().hasValue()) {
    auto& sourceManager = compiler.getSourceMgr();
    auto tokens = swift::tokenize(compiler.getInvocation().getLangOptions(), sourceManager,
                                  primaryFile->getBufferID().getValue());
    for (auto& token : tokens) {
      if (token.getKind() == swift::tok::comment) {
        comments.push_back(token);
      }
    }
  }

  SwiftVisitor visitor(compiler.getSourceMgr(), trap, module, primaryFile);
  auto topLevelDecls = getTopLevelDecls(module, primaryFile);
  for (auto decl : topLevelDecls) {
    visitor.extract(decl);
  }
  for (auto& comment : comments) {
    visitor.extract(comment);
  }
  return std::move(visitor).getEncounteredModules();
}

static std::unordered_set<std::string> collectInputFilenames(swift::CompilerInstance& compiler) {
  // The frontend can be called in many different ways.
  // At each invocation we only extract system and builtin modules and any input source files that
  // have an output associated with them.
  std::unordered_set<std::string> sourceFiles;
  auto inputFiles = compiler.getInvocation().getFrontendOptions().InputsAndOutputs.getAllInputs();
  for (auto& input : inputFiles) {
    if (input.getType() == swift::file_types::TY_Swift && !input.outputFilename().empty()) {
      sourceFiles.insert(input.getFileName());
    }
  }
  return sourceFiles;
}

void codeql::extractSwiftFiles(const SwiftExtractorConfiguration& config,
                               swift::CompilerInstance& compiler) {
  auto inputFiles = collectInputFilenames(compiler);
  std::vector<swift::ModuleDecl*> todo = {compiler.getMainModule()};
  std::unordered_set<swift::ModuleDecl*> seen = {compiler.getMainModule()};

  while (!todo.empty()) {
    auto module = todo.back();
    todo.pop_back();
    llvm::errs() << "processing module " << module->getName() << '\n';
    bool isFromSourceFile = false;
    std::unordered_set<swift::ModuleDecl*> encounteredModules;
    for (auto file : module->getFiles()) {
      auto sourceFile = llvm::dyn_cast<swift::SourceFile>(file);
      if (!sourceFile) {
        continue;
      }
      isFromSourceFile = true;
      if (inputFiles.count(sourceFile->getFilename().str()) == 0) {
        continue;
      }
      archiveFile(config, *sourceFile);
      encounteredModules = extractDeclarations(config, compiler, *module, sourceFile);
    }
    if (!isFromSourceFile) {
      encounteredModules = extractDeclarations(config, compiler, *module);
    }
    for (auto encountered : encounteredModules) {
      if (seen.count(encountered) == 0) {
        todo.push_back(encountered);
        seen.insert(encountered);
      }
    }
  }
}
<|endoftext|>