<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/atomicops.h"
#include "base/message_loop.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {

namespace {

const base::subtle::Atomic32 kMagicValue = 42;

void ReadUninitializedValue(char *ptr) {
  // The || in the conditional is to prevent clang from optimizing away the
  // jump -- valgrind only catches jumps and conditional moves, but clang uses
  // the borrow flag if the condition is just `*ptr == '\0'`.
  if (*ptr == '\0' || *ptr == 64) {
    (*ptr)++;
  } else {
    (*ptr)--;
  }
}

void ReadValueOutOfArrayBoundsLeft(char *ptr) {
  char c = ptr[-2];
  VLOG(1) << "Reading a byte out of bounds: " << c;
}

void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
  char c = ptr[size + 1];
  VLOG(1) << "Reading a byte out of bounds: " << c;
}

// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsLeft(char *ptr) {
  ptr[-1] = kMagicValue;
}

// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
  ptr[size] = kMagicValue;
}

void MakeSomeErrors(char *ptr, size_t size) {
  ReadUninitializedValue(ptr);
  ReadValueOutOfArrayBoundsLeft(ptr);
  ReadValueOutOfArrayBoundsRight(ptr, size);
  WriteValueOutOfArrayBoundsLeft(ptr);
  WriteValueOutOfArrayBoundsRight(ptr, size);
}

}  // namespace

// A memory leak detector should report an error in this test.
TEST(ToolsSanityTest, MemoryLeak) {
  int *leak = new int[256];  // Leak some memory intentionally.
  leak[4] = 1;  // Make sure the allocated memory is used.
}

TEST(ToolsSanityTest, AccessesToNewMemory) {
  // This test may corrupt memory if not run under Valgrind.
  if (!RunningOnValgrind())
    return;

  char *foo = new char[10];
  MakeSomeErrors(foo, 10);
  delete [] foo;
  foo[5] = 0;  // Use after delete. This won't break anything under Valgrind.
}

TEST(ToolsSanityTest, AccessesToMallocMemory) {
  // This test may corrupt memory if not run under Valgrind.
  if (!RunningOnValgrind())
    return;
  char *foo = reinterpret_cast<char*>(malloc(10));
  MakeSomeErrors(foo, 10);
  free(foo);
  foo[5] = 0;  // Use after free. This won't break anything under Valgrind.
}

TEST(ToolsSanityTest, ArrayDeletedWithoutBraces) {
  // This test may corrupt memory if not run under Valgrind.
  if (!RunningOnValgrind())
    return;

  // Without the |volatile|, clang optimizes away the next two lines.
  int* volatile foo = new int[10];
  delete foo;
}

TEST(ToolsSanityTest, SingleElementDeletedWithBraces) {
  // This test may corrupt memory if not run under Valgrind.
  if (!RunningOnValgrind())
    return;

  // Without the |volatile|, clang optimizes away the next two lines.
  int* volatile foo = new int;
  (void) foo;
  delete [] foo;
}

namespace {

// We use caps here just to ensure that the method name doesn't interfere with
// the wildcarded suppressions.
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
 public:
  explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
  ~TOOLS_SANITY_TEST_CONCURRENT_THREAD() {}
  void ThreadMain() {
    *value_ = true;

    // Sleep for a few milliseconds so the two threads are more likely to live
    // simultaneously. Otherwise we may miss the report due to mutex
    // lock/unlock's inside thread creation code in pure-happens-before mode...
    PlatformThread::Sleep(100);
  }
 private:
  bool *value_;
};

class ReleaseStoreThread : public PlatformThread::Delegate {
 public:
  explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {}
  ~ReleaseStoreThread() {}
  void ThreadMain() {
    base::subtle::Release_Store(value_, kMagicValue);

    // Sleep for a few milliseconds so the two threads are more likely to live
    // simultaneously. Otherwise we may miss the report due to mutex
    // lock/unlock's inside thread creation code in pure-happens-before mode...
    PlatformThread::Sleep(100);
  }
 private:
  base::subtle::Atomic32 *value_;
};

class AcquireLoadThread : public PlatformThread::Delegate {
 public:
  explicit AcquireLoadThread(base::subtle::Atomic32 *value) : value_(value) {}
  ~AcquireLoadThread() {}
  void ThreadMain() {
    // Wait for the other thread to make Release_Store
    PlatformThread::Sleep(100);
    base::subtle::Acquire_Load(value_);
  }
 private:
  base::subtle::Atomic32 *value_;
};

void RunInParallel(PlatformThread::Delegate *d1, PlatformThread::Delegate *d2) {
  PlatformThreadHandle a;
  PlatformThreadHandle b;
  PlatformThread::Create(0, d1, &a);
  PlatformThread::Create(0, d2, &b);
  PlatformThread::Join(a);
  PlatformThread::Join(b);
}

}  // namespace

// A data race detector should report an error in this test.
TEST(ToolsSanityTest, DataRace) {
  bool shared = false;
  TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
  RunInParallel(&thread1, &thread2);
  EXPECT_TRUE(shared);
}

TEST(ToolsSanityTest, AnnotateBenignRace) {
  bool shared = false;
  ANNOTATE_BENIGN_RACE(&shared, "Intentional race - make sure doesn't show up");
  TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
  RunInParallel(&thread1, &thread2);
  EXPECT_TRUE(shared);
}

TEST(ToolsSanityTest, AtomicsAreIgnored) {
  base::subtle::Atomic32 shared = 0;
  ReleaseStoreThread thread1(&shared);
  AcquireLoadThread thread2(&shared);
  RunInParallel(&thread1, &thread2);
  EXPECT_EQ(kMagicValue, shared);
}

}  // namespace base
<commit_msg>Actually run the sanity tests under AddressSanitizer. Review URL: http://codereview.chromium.org/8116028<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file contains intentional memory errors, some of which may lead to
// crashes if the test is ran without special memory testing tools. We use these
// errors to verify the sanity of the tools.

#include "base/atomicops.h"
#include "base/message_loop.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {

namespace {

const base::subtle::Atomic32 kMagicValue = 42;

// Helper for memory accesses that can potentially corrupt memory or cause a
// crash during a native run.
#ifdef ADDRESS_SANITIZER
#define HARMFUL_ACCESS(action,error_regexp) EXPECT_DEATH(action,error_regexp)
#else
#define HARMFUL_ACCESS(action,error_regexp) \
do { if (RunningOnValgrind()) { action; } } while (0)
#endif

void ReadUninitializedValue(char *ptr) {
  // The || in the conditional is to prevent clang from optimizing away the
  // jump -- valgrind only catches jumps and conditional moves, but clang uses
  // the borrow flag if the condition is just `*ptr == '\0'`.
  if (*ptr == '\0' || *ptr == 64) {
    (*ptr)++;
  } else {
    (*ptr)--;
  }
}

void ReadValueOutOfArrayBoundsLeft(char *ptr) {
  char c = ptr[-2];
  VLOG(1) << "Reading a byte out of bounds: " << c;
}

void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
  char c = ptr[size + 1];
  VLOG(1) << "Reading a byte out of bounds: " << c;
}

// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsLeft(char *ptr) {
  ptr[-1] = kMagicValue;
}

// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
  ptr[size] = kMagicValue;
}

void MakeSomeErrors(char *ptr, size_t size) {
  ReadUninitializedValue(ptr);
  HARMFUL_ACCESS(ReadValueOutOfArrayBoundsLeft(ptr),
                 "heap-buffer-overflow.*2 bytes to the left");
  HARMFUL_ACCESS(ReadValueOutOfArrayBoundsRight(ptr, size),
                 "heap-buffer-overflow.*1 bytes to the right");
  HARMFUL_ACCESS(WriteValueOutOfArrayBoundsLeft(ptr),
                 "heap-buffer-overflow.*1 bytes to the left");
  HARMFUL_ACCESS(WriteValueOutOfArrayBoundsRight(ptr, size),
                 "heap-buffer-overflow.*0 bytes to the right");
}

}  // namespace

// A memory leak detector should report an error in this test.
TEST(ToolsSanityTest, MemoryLeak) {
  int *leak = new int[256];  // Leak some memory intentionally.
  leak[4] = 1;  // Make sure the allocated memory is used.
}

TEST(ToolsSanityTest, AccessesToNewMemory) {
  char *foo = new char[10];
  MakeSomeErrors(foo, 10);
  delete [] foo;
  // Use after delete.
  HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
}

TEST(ToolsSanityTest, AccessesToMallocMemory) {
  char *foo = reinterpret_cast<char*>(malloc(10));
  MakeSomeErrors(foo, 10);
  free(foo);
  // Use after free.
  HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
}

TEST(ToolsSanityTest, ArrayDeletedWithoutBraces) {
#ifndef ADDRESS_SANITIZER
  // This test may corrupt memory if not run under Valgrind or compiled with
  // AddressSanitizer.
  if (!RunningOnValgrind())
    return;
#endif

  // Without the |volatile|, clang optimizes away the next two lines.
  int* volatile foo = new int[10];
  delete foo;
}

TEST(ToolsSanityTest, SingleElementDeletedWithBraces) {
#ifndef ADDRESS_SANITIZER
  // This test may corrupt memory if not run under Valgrind or compiled with
  // AddressSanitizer.
  if (!RunningOnValgrind())
    return;
#endif

  // Without the |volatile|, clang optimizes away the next two lines.
  int* volatile foo = new int;
  (void) foo;
  delete [] foo;
}

namespace {

// We use caps here just to ensure that the method name doesn't interfere with
// the wildcarded suppressions.
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
 public:
  explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
  ~TOOLS_SANITY_TEST_CONCURRENT_THREAD() {}
  void ThreadMain() {
    *value_ = true;

    // Sleep for a few milliseconds so the two threads are more likely to live
    // simultaneously. Otherwise we may miss the report due to mutex
    // lock/unlock's inside thread creation code in pure-happens-before mode...
    PlatformThread::Sleep(100);
  }
 private:
  bool *value_;
};

class ReleaseStoreThread : public PlatformThread::Delegate {
 public:
  explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {}
  ~ReleaseStoreThread() {}
  void ThreadMain() {
    base::subtle::Release_Store(value_, kMagicValue);

    // Sleep for a few milliseconds so the two threads are more likely to live
    // simultaneously. Otherwise we may miss the report due to mutex
    // lock/unlock's inside thread creation code in pure-happens-before mode...
    PlatformThread::Sleep(100);
  }
 private:
  base::subtle::Atomic32 *value_;
};

class AcquireLoadThread : public PlatformThread::Delegate {
 public:
  explicit AcquireLoadThread(base::subtle::Atomic32 *value) : value_(value) {}
  ~AcquireLoadThread() {}
  void ThreadMain() {
    // Wait for the other thread to make Release_Store
    PlatformThread::Sleep(100);
    base::subtle::Acquire_Load(value_);
  }
 private:
  base::subtle::Atomic32 *value_;
};

void RunInParallel(PlatformThread::Delegate *d1, PlatformThread::Delegate *d2) {
  PlatformThreadHandle a;
  PlatformThreadHandle b;
  PlatformThread::Create(0, d1, &a);
  PlatformThread::Create(0, d2, &b);
  PlatformThread::Join(a);
  PlatformThread::Join(b);
}

}  // namespace

// A data race detector should report an error in this test.
TEST(ToolsSanityTest, DataRace) {
  bool shared = false;
  TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
  RunInParallel(&thread1, &thread2);
  EXPECT_TRUE(shared);
}

TEST(ToolsSanityTest, AnnotateBenignRace) {
  bool shared = false;
  ANNOTATE_BENIGN_RACE(&shared, "Intentional race - make sure doesn't show up");
  TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
  RunInParallel(&thread1, &thread2);
  EXPECT_TRUE(shared);
}

TEST(ToolsSanityTest, AtomicsAreIgnored) {
  base::subtle::Atomic32 shared = 0;
  ReleaseStoreThread thread1(&shared);
  AcquireLoadThread thread2(&shared);
  RunInParallel(&thread1, &thread2);
  EXPECT_EQ(kMagicValue, shared);
}

}  // namespace base
<|endoftext|>


<commit_before>//  Author:Frankie.Chu
//  Date:9 April,2012
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
//
//  Modified record:
//
/*******************************************************************************/
#include "TM1637.h"
#include <inttypes.h>
#include "../wiring/wiring.h"
static int8_t TubeTab[] = {0x3f,0x06,0x5b,0x4f,
                           0x66,0x6d,0x7d,0x07,
                           0x7f,0x6f,0x77,0x7c,
                           0x39,0x5e,0x79,0x71};//0~9,A,b,C,d,E,F
TM1637::TM1637(uint8_t Clk, uint8_t Data)
{
  Clkpin = Clk;
  Datapin = Data;
  pinMode(Clkpin,OUTPUT);
  pinMode(Datapin,OUTPUT);
}

void TM1637::init(void)
{
  clearDisplay();
}

void TM1637::writeByte(int8_t wr_data)
{
  uint8_t i,count1;
  for(i=0;i<8;i++)        //sent 8bit data
  {
    digitalWrite(Clkpin,LOW);
    if(wr_data & 0x01)digitalWrite(Datapin,HIGH);//LSB first
    else digitalWrite(Datapin,LOW);
    wr_data >>= 1;
    digitalWrite(Clkpin,HIGH);

  }
  digitalWrite(Clkpin,LOW); //wait for the ACK
  digitalWrite(Datapin,HIGH);
  digitalWrite(Clkpin,HIGH);
  pinMode(Datapin,INPUT);
  while(digitalRead(Datapin))
  {
    count1 +=1;
    if(count1 == 200)//
    {
     pinMode(Datapin,OUTPUT);
     digitalWrite(Datapin,LOW);
     count1 =0;
    }
    pinMode(Datapin,INPUT);
  }
  pinMode(Datapin,OUTPUT);

}
//send start signal to TM1637
void TM1637::start(void)
{
  digitalWrite(Clkpin,HIGH);//send start signal to TM1637
  digitalWrite(Datapin,HIGH);
  digitalWrite(Datapin,LOW);
  digitalWrite(Clkpin,LOW);
}
//End of transmission
void TM1637::stop(void)
{
  digitalWrite(Clkpin,LOW);
  digitalWrite(Datapin,LOW);
  digitalWrite(Clkpin,HIGH);
  digitalWrite(Datapin,HIGH);
}
//display function.Write to full-screen.
void TM1637::display(int8_t DispData[])
{
  int8_t SegData[4];
  uint8_t i;
  for(i = 0;i < 4;i ++)
  {
    SegData[i] = DispData[i];
  }
  coding(SegData);
  start();          //start signal sent to TM1637 from MCU
  writeByte(ADDR_AUTO);//
  stop();           //
  start();          //
  writeByte(Cmd_SetAddr);//
  for(i=0;i < 4;i ++)
  {
    writeByte(SegData[i]);        //
  }
  stop();           //
  start();          //
  writeByte(Cmd_DispCtrl);//
  stop();           //
}
//******************************************
void TM1637::display(uint8_t BitAddr,int8_t DispData)
{
  int8_t SegData;
  SegData = coding(DispData);
  start();          //start signal sent to TM1637 from MCU
  writeByte(ADDR_FIXED);//
  stop();           //
  start();          //
  writeByte(BitAddr|0xc0);//
  writeByte(SegData);//
  stop();            //
  start();          //
  writeByte(Cmd_DispCtrl);//
  stop();           //
}

void TM1637::clearDisplay(void)
{
  display(0x00,0x7f);
  display(0x01,0x7f);
  display(0x02,0x7f);
  display(0x03,0x7f);
}
//To take effect the next time it displays.
void TM1637::set(uint8_t brightness,uint8_t SetData,uint8_t SetAddr)
{
  Cmd_SetData = SetData;
  Cmd_SetAddr = SetAddr;
  Cmd_DispCtrl = 0x88 + brightness;//Set the brightness and it takes effect the next time it displays.
}

//Whether to light the clock point ":".
//To take effect the next time it displays.
void TM1637::point(boolean PointFlag)
{
  _PointFlag = PointFlag;
}
void TM1637::coding(int8_t DispData[])
{
  uint8_t PointData;
  if(_PointFlag == POINT_ON)PointData = 0x80;
  else PointData = 0;
  for(uint8_t i = 0;i < 4;i ++)
  {
    if(DispData[i] == 0x7f)DispData[i] = 0x00;
    else DispData[i] = TubeTab[DispData[i]] + PointData;
  }
}
int8_t TM1637::coding(int8_t DispData)
{
  uint8_t PointData;
  if(_PointFlag == POINT_ON)PointData = 0x80;
  else PointData = 0;
  if(DispData == 0x7f) DispData = 0x00 + PointData;//The bit digital tube off
  else DispData = TubeTab[DispData] + PointData;
  return DispData;
}
<commit_msg>Update TM1637.cpp<commit_after>//  Author:Frankie.Chu
//  Date:9 April,2012
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
//
//  Modified record:
//
/*******************************************************************************/
#include "TM1637.h"
#include <inttypes.h>
#include "../wiring/wiring.h"
static int8_t TubeTab[] = {0x3f,0x06,0x5b,0x4f,
                           0x66,0x6d,0x7d,0x07,
                           0x7f,0x6f,0x77,0x7c,
                           0x39,0x5e,0x79,0x71};//0~9,A,b,C,d,E,F
TM1637::TM1637(uint8_t Clk, uint8_t Data)
{
  Clkpin = Clk;
  Datapin = Data;
  pinMode(Clkpin,OUTPUT);
  pinMode(Datapin,OUTPUT);
}

void TM1637::init(void)
{
  clearDisplay();
}

void TM1637::writeByte(int8_t wr_data)
{
  uint8_t i,count1;
  for(i=0;i<8;i++)        //sent 8bit data
  {
    digitalWrite(Clkpin,LOW);
    if(wr_data & 0x01)digitalWrite(Datapin,HIGH);//LSB first
    else digitalWrite(Datapin,LOW);
    wr_data >>= 1;
    digitalWrite(Clkpin,HIGH);

  }
  digitalWrite(Clkpin,LOW); //wait for the ACK
  digitalWrite(Datapin,HIGH);
  digitalWrite(Clkpin,HIGH);
  pinMode(Datapin,INPUT);
  while(digitalRead(Datapin))
  {
    count1 +=1;
    if(count1 == 200)//
    {
     pinMode(Datapin,OUTPUT);
     digitalWrite(Datapin,LOW);
     count1 =0;
    }
    pinMode(Datapin,INPUT);
  }
  pinMode(Datapin,OUTPUT);

}
//send start signal to TM1637
void TM1637::start(void)
{
  digitalWrite(Clkpin,HIGH);//send start signal to TM1637
  digitalWrite(Datapin,HIGH);
  digitalWrite(Datapin,LOW);
  digitalWrite(Clkpin,LOW);
}
//End of transmission
void TM1637::stop(void)
{
  digitalWrite(Clkpin,LOW);
  digitalWrite(Datapin,LOW);
  digitalWrite(Clkpin,HIGH);
  digitalWrite(Datapin,HIGH);
}
//display function.Write to full-screen.
void TM1637::display(int8_t DispData[])
{
  int8_t SegData[4];
  uint8_t i;
  for(i = 0;i < 4;i ++)
  {
    SegData[i] = DispData[i];
  }
  coding(SegData);
  start();          //start signal sent to TM1637 from MCU
  writeByte(ADDR_AUTO);//
  stop();           //
  start();          //
  writeByte(Cmd_SetAddr);//
  for(i=0;i < 4;i ++)
  {
    writeByte(SegData[i]);        //
  }
  stop();           //
  start();          //
  writeByte(Cmd_DispCtrl);//
  stop();           //
}
//******************************************
void TM1637::display(uint8_t BitAddr,int8_t DispData)
{
  int8_t SegData;
  SegData = coding(DispData);
  start();          //start signal sent to TM1637 from MCU
  writeByte(ADDR_FIXED);//
  stop();           //
  start();          //
  writeByte(BitAddr|0xc0);//
  writeByte(SegData);//
  stop();            //
  start();          //
  writeByte(Cmd_DispCtrl);//
  stop();           //
}

void TM1637::clearDisplay(void)
{
  display(0x00,0x7f);
  display(0x01,0x7f);
  display(0x02,0x7f);
  display(0x03,0x7f);
}
//To take effect the next time it displays.
void TM1637::set(uint8_t brightness,uint8_t SetData,uint8_t SetAddr)
{
  Cmd_SetData = SetData;
  Cmd_SetAddr = SetAddr;
  Cmd_DispCtrl = 0x88 + brightness;//Set the brightness and it takes effect the next time it displays.
}

//Whether to light the clock point ":".
//To take effect the next time it displays.
void TM1637::point(bool PointFlag)
{
  _PointFlag = PointFlag;
}
void TM1637::coding(int8_t DispData[])
{
  uint8_t PointData;
  if(_PointFlag == POINT_ON)PointData = 0x80;
  else PointData = 0;
  for(uint8_t i = 0;i < 4;i ++)
  {
    if(DispData[i] == 0x7f)DispData[i] = 0x00;
    else DispData[i] = TubeTab[DispData[i]] + PointData;
  }
}
int8_t TM1637::coding(int8_t DispData)
{
  uint8_t PointData;
  if(_PointFlag == POINT_ON)PointData = 0x80;
  else PointData = 0;
  if(DispData == 0x7f) DispData = 0x00 + PointData;//The bit digital tube off
  else DispData = TubeTab[DispData] + PointData;
  return DispData;
}
<|endoftext|>


<commit_before>// zlib
#include <zlib.h>

// std
#include <stdexcept>

namespace mapnik
{

namespace vector_tile_impl
{

// decodes both zlib and gzip
// http://stackoverflow.com/a/1838702/2333354
void zlib_decompress(const char * data, std::size_t size, std::string & output)
{
    z_stream inflate_s;
    inflate_s.zalloc = Z_NULL;
    inflate_s.zfree = Z_NULL;
    inflate_s.opaque = Z_NULL;
    inflate_s.avail_in = 0;
    inflate_s.next_in = Z_NULL;
    inflateInit2(&inflate_s, 32 + 15);
    inflate_s.next_in = (Bytef *)data;
    inflate_s.avail_in = size;
    size_t length = 0;
    do {
        output.resize(length + 2 * size);
        inflate_s.avail_out = 2 * size;
        inflate_s.next_out = (Bytef *)(output.data() + length);
        int ret = inflate(&inflate_s, Z_FINISH);
        if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR)
        {
            inflateEnd(&inflate_s);
            throw std::runtime_error(inflate_s.msg);
        }

        length += (2 * size - inflate_s.avail_out);
    } while (inflate_s.avail_out == 0);
    inflateEnd(&inflate_s);
    output.resize(length);
}

void zlib_decompress(std::string const& input, std::string & output)
{
    zlib_decompress(input.data(),input.size(),output);
}

void zlib_compress(const char * data, std::size_t size, std::string & output, bool gzip, int level, int strategy)
{
    z_stream deflate_s;
    deflate_s.zalloc = Z_NULL;
    deflate_s.zfree = Z_NULL;
    deflate_s.opaque = Z_NULL;
    deflate_s.avail_in = 0;
    deflate_s.next_in = Z_NULL;
    int windowsBits = 15;
    if (gzip)
    {
        windowsBits = windowsBits | 16;
    }
    if (deflateInit2(&deflate_s, level, Z_DEFLATED, windowsBits, 8, strategy) != Z_OK)
    {
        deflateEnd(&deflate_s);
        throw std::runtime_error("deflate init failed");
    }
    deflate_s.next_in = (Bytef *)data;
    deflate_s.avail_in = size;
    size_t length = 0;
    do {
        size_t increase = size / 2 + 1024;
        output.resize(length + increase);
        deflate_s.avail_out = increase;
        deflate_s.next_out = (Bytef *)(output.data() + length);
        // From http://www.zlib.net/zlib_how.html
        // "deflate() has a return value that can indicate errors, yet we do not check it here.
        // Why not? Well, it turns out that deflate() can do no wrong here."
        // Basically only possible error is from deflateInit not working properly
        deflate(&deflate_s, Z_FINISH);
        length += (increase - deflate_s.avail_out);
    } while (deflate_s.avail_out == 0);
    deflateEnd(&deflate_s);
    output.resize(length);
}

void zlib_compress(std::string const& input, std::string & output, bool gzip, int level, int strategy)
{
    zlib_compress(input.data(),input.size(),output,gzip,level,strategy);
}

} // end ns vector_tile_impl

} // end ns mapnik
<commit_msg>Remove possible invalidated memory situation<commit_after>// zlib
#include <zlib.h>

// std
#include <stdexcept>

namespace mapnik
{

namespace vector_tile_impl
{

// decodes both zlib and gzip
// http://stackoverflow.com/a/1838702/2333354
void zlib_decompress(const char * data, std::size_t size, std::string & output)
{
    z_stream inflate_s;
    inflate_s.zalloc = Z_NULL;
    inflate_s.zfree = Z_NULL;
    inflate_s.opaque = Z_NULL;
    inflate_s.avail_in = 0;
    inflate_s.next_in = Z_NULL;
    inflateInit2(&inflate_s, 32 + 15);
    inflate_s.next_in = (Bytef *)data;
    inflate_s.avail_in = size;
    size_t length = 0;
    do {
        output.resize(length + 2 * size);
        inflate_s.avail_out = 2 * size;
        inflate_s.next_out = (Bytef *)(output.data() + length);
        int ret = inflate(&inflate_s, Z_FINISH);
        if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR)
        {
            std::string error_msg = inflate_s.msg;
            inflateEnd(&inflate_s);
            throw std::runtime_error(error_msg);
        }

        length += (2 * size - inflate_s.avail_out);
    } while (inflate_s.avail_out == 0);
    inflateEnd(&inflate_s);
    output.resize(length);
}

void zlib_decompress(std::string const& input, std::string & output)
{
    zlib_decompress(input.data(),input.size(),output);
}

void zlib_compress(const char * data, std::size_t size, std::string & output, bool gzip, int level, int strategy)
{
    z_stream deflate_s;
    deflate_s.zalloc = Z_NULL;
    deflate_s.zfree = Z_NULL;
    deflate_s.opaque = Z_NULL;
    deflate_s.avail_in = 0;
    deflate_s.next_in = Z_NULL;
    int windowsBits = 15;
    if (gzip)
    {
        windowsBits = windowsBits | 16;
    }
    if (deflateInit2(&deflate_s, level, Z_DEFLATED, windowsBits, 8, strategy) != Z_OK)
    {
        deflateEnd(&deflate_s);
        throw std::runtime_error("deflate init failed");
    }
    deflate_s.next_in = (Bytef *)data;
    deflate_s.avail_in = size;
    size_t length = 0;
    do {
        size_t increase = size / 2 + 1024;
        output.resize(length + increase);
        deflate_s.avail_out = increase;
        deflate_s.next_out = (Bytef *)(output.data() + length);
        // From http://www.zlib.net/zlib_how.html
        // "deflate() has a return value that can indicate errors, yet we do not check it here.
        // Why not? Well, it turns out that deflate() can do no wrong here."
        // Basically only possible error is from deflateInit not working properly
        deflate(&deflate_s, Z_FINISH);
        length += (increase - deflate_s.avail_out);
    } while (deflate_s.avail_out == 0);
    deflateEnd(&deflate_s);
    output.resize(length);
}

void zlib_compress(std::string const& input, std::string & output, bool gzip, int level, int strategy)
{
    zlib_compress(input.data(),input.size(),output,gzip,level,strategy);
}

} // end ns vector_tile_impl

} // end ns mapnik
<|endoftext|>


<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2007. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <libtorrent/extensions.hpp>
#include <libtorrent/entry.hpp>
#include <libtorrent/peer_request.hpp>
#include <libtorrent/peer_connection.hpp>
#include <libtorrent/extensions/ut_pex.hpp>
#include <libtorrent/extensions/metadata_transfer.hpp>
#include <boost/python.hpp>
#include "gil.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{

  struct torrent_plugin_wrap : torrent_plugin, wrapper<torrent_plugin>
  {
      boost::shared_ptr<peer_plugin> new_connection(peer_connection* p)
      {
          lock_gil lock;

          if (override f = this->get_override("new_connection"))
              return f(ptr(p));
          return torrent_plugin::new_connection(p);
      }

      boost::shared_ptr<peer_plugin> default_new_connection(peer_connection* p)
      {
          return this->torrent_plugin::new_connection(p);
      }

      void on_piece_pass(int index)
      {
          lock_gil lock;

          if (override f = this->get_override("on_piece_pass"))
              f(index);
          else
            torrent_plugin::on_piece_pass(index);
      }

      void default_on_piece_pass(int index)
      {
          this->torrent_plugin::on_piece_pass(index);
      }

      void on_piece_failed(int index)
      {
          lock_gil lock;

          if (override f = this->get_override("on_piece_failed"))
              f(index);
          else
              torrent_plugin::on_piece_failed(index);
      }

      void default_on_piece_failed(int index)
      {
          return this->torrent_plugin::on_piece_failed(index);
      }

      void tick()
      {
          lock_gil lock;

          if (override f = this->get_override("tick"))
              f();
          else
              torrent_plugin::tick();
      }

      void default_tick()
      {
          return this->torrent_plugin::tick();
      }

      bool on_pause()
      {
          lock_gil lock;

          if (override f = this->get_override("on_pause"))
              return f();
          return torrent_plugin::on_pause();
      }

      bool default_on_pause()
      {
          return this->torrent_plugin::on_pause();
      }

      bool on_resume()
      {
          lock_gil lock;

          if (override f = this->get_override("on_resume"))
              return f();
          return torrent_plugin::on_resume();
      }

      bool default_on_resume()
      {
          return this->torrent_plugin::on_resume();
      }
  };

} // namespace unnamed

boost::shared_ptr<torrent_plugin> create_metadata_plugin_wrapper(torrent* t) {
    return create_metadata_plugin(t, NULL);
}

boost::shared_ptr<torrent_plugin> create_ut_pex_plugin_wrapper(torrent* t) {
    return create_ut_pex_plugin(t, NULL);
}

void bind_extensions()
{
    class_<
        torrent_plugin_wrap, boost::shared_ptr<torrent_plugin_wrap>, boost::noncopyable
    >("torrent_plugin")
        .def(
            "new_connection"
          , &torrent_plugin::new_connection, &torrent_plugin_wrap::default_new_connection
        )
        .def(
            "on_piece_pass"
          , &torrent_plugin::on_piece_pass, &torrent_plugin_wrap::default_on_piece_pass
        )
        .def(
            "on_piece_failed"
          , &torrent_plugin::on_piece_failed, &torrent_plugin_wrap::default_on_piece_failed
        )
        .def(
            "tick"
          , &torrent_plugin::tick, &torrent_plugin_wrap::default_tick
        )
        .def(
            "on_pause"
          , &torrent_plugin::on_pause, &torrent_plugin_wrap::default_on_pause
        )
        .def(
            "on_resume"
          , &torrent_plugin::on_resume, &torrent_plugin_wrap::default_on_resume
        );

    // TODO move to it's own file
    class_<peer_connection, boost::noncopyable>("peer_connection", no_init);

    class_<torrent_plugin, boost::shared_ptr<torrent_plugin> >("torrent_plugin", no_init);
    def("create_ut_pex_plugin", create_ut_pex_plugin_wrapper);
    def("create_metadata_plugin", create_metadata_plugin_wrapper);
}

<commit_msg>Add create_ut_metadata_plugin() to bindings<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2007. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <libtorrent/extensions.hpp>
#include <libtorrent/entry.hpp>
#include <libtorrent/peer_request.hpp>
#include <libtorrent/peer_connection.hpp>
#include <libtorrent/extensions/ut_pex.hpp>
#include <libtorrent/extensions/metadata_transfer.hpp>
#include <libtorrent/extensions/ut_metadata.hpp>
#include <boost/python.hpp>
#include "gil.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{

  struct torrent_plugin_wrap : torrent_plugin, wrapper<torrent_plugin>
  {
      boost::shared_ptr<peer_plugin> new_connection(peer_connection* p)
      {
          lock_gil lock;

          if (override f = this->get_override("new_connection"))
              return f(ptr(p));
          return torrent_plugin::new_connection(p);
      }

      boost::shared_ptr<peer_plugin> default_new_connection(peer_connection* p)
      {
          return this->torrent_plugin::new_connection(p);
      }

      void on_piece_pass(int index)
      {
          lock_gil lock;

          if (override f = this->get_override("on_piece_pass"))
              f(index);
          else
            torrent_plugin::on_piece_pass(index);
      }

      void default_on_piece_pass(int index)
      {
          this->torrent_plugin::on_piece_pass(index);
      }

      void on_piece_failed(int index)
      {
          lock_gil lock;

          if (override f = this->get_override("on_piece_failed"))
              f(index);
          else
              torrent_plugin::on_piece_failed(index);
      }

      void default_on_piece_failed(int index)
      {
          return this->torrent_plugin::on_piece_failed(index);
      }

      void tick()
      {
          lock_gil lock;

          if (override f = this->get_override("tick"))
              f();
          else
              torrent_plugin::tick();
      }

      void default_tick()
      {
          return this->torrent_plugin::tick();
      }

      bool on_pause()
      {
          lock_gil lock;

          if (override f = this->get_override("on_pause"))
              return f();
          return torrent_plugin::on_pause();
      }

      bool default_on_pause()
      {
          return this->torrent_plugin::on_pause();
      }

      bool on_resume()
      {
          lock_gil lock;

          if (override f = this->get_override("on_resume"))
              return f();
          return torrent_plugin::on_resume();
      }

      bool default_on_resume()
      {
          return this->torrent_plugin::on_resume();
      }
  };

} // namespace unnamed

boost::shared_ptr<torrent_plugin> create_metadata_plugin_wrapper(torrent* t) {
    return create_metadata_plugin(t, NULL);
}

boost::shared_ptr<torrent_plugin> create_ut_metadata_plugin_wrapper(torrent *t) {
    return create_ut_metadata_plugin(t, NULL);
}

boost::shared_ptr<torrent_plugin> create_ut_pex_plugin_wrapper(torrent* t) {
    return create_ut_pex_plugin(t, NULL);
}

void bind_extensions()
{
    class_<
        torrent_plugin_wrap, boost::shared_ptr<torrent_plugin_wrap>, boost::noncopyable
    >("torrent_plugin")
        .def(
            "new_connection"
          , &torrent_plugin::new_connection, &torrent_plugin_wrap::default_new_connection
        )
        .def(
            "on_piece_pass"
          , &torrent_plugin::on_piece_pass, &torrent_plugin_wrap::default_on_piece_pass
        )
        .def(
            "on_piece_failed"
          , &torrent_plugin::on_piece_failed, &torrent_plugin_wrap::default_on_piece_failed
        )
        .def(
            "tick"
          , &torrent_plugin::tick, &torrent_plugin_wrap::default_tick
        )
        .def(
            "on_pause"
          , &torrent_plugin::on_pause, &torrent_plugin_wrap::default_on_pause
        )
        .def(
            "on_resume"
          , &torrent_plugin::on_resume, &torrent_plugin_wrap::default_on_resume
        );

    // TODO move to it's own file
    class_<peer_connection, boost::noncopyable>("peer_connection", no_init);

    class_<torrent_plugin, boost::shared_ptr<torrent_plugin> >("torrent_plugin", no_init);
    def("create_ut_pex_plugin", create_ut_pex_plugin_wrapper);
    def("create_metadata_plugin", create_metadata_plugin_wrapper);
    def("create_ut_metadata_plugin", create_ut_metadata_plugin_wrapper);
}

<|endoftext|>


<commit_before>/*
* This is the main cpp file for cPlusPlusPlusLib
* cPPPLib - A library of functions that should be in the C++ Standard Library
* (C) - Charles Machalow - MIT License
*/

#ifndef cPPPLib_CPP
#define cPPPLib_CPP

#include "cPPPLib.h"

/// <summary>
/// Splits the original_str into a std::vector by delimiter
/// </summary>
/// <param name="original_str">The original_str.</param>
/// <param name="delim">The delimiter.</param>
/// <returns></returns>
std::vector<std::string> StringFunctions::splitIntoVector(const std::string &original_str, const std::string &delim)
{
	std::string working_str = original_str;
	std::vector<std::string> ret_vec;

	while (!working_str.empty())
	{
		unsigned int loc = working_str.find(delim);
		// found in string
		if (loc != std::string::npos)
		{
			ret_vec.push_back(working_str.substr(0, loc));
			working_str = working_str.substr(loc + 1);
		}
		else
		{
			ret_vec.push_back(working_str);
			break;
		}
	}

	return ret_vec;
}

/// <summary>
/// Splits the original_str into a std::vector by whitespace.
/// </summary>
/// <param name="original_str">The original_str.</param>
/// <returns></returns>
std::vector<std::string> StringFunctions::splitIntoVectorByWhitespace(const std::string &original_str)
{
	std::string working_str = original_str;
	std::vector<std::string> ret_vec;

	while (!working_str.empty())
	{
		unsigned int loc = working_str.find(" ");
		// found in string
		if (loc != std::string::npos)
		{
			if (working_str.substr(0, loc) != "")
			{
				ret_vec.push_back(working_str.substr(0, loc));
			}
			working_str = working_str.substr(loc + 1);
		}
		else
		{
			if (working_str != "")
			{
				ret_vec.push_back(working_str);
			}
			break;
		}
	}

	return ret_vec;
}

int main()
{
	std::cout << "cPlusPlusPlusLib Version " << cPPPLib_H::cPPPLib_V << std::endl << "(C) - Charles Machalow - MIT License" << std::endl;

	std::string t = "a";
	std::vector<std::string> tmp = StringFunctions::splitIntoVectorByWhitespace("     ");

	system("PAUSE");
	return 1;
}

#endif cPPPLib_CPP<commit_msg>Add returns documentation to existing functions.<commit_after>/*
* This is the main cpp file for cPlusPlusPlusLib
* cPPPLib - A library of functions that should be in the C++ Standard Library
* (C) - Charles Machalow - MIT License
*/

#ifndef cPPPLib_CPP
#define cPPPLib_CPP

#include "cPPPLib.h"

/// <summary>
/// Splits the original_str into a std::vector by delimiter
/// </summary>
/// <param name="original_str">The original_str.</param>
/// <param name="delim">The delimiter.</param>
/// <returns>std::vector<string> where each item is a string that has been delimited</returns>
std::vector<std::string> StringFunctions::splitIntoVector(const std::string &original_str, const std::string &delim)
{
	std::string working_str = original_str;
	std::vector<std::string> ret_vec;

	while (!working_str.empty())
	{
		unsigned int loc = working_str.find(delim);
		// found in string
		if (loc != std::string::npos)
		{
			ret_vec.push_back(working_str.substr(0, loc));
			working_str = working_str.substr(loc + 1);
		}
		else
		{
			ret_vec.push_back(working_str);
			break;
		}
	}

	return ret_vec;
}

/// <summary>
/// Splits the original_str into a std::vector by whitespace.
/// </summary>
/// <param name="original_str">The original_str.</param>
/// <returns>std::vector<string> where each item is a string that has been delimited by whitespace</returns>
std::vector<std::string> StringFunctions::splitIntoVectorByWhitespace(const std::string &original_str)
{
	std::string working_str = original_str;
	std::vector<std::string> ret_vec;

	while (!working_str.empty())
	{
		unsigned int loc = working_str.find(" ");
		// found in string
		if (loc != std::string::npos)
		{
			if (working_str.substr(0, loc) != "")
			{
				ret_vec.push_back(working_str.substr(0, loc));
			}
			working_str = working_str.substr(loc + 1);
		}
		else
		{
			if (working_str != "")
			{
				ret_vec.push_back(working_str);
			}
			break;
		}
	}

	return ret_vec;
}

int main()
{
	std::cout << "cPlusPlusPlusLib Version " << cPPPLib_H::cPPPLib_V << std::endl << "(C) - Charles Machalow - MIT License" << std::endl;

	std::string t = "a";
	std::vector<std::string> tmp = StringFunctions::splitIntoVectorByWhitespace("     ");

	system("PAUSE");
	return 1;
}

#endif cPPPLib_CPP<|endoftext|>


<commit_before>#include "modules/temperature.hpp"

#include "drawtypes/label.hpp"
#include "drawtypes/ramp.hpp"
#include "utils/file.hpp"
#include "utils/math.hpp"
#include <cmath>

#include "modules/meta/base.inl"

POLYBAR_NS

namespace modules {
  template class module<temperature_module>;

  temperature_module::temperature_module(const bar_settings& bar, string name_)
      : timer_module<temperature_module>(bar, move(name_)) {
    m_zone = m_conf.get(name(), "thermal-zone", 0);
    m_path = m_conf.get(name(), "hwmon-path", ""s);
    m_tempwarn = m_conf.get(name(), "warn-temperature", 80);
    m_interval = m_conf.get<decltype(m_interval)>(name(), "interval", 1s);
    m_units = m_conf.get(name(), "units", m_units);

    if (m_path.empty()) {
      m_path = string_util::replace(PATH_TEMPERATURE_INFO, "%zone%", to_string(m_zone));
    }

    if (!file_util::exists(m_path)) {
      throw module_error("The file '" + m_path + "' does not exist");
    }

    m_formatter->add(DEFAULT_FORMAT, TAG_LABEL, {TAG_LABEL, TAG_RAMP});
    m_formatter->add(FORMAT_WARN, TAG_LABEL_WARN, {TAG_LABEL_WARN, TAG_RAMP});

    if (m_formatter->has(TAG_LABEL)) {
      m_label[temp_state::NORMAL] = load_optional_label(m_conf, name(), TAG_LABEL, "%temperature-c%");
    }
    if (m_formatter->has(TAG_LABEL_WARN)) {
      m_label[temp_state::WARN] = load_optional_label(m_conf, name(), TAG_LABEL_WARN, "%temperature-c%");
    }
    if (m_formatter->has(TAG_RAMP)) {
      m_ramp = load_ramp(m_conf, name(), TAG_RAMP);
    }

    // Deprecation warning for the %temperature% token
    if((m_label[temp_state::NORMAL] && m_label[temp_state::NORMAL]->has_token("%temperature%")) ||
        ((m_label[temp_state::WARN] && m_label[temp_state::WARN]->has_token("%temperature%")))) {
      m_log.warn("%s: The token `%%temperature%%` is deprecated, use `%%temperature-c%%` instead.", name());
    }
  }

  bool temperature_module::update() {
    m_temp = std::strtol(file_util::contents(m_path).c_str(), nullptr, 10) / 1000.0f + 0.5f;
    int m_temp_f = floor(((1.8 * m_temp) + 32) + 0.5);
    m_perc = math_util::cap(math_util::percentage(m_temp, 0, m_tempwarn), 0, 100);

    string temp_c_string = to_string(m_temp);
    string temp_f_string = to_string(m_temp_f);

    // Add units if `units = true` in config
    if(m_units) {
      temp_c_string += "°C";
      temp_f_string += "°F";
    }

    const auto replace_tokens = [&](label_t& label) {
      label->reset_tokens();
      label->replace_token("%temperature-f%", temp_f_string);
      label->replace_token("%temperature-c%", temp_c_string);

      // DEPRECATED: Will be removed in later release
      label->replace_token("%temperature%", temp_c_string);
    };

    if (m_label[temp_state::NORMAL]) {
      replace_tokens(m_label[temp_state::NORMAL]);
    }
    if (m_label[temp_state::WARN]) {
      replace_tokens(m_label[temp_state::WARN]);
    }

    return true;
  }

  string temperature_module::get_format() const {
    if (m_temp > m_tempwarn) {
      return FORMAT_WARN;
    } else {
      return DEFAULT_FORMAT;
    }
  }

  bool temperature_module::build(builder* builder, const string& tag) const {
    if (tag == TAG_LABEL) {
      builder->node(m_label.at(temp_state::NORMAL));
    } else if (tag == TAG_LABEL_WARN) {
      builder->node(m_label.at(temp_state::WARN));
    } else if (tag == TAG_RAMP) {
      builder->node(m_ramp->get_by_percentage(m_perc));
    } else {
      return false;
    }
    return true;
  }
}

POLYBAR_NS_END
<commit_msg>refactor(temperature): Do not use 'm_' prefix with local variable<commit_after>#include "modules/temperature.hpp"

#include "drawtypes/label.hpp"
#include "drawtypes/ramp.hpp"
#include "utils/file.hpp"
#include "utils/math.hpp"
#include <cmath>

#include "modules/meta/base.inl"

POLYBAR_NS

namespace modules {
  template class module<temperature_module>;

  temperature_module::temperature_module(const bar_settings& bar, string name_)
      : timer_module<temperature_module>(bar, move(name_)) {
    m_zone = m_conf.get(name(), "thermal-zone", 0);
    m_path = m_conf.get(name(), "hwmon-path", ""s);
    m_tempwarn = m_conf.get(name(), "warn-temperature", 80);
    m_interval = m_conf.get<decltype(m_interval)>(name(), "interval", 1s);
    m_units = m_conf.get(name(), "units", m_units);

    if (m_path.empty()) {
      m_path = string_util::replace(PATH_TEMPERATURE_INFO, "%zone%", to_string(m_zone));
    }

    if (!file_util::exists(m_path)) {
      throw module_error("The file '" + m_path + "' does not exist");
    }

    m_formatter->add(DEFAULT_FORMAT, TAG_LABEL, {TAG_LABEL, TAG_RAMP});
    m_formatter->add(FORMAT_WARN, TAG_LABEL_WARN, {TAG_LABEL_WARN, TAG_RAMP});

    if (m_formatter->has(TAG_LABEL)) {
      m_label[temp_state::NORMAL] = load_optional_label(m_conf, name(), TAG_LABEL, "%temperature-c%");
    }
    if (m_formatter->has(TAG_LABEL_WARN)) {
      m_label[temp_state::WARN] = load_optional_label(m_conf, name(), TAG_LABEL_WARN, "%temperature-c%");
    }
    if (m_formatter->has(TAG_RAMP)) {
      m_ramp = load_ramp(m_conf, name(), TAG_RAMP);
    }

    // Deprecation warning for the %temperature% token
    if((m_label[temp_state::NORMAL] && m_label[temp_state::NORMAL]->has_token("%temperature%")) ||
        ((m_label[temp_state::WARN] && m_label[temp_state::WARN]->has_token("%temperature%")))) {
      m_log.warn("%s: The token `%%temperature%%` is deprecated, use `%%temperature-c%%` instead.", name());
    }
  }

  bool temperature_module::update() {
    m_temp = std::strtol(file_util::contents(m_path).c_str(), nullptr, 10) / 1000.0f + 0.5f;
    int temp_f = floor(((1.8 * m_temp) + 32) + 0.5);
    m_perc = math_util::cap(math_util::percentage(m_temp, 0, m_tempwarn), 0, 100);

    string temp_c_string = to_string(m_temp);
    string temp_f_string = to_string(temp_f);

    // Add units if `units = true` in config
    if(m_units) {
      temp_c_string += "°C";
      temp_f_string += "°F";
    }

    const auto replace_tokens = [&](label_t& label) {
      label->reset_tokens();
      label->replace_token("%temperature-f%", temp_f_string);
      label->replace_token("%temperature-c%", temp_c_string);

      // DEPRECATED: Will be removed in later release
      label->replace_token("%temperature%", temp_c_string);
    };

    if (m_label[temp_state::NORMAL]) {
      replace_tokens(m_label[temp_state::NORMAL]);
    }
    if (m_label[temp_state::WARN]) {
      replace_tokens(m_label[temp_state::WARN]);
    }

    return true;
  }

  string temperature_module::get_format() const {
    if (m_temp > m_tempwarn) {
      return FORMAT_WARN;
    } else {
      return DEFAULT_FORMAT;
    }
  }

  bool temperature_module::build(builder* builder, const string& tag) const {
    if (tag == TAG_LABEL) {
      builder->node(m_label.at(temp_state::NORMAL));
    } else if (tag == TAG_LABEL_WARN) {
      builder->node(m_label.at(temp_state::WARN));
    } else if (tag == TAG_RAMP) {
      builder->node(m_ramp->get_by_percentage(m_perc));
    } else {
      return false;
    }
    return true;
  }
}

POLYBAR_NS_END
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: imagemgr.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 12:49:41 $
 *
 *  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 EXPRESSED 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): _______________________________________
 *
 *
 ************************************************************************/

#include "sal/config.h"

#include "imagemgr.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_
#include <drafts/com/sun/star/ui/XImageManager.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <drafts/com/sun/star/frame/XModuleManager.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGERSUPPLIER_HPP_
#include <drafts/com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_IMAGETYPE_HPP_
#include <drafts/com/sun/star/ui/ImageType.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPPLIER_HPP_
#include <drafts/com/sun/star/ui/XUIConfigurationManagerSupplier.hpp>
#endif

#include <tools/urlobj.hxx>
#include <svtools/imagemgr.hxx>
#include <comphelper/processfactory.hxx>
#include <rtl/ustring.hxx>
#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif

#include "imgmgr.hxx"
#include "app.hxx"
#include "unoctitm.hxx"
#include "dispatch.hxx"
#include "msg.hxx"
#include "msgpool.hxx"
#include "viewfrm.hxx"
#include "module.hxx"
#include "objsh.hxx"
#include "docfac.hxx"

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::drafts::com::sun::star::ui;
using namespace ::drafts::com::sun::star::frame;

typedef std::hash_map< ::rtl::OUString,
                       WeakReference< XImageManager >,
                       ::rtl::OUStringHash,
                       ::std::equal_to< ::rtl::OUString > > ModuleIdToImagegMgr;

static WeakReference< XModuleManager >                        m_xModuleManager;
static WeakReference< XModuleUIConfigurationManagerSupplier > m_xModuleCfgMgrSupplier;
static WeakReference< XURLTransformer >                       m_xURLTransformer;
static ModuleIdToImagegMgr                                    m_aModuleIdToImageMgrMap;

Image SAL_CALL GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig, BOOL bHiContrast )
{
    // TODO/LATeR: shouldn't this become a method at SfxViewFrame?! That would save the UnoTunnel
    if ( !rFrame.is() )
        return Image();

    INetURLObject aObj( aURL );
    INetProtocol  nProtocol = aObj.GetProtocol();

    Reference < XController > xController;
    Reference < XModel > xModel;
    if ( rFrame.is() )
        xController = rFrame->getController();
    if ( xController.is() )
        xModel = xController->getModel();

    rtl::OUString aCommandURL( aURL );
    if ( nProtocol == INET_PROT_SLOT )
    {
        /*
        // Support old way to retrieve image via slot URL
        Reference< XURLTransformer > xURLTransformer = m_xURLTransformer;
        if ( !xURLTransformer.is() )
        {
            xURLTransformer = Reference< XURLTransformer >(
                                ::comphelper::getProcessServiceFactory()->createInstance(
                                    rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )),
                                UNO_QUERY );
            m_xURLTransformer = xURLTransformer;
        }

        URL aTargetURL;
        aTargetURL.Complete = aURL;
        xURLTransformer->parseStrict( aTargetURL );
        USHORT nId = ( USHORT ) aTargetURL.Path.toInt32();*/
        USHORT nId = ( USHORT ) String(aURL).Copy(5).ToInt32();
        const SfxSlot* pSlot = 0;
        if ( xModel.is() )
        {
            Reference < XUnoTunnel > xObj( xModel, UNO_QUERY );
            Sequence < sal_Int8 > aSeq( SvGlobalName( SFX_GLOBAL_CLASSID ).GetByteSequence() );
            sal_Int64 nHandle = xObj.is() ? xObj->getSomething( aSeq ) : 0;
            if ( nHandle )
            {
                SfxObjectShell* pDoc = (SfxObjectShell*) (sal_Int32*) nHandle;
                SfxModule* pModule = pDoc->GetFactory().GetModule();
                pSlot = pModule->GetSlotPool()->GetSlot( nId );
            }
        }
        else
            pSlot = SFX_APP()->GetSlotPool().GetSlot( nId );

        if ( pSlot )
        {
            aCommandURL = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:" ));
            aCommandURL += rtl::OUString::createFromAscii( pSlot->GetUnoName() );
        }
        else
            aCommandURL = rtl::OUString();
    }

    Reference< XImageManager > xDocImgMgr;
    if ( xModel.is() )
    {
        Reference< XUIConfigurationManagerSupplier > xSupplier( xModel, UNO_QUERY );
        if ( xSupplier.is() )
        {
            Reference< XUIConfigurationManager > xDocUICfgMgr( xSupplier->getUIConfigurationManager(), UNO_QUERY );
            xDocImgMgr = Reference< XImageManager >( xDocUICfgMgr->getImageManager(), UNO_QUERY );
        }
    }

    sal_Int16 nImageType( ::drafts::com::sun::star::ui::ImageType::COLOR_NORMAL|
                            ::drafts::com::sun::star::ui::ImageType::SIZE_DEFAULT );
    if ( bBig )
        nImageType |= ::drafts::com::sun::star::ui::ImageType::SIZE_LARGE;
    if ( bHiContrast )
        nImageType |= ::drafts::com::sun::star::ui::ImageType::COLOR_HIGHCONTRAST;

    if ( xDocImgMgr.is() )
    {
        Sequence< Reference< ::com::sun::star::graphic::XGraphic > > aGraphicSeq;
        Sequence< rtl::OUString > aImageCmdSeq( 1 );
        aImageCmdSeq[0] = aCommandURL;

        try
        {
            aGraphicSeq = xDocImgMgr->getImages( nImageType, aImageCmdSeq );
            Reference< ::com::sun::star::graphic::XGraphic > xGraphic = aGraphicSeq[0];
            Image aImage( xGraphic );

            if ( !!aImage )
                return aImage;
        }
        catch ( Exception& )
        {
        }
    }

    Reference< XModuleManager > xModuleManager = m_xModuleManager;

    if ( !xModuleManager.is() )
    {
        xModuleManager = Reference< XModuleManager >(
                            ::comphelper::getProcessServiceFactory()->createInstance(
                                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                    "drafts.com.sun.star.frame.ModuleManager" ))),
                            UNO_QUERY );
        m_xModuleManager = xModuleManager;
    }

    try
    {
        if ( aCommandURL.getLength() > 0 )
        {
            Reference< XImageManager > xModuleImageManager;
            rtl::OUString aModuleId = xModuleManager->identify( rFrame );
            ModuleIdToImagegMgr::iterator pIter = m_aModuleIdToImageMgrMap.find( aModuleId );
            if ( pIter != m_aModuleIdToImageMgrMap.end() )
                xModuleImageManager = pIter->second;
            else
            {
                Reference< XModuleUIConfigurationManagerSupplier > xModuleCfgMgrSupplier = m_xModuleCfgMgrSupplier;

                if ( !xModuleCfgMgrSupplier.is() )
                {
                    xModuleCfgMgrSupplier = Reference< XModuleUIConfigurationManagerSupplier >(
                                                ::comphelper::getProcessServiceFactory()->createInstance(
                                                    rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                                        "drafts.com.sun.star.ui.ModuleUIConfigurationManagerSupplier" ))),
                                                UNO_QUERY );

                    m_xModuleCfgMgrSupplier = xModuleCfgMgrSupplier;
                }

                Reference< XUIConfigurationManager > xUICfgMgr = xModuleCfgMgrSupplier->getUIConfigurationManager( aModuleId );
                xModuleImageManager = Reference< XImageManager >( xUICfgMgr->getImageManager(), UNO_QUERY );
                m_aModuleIdToImageMgrMap.insert( ModuleIdToImagegMgr::value_type( aModuleId, xModuleImageManager ));
            }

            sal_Int16 nImageType( ::drafts::com::sun::star::ui::ImageType::COLOR_NORMAL|
                                  ::drafts::com::sun::star::ui::ImageType::SIZE_DEFAULT );
            if ( bBig )
                nImageType |= ::drafts::com::sun::star::ui::ImageType::SIZE_LARGE;
            if ( bHiContrast )
                nImageType |= ::drafts::com::sun::star::ui::ImageType::COLOR_HIGHCONTRAST;

            Sequence< Reference< ::com::sun::star::graphic::XGraphic > > aGraphicSeq;
            Sequence< rtl::OUString > aImageCmdSeq( 1 );
            aImageCmdSeq[0] = aCommandURL;

            aGraphicSeq = xModuleImageManager->getImages( nImageType, aImageCmdSeq );

            Reference< ::com::sun::star::graphic::XGraphic > xGraphic = aGraphicSeq[0];
            Image aImage( xGraphic );

            if ( !!aImage )
                return aImage;
            else if ( nProtocol != INET_PROT_UNO && nProtocol != INET_PROT_SLOT )
                return SvFileInformationManager::GetImageNoDefault( aObj, bBig, bHiContrast );
        }
    }
    catch ( Exception& )
    {
    }

    return Image();
}
<commit_msg>INTEGRATION: CWS removedrafts (1.12.46); FILE MERGED 2005/02/17 14:02:11 cd 1.12.46.1: #i42557# Move UNOIDL types from drafts to com<commit_after>/*************************************************************************
 *
 *  $RCSfile: imagemgr.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-01 19:57:56 $
 *
 *  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 EXPRESSED 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): _______________________________________
 *
 *
 ************************************************************************/

#include "sal/config.h"

#include "imagemgr.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_
#include <com/sun/star/ui/XImageManager.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <com/sun/star/frame/XModuleManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGERSUPPLIER_HPP_
#include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_IMAGETYPE_HPP_
#include <com/sun/star/ui/ImageType.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPPLIER_HPP_
#include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp>
#endif

#include <tools/urlobj.hxx>
#include <svtools/imagemgr.hxx>
#include <comphelper/processfactory.hxx>
#include <rtl/ustring.hxx>
#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif

#include "imgmgr.hxx"
#include "app.hxx"
#include "unoctitm.hxx"
#include "dispatch.hxx"
#include "msg.hxx"
#include "msgpool.hxx"
#include "viewfrm.hxx"
#include "module.hxx"
#include "objsh.hxx"
#include "docfac.hxx"

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::ui;
using namespace ::com::sun::star::frame;

typedef std::hash_map< ::rtl::OUString,
                       WeakReference< XImageManager >,
                       ::rtl::OUStringHash,
                       ::std::equal_to< ::rtl::OUString > > ModuleIdToImagegMgr;

static WeakReference< XModuleManager >                        m_xModuleManager;
static WeakReference< XModuleUIConfigurationManagerSupplier > m_xModuleCfgMgrSupplier;
static WeakReference< XURLTransformer >                       m_xURLTransformer;
static ModuleIdToImagegMgr                                    m_aModuleIdToImageMgrMap;

Image SAL_CALL GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig, BOOL bHiContrast )
{
    // TODO/LATeR: shouldn't this become a method at SfxViewFrame?! That would save the UnoTunnel
    if ( !rFrame.is() )
        return Image();

    INetURLObject aObj( aURL );
    INetProtocol  nProtocol = aObj.GetProtocol();

    Reference < XController > xController;
    Reference < XModel > xModel;
    if ( rFrame.is() )
        xController = rFrame->getController();
    if ( xController.is() )
        xModel = xController->getModel();

    rtl::OUString aCommandURL( aURL );
    if ( nProtocol == INET_PROT_SLOT )
    {
        /*
        // Support old way to retrieve image via slot URL
        Reference< XURLTransformer > xURLTransformer = m_xURLTransformer;
        if ( !xURLTransformer.is() )
        {
            xURLTransformer = Reference< XURLTransformer >(
                                ::comphelper::getProcessServiceFactory()->createInstance(
                                    rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )),
                                UNO_QUERY );
            m_xURLTransformer = xURLTransformer;
        }

        URL aTargetURL;
        aTargetURL.Complete = aURL;
        xURLTransformer->parseStrict( aTargetURL );
        USHORT nId = ( USHORT ) aTargetURL.Path.toInt32();*/
        USHORT nId = ( USHORT ) String(aURL).Copy(5).ToInt32();
        const SfxSlot* pSlot = 0;
        if ( xModel.is() )
        {
            Reference < XUnoTunnel > xObj( xModel, UNO_QUERY );
            Sequence < sal_Int8 > aSeq( SvGlobalName( SFX_GLOBAL_CLASSID ).GetByteSequence() );
            sal_Int64 nHandle = xObj.is() ? xObj->getSomething( aSeq ) : 0;
            if ( nHandle )
            {
                SfxObjectShell* pDoc = (SfxObjectShell*) (sal_Int32*) nHandle;
                SfxModule* pModule = pDoc->GetFactory().GetModule();
                pSlot = pModule->GetSlotPool()->GetSlot( nId );
            }
        }
        else
            pSlot = SFX_APP()->GetSlotPool().GetSlot( nId );

        if ( pSlot )
        {
            aCommandURL = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:" ));
            aCommandURL += rtl::OUString::createFromAscii( pSlot->GetUnoName() );
        }
        else
            aCommandURL = rtl::OUString();
    }

    Reference< XImageManager > xDocImgMgr;
    if ( xModel.is() )
    {
        Reference< XUIConfigurationManagerSupplier > xSupplier( xModel, UNO_QUERY );
        if ( xSupplier.is() )
        {
            Reference< XUIConfigurationManager > xDocUICfgMgr( xSupplier->getUIConfigurationManager(), UNO_QUERY );
            xDocImgMgr = Reference< XImageManager >( xDocUICfgMgr->getImageManager(), UNO_QUERY );
        }
    }

    sal_Int16 nImageType( ::com::sun::star::ui::ImageType::COLOR_NORMAL|
                            ::com::sun::star::ui::ImageType::SIZE_DEFAULT );
    if ( bBig )
        nImageType |= ::com::sun::star::ui::ImageType::SIZE_LARGE;
    if ( bHiContrast )
        nImageType |= ::com::sun::star::ui::ImageType::COLOR_HIGHCONTRAST;

    if ( xDocImgMgr.is() )
    {
        Sequence< Reference< ::com::sun::star::graphic::XGraphic > > aGraphicSeq;
        Sequence< rtl::OUString > aImageCmdSeq( 1 );
        aImageCmdSeq[0] = aCommandURL;

        try
        {
            aGraphicSeq = xDocImgMgr->getImages( nImageType, aImageCmdSeq );
            Reference< ::com::sun::star::graphic::XGraphic > xGraphic = aGraphicSeq[0];
            Image aImage( xGraphic );

            if ( !!aImage )
                return aImage;
        }
        catch ( Exception& )
        {
        }
    }

    Reference< XModuleManager > xModuleManager = m_xModuleManager;

    if ( !xModuleManager.is() )
    {
        xModuleManager = Reference< XModuleManager >(
                            ::comphelper::getProcessServiceFactory()->createInstance(
                                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                    "com.sun.star.frame.ModuleManager" ))),
                            UNO_QUERY );
        m_xModuleManager = xModuleManager;
    }

    try
    {
        if ( aCommandURL.getLength() > 0 )
        {
            Reference< XImageManager > xModuleImageManager;
            rtl::OUString aModuleId = xModuleManager->identify( rFrame );
            ModuleIdToImagegMgr::iterator pIter = m_aModuleIdToImageMgrMap.find( aModuleId );
            if ( pIter != m_aModuleIdToImageMgrMap.end() )
                xModuleImageManager = pIter->second;
            else
            {
                Reference< XModuleUIConfigurationManagerSupplier > xModuleCfgMgrSupplier = m_xModuleCfgMgrSupplier;

                if ( !xModuleCfgMgrSupplier.is() )
                {
                    xModuleCfgMgrSupplier = Reference< XModuleUIConfigurationManagerSupplier >(
                                                ::comphelper::getProcessServiceFactory()->createInstance(
                                                    rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                                        "com.sun.star.ui.ModuleUIConfigurationManagerSupplier" ))),
                                                UNO_QUERY );

                    m_xModuleCfgMgrSupplier = xModuleCfgMgrSupplier;
                }

                Reference< XUIConfigurationManager > xUICfgMgr = xModuleCfgMgrSupplier->getUIConfigurationManager( aModuleId );
                xModuleImageManager = Reference< XImageManager >( xUICfgMgr->getImageManager(), UNO_QUERY );
                m_aModuleIdToImageMgrMap.insert( ModuleIdToImagegMgr::value_type( aModuleId, xModuleImageManager ));
            }

            sal_Int16 nImageType( ::com::sun::star::ui::ImageType::COLOR_NORMAL|
                                  ::com::sun::star::ui::ImageType::SIZE_DEFAULT );
            if ( bBig )
                nImageType |= ::com::sun::star::ui::ImageType::SIZE_LARGE;
            if ( bHiContrast )
                nImageType |= ::com::sun::star::ui::ImageType::COLOR_HIGHCONTRAST;

            Sequence< Reference< ::com::sun::star::graphic::XGraphic > > aGraphicSeq;
            Sequence< rtl::OUString > aImageCmdSeq( 1 );
            aImageCmdSeq[0] = aCommandURL;

            aGraphicSeq = xModuleImageManager->getImages( nImageType, aImageCmdSeq );

            Reference< ::com::sun::star::graphic::XGraphic > xGraphic = aGraphicSeq[0];
            Image aImage( xGraphic );

            if ( !!aImage )
                return aImage;
            else if ( nProtocol != INET_PROT_UNO && nProtocol != INET_PROT_SLOT )
                return SvFileInformationManager::GetImageNoDefault( aObj, bBig, bHiContrast );
        }
    }
    catch ( Exception& )
    {
    }

    return Image();
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "Warnings.hpp"
#include "Options.hpp"

#include "mtac/WarningsEngine.hpp"
#include "mtac/Program.hpp"

using namespace eddic;

void mtac::collect_warnings(mtac::Program& program, std::shared_ptr<Configuration> configuration){
    if(configuration->option_defined("warning-unused")){
        for(auto& function : program.functions){
            if(program.call_graph.node(function.definition())->in_edges.size() == 0){
                warn("Unused function: " + function.get_name());
            }
        }
    }
}
<commit_msg>No unused warning for main<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "Warnings.hpp"
#include "Options.hpp"

#include "mtac/WarningsEngine.hpp"
#include "mtac/Program.hpp"

using namespace eddic;

void mtac::collect_warnings(mtac::Program& program, std::shared_ptr<Configuration> configuration){
    if(configuration->option_defined("warning-unused")){
        for(auto& function : program.functions){
            if(program.call_graph.node(function.definition())->in_edges.size() == 0 && !function.is_main()){
                warn("Unused function: " + function.get_name());
            }
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 - 2022 by Apex.AI Inc. 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.
//
// SPDX-License-Identifier: Apache-2.0

#ifndef IOX_HOOFS_CXX_UNIQUE_PTR_INL
#define IOX_HOOFS_CXX_UNIQUE_PTR_INL

#include "iceoryx_hoofs/cxx/unique_ptr.hpp"

namespace iox
{
namespace cxx
{
template <typename T>
inline unique_ptr<T>::unique_ptr(T* const object, const function<void(T*)>& deleter) noexcept
    : m_ptr(object)
    , m_deleter(std::move(deleter))
{
    Ensures(object != nullptr);
}

template <typename T>
inline unique_ptr<T>& unique_ptr<T>::operator=(unique_ptr&& rhs) noexcept
{
    if (this != &rhs)
    {
        destroy();
        m_ptr = rhs.m_ptr;
        m_deleter = rhs.m_deleter;
        rhs.m_ptr = nullptr;
    }
    return *this;
}

template <typename T>
inline unique_ptr<T>::unique_ptr(unique_ptr&& rhs) noexcept
    : m_ptr{rhs.m_ptr}
    , m_deleter{rhs.m_deleter}
{
    rhs.m_ptr = nullptr;
}

template <typename T>
inline unique_ptr<T>::~unique_ptr() noexcept
{
    destroy();
}

template <typename T>
inline T* unique_ptr<T>::operator->() noexcept
{
    cxx::Expects(m_ptr != nullptr);
    return get();
}

template <typename T>
inline const T* unique_ptr<T>::operator->() const noexcept
{
    // Avoid code duplication
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
    return const_cast<unique_ptr<T>*>(this)->operator->();
}

template <typename T>
inline T* unique_ptr<T>::get() noexcept
{
    return m_ptr;
}

template <typename T>
inline const T* unique_ptr<T>::get() const noexcept
{
    // AXIVION Next Construct AutosarC++19_03-A5.2.3 : Avoid code duplication
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
    return const_cast<unique_ptr<T>*>(this)->get();
}

template <typename T>
inline T* unique_ptr<T>::release(unique_ptr&& ptrToBeReleased) noexcept
{
    auto ptr = ptrToBeReleased.m_ptr;
    ptrToBeReleased.m_ptr = nullptr;
    return ptr;
}

template <typename T>
inline void unique_ptr<T>::reset(T* const ptr) noexcept
{
    Ensures(ptr != nullptr);
    destroy();
    m_ptr = ptr;
}

template <typename T>
inline void unique_ptr<T>::destroy() noexcept
{
    if (m_ptr)
    {
        m_deleter(m_ptr);
    }
    m_ptr = nullptr;
}

template <typename T>
inline void unique_ptr<T>::swap(unique_ptr<T>& other) noexcept
{
    std::swap(m_ptr, other.m_ptr);
    std::swap(m_deleter, other.m_deleter);
}

template <typename T, typename U>
inline bool operator==(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept
{
    return lhs.get() == rhs.get();
}

template <typename T, typename U>
inline bool operator!=(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept
{
    return !(lhs == rhs);
}
} // namespace cxx
} // namespace iox

#endif // IOX_HOOFS_CXX_UNIQUE_PTR_INL
<commit_msg>iox-#1104 Add std::move in move operation<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 - 2022 by Apex.AI Inc. 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.
//
// SPDX-License-Identifier: Apache-2.0

#ifndef IOX_HOOFS_CXX_UNIQUE_PTR_INL
#define IOX_HOOFS_CXX_UNIQUE_PTR_INL

#include "iceoryx_hoofs/cxx/unique_ptr.hpp"

namespace iox
{
namespace cxx
{
template <typename T>
inline unique_ptr<T>::unique_ptr(T* const object, const function<void(T*)>& deleter) noexcept
    : m_ptr(object)
    , m_deleter(std::move(deleter))
{
    Ensures(object != nullptr);
}

template <typename T>
inline unique_ptr<T>& unique_ptr<T>::operator=(unique_ptr&& rhs) noexcept
{
    if (this != &rhs)
    {
        destroy();
        m_ptr = rhs.m_ptr;
        m_deleter = std::move(rhs.m_deleter);
        rhs.m_ptr = nullptr;
    }
    return *this;
}

template <typename T>
inline unique_ptr<T>::unique_ptr(unique_ptr&& rhs) noexcept
    : m_ptr{rhs.m_ptr}
    , m_deleter{rhs.m_deleter}
{
    rhs.m_ptr = nullptr;
}

template <typename T>
inline unique_ptr<T>::~unique_ptr() noexcept
{
    destroy();
}

template <typename T>
inline T* unique_ptr<T>::operator->() noexcept
{
    cxx::Expects(m_ptr != nullptr);
    return get();
}

template <typename T>
inline const T* unique_ptr<T>::operator->() const noexcept
{
    // Avoid code duplication
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
    return const_cast<unique_ptr<T>*>(this)->operator->();
}

template <typename T>
inline T* unique_ptr<T>::get() noexcept
{
    return m_ptr;
}

template <typename T>
inline const T* unique_ptr<T>::get() const noexcept
{
    // AXIVION Next Construct AutosarC++19_03-A5.2.3 : Avoid code duplication
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
    return const_cast<unique_ptr<T>*>(this)->get();
}

template <typename T>
inline T* unique_ptr<T>::release(unique_ptr&& ptrToBeReleased) noexcept
{
    auto ptr = ptrToBeReleased.m_ptr;
    ptrToBeReleased.m_ptr = nullptr;
    return ptr;
}

template <typename T>
inline void unique_ptr<T>::reset(T* const ptr) noexcept
{
    Ensures(ptr != nullptr);
    destroy();
    m_ptr = ptr;
}

template <typename T>
inline void unique_ptr<T>::destroy() noexcept
{
    if (m_ptr)
    {
        m_deleter(m_ptr);
    }
    m_ptr = nullptr;
}

template <typename T>
inline void unique_ptr<T>::swap(unique_ptr<T>& other) noexcept
{
    std::swap(m_ptr, other.m_ptr);
    std::swap(m_deleter, other.m_deleter);
}

template <typename T, typename U>
inline bool operator==(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept
{
    return lhs.get() == rhs.get();
}

template <typename T, typename U>
inline bool operator!=(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept
{
    return !(lhs == rhs);
}
} // namespace cxx
} // namespace iox

#endif // IOX_HOOFS_CXX_UNIQUE_PTR_INL
<|endoftext|>


<commit_before>/*
 * File:   property.cc
 * Author: ruehle
 *
 * Created on November 13, 2008, 5:54 PM
 */

#include <libxml/parser.h>
#include <iostream>
#include "property.h"
#include <stdexcept>
#include "tokenizer.h"

Property &Property::get(const string &key)
{
    Tokenizer tok(key, ".");
    Tokenizer::iterator n;

    n = tok.begin();

    map<string, Property*>::iterator iter;
    iter = _map.find(*n);
    if(iter == _map.end())
        throw runtime_error("property not found: " + key);

    Property *p(((*iter).second));
    ++n;
    try {
        for(; n!=tok.end(); ++n)
        p = &p->get(*n);
    }
    catch(string err) { // catch here to get full key in exception
        throw runtime_error("property not found: " + key);
    }

    return *p;
}

std::list<Property *> Property::Select(const string &filter)
{
    Tokenizer tok(filter, ".");

    std::list<Property *> selection;

    if(tok.begin()==tok.end()) return selection;

    selection.push_back(this);

    for (Tokenizer::iterator n = tok.begin();
            n != tok.end(); ++n) {
        std::list<Property *> childs;
        for (std::list<Property *>::iterator p = selection.begin();
                p != selection.end(); ++p) {
                for (list<Property>::iterator iter = (*p)->_properties.begin();
                    iter != (*p)->_properties.end(); ++iter) {
                    if (wildcmp((*n).c_str(), (*iter).name().c_str())) {
                        childs.push_back(&(*iter));
                    }
                }
        }
        selection = childs;
    }

    return selection;
}

void Property::PrintNode(std::ostream &out, const string &prefix, Property &p)
{

    map<string, Property*>::iterator iter;
    if((p._value != "") || p.HasChilds())
        out << prefix << " = " << p._value << endl;
    for(iter = p._map.begin(); iter!=p._map.end(); ++iter) {
        if(prefix=="")
            PrintNode(out, prefix + (*iter).first, *(*iter).second);
        else
            PrintNode(out, prefix + "." + (*iter).first, *(*iter).second);
    }
}

static void parse_node(Property &p, xmlDocPtr doc, xmlNodePtr cur)
{
    xmlChar *key;

    key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);

    string value("");
    if(key) value = (const char *)key;

    // \todo test if unique
    Property &np = p.add((const char *)cur->name, value);
    xmlFree(key);

    for(xmlNodePtr node = cur->xmlChildrenNode; node != NULL; node = node->next) {
        if (node->type == XML_ELEMENT_NODE)
            parse_node(np, doc, node);
    }
}

bool load_property_from_xml(Property &p, string filename)
{
    xmlDocPtr doc;
    xmlNodePtr node;
    xmlChar *key;

    doc = xmlParseFile(filename.c_str());
    if(doc == NULL)
        throw std::ios_base::failure("Error on open xml bead map: " + filename);

    node = xmlDocGetRootElement(doc);

    if(node == NULL) {
        xmlFreeDoc(doc);
        throw std::invalid_argument("Error, empty xml document: " + filename);
    }

    //if(xmlStrcmp(node->name, (const xmlChar *)"cg_molecule")) {
    //    xmlFreeDoc(doc);
    //    throw std::invalid_argument("Error, in xml file: " + filename);
    //}

    // parse xml tree
    parse_node(p, doc, node);

    // free the document
    xmlFreeDoc(doc);
    xmlCleanupParser();
}

std::ostream &operator<<(std::ostream &out, Property& p)
{
      Property::PrintNode(out, "", p);
      return out;
}
<commit_msg>better property get<commit_after>/*
 * File:   property.cc
 * Author: ruehle
 *
 * Created on November 13, 2008, 5:54 PM
 */

#include <libxml/parser.h>
#include <iostream>
#include "property.h"
#include <stdexcept>
#include "tokenizer.h"

Property &Property::get(const string &key)
{
    Tokenizer tok(key, ".");
    Tokenizer::iterator n;

    n = tok.begin();
    if(n==tok.end()) return *this;

    Property *p;
    map<string, Property*>::iterator iter;
    if(*n=="") {
        p = this;
    }
    else {
        iter = _map.find(*n);

        if(iter == _map.end())
            throw runtime_error("property not found: " + key);

        p = (((*iter).second));
    }
    ++n;
    try {
        for(; n!=tok.end(); ++n) {
            p = &p->get(*n);
            cout << "tok <" << *n << ">" << endl;
        }
    }
    catch(string err) { // catch here to get full key in exception
        throw runtime_error("property not found: " + key);
    }

    return *p;
}

std::list<Property *> Property::Select(const string &filter)
{
    Tokenizer tok(filter, ".");

    std::list<Property *> selection;

    if(tok.begin()==tok.end()) return selection;

    selection.push_back(this);

    for (Tokenizer::iterator n = tok.begin();
            n != tok.end(); ++n) {
        std::list<Property *> childs;
        for (std::list<Property *>::iterator p = selection.begin();
                p != selection.end(); ++p) {
                for (list<Property>::iterator iter = (*p)->_properties.begin();
                    iter != (*p)->_properties.end(); ++iter) {
                    if (wildcmp((*n).c_str(), (*iter).name().c_str())) {
                        childs.push_back(&(*iter));
                    }
                }
        }
        selection = childs;
    }

    return selection;
}

void Property::PrintNode(std::ostream &out, const string &prefix, Property &p)
{

    map<string, Property*>::iterator iter;
    if((p._value != "") || p.HasChilds())
        out << prefix << " = " << p._value << endl;
    for(iter = p._map.begin(); iter!=p._map.end(); ++iter) {
        if(prefix=="")
            PrintNode(out, prefix + (*iter).first, *(*iter).second);
        else
            PrintNode(out, prefix + "." + (*iter).first, *(*iter).second);
    }
}

static void parse_node(Property &p, xmlDocPtr doc, xmlNodePtr cur)
{
    xmlChar *key;

    key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);

    string value("");
    if(key) value = (const char *)key;

    // \todo test if unique
    Property &np = p.add((const char *)cur->name, value);
    xmlFree(key);

    for(xmlNodePtr node = cur->xmlChildrenNode; node != NULL; node = node->next) {
        if (node->type == XML_ELEMENT_NODE)
            parse_node(np, doc, node);
    }
}

bool load_property_from_xml(Property &p, string filename)
{
    xmlDocPtr doc;
    xmlNodePtr node;
    xmlChar *key;

    doc = xmlParseFile(filename.c_str());
    if(doc == NULL)
        throw std::ios_base::failure("Error on open xml bead map: " + filename);

    node = xmlDocGetRootElement(doc);

    if(node == NULL) {
        xmlFreeDoc(doc);
        throw std::invalid_argument("Error, empty xml document: " + filename);
    }

    //if(xmlStrcmp(node->name, (const xmlChar *)"cg_molecule")) {
    //    xmlFreeDoc(doc);
    //    throw std::invalid_argument("Error, in xml file: " + filename);
    //}

    // parse xml tree
    parse_node(p, doc, node);

    // free the document
    xmlFreeDoc(doc);
    xmlCleanupParser();
}

std::ostream &operator<<(std::ostream &out, Property& p)
{
      Property::PrintNode(out, "", p);
      return out;
}
<|endoftext|>


<commit_before>/****************************************************************************/
/* Copyright 2005-2008, Francis Russell                                     */
/*                                                                          */
/* 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.                                           */
/*                                                                          */
/****************************************************************************/

#ifndef DESOLIN_ITL_BLAS_INTERFACE_HPP
#define DESOLIN_ITL_BLAS_INTERFACE_HPP

#include <cassert>
#include <complex>
#include <itl/itl_tags.h>
#include <itl/number_traits.h>

namespace itl {
  using desolin::blas_wrappers::BLASVector;
  using desolin::blas_wrappers::BLASGeneralMatrix;

  //: The vector type used inside of the ITL routines for work space
  template <typename Vec>
  struct itl_traits {
    // TODO: Work out what this does before allowing it to be defined.
    //typedef referencing_object_tag vector_category;
    typedef typename Vec::value_type value_type;
    typedef typename Vec::size_type size_type;
  };

  template <class Vec>
  struct Scaled {
    typedef typename Vec::value_type T;
    inline Scaled(const Vec& v, const T& alpha) : _alpha(alpha), _v(v) { }
    inline T alpha() const { return _alpha; }
    inline const Vec& vec() const { return _v; }
    inline int nrows() const { return _v.nrows(); }

  protected:
    T _alpha;
    const Vec _v;
  };

  // Getting the scaling factor for scaled and unscaled vectors
  template<typename Vec>
  inline typename Vec::value_type scale_factor(const Vec& v)
  {
    return static_cast<typename Vec::value_type>(1.0);
  }

  template<typename Vec>
  inline typename Vec::value_type scale_factor(const Scaled<Vec>& s)
  {
    return s.alpha();
  }

  // Getting the data for scaled and unscaled vectors
  template<typename Vec>
  inline typename Vec::value_type* get_data(Vec& v)
  {
    return v.data();
  }

  template<typename Vec>
  inline const typename Vec::value_type* get_data(const Vec& v)
  {
    return v.data();
  }

  template<typename Vec>
  inline const typename Vec::value_type* get_data(const Scaled<Vec>& s)
  {
    return s.vec().data();
  }

  // ITL interface implementation
  inline void copy(const BLASVector<double>& a, BLASVector<double>& b)
  {
    cblas_dcopy(a.nrows(), a.data(), 1, b.data(), 1);
  }

  inline void copy(const Scaled< BLASVector<double> >& a, BLASVector<double>& b)
  {
    cblas_dcopy(a.nrows(), a.vec().data(), 1, b.data(), 1);
    cblas_dscal(b.nrows(), a.alpha(), b.data(), 1);
  }

  inline double dot(const BLASVector<double>& a, const BLASVector<double>& b)
  {
    return cblas_ddot(a.nrows(), a.data(), 1, b.data(), 1);
  }

  inline double dot_conj(const BLASVector<double>& a, const BLASVector<double>& b)
  {
    return cblas_ddot(a.nrows(), a.data(), 1, b.data(), 1);
  }

  inline double two_norm(const BLASVector<double>& v)
  {
    return cblas_dnrm2(v.nrows(), v.data(), 1);
  }

  template<typename VecX>
  inline void add(const VecX& x, BLASVector<double>& y)
  {
    cblas_daxpy(x.nrows(), scale_factor(x), get_data(x), 1, y.data(), 1);
  }

  template<typename VecX, typename VecY>
  inline void add(const VecX& x, const VecY& y, BLASVector<double>& z)
  {
    itl::copy(x, z);
    itl::add(y, z);
  }

  template<typename VecX, typename VecY, typename VecZ>
  inline void add(const VecX& x, const VecY& y, const VecZ& z, BLASVector<double>& r)
  {
    itl::copy(x, r);
    itl::add(y, r);
    itl::add(z, r);
  }

  template<typename VecX>
  inline void mult(const BLASGeneralMatrix<double>& A, const VecX& x, BLASVector<double>& y)
  {
    cblas_dgemv(CblasRowMajor, CblasNoTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, 0.0, y.data(), 1);
  }

  template<typename VecX, typename VecY>
  inline void mult(const BLASGeneralMatrix<double>& A, const VecX& x, const VecY& y, BLASVector<double>& z)
  {
    cblas_dcopy(y.nrows(), y.data(), 1, z.data(), 1);
    cblas_dgemv(CblasRowMajor, CblasNoTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, scale_factor(y), z.data(), 1);
  }

  template <class VecX>
  inline void trans_mult(const BLASGeneralMatrix<double>& A, const VecX& x, BLASVector<double>& y)
  {
    cblas_dgemv(CblasRowMajor, CblasTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, 0.0, y.data(), 1);
  }

  inline void scale(BLASVector<double>& s, const itl_traits< BLASVector<double> >::value_type& alpha)
  {
    cblas_dscal(s.nrows(), alpha, s.data(), 1);
  }

  inline Scaled< BLASVector<double> > scaled(const BLASVector<double>& s, const itl_traits< BLASVector<double> >::value_type& alpha)
  {
    return Scaled< BLASVector<double> >(s, alpha);
  }

  template<typename T>
  inline typename BLASVector<T>::size_type size(const BLASVector<T>& x)
  {
    return x.nrows();
  }

// Only define this when semantics are understood
/*
  template <class Vector>
  inline void resize(Vector& x, const int sz)
  {
    x.resize(sz);
  }
*/
}

#endif
<commit_msg>propagate from branch 'uk.co.unchartedbackwaters.desolin.sparse' (head 9138ea68b7b129b15340f2c1d7fc4cea6aea59e9)             to branch 'uk.co.unchartedbackwaters.desolin' (head 9cae03e2742bca5d2863a6a21f61e57c3d5317b7)<commit_after>/****************************************************************************/
/* Copyright 2005-2008, Francis Russell                                     */
/*                                                                          */
/* 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.                                           */
/*                                                                          */
/****************************************************************************/

#ifndef DESOLIN_ITL_BLAS_INTERFACE_HPP
#define DESOLIN_ITL_BLAS_INTERFACE_HPP

#include <cassert>
#include <complex>
#include <itl/itl_tags.h>
#include <itl/number_traits.h>

namespace itl {
  using desolin::blas_wrappers::BLASVector;
  using desolin::blas_wrappers::BLASGeneralMatrix;

  //: The vector type used inside of the ITL routines for work space
  template <typename Vec>
  struct itl_traits {
    // TODO: Work out what this does before allowing it to be defined.
    //typedef referencing_object_tag vector_category;
    typedef typename Vec::value_type value_type;
    typedef typename Vec::size_type size_type;
  };

  template <class Vec>
  struct Scaled {
    typedef typename Vec::value_type T;
    inline Scaled(const Vec& v, const T& alpha) : _alpha(alpha), _v(v) { }
    inline T alpha() const { return _alpha; }
    inline const Vec& vec() const { return _v; }
    inline int nrows() const { return _v.nrows(); }

  protected:
    T _alpha;
    const Vec _v;
  };

  // Getting the scaling factor for scaled and unscaled vectors
  template<typename Vec>
  inline typename Vec::value_type scale_factor(const Vec& v)
  {
    return static_cast<typename Vec::value_type>(1.0);
  }

  template<typename Vec>
  inline typename Vec::value_type scale_factor(const Scaled<Vec>& s)
  {
    return s.alpha();
  }

  // Getting the data for scaled and unscaled vectors
  template<typename Vec>
  inline typename Vec::value_type* get_data(Vec& v)
  {
    return v.data();
  }

  template<typename Vec>
  inline const typename Vec::value_type* get_data(const Vec& v)
  {
    return v.data();
  }

  template<typename Vec>
  inline const typename Vec::value_type* get_data(const Scaled<Vec>& s)
  {
    return s.vec().data();
  }

  // ITL interface implementation
  inline void copy(const BLASVector<double>& a, BLASVector<double>& b)
  {
    cblas_dcopy(a.nrows(), a.data(), 1, b.data(), 1);
  }

  inline void copy(const Scaled< BLASVector<double> >& a, BLASVector<double>& b)
  {
    cblas_dcopy(a.nrows(), a.vec().data(), 1, b.data(), 1);
    cblas_dscal(b.nrows(), a.alpha(), b.data(), 1);
  }

  inline double dot(const BLASVector<double>& a, const BLASVector<double>& b)
  {
    return cblas_ddot(a.nrows(), a.data(), 1, b.data(), 1);
  }

  inline double dot_conj(const BLASVector<double>& a, const BLASVector<double>& b)
  {
    return cblas_ddot(a.nrows(), a.data(), 1, b.data(), 1);
  }

  inline double two_norm(const BLASVector<double>& v)
  {
    return cblas_dnrm2(v.nrows(), v.data(), 1);
  }

  template<typename VecX>
  inline void add(const VecX& x, BLASVector<double>& y)
  {
    cblas_daxpy(x.nrows(), scale_factor(x), get_data(x), 1, y.data(), 1);
  }

  template<typename VecX, typename VecY>
  inline void add(const VecX& x, const VecY& y, BLASVector<double>& z)
  {
    itl::copy(x, z);
    itl::add(y, z);
  }

  template<typename VecX, typename VecY, typename VecZ>
  inline void add(const VecX& x, const VecY& y, const VecZ& z, BLASVector<double>& r)
  {
    itl::copy(x, r);
    itl::add(y, r);
    itl::add(z, r);
  }

  template<typename VecX>
  inline void mult(const BLASGeneralMatrix<double>& A, const VecX& x, BLASVector<double>& y)
  {
    cblas_dgemv(CblasRowMajor, CblasNoTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, 0.0, y.data(), 1);
  }

  template<typename VecX, typename VecY>
  inline void mult(const BLASGeneralMatrix<double>& A, const VecX& x, const VecY& y, BLASVector<double>& z)
  {
    cblas_dcopy(y.nrows(), get_data(y), 1, z.data(), 1);
    cblas_dgemv(CblasRowMajor, CblasNoTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, scale_factor(y), z.data(), 1);
  }

  template <class VecX>
  inline void trans_mult(const BLASGeneralMatrix<double>& A, const VecX& x, BLASVector<double>& y)
  {
    cblas_dgemv(CblasRowMajor, CblasTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, 0.0, y.data(), 1);
  }

  inline void scale(BLASVector<double>& s, const itl_traits< BLASVector<double> >::value_type& alpha)
  {
    cblas_dscal(s.nrows(), alpha, s.data(), 1);
  }

  inline Scaled< BLASVector<double> > scaled(const BLASVector<double>& s, const itl_traits< BLASVector<double> >::value_type& alpha)
  {
    return Scaled< BLASVector<double> >(s, alpha);
  }

  template<typename T>
  inline typename BLASVector<T>::size_type size(const BLASVector<T>& x)
  {
    return x.nrows();
  }

// Only define this when semantics are understood
/*
  template <class Vector>
  inline void resize(Vector& x, const int sz)
  {
    x.resize(sz);
  }
*/
}

#endif
<|endoftext|>