<commit_before>#include <string>
#include <vector>
#include <iostream>

typedef std::vector<std::string> nomi_squadre_t;
typedef std::vector<unsigned int> punti_giornata_t;
typedef std::vector<punti_giornata_t> punti_giornate_t;

int trova_indice_squadra(nomi_squadre_t nomi_squadre, std::string nome_squadra)
{
  for (unsigned int i = 0; i < nomi_squadre.size(); i++) {
    if (nomi_squadre[i] == nome_squadra) {
      return i;
    }
  }

  return -1;
}

int trova_punti_squadra(unsigned int indice_squadra, punti_giornate_t punti_giornate)
{
  unsigned int punti = 0;
  unsigned int i;

  for (i = 0; i < punti_giornate.size(); i++) {
    punti += punti_giornate[i][indice_squadra];
  }

  return punti;
}

std::vector<unsigned int> trova_punti_squadre(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate)
{
  std::vector<unsigned int> punti_squadre;
  punti_squadre.resize(nomi_squadre.size(), 0);

  for (unsigned int i = 0; i < nomi_squadre.size(); i++) {
    punti_squadre[i] = trova_punti_squadra(i, punti_giornate);
  }

  return punti_squadre;
}

std::vector<unsigned int> trova_vincitori_giornata(unsigned int giornata, punti_giornate_t punti_giornate)
{
  unsigned int i;
  std::vector<unsigned int> vincitori;

  for (i = 0; i < punti_giornate[giornata - 1].size(); i++) {
    if (punti_giornate[giornata - 1][i] == 3) {
      vincitori.push_back(i);
    }
  }

  return vincitori;
}

unsigned int trova_vincitore_campionato(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate)
{
  unsigned int i, indice_vincitore, punti_vincitore = 0;

  std::vector<unsigned int> punti_squadre = trova_punti_squadre(nomi_squadre, punti_giornate);

  for (i = 0; i < punti_squadre.size(); i++) {
    if (punti_squadre[i] > punti_vincitore) {
      punti_vincitore = punti_squadre[i];
      indice_vincitore = i;
    }
  }

  return indice_vincitore;
}

void inizializzazione(nomi_squadre_t& nomi_squadre, punti_giornate_t& punti_giornate)
{
  unsigned int numero_giornate, numero_squadre;
  unsigned int i;

  std::cout << "Inserisci il numero di giornate: ";
  std::cin >> numero_giornate;

  std::cout << "Inserisci il numero di squadre: ";
  std::cin >> numero_squadre;

  nomi_squadre.resize(numero_squadre);
  punti_giornate.resize(numero_giornate);

  for (i = 0; i < punti_giornate.size(); i++) {
    punti_giornate[i].resize(numero_squadre);
  }
}

void caricamento(nomi_squadre_t& nomi_squadre, punti_giornate_t& punti_giornate)
{
  unsigned int i, j;

  for (i = 0; i < nomi_squadre.size(); i++) {
    std::cout << "Inserisci il nome della squadra " << i + 1 << ": ";
    std::cin >> nomi_squadre[i];
  }

  std::cout << std::endl;

  for (i = 0; i < punti_giornate.size(); i++) {
    for (j = 0; j < nomi_squadre.size(); j++) {
      do {
        std::cout << "Inserisci punti " << nomi_squadre[j] << " (giornata " << i + 1 << "): ";
        std::cin >> punti_giornate[i][j];
      } while (punti_giornate[i][j] != 0 && punti_giornate[i][j] != 1 && punti_giornate[i][j] != 3);
    }

    std::cout << std::endl;
  }
}

void mostra_vincitori_giornata(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate)
{
  unsigned int i;
  unsigned int giornata;
  std::vector<unsigned int> vincitori;

  do {
    std::cout << "Di quale giornata vuoi sapere i vincitori? ";
    std::cin >> giornata;
  } while (giornata < 1 || giornata > punti_giornate.size());

  std::cout << std::endl;

  vincitori = trova_vincitori_giornata(giornata, punti_giornate);

  for (i = 0; i < vincitori.size(); i++) {
    std::cout << "La squadra " << nomi_squadre[vincitori[i]] << " ha vinto la giornata " << giornata << "." << std::endl;
  }
}

void mostra_punti_squadra(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate)
{
  std::string nome_squadra;
  int indice_squadra;
  unsigned int punti;

  do {
    std::cout << "Di quale squadra vuoi conoscere i punti? ";
    std::cin >> nome_squadra;

    indice_squadra = trova_indice_squadra(nomi_squadre, nome_squadra);
  } while (indice_squadra == -1);

  std::cout << std::endl;

  punti = trova_punti_squadra(indice_squadra, punti_giornate);

  std::cout << "La squadra " << nome_squadra << " ha totalizzato " << punti << " punti." << std::endl;
}

void mostra_vincitore_campionato(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate)
{
  unsigned int indice_vincitore;

  indice_vincitore = trova_vincitore_campionato(nomi_squadre, punti_giornate);
  std::cout << "La squadra che ha vinto il campionato è " << nomi_squadre[indice_vincitore] << "." << std::endl;
}

int main()
{
  nomi_squadre_t nomi_squadre;
  punti_giornate_t punti_giornate;

  unsigned int scelta;

  inizializzazione(nomi_squadre, punti_giornate);
  std::cout << std::endl;

  caricamento(nomi_squadre, punti_giornate);

  do {
    std::cout << "1. Vincitori giornata" << std::endl;
    std::cout << "2. Punti squadra" << std::endl;
    std::cout << "3. Vincitore campionato" << std::endl;
    std::cout << "0. Uscita" << std::endl;

    std::cout << std::endl;

    std::cout << "Inserisci un'opzione: ";
    std::cin >> scelta;

    if (scelta != 0) {
      std::cout << std::endl;
    }

    switch (scelta) {
      case 1:
        mostra_vincitori_giornata(nomi_squadre, punti_giornate);
        break;

      case 2:
        mostra_punti_squadra(nomi_squadre, punti_giornate);
        break;

      case 3:
        mostra_vincitore_campionato(nomi_squadre, punti_giornate);
        break;

      case 0:
        break;

      default:
        std::cout << "Scelta non valida." << std::endl;
    }

    if (scelta != 0) {
      std::cout << std::endl;
    }
  } while (scelta != 0);

  return 0;
}
<commit_msg>Extract some request methods<commit_after>#include <string>
#include <vector>
#include <iostream>

typedef std::vector<std::string> nomi_squadre_t;
typedef std::vector<unsigned int> punti_giornata_t;
typedef std::vector<punti_giornata_t> punti_giornate_t;

int trova_indice_squadra(nomi_squadre_t nomi_squadre, std::string nome_squadra)
{
  for (unsigned int i = 0; i < nomi_squadre.size(); i++) {
    if (nomi_squadre[i] == nome_squadra) {
      return i;
    }
  }

  return -1;
}

int trova_punti_squadra(unsigned int indice_squadra, punti_giornate_t punti_giornate)
{
  unsigned int punti = 0;
  unsigned int i;

  for (i = 0; i < punti_giornate.size(); i++) {
    punti += punti_giornate[i][indice_squadra];
  }

  return punti;
}

std::vector<unsigned int> trova_punti_squadre(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate)
{
  std::vector<unsigned int> punti_squadre;
  punti_squadre.resize(nomi_squadre.size(), 0);

  for (unsigned int i = 0; i < nomi_squadre.size(); i++) {
    punti_squadre[i] = trova_punti_squadra(i, punti_giornate);
  }

  return punti_squadre;
}

std::vector<unsigned int> trova_vincitori_giornata(unsigned int giornata, punti_giornate_t punti_giornate)
{
  unsigned int i;
  std::vector<unsigned int> vincitori;

  for (i = 0; i < punti_giornate[giornata - 1].size(); i++) {
    if (punti_giornate[giornata - 1][i] == 3) {
      vincitori.push_back(i);
    }
  }

  return vincitori;
}

unsigned int trova_vincitore_campionato(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate)
{
  unsigned int i, indice_vincitore, punti_vincitore = 0;

  std::vector<unsigned int> punti_squadre = trova_punti_squadre(nomi_squadre, punti_giornate);

  for (i = 0; i < punti_squadre.size(); i++) {
    if (punti_squadre[i] > punti_vincitore) {
      punti_vincitore = punti_squadre[i];
      indice_vincitore = i;
    }
  }

  return indice_vincitore;
}

unsigned int chiedi_giornata(punti_giornate_t punti_giornate)
{
  unsigned int giornata;

  do {
    std::cout << "Di quale giornata vuoi sapere i vincitori? ";
    std::cin >> giornata;
  } while (giornata < 1 || giornata > punti_giornate.size());

  return giornata;
}

unsigned int chiedi_squadra(nomi_squadre_t nomi_squadre)
{
  int indice_squadra;
  std::string nome_squadra;

  do {
    std::cout << "Di quale squadra vuoi conoscere i punti? ";
    std::cin >> nome_squadra;

    indice_squadra = trova_indice_squadra(nomi_squadre, nome_squadra);
  } while (indice_squadra == -1);

  return indice_squadra;
}

void inizializzazione(nomi_squadre_t& nomi_squadre, punti_giornate_t& punti_giornate)
{
  unsigned int numero_giornate, numero_squadre;
  unsigned int i;

  std::cout << "Inserisci il numero di giornate: ";
  std::cin >> numero_giornate;

  std::cout << "Inserisci il numero di squadre: ";
  std::cin >> numero_squadre;

  nomi_squadre.resize(numero_squadre);
  punti_giornate.resize(numero_giornate);

  for (i = 0; i < punti_giornate.size(); i++) {
    punti_giornate[i].resize(numero_squadre);
  }
}

void caricamento(nomi_squadre_t& nomi_squadre, punti_giornate_t& punti_giornate)
{
  unsigned int i, j;

  for (i = 0; i < nomi_squadre.size(); i++) {
    std::cout << "Inserisci il nome della squadra " << i + 1 << ": ";
    std::cin >> nomi_squadre[i];
  }

  std::cout << std::endl;

  for (i = 0; i < punti_giornate.size(); i++) {
    for (j = 0; j < nomi_squadre.size(); j++) {
      do {
        std::cout << "Inserisci punti " << nomi_squadre[j] << " (giornata " << i + 1 << "): ";
        std::cin >> punti_giornate[i][j];
      } while (punti_giornate[i][j] != 0 && punti_giornate[i][j] != 1 && punti_giornate[i][j] != 3);
    }

    std::cout << std::endl;
  }
}

void mostra_vincitori_giornata(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate)
{
  unsigned int i;
  unsigned int giornata;
  std::vector<unsigned int> vincitori;

  giornata = chiedi_giornata(punti_giornate);
  std::cout << std::endl;

  vincitori = trova_vincitori_giornata(giornata, punti_giornate);

  for (i = 0; i < vincitori.size(); i++) {
    std::cout << "La squadra " << nomi_squadre[vincitori[i]] << " ha vinto la giornata " << giornata << "." << std::endl;
  }
}

void mostra_punti_squadra(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate)
{
  int indice_squadra;
  unsigned int punti;

  indice_squadra = chiedi_squadra(nomi_squadre);
  std::cout << std::endl;

  punti = trova_punti_squadra(indice_squadra, punti_giornate);

  std::cout << "La squadra " << nomi_squadre[indice_squadra] << " ha totalizzato " << punti << " punti." << std::endl;
}

void mostra_vincitore_campionato(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate)
{
  unsigned int indice_vincitore;

  indice_vincitore = trova_vincitore_campionato(nomi_squadre, punti_giornate);
  std::cout << "La squadra che ha vinto il campionato è " << nomi_squadre[indice_vincitore] << "." << std::endl;
}

int main()
{
  nomi_squadre_t nomi_squadre;
  punti_giornate_t punti_giornate;

  unsigned int scelta;

  inizializzazione(nomi_squadre, punti_giornate);
  std::cout << std::endl;

  caricamento(nomi_squadre, punti_giornate);

  do {
    std::cout << "1. Vincitori giornata" << std::endl;
    std::cout << "2. Punti squadra" << std::endl;
    std::cout << "3. Vincitore campionato" << std::endl;
    std::cout << "0. Uscita" << std::endl;

    std::cout << std::endl;

    std::cout << "Inserisci un'opzione: ";
    std::cin >> scelta;

    if (scelta != 0) {
      std::cout << std::endl;
    }

    switch (scelta) {
      case 1:
        mostra_vincitori_giornata(nomi_squadre, punti_giornate);
        break;

      case 2:
        mostra_punti_squadra(nomi_squadre, punti_giornate);
        break;

      case 3:
        mostra_vincitore_campionato(nomi_squadre, punti_giornate);
        break;

      case 0:
        break;

      default:
        std::cout << "Scelta non valida." << std::endl;
    }

    if (scelta != 0) {
      std::cout << std::endl;
    }
  } while (scelta != 0);

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>valgrind: memset the window command data structure.  |timestamp| is aligned on a 16 byte boundary leaving 4 bytes of uninitialized data in the middle of the struct.  We write this data to disk, which is a possible security risk.<commit_after><|endoftext|>


<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/lite/kernels/internal/reference/pooling.h"

// These are headers from the ARM CMSIS-NN library.
#include "arm_nnfunctions.h"  // NOLINT
#include "scratch_buffer.h"   // NOLINT
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/kernels/internal/reference/integer_ops/pooling.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/padding.h"

namespace tflite {
namespace ops {
namespace micro {
namespace pooling {

namespace {

constexpr int kInputTensor = 0;
constexpr int kOutputTensor = 0;

struct OpData {
  TfLitePaddingValues padding;
};

TfLiteStatus CalculateOpData(const TfLiteContext* context,
                             const TfLitePoolParams* params,
                             const TfLiteTensor* input,
                             const TfLiteTensor* output, OpData* data) {
  // input: batch, height, width, channel
  int height = SizeOfDimension(input, 1);
  int width = SizeOfDimension(input, 2);

  int out_height, out_width;

  data->padding = ComputePaddingHeightWidth(
      params->stride_height, params->stride_width,
      /*dilation_rate_height=*/1,
      /*dilation_rate_width=*/1, height, width, params->filter_height,
      params->filter_width, params->padding, &out_height, &out_width);

  return kTfLiteOk;
}

void AverageEvalFloat(const TfLiteContext* context, const TfLiteNode* node,
                      const TfLitePoolParams* params, const OpData* data,
                      const TfLiteTensor* input, TfLiteTensor* output) {
  float activation_min, activation_max;
  CalculateActivationRange(params->activation, &activation_min,
                           &activation_max);

  PoolParams op_params;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.filter_height = params->filter_height;
  op_params.filter_width = params->filter_width;
  op_params.padding_values.height = data->padding.height;
  op_params.padding_values.width = data->padding.width;
  op_params.float_activation_min = activation_min;
  op_params.float_activation_max = activation_max;
  reference_ops::AveragePool(
      op_params, GetTensorShape(input), GetTensorData<float>(input),
      GetTensorShape(output), GetTensorData<float>(output));
}

void AverageEvalUint8(const TfLiteContext* context, const TfLiteNode* node,
                      const TfLitePoolParams* params, const OpData* data,
                      const TfLiteTensor* input, TfLiteTensor* output) {
  int32_t activation_min, activation_max;
  (void)CalculateActivationRangeQuantized(context, params->activation, output,
                                          &activation_min, &activation_max);

  PoolParams op_params;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.filter_height = params->filter_height;
  op_params.filter_width = params->filter_width;
  op_params.padding_values.height = data->padding.height;
  op_params.padding_values.width = data->padding.width;
  op_params.quantized_activation_min = activation_min;
  op_params.quantized_activation_max = activation_max;
  reference_ops::AveragePool(
      op_params, GetTensorShape(input), GetTensorData<uint8_t>(input),
      GetTensorShape(output), GetTensorData<uint8_t>(output));
}

TfLiteStatus AverageEvalInt8(TfLiteContext* context, const TfLiteNode* node,
                             const TfLitePoolParams* params, const OpData* data,
                             TfLiteTensor* input, TfLiteTensor* output) {
  int32_t activation_min, activation_max;
  (void)CalculateActivationRangeQuantized(context, params->activation, output,
                                          &activation_min, &activation_max);

  TFLITE_DCHECK_LE(activation_min, activation_max);

#if defined(ARM_MATH_DSP) && defined(ARM_MATH_LOOPUNROLL)
  RuntimeShape input_shape = GetTensorShape(input);
  TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);

  RuntimeShape output_shape = GetTensorShape(output);
  TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);

  const int depth = MatchingDim(input_shape, 3, output_shape, 3);
  const int input_height = input_shape.Dims(1);
  const int input_width = input_shape.Dims(2);
  const int output_height = output_shape.Dims(1);
  const int output_width = output_shape.Dims(2);
  const int stride_height = params->stride_height;
  const int stride_width = params->stride_width;

  const int filter_height = params->filter_height;
  const int filter_width = params->filter_width;
  const int padding_height = data->padding.height;
  const int padding_width = data->padding.width;

  int16_t* scratch_buffer = nullptr;
  int32_t buffer_size = arm_avgpool_s8_get_buffer_size(output_width, depth);

  TF_LITE_ENSURE_OK(
      context, get_cmsis_scratch_buffer(context, &scratch_buffer, buffer_size));

  TF_LITE_ENSURE_EQ(
      context,
      arm_avgpool_s8(input_height, input_width, output_height, output_width,
                     stride_height, stride_width, filter_height, filter_width,
                     padding_height, padding_width, activation_min,
                     activation_max, depth, GetTensorData<int8_t>(input),
                     scratch_buffer, GetTensorData<int8_t>(output)),
      ARM_MATH_SUCCESS);
#else
  PoolParams op_params;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.filter_height = params->filter_height;
  op_params.filter_width = params->filter_width;
  op_params.padding_values.height = data->padding.height;
  op_params.padding_values.width = data->padding.width;
  op_params.quantized_activation_min = activation_min;
  op_params.quantized_activation_max = activation_max;
  reference_integer_ops::AveragePool(
      op_params, GetTensorShape(input), GetTensorData<int8_t>(input),
      GetTensorShape(output), GetTensorData<int8_t>(output));

#endif
  return kTfLiteOk;
}

void MaxEvalFloat(TfLiteContext* context, TfLiteNode* node,
                  TfLitePoolParams* params, OpData* data,
                  const TfLiteTensor* input, TfLiteTensor* output) {
  float activation_min, activation_max;
  CalculateActivationRange(params->activation, &activation_min,
                           &activation_max);

  tflite::PoolParams op_params;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.filter_height = params->filter_height;
  op_params.filter_width = params->filter_width;
  op_params.padding_values.height = data->padding.height;
  op_params.padding_values.width = data->padding.width;
  op_params.float_activation_min = activation_min;
  op_params.float_activation_max = activation_max;
  reference_ops::MaxPool(op_params, GetTensorShape(input),
                         GetTensorData<float>(input), GetTensorShape(output),
                         GetTensorData<float>(output));
}

void MaxEvalQuantizedUInt8(TfLiteContext* context, TfLiteNode* node,
                           TfLitePoolParams* params, OpData* data,
                           const TfLiteTensor* input, TfLiteTensor* output) {
  int32_t activation_min, activation_max;
  (void)CalculateActivationRangeQuantized(context, params->activation, output,
                                          &activation_min, &activation_max);

  tflite::PoolParams op_params;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.filter_height = params->filter_height;
  op_params.filter_width = params->filter_width;
  op_params.padding_values.height = data->padding.height;
  op_params.padding_values.width = data->padding.width;
  op_params.quantized_activation_min = activation_min;
  op_params.quantized_activation_max = activation_max;
  reference_ops::MaxPool(op_params, GetTensorShape(input),
                         GetTensorData<uint8_t>(input), GetTensorShape(output),
                         GetTensorData<uint8_t>(output));
}

}  // namespace

void* Init(TfLiteContext* context, const char* buffer, size_t length) {
  return nullptr;
}

void Free(TfLiteContext* context, void* buffer) {}

TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  return kTfLiteOk;
}

TfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) {
  auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
  OpData data;

  // Todo: make 'input' const once CMSIS-reuse is fixed
  TfLiteTensor* input = &context->tensors[flatbuffers::EndianScalar(
      node->inputs->data[kInputTensor])];
  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);

  TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data));

  // Inputs and outputs share the same type, guarenteed by the converter.
  switch (input->type) {
    case kTfLiteFloat32:
      AverageEvalFloat(context, node, params, &data, input, output);
      break;
    case kTfLiteUInt8:
      AverageEvalUint8(context, node, params, &data, input, output);
      break;
    case kTfLiteInt8:
      return AverageEvalInt8(context, node, params, &data, input, output);
      break;
    default:
      context->ReportError(context, "Input type %s is not currently supported",
                           TfLiteTypeGetName(input->type));
      return kTfLiteError;
  }
  return kTfLiteOk;
}

TfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) {
  auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
  OpData data;

  const TfLiteTensor* input = GetInput(context, node, kInputTensor);
  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);

  TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data));

  switch (input->type) {
    case kTfLiteFloat32:
      MaxEvalFloat(context, node, params, &data, input, output);
      break;
    case kTfLiteUInt8:
      MaxEvalQuantizedUInt8(context, node, params, &data, input, output);
      break;
    default:
      context->ReportError(context, "Type %s not currently supported.",
                           TfLiteTypeGetName(input->type));
      return kTfLiteError;
  }
  return kTfLiteOk;
}

}  // namespace pooling

TfLiteRegistration* Register_AVERAGE_POOL_2D() {
  static TfLiteRegistration r = {
      pooling::Init,
      pooling::Free,
      pooling::Prepare,
      pooling::AverageEval,
  };
  return &r;
}

TfLiteRegistration* Register_MAX_POOL_2D() {
  static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::Prepare,
                                 pooling::MaxEval};
  return &r;
}

}  // namespace micro
}  // namespace ops
}  // namespace tflite
<commit_msg>Micro: Fix compile error for Arm Mbed OS.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/lite/kernels/internal/reference/pooling.h"

// These are headers from the ARM CMSIS-NN library.
#include "arm_nnfunctions.h"  // NOLINT
#include "scratch_buffer.h"   // NOLINT
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/kernels/internal/reference/integer_ops/pooling.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/padding.h"

namespace tflite {
namespace ops {
namespace micro {
namespace pooling {

namespace {

constexpr int kInputTensor = 0;
constexpr int kOutputTensor = 0;

struct OpData {
  TfLitePaddingValues padding;
};

TfLiteStatus CalculateOpData(const TfLiteContext* context,
                             const TfLitePoolParams* params,
                             const TfLiteTensor* input,
                             const TfLiteTensor* output, OpData* data) {
  // input: batch, height, width, channel
  int height = SizeOfDimension(input, 1);
  int width = SizeOfDimension(input, 2);

  int out_height, out_width;

  data->padding = ComputePaddingHeightWidth(
      params->stride_height, params->stride_width,
      /*dilation_rate_height=*/1,
      /*dilation_rate_width=*/1, height, width, params->filter_height,
      params->filter_width, params->padding, &out_height, &out_width);

  return kTfLiteOk;
}

void AverageEvalFloat(const TfLiteContext* context, const TfLiteNode* node,
                      const TfLitePoolParams* params, const OpData* data,
                      const TfLiteTensor* input, TfLiteTensor* output) {
  float activation_min, activation_max;
  CalculateActivationRange(params->activation, &activation_min,
                           &activation_max);

  PoolParams op_params;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.filter_height = params->filter_height;
  op_params.filter_width = params->filter_width;
  op_params.padding_values.height = data->padding.height;
  op_params.padding_values.width = data->padding.width;
  op_params.float_activation_min = activation_min;
  op_params.float_activation_max = activation_max;
  reference_ops::AveragePool(
      op_params, GetTensorShape(input), GetTensorData<float>(input),
      GetTensorShape(output), GetTensorData<float>(output));
}

void AverageEvalUint8(TfLiteContext* context, const TfLiteNode* node,
                      const TfLitePoolParams* params, const OpData* data,
                      const TfLiteTensor* input, TfLiteTensor* output) {
  int32_t activation_min, activation_max;
  (void)CalculateActivationRangeQuantized(context, params->activation, output,
                                          &activation_min, &activation_max);

  PoolParams op_params;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.filter_height = params->filter_height;
  op_params.filter_width = params->filter_width;
  op_params.padding_values.height = data->padding.height;
  op_params.padding_values.width = data->padding.width;
  op_params.quantized_activation_min = activation_min;
  op_params.quantized_activation_max = activation_max;
  reference_ops::AveragePool(
      op_params, GetTensorShape(input), GetTensorData<uint8_t>(input),
      GetTensorShape(output), GetTensorData<uint8_t>(output));
}

TfLiteStatus AverageEvalInt8(TfLiteContext* context, const TfLiteNode* node,
                             const TfLitePoolParams* params, const OpData* data,
                             TfLiteTensor* input, TfLiteTensor* output) {
  int32_t activation_min, activation_max;
  (void)CalculateActivationRangeQuantized(context, params->activation, output,
                                          &activation_min, &activation_max);

  TFLITE_DCHECK_LE(activation_min, activation_max);

#if defined(ARM_MATH_DSP) && defined(ARM_MATH_LOOPUNROLL)
  RuntimeShape input_shape = GetTensorShape(input);
  TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);

  RuntimeShape output_shape = GetTensorShape(output);
  TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);

  const int depth = MatchingDim(input_shape, 3, output_shape, 3);
  const int input_height = input_shape.Dims(1);
  const int input_width = input_shape.Dims(2);
  const int output_height = output_shape.Dims(1);
  const int output_width = output_shape.Dims(2);
  const int stride_height = params->stride_height;
  const int stride_width = params->stride_width;

  const int filter_height = params->filter_height;
  const int filter_width = params->filter_width;
  const int padding_height = data->padding.height;
  const int padding_width = data->padding.width;

  int16_t* scratch_buffer = nullptr;
  int32_t buffer_size = arm_avgpool_s8_get_buffer_size(output_width, depth);

  TF_LITE_ENSURE_OK(
      context, get_cmsis_scratch_buffer(context, &scratch_buffer, buffer_size));

  TF_LITE_ENSURE_EQ(
      context,
      arm_avgpool_s8(input_height, input_width, output_height, output_width,
                     stride_height, stride_width, filter_height, filter_width,
                     padding_height, padding_width, activation_min,
                     activation_max, depth, GetTensorData<int8_t>(input),
                     scratch_buffer, GetTensorData<int8_t>(output)),
      ARM_MATH_SUCCESS);
#else
  PoolParams op_params;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.filter_height = params->filter_height;
  op_params.filter_width = params->filter_width;
  op_params.padding_values.height = data->padding.height;
  op_params.padding_values.width = data->padding.width;
  op_params.quantized_activation_min = activation_min;
  op_params.quantized_activation_max = activation_max;
  reference_integer_ops::AveragePool(
      op_params, GetTensorShape(input), GetTensorData<int8_t>(input),
      GetTensorShape(output), GetTensorData<int8_t>(output));

#endif
  return kTfLiteOk;
}

void MaxEvalFloat(TfLiteContext* context, TfLiteNode* node,
                  TfLitePoolParams* params, OpData* data,
                  const TfLiteTensor* input, TfLiteTensor* output) {
  float activation_min, activation_max;
  CalculateActivationRange(params->activation, &activation_min,
                           &activation_max);

  tflite::PoolParams op_params;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.filter_height = params->filter_height;
  op_params.filter_width = params->filter_width;
  op_params.padding_values.height = data->padding.height;
  op_params.padding_values.width = data->padding.width;
  op_params.float_activation_min = activation_min;
  op_params.float_activation_max = activation_max;
  reference_ops::MaxPool(op_params, GetTensorShape(input),
                         GetTensorData<float>(input), GetTensorShape(output),
                         GetTensorData<float>(output));
}

void MaxEvalQuantizedUInt8(TfLiteContext* context, TfLiteNode* node,
                           TfLitePoolParams* params, OpData* data,
                           const TfLiteTensor* input, TfLiteTensor* output) {
  int32_t activation_min, activation_max;
  (void)CalculateActivationRangeQuantized(context, params->activation, output,
                                          &activation_min, &activation_max);

  tflite::PoolParams op_params;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.filter_height = params->filter_height;
  op_params.filter_width = params->filter_width;
  op_params.padding_values.height = data->padding.height;
  op_params.padding_values.width = data->padding.width;
  op_params.quantized_activation_min = activation_min;
  op_params.quantized_activation_max = activation_max;
  reference_ops::MaxPool(op_params, GetTensorShape(input),
                         GetTensorData<uint8_t>(input), GetTensorShape(output),
                         GetTensorData<uint8_t>(output));
}

}  // namespace

void* Init(TfLiteContext* context, const char* buffer, size_t length) {
  return nullptr;
}

void Free(TfLiteContext* context, void* buffer) {}

TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  return kTfLiteOk;
}

TfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) {
  auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
  OpData data;

  // Todo: make 'input' const once CMSIS-reuse is fixed
  TfLiteTensor* input = &context->tensors[flatbuffers::EndianScalar(
      node->inputs->data[kInputTensor])];
  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);

  TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data));

  // Inputs and outputs share the same type, guarenteed by the converter.
  switch (input->type) {
    case kTfLiteFloat32:
      AverageEvalFloat(context, node, params, &data, input, output);
      break;
    case kTfLiteUInt8:
      AverageEvalUint8(context, node, params, &data, input, output);
      break;
    case kTfLiteInt8:
      return AverageEvalInt8(context, node, params, &data, input, output);
      break;
    default:
      context->ReportError(context, "Input type %s is not currently supported",
                           TfLiteTypeGetName(input->type));
      return kTfLiteError;
  }
  return kTfLiteOk;
}

TfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) {
  auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
  OpData data;

  const TfLiteTensor* input = GetInput(context, node, kInputTensor);
  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);

  TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data));

  switch (input->type) {
    case kTfLiteFloat32:
      MaxEvalFloat(context, node, params, &data, input, output);
      break;
    case kTfLiteUInt8:
      MaxEvalQuantizedUInt8(context, node, params, &data, input, output);
      break;
    default:
      context->ReportError(context, "Type %s not currently supported.",
                           TfLiteTypeGetName(input->type));
      return kTfLiteError;
  }
  return kTfLiteOk;
}

}  // namespace pooling

TfLiteRegistration* Register_AVERAGE_POOL_2D() {
  static TfLiteRegistration r = {
      pooling::Init,
      pooling::Free,
      pooling::Prepare,
      pooling::AverageEval,
  };
  return &r;
}

TfLiteRegistration* Register_MAX_POOL_2D() {
  static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::Prepare,
                                 pooling::MaxEval};
  return &r;
}

}  // namespace micro
}  // namespace ops
}  // namespace tflite
<|endoftext|>


<commit_before>// infoware - C++ System information Library
//
// Written in 2016 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>

#ifndef _WIN32
#ifdef INFOWARE_USE_X11

#include "infoware/system.hpp"
#include <X11/Xlib.h>
#include <cstdlib>

std::vector<iware::system::display_t> iware::system::displays() {
	std::vector<iware::system::display_t> ret;

	if(const auto display_name = std::getenv("DISPLAY"))
		if(const auto display = XOpenDisplay(display_name))
			for(int i = 0; i < ScreenCount(display); ++i) {
				const unsigned int width = DisplayWidth(display, i);
				// 25.4 millimeters per inch
				ret.emplace_back(iware::system::display_t{width, DisplayHeight(display, i), static_cast<unsigned int>(25.4 * DisplayWidthMM(display, i) / width),
				                                          DefaultDepth(display, i)});
			}

	return ret;
}

#endif
#endif
<commit_msg>Fixes for narrowing conversions.<commit_after>// infoware - C++ System information Library
//
// Written in 2016 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>

#ifndef _WIN32
#ifdef INFOWARE_USE_X11

#include "infoware/system.hpp"
#include <X11/Xlib.h>
#include <cstdlib>

std::vector<iware::system::display_t> iware::system::displays() {
	std::vector<iware::system::display_t> ret;

	if(const auto display_name = std::getenv("DISPLAY"))
		if(const auto display = XOpenDisplay(display_name))
			for(int i = 0; i < ScreenCount(display); ++i) {
				const unsigned int width = DisplayWidth(display, i);
				// 25.4 millimeters per inch
				ret.emplace_back(iware::system::display_t{ width, static_cast<std::uint32_t>(DisplayHeight(display, i)), static_cast<std::uint32_t>(25.4 * DisplayWidthMM(display, i) / width),
					static_cast<std::uint32_t>(DefaultDepth(display, i)) });
			}

	return ret;
}

#endif
#endif
<|endoftext|>


<commit_before>/*
    This file is part of Kontact.
    Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/
#include <qimage.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qtooltip.h>

#include <dcopclient.h>
#include <dcopref.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kurllabel.h>

#include "summarywidget.h"

SummaryWidget::SummaryWidget( QWidget *parent, const char *name )
  : Kontact::Summary( parent, name ),
    DCOPObject( "WeatherSummaryWidget" ), mProc( 0 )
{
  mLayout = new QVBoxLayout( this );
  mLayout->setAlignment( Qt::AlignTop );

  QPixmap icon = KGlobal::iconLoader()->loadIcon( "kweather", KIcon::Desktop, KIcon::SizeMedium );
  QWidget *header = createHeader( this, icon, i18n( "Weather Information" ) );
  mLayout->addWidget( header );

  QString error;
  QCString appID;
  bool serviceAvailable = true;
  if ( !kapp->dcopClient()->isApplicationRegistered( "KWeatherService" ) ) {
    if ( KApplication::startServiceByDesktopName( "kweatherservice", QStringList(), &error, &appID ) ) {
      QLabel *label = new QLabel( i18n( "No weather dcop service available;\nyou need KWeather to use this plugin." ), this );
      mLayout->addWidget( label, Qt::AlignHCenter );
      serviceAvailable = false;
    }
  }

  if ( serviceAvailable ) {
    connectDCOPSignal( 0, 0, "fileUpdate(QString)", "refresh(QString)", false );
    connectDCOPSignal( 0, 0, "stationRemoved(QString)", "stationRemoved(QString)", false );

    DCOPRef dcopCall( "KWeatherService", "WeatherService" );
    DCOPReply reply = dcopCall.call( "listStations()", true );
    if ( reply.isValid() ) {
      mStations = reply;

      connect( &mTimer, SIGNAL( timeout() ), this, SLOT( timeout() ) );
      mTimer.start( 0 );
    } else {
      kdDebug(5602) << "ERROR: dcop reply not valid..." << endl;
    }
  }
}

void SummaryWidget::updateView()
{
  mLayouts.setAutoDelete( true );
  mLayouts.clear();
  mLayouts.setAutoDelete( false );

  mLabels.setAutoDelete( true );
  mLabels.clear();
  mLabels.setAutoDelete( false );

  if ( mStations.count() == 0 ) {
    kdDebug(5602) << "No weather stations defined..." << endl;
    return;
  }

  QValueList<WeatherData> dataList = mWeatherMap.values();
  qHeapSort( dataList );

  QValueList<WeatherData>::Iterator it;
  for ( it = dataList.begin(); it != dataList.end(); ++it ) {
    QString cover;
    for ( uint i = 0; i < (*it).cover().count(); ++i )
      cover += QString( "- %1\n" ).arg( (*it).cover()[ i ] );

    QImage img;
    img = (*it).icon();

    QGridLayout *layout = new QGridLayout( mLayout, 3, 3, 3 );
    mLayout->addStretch( 10 );
    mLayouts.append( layout );

    KURLLabel* urlLabel = new KURLLabel(this);
    urlLabel->installEventFilter(this);
    urlLabel->setURL((*it).stationID());
    urlLabel->setPixmap( img.smoothScale( 32, 32 ) );
    urlLabel->setMaximumSize(urlLabel->sizeHint());
    urlLabel->setAlignment(/* AlignRight |*/ AlignTop );
    layout->addMultiCellWidget( urlLabel, 0, 1, 0, 0 );
    mLabels.append( urlLabel );
    connect (urlLabel, SIGNAL(leftClickedURL( const QString&) ),
    	this, SLOT(slotShowReport(const QString& )));

    QLabel* label = new QLabel( this );
    label->setText( QString( "%1 (%2)" ).arg( (*it).name() ).arg( (*it).temperature() ) );
    QFont font = label->font();
    font.setBold( true );
    label->setFont( font );
    label->setAlignment( AlignLeft );
    layout->addMultiCellWidget( label, 0, 0, 1, 2 );
    mLabels.append( label );

    QString labelText;
    labelText = QString( "%1: %2
"
                         "%3: %4" )
                         .arg( i18n( "Wind Speed" ) )
                         .arg( (*it).windSpeed() )
                         .arg( i18n( "Rel. Humidity" ) )
                         .arg( (*it).relativeHumidity() );

    QToolTip::add( label, labelText.replace( " ", " " ) );

    label = new QLabel( cover, this );
    label->setAlignment( AlignLeft );
    layout->addMultiCellWidget( label, 1, 1, 1, 2 );
    mLabels.append( label );
  }

  for ( QLabel *label = mLabels.first(); label; label = mLabels.next() )
    label->show();

  mLayout->addStretch( 1 );
}

void SummaryWidget::timeout()
{
  mTimer.stop();

  DCOPRef dcopCall( "KWeatherService", "WeatherService" );
  dcopCall.send( "updateAll()" );

  mTimer.start( 15 * 60000 );
}

void SummaryWidget::refresh( QString station )
{
  DCOPRef dcopCall( "KWeatherService", "WeatherService" );

  mWeatherMap[ station ].setIcon( dcopCall.call( "currentIcon(QString)", station, true ) );
  mWeatherMap[ station ].setName( dcopCall.call( "stationName(QString)", station, true ) );
  mWeatherMap[ station ].setCover( dcopCall.call( "cover(QString)", station, true ) );
  mWeatherMap[ station ].setTemperature( dcopCall.call( "temperature(QString)", station, true ) );
  mWeatherMap[ station ].setWindSpeed( dcopCall.call( "wind(QString)", station, true ) );
  mWeatherMap[ station ].setRelativeHumidity( dcopCall.call( "relativeHumidity(QString)", station, true ) );
  mWeatherMap[ station ].setStationID(station);

  updateView();
}

void SummaryWidget::stationRemoved( QString station )
{
  mWeatherMap.remove( station );
  updateView();
}

QStringList SummaryWidget::configModules() const
{
  return QStringList( "kcmweatherservice.desktop" );
}

void SummaryWidget::slotShowReport(const QString &stationID)
{
  mProc = new KProcess;
  QApplication::connect(mProc, SIGNAL(processExited(KProcess *)),
	this, SLOT(slotReportFinished(KProcess* )));
  *mProc << "kweatherreport";
  *mProc << stationID;
  if ( !mProc->start() )
  {
    delete mProc;
    mProc=0;
  }
}

void SummaryWidget::slotReportFinished(KProcess* /*proc*/){
  delete mProc;
 mProc = 0;
}

#include "summarywidget.moc"
<commit_msg>Don't add extra space on every view update. That fixes #85031.<commit_after>/*
    This file is part of Kontact.
    Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/
#include <qimage.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qtooltip.h>

#include <dcopclient.h>
#include <dcopref.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kurllabel.h>

#include "summarywidget.h"

SummaryWidget::SummaryWidget( QWidget *parent, const char *name )
  : Kontact::Summary( parent, name ),
    DCOPObject( "WeatherSummaryWidget" ), mProc( 0 )
{
  mLayout = new QVBoxLayout( this );
  mLayout->setAlignment( Qt::AlignTop );

  QPixmap icon = KGlobal::iconLoader()->loadIcon( "kweather", KIcon::Desktop, KIcon::SizeMedium );
  QWidget *header = createHeader( this, icon, i18n( "Weather Information" ) );
  mLayout->addWidget( header );

  QString error;
  QCString appID;
  bool serviceAvailable = true;
  if ( !kapp->dcopClient()->isApplicationRegistered( "KWeatherService" ) ) {
    if ( KApplication::startServiceByDesktopName( "kweatherservice", QStringList(), &error, &appID ) ) {
      QLabel *label = new QLabel( i18n( "No weather dcop service available;\nyou need KWeather to use this plugin." ), this );
      mLayout->addWidget( label, Qt::AlignHCenter );
      serviceAvailable = false;
    }
  }

  if ( serviceAvailable ) {
    connectDCOPSignal( 0, 0, "fileUpdate(QString)", "refresh(QString)", false );
    connectDCOPSignal( 0, 0, "stationRemoved(QString)", "stationRemoved(QString)", false );

    DCOPRef dcopCall( "KWeatherService", "WeatherService" );
    DCOPReply reply = dcopCall.call( "listStations()", true );
    if ( reply.isValid() ) {
      mStations = reply;

      connect( &mTimer, SIGNAL( timeout() ), this, SLOT( timeout() ) );
      mTimer.start( 0 );
    } else {
      kdDebug(5602) << "ERROR: dcop reply not valid..." << endl;
    }
  }
}

void SummaryWidget::updateView()
{
  mLayouts.setAutoDelete( true );
  mLayouts.clear();
  mLayouts.setAutoDelete( false );

  mLabels.setAutoDelete( true );
  mLabels.clear();
  mLabels.setAutoDelete( false );

  if ( mStations.count() == 0 ) {
    kdDebug(5602) << "No weather stations defined..." << endl;
    return;
  }

  QValueList<WeatherData> dataList = mWeatherMap.values();
  qHeapSort( dataList );

  QValueList<WeatherData>::Iterator it;
  for ( it = dataList.begin(); it != dataList.end(); ++it ) {
    QString cover;
    for ( uint i = 0; i < (*it).cover().count(); ++i )
      cover += QString( "- %1\n" ).arg( (*it).cover()[ i ] );

    QImage img;
    img = (*it).icon();

    QGridLayout *layout = new QGridLayout( mLayout, 3, 3, 3 );
    mLayouts.append( layout );

    KURLLabel* urlLabel = new KURLLabel(this);
    urlLabel->installEventFilter(this);
    urlLabel->setURL((*it).stationID());
    urlLabel->setPixmap( img.smoothScale( 32, 32 ) );
    urlLabel->setMaximumSize(urlLabel->sizeHint());
    urlLabel->setAlignment(/* AlignRight |*/ AlignTop );
    layout->addMultiCellWidget( urlLabel, 0, 1, 0, 0 );
    mLabels.append( urlLabel );
    connect (urlLabel, SIGNAL(leftClickedURL( const QString&) ),
    	this, SLOT(slotShowReport(const QString& )));

    QLabel* label = new QLabel( this );
    label->setText( QString( "%1 (%2)" ).arg( (*it).name() ).arg( (*it).temperature() ) );
    QFont font = label->font();
    font.setBold( true );
    label->setFont( font );
    label->setAlignment( AlignLeft );
    layout->addMultiCellWidget( label, 0, 0, 1, 2 );
    mLabels.append( label );

    QString labelText;
    labelText = QString( "%1: %2
"
                         "%3: %4" )
                         .arg( i18n( "Wind Speed" ) )
                         .arg( (*it).windSpeed() )
                         .arg( i18n( "Rel. Humidity" ) )
                         .arg( (*it).relativeHumidity() );

    QToolTip::add( label, labelText.replace( " ", " " ) );

    label = new QLabel( cover, this );
    label->setAlignment( AlignLeft );
    layout->addMultiCellWidget( label, 1, 1, 1, 2 );
    mLabels.append( label );
  }

  for ( QLabel *label = mLabels.first(); label; label = mLabels.next() )
    label->show();

  mLayout->addStretch( 1 );
}

void SummaryWidget::timeout()
{
  mTimer.stop();

  DCOPRef dcopCall( "KWeatherService", "WeatherService" );
  dcopCall.send( "updateAll()" );

  mTimer.start( 15 * 60000 );
}

void SummaryWidget::refresh( QString station )
{
  DCOPRef dcopCall( "KWeatherService", "WeatherService" );

  mWeatherMap[ station ].setIcon( dcopCall.call( "currentIcon(QString)", station, true ) );
  mWeatherMap[ station ].setName( dcopCall.call( "stationName(QString)", station, true ) );
  mWeatherMap[ station ].setCover( dcopCall.call( "cover(QString)", station, true ) );
  mWeatherMap[ station ].setTemperature( dcopCall.call( "temperature(QString)", station, true ) );
  mWeatherMap[ station ].setWindSpeed( dcopCall.call( "wind(QString)", station, true ) );
  mWeatherMap[ station ].setRelativeHumidity( dcopCall.call( "relativeHumidity(QString)", station, true ) );
  mWeatherMap[ station ].setStationID(station);

  updateView();
}

void SummaryWidget::stationRemoved( QString station )
{
  mWeatherMap.remove( station );
  updateView();
}

QStringList SummaryWidget::configModules() const
{
  return QStringList( "kcmweatherservice.desktop" );
}

void SummaryWidget::slotShowReport(const QString &stationID)
{
  mProc = new KProcess;
  QApplication::connect(mProc, SIGNAL(processExited(KProcess *)),
	this, SLOT(slotReportFinished(KProcess* )));
  *mProc << "kweatherreport";
  *mProc << stationID;
  if ( !mProc->start() )
  {
    delete mProc;
    mProc=0;
  }
}

void SummaryWidget::slotReportFinished(KProcess* /*proc*/){
  delete mProc;
 mProc = 0;
}

#include "summarywidget.moc"
<|endoftext|>


<commit_before>/*
 * TCPServer.cpp
 *
 *  Created on: Apr 4, 2016
 *      Author: james
 */

#include "tcp/TCPDeviceServer.h"

#include <netinet/in.h>
#include <stddef.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstdint>
#include <iostream>
#include <utility>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

#include "device/socket/tcp/TCPClient.h"
#include "device/socket/tcp/TCPClientProxy.h"
#include "Debug.h"
#include "tcp/TCPConnParams.h"
#include "tcp/SSLConfig.h"
#include "util/write.h"

TCPDeviceServer::TCPDeviceServer(Beetle &beetle, SSLConfig sslConfig, int port)
: beetle(beetle), sslConfig(sslConfig) {
	running = true;
	sockfd = -1;
	t = std::thread(&TCPDeviceServer::serverDaemon, this, port);
}

TCPDeviceServer::~TCPDeviceServer() {
	running = false;
	shutdown(sockfd, SHUT_RDWR);
	t.join();
}

void TCPDeviceServer::serverDaemon(int port) {
	if (debug) pdebug("tcp serverDaemon started on port: " + std::to_string(port));

	sockfd = socket(AF_INET, SOCK_STREAM, 0);

	if (sockfd < 0) {
		throw ServerException("error creating socket");
	}

	struct sockaddr_in server_addr = {0};
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = INADDR_ANY;
	server_addr.sin_port = htons(port);

	if (bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
		throw ServerException("error on bind");
	}

	listen(sockfd, 5);
	while (running) {
		struct sockaddr_in client_addr;
		socklen_t clilen = sizeof(client_addr);

		int clifd = accept(sockfd, (struct sockaddr *)&client_addr, &clilen);
		if (clifd < 0) {
			if (!running) {
				break;
			}
			pwarn("error on accept");
			continue;
		}

		SSL *ssl = SSL_new(sslConfig.getCtx());
		SSL_set_fd(ssl, clifd);
		if (SSL_accept(ssl) <= 0) {
			pwarn("error on ssl accept");
			ERR_print_errors_fp(stderr);
			SSL_shutdown(ssl);
			SSL_free(ssl);
			close(clifd);
			continue;
		}

		startTcpDeviceHelper(ssl, clifd, client_addr);
	}
	close(sockfd);
	if (debug) pdebug("tcp serverDaemon exited");
}

void TCPDeviceServer::startTcpDeviceHelper(SSL *ssl, int clifd, struct sockaddr_in cliaddr) {
	uint32_t clientParamsLen;
	if (SSL_read(ssl, &clientParamsLen, sizeof(uint32_t)) != sizeof(uint32_t)) {
		if (debug) {
			pdebug("could not read tcp connection client parameters length");
		}
		ERR_print_errors_fp(stderr);
		SSL_shutdown(ssl);
		SSL_free(ssl);
		close(clifd);
		return;
	}

	/*
	 * Read params from the client.
	 */
	clientParamsLen = ntohl(clientParamsLen);
	if (debug) {
		pdebug("expecting " + std::to_string(clientParamsLen) + " bytes of parameters");
	}

	std::map<std::string, std::string> clientParams;
	if (!readParamsHelper(ssl, clientParamsLen, clientParams)) {
		pwarn("unable to read parameters");
		close(clifd);
		return;
	}

	if (debug) {
		for (auto &kv : clientParams) {
			pdebug("parsed param (" + kv.first + "," + kv.second + ")");
		}
		pdebug("done reading tcp connection parameters");
	}

	/*
	 * Send params to the client.
	 */
    std::stringstream ss;
    ss << TCP_PARAM_GATEWAY << " " << beetle.name;
    std::string serverParams = ss.str();
    uint32_t serverParamsLen = htonl(serverParams.length());

    if (SSL_write_all(ssl, (uint8_t *)&serverParamsLen, sizeof(serverParamsLen)) == false) {
    	ERR_print_errors_fp(stderr);
    	SSL_shutdown(ssl);
    	SSL_free(ssl);
    	close(clifd);
    	if (debug) pdebug("could not write server params length");
    }

    if (SSL_write_all(ssl, (uint8_t *)serverParams.c_str(), serverParams.length()) == false) {
    	ERR_print_errors_fp(stderr);
    	SSL_shutdown(ssl);
    	SSL_free(ssl);
    	close(clifd);
    	if (debug) pdebug("could not write server params");
    }

    /*
     * Instantiate the virtual device around the client socket.
     */
	VirtualDevice *device = NULL;
	try {
		/*
		 * Takes over the clifd
		 */
		if (clientParams.find(TCP_PARAM_GATEWAY) == clientParams.end()) {
			device = new TCPClient(beetle, ssl, clifd, clientParams[TCP_PARAM_CLIENT], cliaddr);
		} else {
			// name of the client gateway
			std::string client = clientParams[TCP_PARAM_GATEWAY];
			// device that the client is requesting
			device_t deviceId = std::stol(clientParams[TCP_PARAM_DEVICE]);
			device = new TCPClientProxy(beetle, ssl, clifd, client, cliaddr, deviceId);
		}

		if (clientParams[TCP_PARAM_SERVER] == "true") {
			device->start();
		} else {
			device->startNd();
		}

		beetle.addDevice(device);

		pdebug("connected to " + device->getName());
		if (debug) {
			pdebug(device->getName() + " has handle range [0,"
					+ std::to_string(device->getHighestHandle()) + "]");
		}
	} catch (std::exception& e) {
		std::cout << "caught exception: " << e.what() << std::endl;
		if (device) {
			beetle.removeDevice(device->getId());
		}
	}
}
<commit_msg>Change import.<commit_after>/*
 * TCPServer.cpp
 *
 *  Created on: Apr 4, 2016
 *      Author: james
 */

#include "tcp/TCPDeviceServer.h"

#include <netinet/in.h>
#include <stddef.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstdint>
#include <iostream>
#include <utility>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

#include "device/socket/tcp/TCPClient.h"
#include "device/socket/tcp/TCPClientProxy.h"
#include "Debug.h"
#include "tcp/TCPConnParams.h"
#include "util/write.h"

TCPDeviceServer::TCPDeviceServer(Beetle &beetle, SSLConfig sslConfig, int port)
: beetle(beetle), sslConfig(sslConfig) {
	running = true;
	sockfd = -1;
	t = std::thread(&TCPDeviceServer::serverDaemon, this, port);
}

TCPDeviceServer::~TCPDeviceServer() {
	running = false;
	shutdown(sockfd, SHUT_RDWR);
	t.join();
}

void TCPDeviceServer::serverDaemon(int port) {
	if (debug) pdebug("tcp serverDaemon started on port: " + std::to_string(port));

	sockfd = socket(AF_INET, SOCK_STREAM, 0);

	if (sockfd < 0) {
		throw ServerException("error creating socket");
	}

	struct sockaddr_in server_addr = {0};
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = INADDR_ANY;
	server_addr.sin_port = htons(port);

	if (bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
		throw ServerException("error on bind");
	}

	listen(sockfd, 5);
	while (running) {
		struct sockaddr_in client_addr;
		socklen_t clilen = sizeof(client_addr);

		int clifd = accept(sockfd, (struct sockaddr *)&client_addr, &clilen);
		if (clifd < 0) {
			if (!running) {
				break;
			}
			pwarn("error on accept");
			continue;
		}

		SSL *ssl = SSL_new(sslConfig.getCtx());
		SSL_set_fd(ssl, clifd);
		if (SSL_accept(ssl) <= 0) {
			pwarn("error on ssl accept");
			ERR_print_errors_fp(stderr);
			SSL_shutdown(ssl);
			SSL_free(ssl);
			close(clifd);
			continue;
		}

		startTcpDeviceHelper(ssl, clifd, client_addr);
	}
	close(sockfd);
	if (debug) pdebug("tcp serverDaemon exited");
}

void TCPDeviceServer::startTcpDeviceHelper(SSL *ssl, int clifd, struct sockaddr_in cliaddr) {
	uint32_t clientParamsLen;
	if (SSL_read(ssl, &clientParamsLen, sizeof(uint32_t)) != sizeof(uint32_t)) {
		if (debug) {
			pdebug("could not read tcp connection client parameters length");
		}
		ERR_print_errors_fp(stderr);
		SSL_shutdown(ssl);
		SSL_free(ssl);
		close(clifd);
		return;
	}

	/*
	 * Read params from the client.
	 */
	clientParamsLen = ntohl(clientParamsLen);
	if (debug) {
		pdebug("expecting " + std::to_string(clientParamsLen) + " bytes of parameters");
	}

	std::map<std::string, std::string> clientParams;
	if (!readParamsHelper(ssl, clientParamsLen, clientParams)) {
		pwarn("unable to read parameters");
		close(clifd);
		return;
	}

	if (debug) {
		for (auto &kv : clientParams) {
			pdebug("parsed param (" + kv.first + "," + kv.second + ")");
		}
		pdebug("done reading tcp connection parameters");
	}

	/*
	 * Send params to the client.
	 */
    std::stringstream ss;
    ss << TCP_PARAM_GATEWAY << " " << beetle.name;
    std::string serverParams = ss.str();
    uint32_t serverParamsLen = htonl(serverParams.length());

    if (SSL_write_all(ssl, (uint8_t *)&serverParamsLen, sizeof(serverParamsLen)) == false) {
    	ERR_print_errors_fp(stderr);
    	SSL_shutdown(ssl);
    	SSL_free(ssl);
    	close(clifd);
    	if (debug) pdebug("could not write server params length");
    }

    if (SSL_write_all(ssl, (uint8_t *)serverParams.c_str(), serverParams.length()) == false) {
    	ERR_print_errors_fp(stderr);
    	SSL_shutdown(ssl);
    	SSL_free(ssl);
    	close(clifd);
    	if (debug) pdebug("could not write server params");
    }

    /*
     * Instantiate the virtual device around the client socket.
     */
	VirtualDevice *device = NULL;
	try {
		/*
		 * Takes over the clifd
		 */
		if (clientParams.find(TCP_PARAM_GATEWAY) == clientParams.end()) {
			device = new TCPClient(beetle, ssl, clifd, clientParams[TCP_PARAM_CLIENT], cliaddr);
		} else {
			// name of the client gateway
			std::string client = clientParams[TCP_PARAM_GATEWAY];
			// device that the client is requesting
			device_t deviceId = std::stol(clientParams[TCP_PARAM_DEVICE]);
			device = new TCPClientProxy(beetle, ssl, clifd, client, cliaddr, deviceId);
		}

		if (clientParams[TCP_PARAM_SERVER] == "true") {
			device->start();
		} else {
			device->startNd();
		}

		beetle.addDevice(device);

		pdebug("connected to " + device->getName());
		if (debug) {
			pdebug(device->getName() + " has handle range [0,"
					+ std::to_string(device->getHighestHandle()) + "]");
		}
	} catch (std::exception& e) {
		std::cout << "caught exception: " << e.what() << std::endl;
		if (device) {
			beetle.removeDevice(device->getId());
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>Match up array delete to array allocate.<commit_after><|endoftext|>


<commit_before>/*
    Kopete View Item Delegate

    Copyright (c) 2007 by Matt Rogers <mattr@kde.org>

    Kopete    (c) 2002-2007 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include "kopeteitemdelegate.h"
#include "kopeteitembase.h"

#include <QPainter>
#include <QStyleOptionViewItem>
#include <QModelIndex>
#include <QAbstractItemView>
#include <QItemDelegate>

#include "kopetemetacontact.h"
#include "kopeteappearancesettings.h"

KopeteItemDelegate::KopeteItemDelegate( QAbstractItemView* parent )
: QItemDelegate( parent )
{
}

KopeteItemDelegate::~KopeteItemDelegate()
{
}

QSize KopeteItemDelegate::sizeHint(const QStyleOptionViewItem &option,
                                   const QModelIndex &index) const
{
	return QSize(45, 20);
}

void KopeteItemDelegate::paint( QPainter* painter,
                                const QStyleOptionViewItem& option,
                                const QModelIndex& index ) const
{
	//pull in contact settings: idleContactColor, greyIdleMetaContacts
	//pull in contact list settings: contactListDisplayMode
	QStyleOptionViewItem opt = option;

	if ( index.data( Kopete::Items::TypeRole ) ==
		Kopete::Items::MetaContact )
	{
		//check the idle state of the metacontact and apply the appropriate
		//color
		QVariant v = index.data( Kopete::Items::IdleTimeRole );
		if ( Kopete::AppearanceSettings::self()->greyIdleMetaContacts() &&
		     v.toInt() > 0 )
		{
		QColor idleColor( Kopete::AppearanceSettings::self()->idleContactColor() );
		opt.palette.setColor( QPalette::Text, idleColor );
		}
	}

	if (  index.data( Kopete::Items::TypeRole ) == Kopete::Items::Group )
	{
		QColor gc( Kopete::AppearanceSettings::self()->groupNameColor() );
		opt.palette.setColor( QPalette::Text, gc );
	}

	QItemDelegate::paint( painter, opt, index );

}

<commit_msg>Use the QItemDelegate size hint instead of our own custom hint for now<commit_after>/*
    Kopete View Item Delegate

    Copyright (c) 2007 by Matt Rogers <mattr@kde.org>

    Kopete    (c) 2002-2007 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include "kopeteitemdelegate.h"
#include "kopeteitembase.h"

#include <QPainter>
#include <QStyleOptionViewItem>
#include <QModelIndex>
#include <QAbstractItemView>
#include <QItemDelegate>

#include "kopetemetacontact.h"
#include "kopeteappearancesettings.h"

KopeteItemDelegate::KopeteItemDelegate( QAbstractItemView* parent )
: QItemDelegate( parent )
{
}

KopeteItemDelegate::~KopeteItemDelegate()
{
}

QSize KopeteItemDelegate::sizeHint(const QStyleOptionViewItem &option,
                                   const QModelIndex &index) const
{
	return QItemDelegate::sizeHint( option, index );
}

void KopeteItemDelegate::paint( QPainter* painter,
                                const QStyleOptionViewItem& option,
                                const QModelIndex& index ) const
{
	//pull in contact settings: idleContactColor, greyIdleMetaContacts
	//pull in contact list settings: contactListDisplayMode
	QStyleOptionViewItem opt = option;

	if ( index.data( Kopete::Items::TypeRole ) ==
		Kopete::Items::MetaContact )
	{
		//check the idle state of the metacontact and apply the appropriate
		//color
		QVariant v = index.data( Kopete::Items::IdleTimeRole );
		if ( Kopete::AppearanceSettings::self()->greyIdleMetaContacts() &&
		     v.toInt() > 0 )
		{
		QColor idleColor( Kopete::AppearanceSettings::self()->idleContactColor() );
		opt.palette.setColor( QPalette::Text, idleColor );
		}
	}

	if (  index.data( Kopete::Items::TypeRole ) == Kopete::Items::Group )
	{
		QColor gc( Kopete::AppearanceSettings::self()->groupNameColor() );
		opt.palette.setColor( QPalette::Text, gc );
	}

	QItemDelegate::paint( painter, opt, index );

}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014-2015, Julien Bernard
 *
 * 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 "Assets.h"

#include <cassert>

#include <boost/filesystem.hpp>

#include "Log.h"

namespace fs = boost::filesystem;

namespace game {

  void AssetManager::addSearchDir(std::string path) {
    Log::info(Log::RESOURCES, "Added a new search directory: %s\n", path.c_str());
    m_searchdirs.emplace_back(std::move(path));
  }

  std::string AssetManager::getAbsolutePath(const std::string& relative_path) {
    fs::path file(relative_path);

    if (file.is_absolute()) {
      return relative_path;
    }

    for (fs::path base : m_searchdirs) {
      fs::path absolute_path = base / file;

      if (fs::is_regular_file(absolute_path)) {
        Log::info(Log::RESOURCES, "Found a resource file: %s\n", absolute_path.string().c_str());
        return absolute_path.string();
      }
    }

    Log::error(Log::RESOURCES, "Could not find the following file: %s\n", relative_path.c_str());
    return std::string();
  }

}
<commit_msg>add some log for absolute filenames<commit_after>/*
 * Copyright (c) 2014-2015, Julien Bernard
 *
 * 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 "Assets.h"

#include <cassert>

#include <boost/filesystem.hpp>

#include "Log.h"

namespace fs = boost::filesystem;

namespace game {

  void AssetManager::addSearchDir(std::string path) {
    Log::info(Log::RESOURCES, "Added a new search directory: %s\n", path.c_str());
    m_searchdirs.emplace_back(std::move(path));
  }

  std::string AssetManager::getAbsolutePath(const std::string& relative_path) {
    fs::path file(relative_path);

    if (file.is_absolute()) {
      assert(fs::is_regular_file(file));
      Log::info(Log::RESOURCES, "Found a resource file: %s\n", relative_path.c_str());
      return relative_path;
    }

    for (fs::path base : m_searchdirs) {
      fs::path absolute_path = base / file;

      if (fs::is_regular_file(absolute_path)) {
        Log::info(Log::RESOURCES, "Found a resource file: %s\n", absolute_path.string().c_str());
        return absolute_path.string();
      }
    }

    Log::error(Log::RESOURCES, "Could not find the following file: %s\n", relative_path.c_str());
    return std::string();
  }

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dsbrowserDnD.cxx,v $
 *
 *  $Revision: 1.64 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 15:33:59 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SBA_UNODATBR_HXX_
#include "unodatbr.hxx"
#endif

#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_
#include <com/sun/star/sdb/CommandType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef DBAUI_DBTREEMODEL_HXX
#include "dbtreemodel.hxx"
#endif
#ifndef DBACCESS_UI_DBTREEVIEW_HXX
#include "dbtreeview.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _DBU_BRW_HRC_
#include "dbu_brw.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef DBAUI_DBEXCHANGE_HXX
#include "dbexchange.hxx"
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _SVX_DATACCESSDESCRIPTOR_HXX_
#include <svx/dataaccessdescriptor.hxx>
#endif
#ifndef DBAUI_DBTREELISTBOX_HXX
#include "dbtreelistbox.hxx"
#endif
// .........................................................................
namespace dbaui
{
// .........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::util;
    using namespace ::com::sun::star::frame;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::form;
    using namespace ::com::sun::star::io;
    using namespace ::com::sun::star::i18n;
    using namespace ::com::sun::star::task;
    using namespace ::com::sun::star::datatransfer;
    using namespace ::dbtools;
    using namespace ::svx;

    // -----------------------------------------------------------------------------
    TransferableHelper* SbaTableQueryBrowser::implCopyObject( SvLBoxEntry* _pApplyTo, sal_Int32 _nCommandType, sal_Bool _bAllowConnection )
    {
        try
        {
            ::osl::MutexGuard aGuard(m_aEntryMutex);

            ::rtl::OUString aName = GetEntryText( _pApplyTo );
            ::rtl::OUString aDSName = GetEntryText( m_pTreeView->getListBox()->GetRootLevelParent( _pApplyTo ) );

            ODataClipboard* pData = NULL;
            Reference<XConnection> xConnection;  // supports the service sdb::connection
            if ( CommandType::QUERY != _nCommandType )
            {
                if (_bAllowConnection && !ensureConnection(_pApplyTo, xConnection))
                    return NULL;
                pData = new ODataClipboard(aDSName, _nCommandType, aName, xConnection, getNumberFormatter(), getORB());
            }
            else
                pData = new ODataClipboard(aDSName, _nCommandType, aName, getNumberFormatter(), getORB());

            // the owner ship goes to ODataClipboards
            return pData;
        }
        catch(SQLException& e)
        {
            showError(SQLExceptionInfo(e));
        }
        catch(Exception&)
        {
            DBG_ERROR("SbaTableQueryBrowser::implCopyObject: caught a generic exception!");
        }
        return NULL;
    }
    // -----------------------------------------------------------------------------
    sal_Int8 SbaTableQueryBrowser::queryDrop( const AcceptDropEvent& _rEvt, const DataFlavorExVector& _rFlavors )
    {
        return DND_ACTION_NONE;
    }
    // -----------------------------------------------------------------------------
    sal_Int8 SbaTableQueryBrowser::executeDrop( const ExecuteDropEvent& _rEvt )
    {
        return DND_ACTION_NONE;
    }

    // -----------------------------------------------------------------------------
    sal_Bool SbaTableQueryBrowser::requestDrag( sal_Int8 _nAction, const Point& _rPosPixel )
    {
        // get the affected list entry
        // ensure that the entry which the user clicked at is selected
        SvLBoxEntry* pHitEntry = m_pTreeView->getListBox()->GetEntry( _rPosPixel );
        if (!pHitEntry)
            // no drag of no entry was hit ....
            return sal_False;

        // it must be a query/table
        EntryType eEntryType = getEntryType( pHitEntry );
        if (!isObject(eEntryType))
            return DND_ACTION_NONE;

        TransferableHelper* pTransfer = implCopyObject( pHitEntry, (etTable == eEntryType || etView == eEntryType) ? CommandType::TABLE : CommandType::QUERY);
        Reference< XTransferable> xEnsureDelete = pTransfer;

        if (pTransfer)
            pTransfer->StartDrag( m_pTreeView->getListBox(), DND_ACTION_COPY );

        return NULL != pTransfer;
    }
    // -----------------------------------------------------------------------------
    IMPL_LINK(SbaTableQueryBrowser, OnCopyEntry, SvLBoxEntry*, _pEntry)
    {
        if( isEntryCopyAllowed(_pEntry) )
            copyEntry(_pEntry);
        return 0;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SbaTableQueryBrowser::isEntryCutAllowed(SvLBoxEntry* _pEntry) const
    {
        // at the momoent this isn't allowed
        return sal_False;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SbaTableQueryBrowser::isEntryCopyAllowed(SvLBoxEntry* _pEntry) const
    {
        EntryType eType = getEntryType(_pEntry);
        return  (eType == etTable || eType == etQuery || eType == etView);
    }
    // -----------------------------------------------------------------------------
    sal_Bool SbaTableQueryBrowser::isEntryPasteAllowed(SvLBoxEntry* _pEntry) const
    {
        return sal_False;
    }
    // -----------------------------------------------------------------------------
    void SbaTableQueryBrowser::copyEntry(SvLBoxEntry* _pEntry)
    {
        TransferableHelper* pTransfer = NULL;
        Reference< XTransferable> aEnsureDelete;
        EntryType eType = getEntryType(_pEntry);
        pTransfer       = implCopyObject( _pEntry, eType == etQuery ? CommandType::QUERY : CommandType::TABLE);
        aEnsureDelete   = pTransfer;
        if (pTransfer)
            pTransfer->CopyToClipboard(getView());
    }
    // -----------------------------------------------------------------------------
// .........................................................................
}   // namespace dbaui
// .........................................................................

<commit_msg>INTEGRATION: CWS ooo20040704 (1.63.12); FILE MERGED 2004/07/02 13:42:26 cmc 1.63.12.2: #i30891# revert header and namespace change 2004/06/30 15:32:02 cmc 1.63.12.1: #i30801# allow using system stl if possible<commit_after>/*************************************************************************
 *
 *  $RCSfile: dsbrowserDnD.cxx,v $
 *
 *  $Revision: 1.65 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-08 16:28:51 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SBA_UNODATBR_HXX_
#include "unodatbr.hxx"
#endif

#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_
#include <com/sun/star/sdb/CommandType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef DBAUI_DBTREEMODEL_HXX
#include "dbtreemodel.hxx"
#endif
#ifndef DBACCESS_UI_DBTREEVIEW_HXX
#include "dbtreeview.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _DBU_BRW_HRC_
#include "dbu_brw.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef DBAUI_DBEXCHANGE_HXX
#include "dbexchange.hxx"
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _SVX_DATACCESSDESCRIPTOR_HXX_
#include <svx/dataaccessdescriptor.hxx>
#endif
#ifndef DBAUI_DBTREELISTBOX_HXX
#include "dbtreelistbox.hxx"
#endif
#include <functional>
// .........................................................................
namespace dbaui
{
// .........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::util;
    using namespace ::com::sun::star::frame;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::form;
    using namespace ::com::sun::star::io;
    using namespace ::com::sun::star::i18n;
    using namespace ::com::sun::star::task;
    using namespace ::com::sun::star::datatransfer;
    using namespace ::dbtools;
    using namespace ::svx;

    // -----------------------------------------------------------------------------
    TransferableHelper* SbaTableQueryBrowser::implCopyObject( SvLBoxEntry* _pApplyTo, sal_Int32 _nCommandType, sal_Bool _bAllowConnection )
    {
        try
        {
            ::osl::MutexGuard aGuard(m_aEntryMutex);

            ::rtl::OUString aName = GetEntryText( _pApplyTo );
            ::rtl::OUString aDSName = GetEntryText( m_pTreeView->getListBox()->GetRootLevelParent( _pApplyTo ) );

            ODataClipboard* pData = NULL;
            Reference<XConnection> xConnection;  // supports the service sdb::connection
            if ( CommandType::QUERY != _nCommandType )
            {
                if (_bAllowConnection && !ensureConnection(_pApplyTo, xConnection))
                    return NULL;
                pData = new ODataClipboard(aDSName, _nCommandType, aName, xConnection, getNumberFormatter(), getORB());
            }
            else
                pData = new ODataClipboard(aDSName, _nCommandType, aName, getNumberFormatter(), getORB());

            // the owner ship goes to ODataClipboards
            return pData;
        }
        catch(SQLException& e)
        {
            showError(SQLExceptionInfo(e));
        }
        catch(Exception&)
        {
            DBG_ERROR("SbaTableQueryBrowser::implCopyObject: caught a generic exception!");
        }
        return NULL;
    }
    // -----------------------------------------------------------------------------
    sal_Int8 SbaTableQueryBrowser::queryDrop( const AcceptDropEvent& _rEvt, const DataFlavorExVector& _rFlavors )
    {
        return DND_ACTION_NONE;
    }
    // -----------------------------------------------------------------------------
    sal_Int8 SbaTableQueryBrowser::executeDrop( const ExecuteDropEvent& _rEvt )
    {
        return DND_ACTION_NONE;
    }

    // -----------------------------------------------------------------------------
    sal_Bool SbaTableQueryBrowser::requestDrag( sal_Int8 _nAction, const Point& _rPosPixel )
    {
        // get the affected list entry
        // ensure that the entry which the user clicked at is selected
        SvLBoxEntry* pHitEntry = m_pTreeView->getListBox()->GetEntry( _rPosPixel );
        if (!pHitEntry)
            // no drag of no entry was hit ....
            return sal_False;

        // it must be a query/table
        EntryType eEntryType = getEntryType( pHitEntry );
        if (!isObject(eEntryType))
            return DND_ACTION_NONE;

        TransferableHelper* pTransfer = implCopyObject( pHitEntry, (etTable == eEntryType || etView == eEntryType) ? CommandType::TABLE : CommandType::QUERY);
        Reference< XTransferable> xEnsureDelete = pTransfer;

        if (pTransfer)
            pTransfer->StartDrag( m_pTreeView->getListBox(), DND_ACTION_COPY );

        return NULL != pTransfer;
    }
    // -----------------------------------------------------------------------------
    IMPL_LINK(SbaTableQueryBrowser, OnCopyEntry, SvLBoxEntry*, _pEntry)
    {
        if( isEntryCopyAllowed(_pEntry) )
            copyEntry(_pEntry);
        return 0;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SbaTableQueryBrowser::isEntryCutAllowed(SvLBoxEntry* _pEntry) const
    {
        // at the momoent this isn't allowed
        return sal_False;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SbaTableQueryBrowser::isEntryCopyAllowed(SvLBoxEntry* _pEntry) const
    {
        EntryType eType = getEntryType(_pEntry);
        return  (eType == etTable || eType == etQuery || eType == etView);
    }
    // -----------------------------------------------------------------------------
    sal_Bool SbaTableQueryBrowser::isEntryPasteAllowed(SvLBoxEntry* _pEntry) const
    {
        return sal_False;
    }
    // -----------------------------------------------------------------------------
    void SbaTableQueryBrowser::copyEntry(SvLBoxEntry* _pEntry)
    {
        TransferableHelper* pTransfer = NULL;
        Reference< XTransferable> aEnsureDelete;
        EntryType eType = getEntryType(_pEntry);
        pTransfer       = implCopyObject( _pEntry, eType == etQuery ? CommandType::QUERY : CommandType::TABLE);
        aEnsureDelete   = pTransfer;
        if (pTransfer)
            pTransfer->CopyToClipboard(getView());
    }
    // -----------------------------------------------------------------------------
// .........................................................................
}   // namespace dbaui
// .........................................................................

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "LimitBox.hxx"
#include "dbu_qry.hrc"
#include "moduledbu.hxx"

#define ALL_STRING ModuleRes(STR_QUERY_LIMIT_ALL).toString()
#define ALL_INT -1

namespace global{

/// Default values
sal_Int64 aDefLimitAry[] =
{
    5,
    10,
    20,
    50
};

}

namespace dbaui
{

LimitBox::LimitBox( Window* pParent, WinBits nStyle )
    : NumericBox( pParent, nStyle )
{
    SetShowTrailingZeros( sal_False );
    SetDecimalDigits( 0 );
    SetMin( -1 );

    ///Use the maximum value of Int32
    SetMax( 2147483647 );
    LoadDefaultLimits();

    Size aSize(
        GetSizePixel().Width(),
        CalcWindowSizePixel(GetEntryCount() + 1) );
    SetSizePixel(aSize);
}

LimitBox::~LimitBox()
{
}

OUString LimitBox::CreateFieldText( sal_Int64 nValue ) const
{
    if( nValue == ALL_INT )
        return ALL_STRING;
    else
        return NumericBox::CreateFieldText( nValue );
}

void LimitBox::Reformat()
{

    if( GetText() == ALL_STRING )
    {
        SetValue( ALL_INT );
    }
    ///Reformat only when text is not All
    else
    {
        ///Not allow user to type in -1
        if( GetText() == "-1" )
        {
            Undo();
        }
        else
            NumericBox::Reformat();
    }
}

void LimitBox::ReformatAll()
{
    ///First entry is All, which do not need numeric reformat
    if ( GetEntryCount() > 0 )
    {
        RemoveEntry( 0 );
        NumericBox::ReformatAll();
        InsertEntry( ALL_STRING, 0);
    }
    else
    {
        NumericBox::ReformatAll();
    }
}

Size LimitBox::GetOptimalSize() const
{
    return CalcSize(10,1);
}

///Initialize entries
void LimitBox::LoadDefaultLimits()
{
    SetValue( ALL_INT );
    InsertEntry( ALL_STRING );

    const unsigned nSize =
        sizeof(global::aDefLimitAry)/sizeof(global::aDefLimitAry[0]);
    for( unsigned nIndex = 0; nIndex< nSize; ++nIndex)
    {
        InsertValue( global::aDefLimitAry[nIndex] );
    }
}

extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeLimitBox( Window *pParent )
{
    LimitBox* pBox = new LimitBox( pParent, WB_DROPDOWN | WB_VSCROLL );
    return pBox;
}

} ///dbaui namespace

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fdo#61794 Set maximum of LimitBox to SAL_MAX_INT64<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "LimitBox.hxx"
#include "dbu_qry.hrc"
#include "moduledbu.hxx"

#define ALL_STRING ModuleRes(STR_QUERY_LIMIT_ALL).toString()
#define ALL_INT -1

namespace global{

/// Default values
sal_Int64 aDefLimitAry[] =
{
    5,
    10,
    20,
    50
};

}

namespace dbaui
{

LimitBox::LimitBox( Window* pParent, WinBits nStyle )
    : NumericBox( pParent, nStyle )
{
    SetShowTrailingZeros( sal_False );
    SetDecimalDigits( 0 );
    SetMin( -1 );
    SetMax( SAL_MAX_INT64 );
    LoadDefaultLimits();

    Size aSize(
        GetSizePixel().Width(),
        CalcWindowSizePixel(GetEntryCount() + 1) );
    SetSizePixel(aSize);
}

LimitBox::~LimitBox()
{
}

OUString LimitBox::CreateFieldText( sal_Int64 nValue ) const
{
    if( nValue == ALL_INT )
        return ALL_STRING;
    else
        return NumericBox::CreateFieldText( nValue );
}

void LimitBox::Reformat()
{

    if( GetText() == ALL_STRING )
    {
        SetValue( ALL_INT );
    }
    ///Reformat only when text is not All
    else
    {
        ///Not allow user to type in -1
        if( GetText() == "-1" )
        {
            Undo();
        }
        else
            NumericBox::Reformat();
    }
}

void LimitBox::ReformatAll()
{
    ///First entry is All, which do not need numeric reformat
    if ( GetEntryCount() > 0 )
    {
        RemoveEntry( 0 );
        NumericBox::ReformatAll();
        InsertEntry( ALL_STRING, 0);
    }
    else
    {
        NumericBox::ReformatAll();
    }
}

Size LimitBox::GetOptimalSize() const
{
    return CalcSize(10,1);
}

///Initialize entries
void LimitBox::LoadDefaultLimits()
{
    SetValue( ALL_INT );
    InsertEntry( ALL_STRING );

    const unsigned nSize =
        sizeof(global::aDefLimitAry)/sizeof(global::aDefLimitAry[0]);
    for( unsigned nIndex = 0; nIndex< nSize; ++nIndex)
    {
        InsertValue( global::aDefLimitAry[nIndex] );
    }
}

extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeLimitBox( Window *pParent )
{
    LimitBox* pBox = new LimitBox( pParent, WB_DROPDOWN | WB_VSCROLL );
    return pBox;
}

} ///dbaui namespace

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>