text:
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "src/wsiToDcm.h"
#include <dcmtk/dcmdata/dcfilefo.h>
#include <dcmtk/dcmdata/dcistrmb.h>
#include <dcmtk/dcmdata/dcostrma.h>
#include <dcmtk/dcmdata/dcostrmb.h>
#include <dcmtk/dcmdata/dcuid.h>
#include <dcmtk/dcmdata/dcvrat.h>
#include <dcmtk/ofstd/ofvector.h>
#include <gtest/gtest.h>
#include <boost/filesystem.hpp>
#include <memory>
#include <string>
#include <vector>
#include "tests/testUtils.h"

TEST(readTiff, simple) {
  double downsample = 1.;
  std::string dcmFile = std::string(testPath) + "level-0-frames-0-30.dcm";
  wsiToDicomConverter::WsiRequest request;
  request.inputFile = tiffFileName;
  request.outputFileMask = testPath;
  request.frameSizeX = 500;
  request.frameSizeY = 500;
  request.startOnLevel = 0;
  request.compression = dcmCompressionFromString("jpeg");
  request.quality = 80;
  request.imageName = "image";
  request.studyId = "study";
  request.seriesId = "series";
  request.batchLimit = 100;
  request.downsamples = &downsample;
  request.debug = true;
  wsiToDicomConverter::WsiToDcm::wsi2dcm(request);
  ASSERT_TRUE(boost::filesystem::exists(dcmFile));
  DcmFileFormat dcmFileFormat;
  dcmFileFormat.loadFile(dcmFile.c_str());
  char* stringValue;
  findElement(dcmFileFormat.getDataset(), DCM_LossyImageCompression)
      ->getString(stringValue);
  ASSERT_EQ("01", std::string(stringValue));
}

TEST(readTiff, withJson) {
  std::string dcmFile = std::string(testPath) + "level-0-frames-0-1.dcm";
  std::string jsonFile = std::string(testPath) + "testDateTags.json";
  double downsample = 1.;
  wsiToDicomConverter::WsiRequest request;
  request.inputFile = tiffFileName;
  request.outputFileMask = testPath;
  request.frameSizeX = 2220;
  request.frameSizeY = 2967;
  request.compression = dcmCompressionFromString("raw");
  request.quality = 80;
  request.imageName = "image";
  request.jsonFile = jsonFile;
  request.studyId = "study";
  request.seriesId = "series";
  request.batchLimit = 100;
  request.downsamples = &downsample;
  request.debug = true;
  wsiToDicomConverter::WsiToDcm::wsi2dcm(request);
  ASSERT_TRUE(boost::filesystem::exists(dcmFile));
  DcmFileFormat dcmFileFormat;
  dcmFileFormat.loadFile(dcmFile.c_str());
  std::string date = "20190327";
  char* stringValue;
  findElement(dcmFileFormat.getDataset(), DCM_StudyDate)
      ->getString(stringValue);
  ASSERT_EQ(date, std::string(stringValue));
  findElement(dcmFileFormat.getDataset(), DCM_SeriesDate)
      ->getString(stringValue);
  ASSERT_EQ(date, std::string(stringValue));
}

TEST(readTiff, multiFile) {
  std::string dcmFile = std::string(testPath) + "level-0-frames-";
  double downsample = 1.;
  wsiToDicomConverter::WsiRequest request;
  request.inputFile = tiffFileName;
  request.outputFileMask = testPath;
  request.frameSizeX = 500;
  request.frameSizeY = 500;
  request.compression = dcmCompressionFromString("jpeg2000");
  request.quality = 0;
  request.imageName = "image";
  request.studyId = "study";
  request.seriesId = "series";
  request.batchLimit = 10;
  request.downsamples = &downsample;
  request.debug = true;
  wsiToDicomConverter::WsiToDcm::wsi2dcm(request);

  ASSERT_TRUE(boost::filesystem::exists(dcmFile + "0-10.dcm"));
  ASSERT_TRUE(boost::filesystem::exists(dcmFile + "10-20.dcm"));
  ASSERT_TRUE(boost::filesystem::exists(dcmFile + "20-30.dcm"));
}

TEST(compressionString, jpeg) {
    ASSERT_EQ(dcmCompressionFromString("jpeg"), JPEG);
    ASSERT_EQ(dcmCompressionFromString("JPEG"), JPEG);
}

TEST(compressionString, jpeg2000) {
    ASSERT_EQ(dcmCompressionFromString("jpeg2000"), JPEG2000);
    ASSERT_EQ(dcmCompressionFromString("JPEG2000"), JPEG2000);
}

TEST(compressionString, none) {
    ASSERT_EQ(dcmCompressionFromString("none"), RAW);
    ASSERT_EQ(dcmCompressionFromString("raw"), RAW);
}

TEST(compressionString, unknown) {
    ASSERT_EQ(dcmCompressionFromString("unknown"), UNKNOWN);
    ASSERT_EQ(dcmCompressionFromString("random"), UNKNOWN);
    ASSERT_EQ(dcmCompressionFromString("jpeg/"), UNKNOWN);
    ASSERT_EQ(dcmCompressionFromString("jpeg2000."), UNKNOWN);
}

ext: cpp

max_stars_repo_name: Philbrick/wsi-to-dicom-converter

max_issues_repo_name: Philbrick/wsi-to-dicom-converter

max_forks_repo_name: Philbrick/wsi-to-dicom-converter


text:
/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <boost/filesystem/operations.hpp>
#include <optional>

#include <gtest/gtest.h>

#include "ReachableClasses.h"

#include <Creators.h>
#include <DexStore.h>
#include <IRAssembler.h>
#include <RedexContext.h>

#include <mariana-trench/Dependencies.h>
#include <mariana-trench/Redex.h>
#include <mariana-trench/tests/Test.h>

using namespace marianatrench;

namespace {

class TypesTest : public test::Test {
 public:
  std::string temporary_directory() {
    return (boost::filesystem::path(__FILE__).parent_path() / "temp").string();
  }

 private:
  void SetUp() override {
    boost::filesystem::create_directory(this->temporary_directory());
  }

  void TearDown() override {
    boost::filesystem::remove_all(this->temporary_directory());
  }
};

std::string create_proguard_configuration_file(
    const std::string& directory,
    const std::string& file_name,
    const std::string& contents) {
  auto configuration_file = boost::filesystem::path(directory) / file_name;
  boost::filesystem::save_string_file(configuration_file, contents);
  return configuration_file.native();
}

Context test_types(
    const Scope& scope,
    std::optional<std::string> proguard_configuration_file = std::nullopt) {
  Context context;
  auto proguard_configuration_paths = std::vector<std::string>{};
  if (proguard_configuration_file) {
    proguard_configuration_paths.push_back(*proguard_configuration_file);
  }
  context.options = std::make_unique<Options>(
      /* models_path */ std::vector<std::string>{},
      /* field_models_path */ std::vector<std::string>{},
      /* rules_path */ std::vector<std::string>{},
      /* lifecycles_path */ std::vector<std::string>{},
      /* proguard_configuration_paths */
      proguard_configuration_paths,
      /* sequential */ false,
      /* skip_source_indexing */ true,
      /* skip_model_generation */ true,
      /* model_generators_configuration */
      std::vector<ModelGeneratorConfiguration>{},
      /* model_generator_search_paths */ std::vector<std::string>{},
      /* remove_unreachable_code */ false);
  DexStore store("test_store");
  store.add_classes(scope);
  context.stores = {store};
  context.artificial_methods =
      std::make_unique<ArtificialMethods>(*context.kinds, context.stores);
  context.methods = std::make_unique<Methods>(context.stores);
  context.types = std::make_unique<Types>(*context.options, context.stores);
  return context;
}

std::unordered_map<int, const DexType*> register_types_for_method(
    const Context& context,
    const Method* method) {
  auto* code = method->get_code();
  mt_assert(code->cfg_built());

  std::unordered_map<int, const DexType*> register_types;
  for (const auto* block : code->cfg().blocks()) {
    for (const auto& entry : *block) {
      const IRInstruction* instruction = entry.insn;
      for (auto register_id : instruction->srcs()) {
        auto* dex_type =
            context.types->register_type(method, instruction, register_id);
        if (dex_type) {
          register_types[register_id] = dex_type;
        }
      }
    }
  }
  return register_types;
}

} // anonymous namespace

TEST_F(TypesTest, LocalIputTypes) {
  Scope scope;

  auto* dex_method = redex::create_method(scope, "LClass;", R"(
    (method (public) "LClass;.foo:()V"
     (
      (new-instance "Ljava/lang/Object;")
      (move-result-pseudo-object v0)

      (load-param v1)
      (iput-object v1 v0 "LClass;.field:Ljava/lang/Object;")

      (return-void)
     )
    )
  )");

  auto context = test_types(scope);
  auto* method = context.methods->get(dex_method);
  auto register_types = register_types_for_method(context, method);

  EXPECT_EQ(
      register_types.at(0),
      DexType::make_type(DexString::make_string("Ljava/lang/Object;")));
  EXPECT_TRUE(register_types[1] == nullptr);
}

TEST_F(TypesTest, LocalInvokeDirectTypes) {
  Scope scope;

  redex::create_void_method(scope, "LCallee;", "callee");
  auto* dex_caller = redex::create_method(
      scope,
      "LCaller;",
      R"(
          (method (public) "LCaller;.caller:()V"
            (
              (new-instance "LCallee;")
              (move-result-object v0)
              (invoke-direct (v0) "LCallee;.callee:()V")
              (return-void)
            )
          )
      )");

  auto context = test_types(scope);
  auto* method = context.methods->get(dex_caller);
  auto register_types = register_types_for_method(context, method);

  EXPECT_EQ(
      register_types.at(0),
      DexType::make_type(DexString::make_string("LCallee;")));
  EXPECT_TRUE(register_types[1] == nullptr);
}

TEST_F(TypesTest, LocalInvokeVirtualTypes) {
  Scope scope;

  auto* dex_callee = redex::create_void_method(scope, "LCallee;", "callee");
  redex::create_void_method(
      scope,
      /* class_name */ "LSubclass;",
      /* method */ "callee",
      /* parameter_types */ "",
      /* return_type */ "V",
      /* super */ dex_callee->get_class());
  auto* dex_caller = redex::create_method(
      scope,
      "LCaller;",
      R"(
        (method (public) "LCaller;.caller:(LCallee;)V"
        (
          (load-param-object v0)
          (load-param-object v1)

          (invoke-virtual (v1) "LCallee;.callee:()V")
          (return-void)
        )
        )
      )");
  auto* dex_missing_invoke = redex::create_method(
      scope,
      "LNotACaller;",
      R"(
        (method (public) "LNotACaller;.caller:(LCallee;)V"
        (
          (load-param-object v0)
          (load-param-object v1)
          (return-void)
        )
        )
      )");

  auto context = test_types(scope);
  auto* method = context.methods->get(dex_caller);
  auto register_types = register_types_for_method(context, method);

  EXPECT_EQ(
      register_types.at(1),
      DexType::make_type(DexString::make_string("LCallee;")));
  EXPECT_TRUE(register_types[0] == nullptr);

  auto* missing_invoke_method = context.methods->get(dex_missing_invoke);
  auto missing_invoke_register_types =
      register_types_for_method(context, missing_invoke_method);
  assert(!root(dex_missing_invoke));
  EXPECT_TRUE(missing_invoke_register_types[1] == nullptr);
}

TEST_F(TypesTest, GlobalInvokeVirtualTypes) {
  Scope scope;

  auto* dex_callee = redex::create_void_method(scope, "LCallee;", "callee");
  redex::create_void_method(
      scope,
      /* class_name */ "LCalleeSubclass;",
      /* method */ "callee",
      /* parameter_types */ "",
      /* return_type */ "V",
      /* super */ dex_callee->get_class());
  auto* dex_caller = redex::create_method(
      scope,
      "LCaller;",
      R"(
          (method (public) "LCaller;.caller:(LCallee;)V"
            (
              (load-param-object v0)
              (load-param-object v1)

              (new-instance "LCalleeSubclass;")
              (move-result-object v2)
              (invoke-virtual (v2) "LCallee;.callee:()V")

              (invoke-virtual (v1) "LCallee;.callee:()V")

              (return-void)
            )
          )
      )");
  auto* dex_entry_caller = redex::create_method(
      scope,
      "LEntryCaller;",
      R"(
          (method (public) "LEntryCaller;.entrycaller:()V"
          (
            (new-instance "LCalleeSubclass;")
            (move-result-object v0)
            (invoke-direct (v0) "LCalleeSubclass;.<init>:()V")

            (new-instance "LCaller;")
            (move-result-object v1)
            (invoke-direct (v1) "LCaller;.<init>:()V")

            (invoke-virtual (v1 v0) "LCaller;.caller:(LCallee;)V")
            (return-void)
          )
        )
      )");

  auto proguard_configuration = R"(
    -keep class EntryCaller {
        public void entrycaller();
    }
  )";
  auto proguard_configuration_file = create_proguard_configuration_file(
      this->temporary_directory(), "proguard.pro", proguard_configuration);

  /* Proguard configuration should set this as root, but set manually for now.
   */
  dex_entry_caller->rstate.set_root();

  assert(!root(dex_callee));
  assert(!root(dex_caller));
  assert(root(dex_entry_caller));

  auto context = test_types(scope, proguard_configuration_file);
  auto* caller = context.methods->get(dex_caller);
  auto caller_register_types = register_types_for_method(context, caller);

  EXPECT_EQ(
      caller_register_types.at(1),
      DexType::make_type(DexString::make_string("LCalleeSubclass;")));
  EXPECT_EQ(
      caller_register_types.at(2),
      DexType::make_type(DexString::make_string("LCalleeSubclass;")));

  auto* entry_method = context.methods->get(dex_entry_caller);
  auto entry_register_types = register_types_for_method(context, entry_method);

  EXPECT_EQ(
      entry_register_types.at(0),
      DexType::make_type(DexString::make_string("LCalleeSubclass;")));
  EXPECT_EQ(
      entry_register_types.at(1),
      DexType::make_type(DexString::make_string("LCaller;")));
}

max_stars_repo_name: daetalys/mariana-trench

max_issues_repo_name: daetalys/mariana-trench

max_forks_repo_name: daetalys/mariana-trench


text:
// Copyright 2020 Anatoliy Petrov
// (apetrov.projects@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt

#ifndef VARIADIC_DETAIL_SELECT_HPP
#define VARIADIC_DETAIL_SELECT_HPP

/* variadic */
#include <variadic/detail/match.hpp>

/* boost */
#include <boost/preprocessor/seq/filter.hpp>

#define VDC_DETAIL_SELECT(targets, params) \
    BOOST_PP_SEQ_FILTER( \
        VDC_DETAIL_MATCH_OP, \
        targets, \
        params \
    ) \

#define VDC_DETAIL_MATCH_OP(unspec, targets, param) \
    VDC_DETAIL_MATCH(param, targets)

#endif /* VARIADIC_DETAIL_SELECT_HPP */

ext: hpp

max_stars_repo_name: AnatoliyProjects/variadic

max_issues_repo_name: AnatoliyProjects/variadic

max_forks_repo_name: AnatoliyProjects/variadic


text:
//--------------------------------------------------------------------------------------------------
// Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.  You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied.  See the License for the specific language governing permissions and limitations
// under the License.
//
//
// Tree node definitions for INSERT INTO ... JSON clause.
//--------------------------------------------------------------------------------------------------
#include "yb/yql/cql/ql/ptree/pt_insert_json_clause.h"

#include <boost/optional.hpp>

#include "yb/common/ql_type.h"
#include "yb/yql/cql/ql/ptree/pt_expr.h"
#include "yb/yql/cql/ql/ptree/yb_location.h"

namespace yb {
namespace ql {

PTInsertJsonClause::PTInsertJsonClause(MemoryContext* memctx,
                                       const YBLocation::SharedPtr& loc,
                                       const PTExpr::SharedPtr& json_expr,
                                       bool default_null)
    : PTCollection(memctx, loc),
      default_null_(default_null),
      json_expr_(json_expr),
      json_string_(""),
      json_document_(boost::none) {}

PTInsertJsonClause::~PTInsertJsonClause() = default;

Status PTInsertJsonClause::Analyze(SemContext* sem_context) {
  SemState sem_state(sem_context, QLType::Create(DataType::STRING), InternalType::kStringValue);
  sem_state.set_bindvar_name("json"); // To match Cassandra behaviour
  RETURN_NOT_OK(json_expr_->Analyze(sem_context));
  // Most of the work will be done in pre-exec phase
  return Status::OK();
}

void PTInsertJsonClause::PrintSemanticAnalysisResult(SemContext* sem_context) {
  VLOG(3) << "SEMANTIC ANALYSIS RESULT (" << *loc_ << "):\n" << "Not yet avail";
}

}  // namespace ql
}  // namespace yb

ext: cc

max_stars_repo_name: asad-awadia/yugabyte-db

max_issues_repo_name: asad-awadia/yugabyte-db

max_forks_repo_name: asad-awadia/yugabyte-db


text:
// The MIT License (MIT)

// Copyright (c) 2014 Arts Management Systems Ltd.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include "OmnisTools.he"
#include <sstream>
#include <iostream>
#include <map>
#include <boost/lexical_cast.hpp>

using boost::lexical_cast;
using boost::bad_lexical_cast;

#if ! defined(MARKUP_SIZEOFWCHAR)
  #if __SIZEOF_WCHAR_T__ == 4 || __WCHAR_MAX__ > 0x10000
    #define MARKUP_SIZEOFWCHAR 4
  #else
    #define MARKUP_SIZEOFWCHAR 2
  #endif
#endif

// Get a parameter from the thread data
qbool OmnisTools::getParamVar( tThreadData* pThreadData, qshort pParamNum, EXTfldval& pOutVar )
{
	return getParamVar(pThreadData->mEci, pParamNum, pOutVar);
}

// Get a parameter from the EXTCompInfo
qbool OmnisTools::getParamVar( EXTCompInfo* pEci, qshort pParamNum, EXTfldval& pOutVar )
{
	EXTParamInfo* param = ECOfindParamNum( pEci, pParamNum );
	if( !param )
		return qfalse;

	pOutVar.setFldVal(reinterpret_cast<qfldval>(param->mData));
	pOutVar.setReadOnly( qfalse );

	return qtrue;
}

qbool OmnisTools::getParamList( tThreadData* pThreadData, qshort pParamNum, EXTqlist& pOutList, qbool pCanBeRow) {

	EXTParamInfo* param = ECOfindParamNum( pThreadData->mEci, pParamNum );
	if ( !param )
		return qfalse;

	EXTfldval fval(reinterpret_cast<qfldval>(param->mData));
	if ( isList(fval,pCanBeRow) != qtrue)
		return qfalse;

	fval.getList(&pOutList,qfalse);

	return qtrue;
}

qbool OmnisTools::isList( EXTfldval& pFVal, qbool pCanBeRow ) {
	ffttype fft; pFVal.getType(fft);
	return ( (fft == fftList || (pCanBeRow && fft == fftRow)) ? qtrue : qfalse );
}

qbool OmnisTools::getParamBool( tThreadData* pThreadData, qshort pParamNum, qbool& pOutBool ) {
	EXTParamInfo* param = ECOfindParamNum( pThreadData->mEci, pParamNum );
	if ( !param )
		return qfalse;

	EXTfldval fval(reinterpret_cast<qfldval>(param->mData));

	ffttype fft; fval.getType(fft);
	if ( fft != fftInteger && fft != fftBoolean && fft != fftConstant )
		return qfalse;

	qlong x = fval.getLong();
	if ( x != 0 && x != 1 )
		return qfalse;

	pOutBool = qbool(x != 0);
	return qtrue;
}

qbool OmnisTools::getParamShort( tThreadData* pThreadData, qshort pParamNum, qshort& pOutShort ) {

	qlong longVal;
	if( getParamLong(pThreadData, pParamNum, longVal) != qtrue )
		return qfalse;

	if (longVal < 0 || longVal > 255)
		return qfalse;

	pOutShort = static_cast<qshort>(longVal);
	return qtrue;
}

qbool OmnisTools::getParamLong( tThreadData* pThreadData, qshort pParamNum, qlong& pOutInteger ) {
	EXTParamInfo* param = ECOfindParamNum( pThreadData->mEci, pParamNum );
	if ( !param )
		return qfalse;

	EXTfldval fval(reinterpret_cast<qfldval>(param->mData));

	ffttype fft; fval.getType(fft);
	if ( fft == fftCharacter )
	{
		strxxx& s_num = fval.getChar();
		if ( stringToQlong( s_num, pOutInteger ) )
			return qtrue;
	}
	else if ( fft == fftInteger || fft == fftBoolean || fft == fftConstant || fft == fftNumber )
	{
		pOutInteger = fval.getLong();
		return qtrue;
	}

	return qfalse;
}

// Convenience method to return the type of an EXTfldval
OmnisTools::FieldValType OmnisTools::getType( EXTfldval& fVal ) {

	OmnisTools::FieldValType retType;
	fVal.getType(retType.valType, &retType.valSubType);

	return retType;
}

// Get a qbool from a C++ boolean
qbool OmnisTools::getQBoolFromBool(bool b) {
	if (b == true) {
		return qtrue;
	} else if (b == false) {
		return qfalse;
	} else {
		return 0;
	}
}

// Get a C++ boolean from a qbool
bool OmnisTools::getBoolFromQBool(qbool qb) {
	if (qb == qtrue) {
		return true;
	} else if (qb == qfalse) {
		return false;
	} else {
		return NULL;
	}
}

// Get a std::wstring from an EXTfldval object
std::wstring OmnisTools::getWStringFromEXTFldVal(EXTfldval& fVal) {
	std::wstring retString;

	// Get a qchar* string
	qlong maxLength = fVal.getBinLen()+1; // Use binary length as approximation of maximum size
	qlong length = 0, stringLength = 0;
	qchar* omnisString = new qchar[maxLength];
	fVal.getChar(maxLength, omnisString, length);

	wchar_t* cString;
#if MARKUP_SIZEOFWCHAR == 2
	// For 2-Byte UTF16 wchar_t* (Typically Windows)
	// Convert from UTF8 to UTF16 and set new stringLength

	// Translate qchar* string into UTF8 binary
	qbyte* utf8data = reinterpret_cast<qbyte*>(omnisString);
	stringLength = CHRunicode::charToUtf8(omnisString, length, utf8data);

	// Translate UTF8 to UTF16
	CHRconvToUtf16 utf16conv(utf8data, stringLength);
	UChar* utf16data = utf16conv.dataPtr();
	stringLength = utf16conv.len();

	// Translate UTF16 binary into char* string
	cString = reinterpret_cast<wchar_t*>(utf16data);
#else
	// For 4-Byte UTF32 wchar_t* (Typically Mac and Linux)
	// Convert from UTF8 to UTF32 and set new stringLength
	stringLength = length;
	CHRconvToUtf32FromChar utf32conv(omnisString, stringLength, qfalse);
	U32Char* utf32data = utf32conv.dataPtr();
	stringLength = utf32conv.len();

	// Translate UTF16 binary into char* string
	cString = reinterpret_cast<wchar_t*>(utf32data);
#endif

	// Create standard string
	retString = std::wstring(cString,stringLength);

	// Clean-up
	delete [] omnisString;

	return retString;
}

// Set an existing EXTfldval object from a std::wstring
void OmnisTools::getEXTFldValFromWString(EXTfldval& fVal, const std::wstring readString) {
	qlong length;
	qchar* omnisString = getQCharFromWString(readString, length);

	fVal.setChar(omnisString, length); // Set value of character field, but exclude the last character since it will be the null terminator from the C String

	// Clean-up
	delete [] omnisString;
}

// Set an existing EXTfldval object from a std::wstring
void OmnisTools::getEXTFldValFromWChar(EXTfldval& fVal, const wchar_t* readChar) {
    std::wstring readString;
    if (readChar == 0)
        readString = L"";
    else
        readString = readChar;

    getEXTFldValFromWString(fVal, readString);
}

// Get a dynamically allocated qchar* array from a std::wstring
qchar* OmnisTools::getQCharFromWString(const std::wstring readString, qlong &retLength) {
	qlong length = readString.size();

	// Cast-away constness of c_str() pointer
	wchar_t* cString = const_cast<wchar_t*>(readString.c_str());

	qchar* omnisString;

#if MARKUP_SIZEOFWCHAR == 2
	// For 2-Byte UTF16 wchar_t* (Typically Windows)
	// Feed into raw byte data
	UChar* utf16data = reinterpret_cast<UChar*> (cString);

	// Convert to UTF-8
	CHRconvFromUtf16 utf16conv(utf16data, length);
	length = utf16conv.len();
	qbyte* utf8data = utf16conv.dataPtr();

	// Allocate new qchar* string
	omnisString = new qchar[length];

	// Convert to Omnis Character field
	retLength = CHRunicode::utf8ToChar(utf8data, length, omnisString);  // Convert characters into Omnis Char Field
#else
	// For 4-Byte UTF32 wchar_t* (Typically Mac and Linux)
	U32Char* utf32data = reinterpret_cast<U32Char*> (cString);

	// Convert to UTF-8
	CHRconvFromUtf32ToChar utf32conv(utf32data, length, qfalse);
	retLength = length = utf32conv.len();

	omnisString = new qchar[length];
	OMstrcpy(omnisString, utf32conv.dataPtr()); // Copy string so it lives past the end of this function
#endif

	return omnisString;
}

// Get a std::string from an EXTfldval object
std::string OmnisTools::getStringFromEXTFldVal(EXTfldval& fVal) {
	std::string retString;

	// Get a qchar* string
	qlong maxLength = fVal.getBinLen()+1; // Use binary length as approximation of maximum size
	qlong length = 0, stringLength = 0;
	qchar* omnisString = new qchar[maxLength];
	fVal.getChar(maxLength, omnisString, length);

	// Translate qchar* string into UTF8 binary
	qbyte* utf8data = reinterpret_cast<qbyte*>(omnisString);
	stringLength = CHRunicode::charToUtf8(omnisString, length, utf8data);

	// Translate UTF8 binary into char* string
	char* cString = reinterpret_cast<char*> (utf8data);

	// Create standard string
	retString = std::string(cString,stringLength);

	// Clean-up
	delete [] omnisString;

	return retString;
}

// Set an existing EXTfldval object from a std::string
void OmnisTools::getEXTFldValFromString(EXTfldval& fVal, const std::string readString) {
	qlong length;
	qchar* omnisString = getQCharFromString(readString, length);

	fVal.setChar(omnisString, length); // Set value of character field, but exclude the last character since it will be the null terminator from the C String

	// Clean-up
	delete [] omnisString;
}

// Set an existing EXTfldval object from a std::wstring
void OmnisTools::getEXTFldValFromChar(EXTfldval& fVal, const char* readChar) {
    std::string readString;
    if (readChar == 0)
        readString = "";
    else
        readString = readChar;

    getEXTFldValFromString(fVal, readString);
}

// Get a dynamically allocated qchar* array from a std::string
qchar* OmnisTools::getQCharFromString(const std::string readString, qlong &retLength) {
	qlong length = readString.size();

	// Cast-away constness of c_str() pointer
	char* cString = const_cast<char*>(readString.c_str());

	// Feed into raw byte data
	qbyte* utf8data = reinterpret_cast<qbyte*> (cString);

	// Allocate new qchar* string
	qchar* omnisString = new qchar[length];

	// Convert to Omnis Character field
	retLength = CHRunicode::utf8ToChar(utf8data, length, omnisString);  // Convert characters into Omnis Char Field

	return omnisString;
}

// Get a str15 object for a character constant (No string if it doesn't correspond to the conditions)
str15 OmnisTools::initStr15(const char* in){
    str15 theString;
    qshort length = strlen(in);
    if (length > 0 && length <= 15) {
        theString.setUtf8((qbyte*) in, strlen(in));
    }

    return theString;
}

// Get a str31 object for a character constant (No string if it doesn't correspond to the conditions)
str31 OmnisTools::initStr31(const char* in){
    str31 theString;
    qshort length = strlen(in);
    if (length > 0 && length <= 31) {
        theString.setUtf8((qbyte*) in, strlen(in));
    }

    return theString;
}

// Get a str80 object for a character constant (No string if it doesn't correspond to the conditions)
str80 OmnisTools::initStr80(const char* in){
    str80 theString;
    qshort length = strlen(in);
    if (length > 0 && length <= 80) {
        theString.setUtf8((qbyte*) in, strlen(in));
    }

    return theString;
}

// Get a str255 object for a character constant (No string if it doesn't correspond to the conditions)
str255 OmnisTools::initStr255(const char* in) {
    str255 theString;
    qshort length = strlen(in);
    if (length > 0 && length <= 255) {
        theString.setUtf8((qbyte*) in, strlen(in));
    }

    return theString;
}

// Return a C++ bool from an EXTfldval
bool OmnisTools::getBoolFromEXTFldVal(EXTfldval& fVal) {
	qshort omnBool;
	omnBool = fVal.getBool();
	switch (omnBool) {
		case 2:
			return true;
		case 1:
			return false;
		default:
			return false;
	}
}

// Get an EXTfldval for a C++ bool
void OmnisTools::getEXTFldValFromBool(EXTfldval& fVal, bool b) {
	qshort omBool;
	if (b==true)
        omBool = 2;
	else if (b==false)
        omBool = 1;

	fVal.setBool(omBool);
}

// Return a C++ int from an EXTfldval
int OmnisTools::getIntFromEXTFldVal(EXTfldval& fVal) {
	qlong omnInt = fVal.getLong();

	if (omnInt < INT_MIN || omnInt > INT_MAX) {
        omnInt = 0; // zero out any numbers that exceed
	}

	return static_cast<int>( omnInt );
}

// Get an EXTfldval for a C++ int
void OmnisTools::getEXTFldValFromInt(EXTfldval& fVal, int i) {
	fVal.setLong(static_cast<qlong>(i));
}

// Return a C++ long from an EXTfldval
long OmnisTools::getLongFromEXTFldVal(EXTfldval& fVal) {
	long retLong = static_cast<long>(fVal.getLong());
	return retLong;
}

// Get an EXTfldval for a C++ long
void OmnisTools::getEXTFldValFromLong(EXTfldval& fVal, long l) {
	fVal.setLong(static_cast<qlong>(l));
}

// Return a C++ long from an EXTfldval
double OmnisTools::getDoubleFromEXTFldVal(EXTfldval& fVal) {
	qreal omnReal; qshort dp;
	fVal.getNum(omnReal, dp);

	double retDbl = static_cast<double>(omnReal);

	return retDbl;
}

// Get an EXTfldval for a C++ double
void OmnisTools::getEXTFldValFromDouble(EXTfldval& fVal, double d) {
	qreal omnReal = static_cast<qreal>(d);
	qshort dp = dpFmask;
	fVal.setNum(omnReal, dp);
}

// Get an EXTfldval for a defined constant
void OmnisTools::getEXTFldValFromConstant(EXTfldval& fVal, qlong constID, qlong prefixID) {

	// Check for prefix
	str80 prefixRead;
	str255 constantValue;
	if (prefixID > 0) {
		// Read string from resource, and assign it to return parameter
		RESloadString(gInstLib,prefixID,prefixRead);
		constantValue.concat(prefixRead);
	}

	// Read complete resource string
	str255 resourceValue;
	RESloadString(gInstLib,constID,resourceValue);

	// Translate into std::wstring for easy substring
	EXTfldval convVar;
	convVar.setChar(resourceValue, dpDefault);
	std::wstring resourceString = getWStringFromEXTFldVal(convVar);

	// Get substring between tilde (sometimes used for categories) and first colon.
	int tildePos = resourceString.find(L"~") + 1;
	int colonPos = resourceString.find(L":");

	std::wstring constantString = resourceString.substr(tildePos,colonPos-tildePos);
	getEXTFldValFromWString(convVar, constantString);

	// Add constant to EXTfldval
	constantValue.concat(convVar.getChar());
	fVal.setConstant(constantValue);
}

// Get an integer for an EXTfldval where the EXTfldval contains a constant
static std::map<std::wstring,int> constCache;
int OmnisTools::getIntFromEXTFldVal(EXTfldval& fVal, qlong firstID, qlong lastID) {

	if (getType(fVal).valType == fftInteger) {
		return getIntFromEXTFldVal(fVal);
	} else if (getType(fVal).valType == fftConstant) {
		return getIntFromEXTFldVal(fVal);
	}

	int retNum = -1;
	// Get string that needs to be matched
	std::wstring matchString = getWStringFromEXTFldVal(fVal);

	// Get map iterator for searching
	std::map<std::wstring,int>::iterator it;
	it = constCache.find(matchString);
	if (it != constCache.end()) {
		retNum = it->second;
	} else {
		// Unable to find match, must loop constants in range and look for it
		int tildePos, colonPos, numPos, constNum;
		EXTfldval convVar;
		str255 resourceValue;
		std::wstring resourceMatch, resourceString;
		std::wstring numString = L"";

		for( int i = firstID; i <= lastID; ++i) {
			// Load resource and put into std::wstring for easy substr
			RESloadString(gInstLib,i,resourceValue);
			convVar.setChar(resourceValue, dpDefault);
			resourceString = getWStringFromEXTFldVal(convVar);
			tildePos = resourceString.find(L"~") + 1;
			colonPos = resourceString.find(L":");
			if (colonPos != -1) { // All constants should have colons.  If it doesn't then don't interpret the line
				resourceMatch = resourceString.substr(tildePos, colonPos-tildePos);

				// While looping add items to the const cache
				numPos = colonPos + 1;
				numString.clear();
				while (resourceString[numPos] != L':' && numPos < static_cast<int>(resourceString.length())) {
					numString += resourceString[numPos++];
				}
				try {
					constNum = lexical_cast<int>(numString);
				}
				catch(bad_lexical_cast &) {
					constNum = -1;
				}

				constCache[resourceMatch] = constNum;  // Add constant to cache
			}
		}

		// Locate constant now that all the constants have been cached
		it = constCache.find(matchString);
		if (it != constCache.end()) {
			retNum = it->second;
		}
	}
	return retNum;
}

// Get an ISO 8601 Formatted Date String from EXTFldVal
std::string OmnisTools::getISO8601DateStringFromEXTFldVal(EXTfldval& fVal) {
	datestamptype theDate;
	std::string retString;
	std::stringstream sin;

	fVal.getDate(theDate, dpFdtimeC);
	FieldValType theType = getType(fVal);

	if (theType.valType != fftDate)
		return "";

	// Set date part of string
    if (theDate.mDateOk == qtrue
        && !(theType.valSubType == dpFdtime1900
             || theType.valSubType == dpFdtime1980
             || theType.valSubType == dpFdtime2000
             || theType.valSubType == dpFdtimeC
             || theType.valSubType == dpFtime))
    {
        sin << int(theDate.mYear);
        if (theDate.mMonth < 10) {
            sin << "-0" << int(theDate.mMonth);
        } else {
            sin << "-" << int(theDate.mMonth);
        }
        if (theDate.mDay < 10) {
            sin << "-0" << int(theDate.mDay);
        } else {
            sin << "-" << int(theDate.mDay);
        }
	}

	// Set time part of string
    if (theDate.mTimeOk == qtrue
        && !(theType.valSubType == dpFdate1900
             || theType.valSubType == dpFdate1900
             || theType.valSubType == dpFdate1980
             || theType.valSubType == dpFdate2000
             || theType.valSubType == dpFdtime1900
             || theType.valSubType == dpFdtime1980
             || theType.valSubType == dpFdtime2000
             || theType.valSubType == dpFdtimeC))
    {
        sin << "T";
        if (theDate.mHour < 10) {
            sin << "0" << int(theDate.mHour);
        } else {
            sin << int(theDate.mHour);
        }
        if (theDate.mMin < 10) {
            sin << ":0" << int(theDate.mMin);
        } else {
            sin << ":" << int(theDate.mMin);
        }
        if (theDate.mSecOk) {
            if (theDate.mSec < 10) {
                sin << ":0" << int(theDate.mSec);
            } else {
                sin << ":" << int(theDate.mSec);
            }
        }
        // NOTE: Even though Omnis contains hundredths data, it is not part of
        //       the ISO8601 format
    }

    // Place string into return value
    retString = sin.str();

	return retString;
}

qbool OmnisTools::ensurePosixPath(EXTfldval& pathVal) {
#ifdef ismac
	str255 posixCheck, posixPath;
	qshort def = dpFcharacter;
	posixCheck = pathVal.getChar().cString();
	qlong err;
	std::wstring path = getWStringFromEXTFldVal(pathVal);

	if (path[0] != L'/') {
		err = ECOconvertHFSToPosix(posixCheck, posixPath);
		if (err != 0) {
			return qfalse;
		}
		pathVal.setChar(posixPath, def);
	}
#endif

	return qtrue;
}

max_stars_repo_name: artsman/OmnisXL

max_issues_repo_name: artsman/OmnisXL

max_forks_repo_name: artsman/OmnisXL


text:
#ifndef BLUB_LIST_HPP
#define BLUB_LIST_HPP

#include "blub/core/globals.hpp"

#include <boost/container/list.hpp>

namespace blub
{

template <class T>
class list : public boost::container::list<T>
{
public:
    typedef boost::container::list<T> t_base;

    list<T>() : boost::container::list<T>() {;}
    list<T>(const uint32 &num) : boost::container::list<T>() {this->reserve(num);}
    list<T>(boost::container::list<T> lst) : boost::container::list<T>(lst) {;}

    T& at(const uint32& ind)
    {
        BASSERT(ind < t_base::size());
        typename t_base::iterator it(t_base::begin());
        for (uint32 index = 0; index < ind; ++index)
        {
            ++it;
        }
        return *it;
    }

    const T& at(const uint32& ind) const
    {
        BASSERT(ind < t_base::size());
        typename t_base::const_iterator it(t_base::cbegin());
        for (uint32 index = 0; index < ind; ++index)
        {
            ++it;
        }
        return *it;
    }

    void reserve(uint32 size)
    {
        if (t_base::size() > size)
        {
            size = t_base::size();
        }
        t_base::resize(size);
    }

    bool isEmpty(void) const
    {
        return t_base::empty();
    }

    void insertAt(const uint32& ind, const T& toInsert)
    {
        BASSERT(ind < t_base::size());
        t_base::insert(t_base::cbegin()+ind, toInsert);
    }

    void removeAt(const uint32& ind)
    {
        BASSERT(ind < t_base::size());
        typename t_base::const_iterator it(t_base::cbegin());
        for (uint32 index = 0; index < ind; ++index)
        {
            ++it;
        }
        t_base::erase(it);
    }

    int32 indexOf(const T& toFind)
    {
        typename t_base::const_iterator it(t_base::cbegin());
        for (uint32 index = 0; index < t_base::size(); ++index)
        {
            if (*it == toFind)
            {
                return index;
            }
            ++it;
        }
        return -1;
    }

    /*
    T takeAt(uint32 ind)
    {
        T result = *(this->begin()+ind);
        removeAt(ind);
        return result;
    }

    T takeFirst()
    {
        T result = *this->begin();
        removeAt(0);
        return result;
    }*/

    bool push_back_distinct(const T & ins)
    {
        if (t_base::indexOf(ins) == -1)
        {
            t_base::push_back(ins);
            return true;
        }
        else
            return false;
    }
};

}

#endif // BLUB_LIST_HPP


text: #include <boost/icl/type_traits/rep_type_of.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

**/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_X86_SSE2_TAGS_HPP_INCLUDED
#define BOOST_SIMD_ARCH_X86_SSE2_TAGS_HPP_INCLUDED

#include <boost/simd/arch/x86/sse1/tags.hpp>
#include <boost/simd/detail/support.hpp>
#include <boost/simd/detail/cpuid.hpp>

namespace boost { namespace simd
{
  /*!
    @ingroup group-hierarchy
    @brief Intel SSE2 SIMD architecture hierarchy tag

    This tag represent architectures implementing the Intel SSE2 SIMD instructions set.
  **/
  struct sse2_ : sse1_
  {
    using parent = sse1_ ;
  };

  namespace detail
  {
    template<> struct support<::boost::simd::sse2_>
    {
      support()
      {
        #if BOOST_ARCH_X86
        support_ =  detect_feature(26, 0x00000001, detail::edx);
        #else
        support_ =  false;
        #endif
      }

      inline bool is_supported() const { return support_; }

      private:
      bool support_;
    };
  }

  /*!
    @ingroup  group-api
    Global object for accessing SSE2 support informations
  **/
  static detail::support<sse2_> const sse2 = {};

} }

#endif

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
//
// Copyright (c) 2019-2021 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include "boost/mysql/connection.hpp"
#include "boost/mysql/connection_params.hpp"
#include "integration_test_common.hpp"
#include "network_functions.hpp"
#include "test_common.hpp"
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/verify_mode.hpp>
#include <boost/asio/ssl/host_name_verification.hpp>
#include <boost/test/unit_test_suite.hpp>

// Tests containing with label 'sha256' require SHA256 functionality.
// This is used by the build script to exclude these tests on databases
// that do not support this functionality

using namespace boost::mysql::test;

using boost::mysql::socket_connection;
using boost::mysql::ssl_mode;
using boost::mysql::errc;
using boost::mysql::error_code;
using boost::mysql::tcp_connection;
using boost::mysql::connection_params;

BOOST_AUTO_TEST_SUITE(test_handshake)

template <class Stream>
network_result<no_result> do_handshake(
    socket_connection<Stream>& conn,
    connection_params params,
    network_functions<Stream>* net,
    ssl_mode ssl
)
{
    params.set_ssl(ssl);
    return net->handshake(conn, params);
}

template <class Stream>
void do_handshake_ok(
    socket_connection<Stream>& conn,
    connection_params params,
    network_functions<Stream>* net,
    ssl_mode ssl
)
{
    auto result = do_handshake(conn, params, net, ssl);
    result.validate_no_error();
    validate_ssl(conn, ssl);
}

// Handshake tests not depending on whether we use SSL or not
template <class Stream>
struct handshake_fixture : network_fixture<Stream>
{
    handshake_fixture()
    {
        this->physical_connect();
    }
};

// mysql_native_password
BOOST_AUTO_TEST_SUITE(mysql_native_password)

BOOST_MYSQL_NETWORK_TEST(regular_user, handshake_fixture, network_ssl_gen)
{
    this->set_credentials("mysqlnp_user", "mysqlnp_password");
    do_handshake_ok(this->conn, this->params, sample.net, sample.ssl);
}

BOOST_MYSQL_NETWORK_TEST(empty_password, handshake_fixture, network_ssl_gen)
{
    this->set_credentials("mysqlnp_empty_password_user", "");
    do_handshake_ok(this->conn, this->params, sample.net, sample.ssl);
}

BOOST_MYSQL_NETWORK_TEST(bad_password, handshake_fixture, network_ssl_gen)
{
    this->set_credentials("mysqlnp_user", "bad_password");
    auto result = do_handshake(this->conn, this->params, sample.net, sample.ssl);
    result.validate_error(errc::access_denied_error, {"access denied", "mysqlnp_user"});
}

BOOST_AUTO_TEST_SUITE_END() // mysql_native_password

// caching_sha2_password
BOOST_TEST_DECORATOR(*boost::unit_test::label("sha256"))
BOOST_AUTO_TEST_SUITE(caching_sha2_password)

template <class Stream>
struct caching_sha2_fixture : handshake_fixture<Stream>
{
    void load_sha256_cache(boost::string_view user, boost::string_view password)
    {
        tcp_connection conn (this->ctx);
        conn.connect(
            get_endpoint<boost::asio::ip::tcp::socket>(endpoint_kind::localhost),
            connection_params(user, password)
        );
        conn.close();
    }

    void clear_sha256_cache()
    {
        tcp_connection conn (this->ctx);
        conn.connect(
            get_endpoint<boost::asio::ip::tcp::socket>(endpoint_kind::localhost),
            connection_params("root", "")
        );
        conn.query("FLUSH PRIVILEGES");
        conn.close();
    }
};

BOOST_MYSQL_NETWORK_TEST(ssl_on_cache_hit, caching_sha2_fixture, network_gen)
{
    this->set_credentials("csha2p_user", "csha2p_password");
    this->load_sha256_cache("csha2p_user", "csha2p_password");
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::require);
}

BOOST_MYSQL_NETWORK_TEST(ssl_off_cache_hit, caching_sha2_fixture, network_gen)
{
    // As we are sending password hashed, it is OK to not have SSL for this
    this->set_credentials("csha2p_user", "csha2p_password");
    this->load_sha256_cache("csha2p_user", "csha2p_password");
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::disable);
}

BOOST_MYSQL_NETWORK_TEST(ssl_on_cache_miss, caching_sha2_fixture, network_gen)
{
    this->set_credentials("csha2p_user", "csha2p_password");
    this->clear_sha256_cache();
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::require);
}

BOOST_MYSQL_NETWORK_TEST(ssl_off_cache_miss, caching_sha2_fixture, network_gen)
{
    // A cache miss would force us send a plaintext password over
    // a non-TLS connection, so we fail
    this->set_credentials("csha2p_user", "csha2p_password");
    this->clear_sha256_cache();
    auto result = do_handshake(this->conn, this->params, sample.net, ssl_mode::disable);
    result.validate_error(errc::auth_plugin_requires_ssl, {});
}

BOOST_MYSQL_NETWORK_TEST(empty_password_ssl_on_cache_hit, caching_sha2_fixture, network_gen)
{
    this->set_credentials("csha2p_empty_password_user", "");
    this->load_sha256_cache("csha2p_empty_password_user", "");
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::require);
}

BOOST_MYSQL_NETWORK_TEST(empty_password_ssl_off_cache_hit, caching_sha2_fixture, network_gen)
{
    // Empty passwords are allowed over non-TLS connections
    this->set_credentials("csha2p_empty_password_user", "");
    this->load_sha256_cache("csha2p_empty_password_user", "");
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::disable);
}

BOOST_MYSQL_NETWORK_TEST(empty_password_ssl_on_cache_miss, caching_sha2_fixture, network_gen)
{
    this->set_credentials("csha2p_empty_password_user", "");
    this->clear_sha256_cache();
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::require);
}

BOOST_MYSQL_NETWORK_TEST(empty_password_ssl_off_cache_miss, caching_sha2_fixture, network_gen)
{
    // Empty passwords are allowed over non-TLS connections
    this->set_credentials("csha2p_empty_password_user", "");
    this->clear_sha256_cache();
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::disable);
}

BOOST_MYSQL_NETWORK_TEST(bad_password_ssl_on_cache_hit, caching_sha2_fixture, network_gen)
{
    // Note: test over non-TLS would return "ssl required"
    this->set_credentials("csha2p_user", "bad_password");
    this->load_sha256_cache("csha2p_user", "csha2p_password");
    auto result = do_handshake(this->conn, this->params, sample.net, ssl_mode::require);
    result.validate_error(errc::access_denied_error, {"access denied", "csha2p_user"});
}

BOOST_MYSQL_NETWORK_TEST(bad_password_ssl_on_cache_miss, caching_sha2_fixture, network_gen)
{
    // Note: test over non-TLS would return "ssl required"
    this->set_credentials("csha2p_user", "bad_password");
    this->clear_sha256_cache();
    auto result = do_handshake(this->conn, this->params, sample.net, ssl_mode::require);
    result.validate_error(errc::access_denied_error, {"access denied", "csha2p_user"});
}

BOOST_AUTO_TEST_SUITE_END() // caching_sha2_password

// Externally-provided SSL context tests
BOOST_AUTO_TEST_SUITE(external_ssl_context)

template <class Stream>
struct external_ssl_context_fixture : public network_fixture<Stream>
{
    external_ssl_context_fixture(): network_fixture<Stream>(use_external_ctx) {}
};

// The CA file that signed the server's certificate
constexpr const char CA_PEM [] = R"%(-----BEGIN CERTIFICATE-----
MIIDZzCCAk+gAwIBAgIUWznm2UoxXw3j7HCcp9PpiayTvFQwDQYJKoZIhvcNAQEL
BQAwQjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxDjAMBgNVBAoM
BW15c3FsMQ4wDAYDVQQDDAVteXNxbDAgFw0yMDA0MDQxNDMwMjNaGA8zMDE5MDgw
NjE0MzAyM1owQjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxDjAM
BgNVBAoMBW15c3FsMQ4wDAYDVQQDDAVteXNxbDCCASIwDQYJKoZIhvcNAQEBBQAD
ggEPADCCAQoCggEBAN0WYdvsDb+a0TxOGPejcwZT0zvTrf921mmDUlrLN1Z0hJ/S
ydgQCSD7Q+6za4lTFZCXcvs52xvvS2gfC0yXyYLCT/jA4RQRxuF+/+w1gDWEbGk0
KzEpsBuKrEIvEaVdoS78SxInnW/aegshdrRRocp4JQ6KHsZgkLTxSwPfYSUmMUo0
cRO0Q/ak3VK8NP13A6ZFvZjrBxjS3cSw9HqilgADcyj1D4EokvfI1C9LrgwgLlZC
XVkjjBqqoMXGGlnXOEK+pm8bU68HM/QvMBkb1Amo8pioNaaYgqJUCP0Ch0iu1nUU
HtsWt6emXv0jANgIW0oga7xcT4MDGN/M+IRWLTECAwEAAaNTMFEwHQYDVR0OBBYE
FNxhaGwf5ePPhzK7yOAKD3VF6wm2MB8GA1UdIwQYMBaAFNxhaGwf5ePPhzK7yOAK
D3VF6wm2MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAAoeJCAX
IDCFoAaZoQ1niI6Ac/cds8G8It0UCcFGSg+HrZ0YujJxWIruRCUG60Q2OAbEvn0+
uRpTm+4tV1Wt92WFeuRyqkomozx0g4CyfsxGX/x8mLhKPFK/7K9iTXM4/t+xQC4f
J+iRmPVsMKQ8YsHYiWVhlOMH9XJQiqERCB2kOKJCH6xkaF2k0GbM2sGgbS7Z6lrd
fsFTOIVx0VxLVsZnWX3byE9ghnDR5jn18u30Cpb/R/ShxNUGIHqRa4DkM5la6uZX
W1fpSW11JBSUv4WnOO0C2rlIu7UJWOROqZZ0OsybPRGGwagcyff2qVRuI2XFvAMk
OzBrmpfHEhF6NDU=
-----END CERTIFICATE-----
)%";

BOOST_MYSQL_NETWORK_TEST(certificate_valid, external_ssl_context_fixture, network_gen)
{
    this->external_ctx.set_verify_mode(boost::asio::ssl::verify_peer);
    this->external_ctx.add_certificate_authority(boost::asio::buffer(CA_PEM));
    this->physical_connect();
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::require);
}

BOOST_MYSQL_NETWORK_TEST(certificate_invalid, external_ssl_context_fixture, network_gen)
{
    this->external_ctx.set_verify_mode(boost::asio::ssl::verify_peer);
    this->physical_connect();
    auto result = do_handshake(this->conn, this->params, sample.net, ssl_mode::require);
    BOOST_TEST(result.err.message() == "certificate verify failed");
}

BOOST_MYSQL_NETWORK_TEST(custom_certificate_verification_failed, external_ssl_context_fixture, network_gen)
{
    this->external_ctx.set_verify_mode(boost::asio::ssl::verify_peer);
    this->external_ctx.add_certificate_authority(boost::asio::buffer(CA_PEM));
    this->external_ctx.set_verify_callback(boost::asio::ssl::host_name_verification("host.name"));
    this->physical_connect();
    auto result = do_handshake(this->conn, this->params, sample.net, ssl_mode::require);
    BOOST_TEST(result.err.message() == "certificate verify failed");
}

BOOST_MYSQL_NETWORK_TEST(custom_certificate_verification_ok, external_ssl_context_fixture, network_gen)
{
    this->external_ctx.set_verify_mode(boost::asio::ssl::verify_peer);
    this->external_ctx.add_certificate_authority(boost::asio::buffer(CA_PEM));
    this->external_ctx.set_verify_callback(boost::asio::ssl::host_name_verification("mysql"));
    this->physical_connect();
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::require);
}

BOOST_MYSQL_NETWORK_TEST(ssl_disable, external_ssl_context_fixture, network_gen)
{
    this->external_ctx.set_verify_mode(boost::asio::ssl::verify_peer); // should have no effect
    this->physical_connect();
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::disable);
}

BOOST_AUTO_TEST_SUITE_END() // external_ssl_context

// Other handshake tests
BOOST_MYSQL_NETWORK_TEST(no_database, handshake_fixture, network_ssl_gen)
{
    this->params.set_database("");
    do_handshake_ok(this->conn, this->params, sample.net, sample.ssl);
}

BOOST_MYSQL_NETWORK_TEST(bad_database, handshake_fixture, network_ssl_gen)
{
    this->params.set_database("bad_database");
    auto result = do_handshake(this->conn, this->params, sample.net, sample.ssl);
    result.validate_error(errc::dbaccess_denied_error, {"database", "bad_database"});
}

BOOST_TEST_DECORATOR(*boost::unit_test::label("sha256"))
BOOST_MYSQL_NETWORK_TEST(unknown_auth_plugin, handshake_fixture, network_ssl_gen)
{
    // Note: sha256_password is not supported, so it's an unknown plugin to us
    this->set_credentials("sha2p_user", "sha2p_password");
    auto result = do_handshake(this->conn, this->params, sample.net, sample.ssl);
    result.validate_error(errc::unknown_auth_plugin, {});
}

BOOST_MYSQL_NETWORK_TEST(bad_user, handshake_fixture, network_gen)
{
    // unreliable without SSL. If the default plugin requires SSL
    // (like SHA256), this would fail with 'ssl required'
    this->set_credentials("non_existing_user", "bad_password");
    auto result = do_handshake(this->conn, this->params, sample.net, ssl_mode::require);
    result.validate_any_error(); // may be access denied or unknown auth plugin
}

BOOST_MYSQL_NETWORK_TEST(ssl_enable, handshake_fixture, network_gen)
{
    // In all our CI systems, our servers support SSL, so
    // ssl_mode::enable will do the same as ssl_mode::require.
    // We test for this fact.
    do_handshake_ok(this->conn, this->params, sample.net, ssl_mode::enable);
}

BOOST_AUTO_TEST_SUITE_END() // test_handshake

max_stars_repo_name: sehe/mysql

max_issues_repo_name: sehe/mysql

max_forks_repo_name: sehe/mysql


text:
#include <algorithm>
#include <boost/optional.hpp>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)
#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)
#define EACH(e, a) for(auto&& e : a)
#define ALL(a) std::begin(a), std::end(a)
#define RALL(a) std::rbegin(a), std::rend(a)
#define FILL(a, n) memset((a), n, sizeof(a))
#define FILLZ(a) FILL(a, 0)
#define INT(x) (static_cast<int>(x))
#define PRECISION(x) std::fixed << std::setprecision(x)

using namespace std;

using ll = long long;
using VI = std::vector<int>;
using VI2D = std::vector<vector<int>>;
using VLL = std::vector<long long>;
using VLL2D = std::vector<vector<long long>>;

constexpr int INF = 2e9;
constexpr double EPS = 1e-10;
constexpr double PI = acos(-1.0);

constexpr int dx[] = {-1, 0, 1, 0};
constexpr int dy[] = {0, -1, 0, 1};

template <typename T, std::size_t N>
struct make_vector_type {
	using type =
		typename std::vector<typename make_vector_type<T, (N - 1)>::type>;
};

template <typename T>
struct make_vector_type<T, 0> {
	using type = typename std::vector<T>;
};

template <typename T, size_t N>
auto make_vector_impl(const std::vector<std::size_t>& ls, T init_value) {
	if constexpr(N == 0) {
		return std::vector<T>(ls[N], init_value);
	} else {
		return typename make_vector_type<T, N>::type(
			ls[N], make_vector_impl<T, (N - 1)>(ls, init_value));
	}
}

template <typename T, std::size_t N>
auto make_vector(const std::size_t (&ls)[N], T init_value) {
	std::vector<std::size_t> dimensions(N);
	for(int i = 0; i < N; i++) {
		dimensions[N - i - 1] = ls[i];
	}
	return make_vector_impl<T, N - 1>(dimensions, init_value);
}

template <typename T>
std::vector<T> make_vector(std::size_t size, T init_value) {
	return std::vector<T>(size, init_value);
}

template <typename T>
constexpr int sign(T x) {
	return x < 0 ? -1 : x > 0 ? 1 : 0;
}

template <>
constexpr int sign(double x) {
	return x < -EPS ? -1 : x > EPS ? 1 : 0;
}

template <typename T, typename U>
constexpr void chmax(T& m, U x) {
	m = max<T>(m, x);
}

template <typename T, typename U>
constexpr void chmin(T& m, U x) {
	m = min<T>(m, x);
}

template <typename T>
constexpr T square(T x) {
	return x * x;
}

#ifndef ATCODER_FENWICKTREE_HPP
#define ATCODER_FENWICKTREE_HPP 1

#include <cassert>
#include <type_traits>
#include <vector>

namespace atcoder {

namespace internal {

#ifndef _MSC_VER
template <class T>
using is_signed_int128 =
	typename std::conditional<std::is_same<T, __int128_t>::value ||
								  std::is_same<T, __int128>::value,
							  std::true_type,
							  std::false_type>::type;

template <class T>
using is_unsigned_int128 =
	typename std::conditional<std::is_same<T, __uint128_t>::value ||
								  std::is_same<T, unsigned __int128>::value,
							  std::true_type,
							  std::false_type>::type;

template <class T>
using make_unsigned_int128 =
	typename std::conditional<std::is_same<T, __int128_t>::value,
							  __uint128_t,
							  unsigned __int128>;

template <class T>
using is_integral = typename std::conditional<std::is_integral<T>::value ||
												  is_signed_int128<T>::value ||
												  is_unsigned_int128<T>::value,
											  std::true_type,
											  std::false_type>::type;

template <class T>
using is_signed_int = typename std::conditional<(is_integral<T>::value &&
												 std::is_signed<T>::value) ||
													is_signed_int128<T>::value,
												std::true_type,
												std::false_type>::type;

template <class T>
using is_unsigned_int =
	typename std::conditional<(is_integral<T>::value &&
							   std::is_unsigned<T>::value) ||
								  is_unsigned_int128<T>::value,
							  std::true_type,
							  std::false_type>::type;

template <class T>
using to_unsigned = typename std::conditional<
	is_signed_int128<T>::value,
	make_unsigned_int128<T>,
	typename std::conditional<std::is_signed<T>::value,
							  std::make_unsigned<T>,
							  std::common_type<T>>::type>::type;

#else

template <class T>
using is_integral = typename std::is_integral<T>;

template <class T>
using is_signed_int =
	typename std::conditional<is_integral<T>::value && std::is_signed<T>::value,
							  std::true_type,
							  std::false_type>::type;

template <class T>
using is_unsigned_int =
	typename std::conditional<is_integral<T>::value &&
								  std::is_unsigned<T>::value,
							  std::true_type,
							  std::false_type>::type;

template <class T>
using to_unsigned = typename std::conditional<is_signed_int<T>::value,
											  std::make_unsigned<T>,
											  std::common_type<T>>::type;

#endif

template <class T>
using is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;

template <class T>
using is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;

template <class T>
using to_unsigned_t = typename to_unsigned<T>::type;

} // namespace internal

// Reference: https://en.wikipedia.org/wiki/Fenwick_tree
template <class T>
struct fenwick_tree {
	using U = internal::to_unsigned_t<T>;

	public:
	fenwick_tree() : _n(0) {}
	fenwick_tree(int n) : _n(n), data(n) {}

	void add(int p, T x) {
		assert(0 <= p && p < _n);
		p++;
		while(p <= _n) {
			data[p - 1] += U(x);
			p += p & -p;
		}
	}

	T sum(int l, int r) {
		assert(0 <= l && l <= r && r <= _n);
		return sum(r) - sum(l);
	}

	private:
	int _n;
	std::vector<U> data;

	U sum(int r) {
		U s = 0;
		while(r > 0) {
			s += data[r - 1];
			r -= r & -r;
		}
		return s;
	}
};

} // namespace atcoder

#endif // ATCODER_FENWICKTREE_HPP

using namespace atcoder;
int main() {
	int n;
	cin >> n;
	VI a(n);
	EACH(e, a) { cin >> e; }

	auto fw = fenwick_tree<ll>(n + 1);
	ll inv_sum = 0;
	for(int i = n - 1; i >= 0; i--) {
		fw.add(a[i], 1);
		inv_sum += fw.sum(0, a[i]);
	}

	REP(i, n) {
		cout << inv_sum << endl;
		inv_sum -= a[i];
		inv_sum += n - a[i] - 1;
	}
	return 0;
}

max_stars_repo_name: arlechann/atcoder

max_issues_repo_name: arlechann/atcoder

max_forks_repo_name: arlechann/atcoder