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

#include <SoftSPI.h>

SoftSPI::SoftSPI(uint8_t mosi, uint8_t miso, uint8_t sck) {
    _mosi = mosi;
    _miso = miso;
    _sck = sck;
    _delay = 2;
    _cke = 0;
    _ckp = 0;
    _order = MSBFIRST;
}

void SoftSPI::begin() {
    pinMode(_mosi, OUTPUT);
    pinMode(_miso, INPUT);
    pinMode(_sck, OUTPUT);
}

void SoftSPI::end() {
    pinMode(_mosi, INPUT);
    pinMode(_miso, INPUT);
    pinMode(_sck, INPUT);
}

void SoftSPI::setBitOrder(uint8_t order) {
    _order = order & 1;
}

void SoftSPI::setDataMode(uint8_t mode) {
    switch (mode) {
        case SPI_MODE0:
            _ckp = 0;
            _cke = 0;
            break;
        case SPI_MODE1:
            _ckp = 0;
            _cke = 1;
            break;
        case SPI_MODE2:
            _ckp = 1;
            _cke = 0;
            break;
        case SPI_MODE3:
            _ckp = 1;
            _cke = 1;
            break;
    }
}

void SoftSPI::setClockDivider(uint8_t div) {
    switch (div) {
        case SPI_CLOCK_DIV2:
            _delay = 2;
            break;
        case SPI_CLOCK_DIV4:
            _delay = 4;
            break;
        case SPI_CLOCK_DIV8:
            _delay = 8;
            break;
        case SPI_CLOCK_DIV16:
            _delay = 16;
            break;
        case SPI_CLOCK_DIV32:
            _delay = 32;
            break;
        case SPI_CLOCK_DIV64:
            _delay = 64;
            break;
        case SPI_CLOCK_DIV128:
            _delay = 128;
            break;
        default:
            _delay = 128;
            break;
    }
}

uint8_t SoftSPI::transfer(uint8_t val) {
    uint8_t out = 0;

    if (_order == LSBFIRST) {
        uint8_t v2 =
            ((val & 0x01) << 7) |
            ((val & 0x02) << 5) |
            ((val & 0x04) << 3) |
            ((val & 0x08) << 1) |
            ((val & 0x10) >> 1) |
            ((val & 0x20) >> 3) |
            ((val & 0x40) >> 5) |
            ((val & 0x80) >> 7);
        val = v2;
    }

    uint8_t del = _delay >> 1;

    uint8_t bval = 0;
    for (uint8_t bit = 0; bit < 8; bit++) {
        digitalWrite(_sck, _ckp ? LOW : HIGH);

        for (uint8_t i = 0; i < del; i++) {
            asm volatile("nop");
        }

        if (_cke) {
            bval = digitalRead(_miso);
            if (_order == LSBFIRST) {
                out <<= 1;
                out |= bval;
            } else {
                out >>= 1;
                out |= bval << 7;
            }
        } else {
            digitalWrite(_mosi, val & (1<<bit) ? HIGH : LOW);
        }

        for (uint8_t i = 0; i < del; i++) {
            asm volatile("nop");
        }

        digitalWrite(_sck, _ckp ? HIGH : LOW);

        for (uint8_t i = 0; i < del; i++) {
            asm volatile("nop");
        }

        if (_cke) {
            digitalWrite(_mosi, val & (1<<bit) ? HIGH : LOW);
        } else {
            bval = digitalRead(_miso);
            if (_order == LSBFIRST) {
                out <<= 1;
                out |= bval;
            } else {
                out >>= 1;
                out |= bval << 7;
            }
        }

        for (uint8_t i = 0; i < del; i++) {
            asm volatile("nop");
        }
    }
    return out;
}
<commit_msg>removing MISO-related code.<commit_after>/*
 * Copyright (c) 2014, Majenko Technologies
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *
 *  3. Neither the name of Majenko Technologies nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Forked by Jason Pepas (Pepas Labs, LLC) to remove MISO pin requirement.
 * See https://github.com/pepaslabs/WriteOnlySoftSPI
 */

#include <WriteOnlySoftSPI.h>

WriteOnlySoftSPI::WriteOnlySoftSPI(uint8_t mosi, uint8_t sck) {
    _mosi = mosi;
    _sck = sck;
    _delay = 2;
    _cke = 0;
    _ckp = 0;
    _order = MSBFIRST;
}

void WriteOnlySoftSPI::begin() {
    pinMode(_mosi, OUTPUT);
    pinMode(_sck, OUTPUT);
}

void WriteOnlySoftSPI::end() {
    pinMode(_mosi, INPUT);
    pinMode(_sck, INPUT);
}

void WriteOnlySoftSPI::setBitOrder(uint8_t order) {
    _order = order & 1;
}

void WriteOnlySoftSPI::setDataMode(uint8_t mode) {
    switch (mode) {
        case SPI_MODE0:
            _ckp = 0;
            _cke = 0;
            break;
        case SPI_MODE1:
            _ckp = 0;
            _cke = 1;
            break;
        case SPI_MODE2:
            _ckp = 1;
            _cke = 0;
            break;
        case SPI_MODE3:
            _ckp = 1;
            _cke = 1;
            break;
    }
}

void WriteOnlySoftSPI::setClockDivider(uint8_t div) {
    switch (div) {
        case SPI_CLOCK_DIV2:
            _delay = 2;
            break;
        case SPI_CLOCK_DIV4:
            _delay = 4;
            break;
        case SPI_CLOCK_DIV8:
            _delay = 8;
            break;
        case SPI_CLOCK_DIV16:
            _delay = 16;
            break;
        case SPI_CLOCK_DIV32:
            _delay = 32;
            break;
        case SPI_CLOCK_DIV64:
            _delay = 64;
            break;
        case SPI_CLOCK_DIV128:
            _delay = 128;
            break;
        default:
            _delay = 128;
            break;
    }
}

void WriteOnlySoftSPI::transfer(uint8_t val) {

    if (_order == LSBFIRST) {
        uint8_t v2 =
            ((val & 0x01) << 7) |
            ((val & 0x02) << 5) |
            ((val & 0x04) << 3) |
            ((val & 0x08) << 1) |
            ((val & 0x10) >> 1) |
            ((val & 0x20) >> 3) |
            ((val & 0x40) >> 5) |
            ((val & 0x80) >> 7);
        val = v2;
    }

    uint8_t del = _delay >> 1;

    uint8_t bval = 0;
    for (uint8_t bit = 0; bit < 8; bit++) {
        digitalWrite(_sck, _ckp ? LOW : HIGH);

        for (uint8_t i = 0; i < del; i++) {
            asm volatile("nop");
        }

        if (_cke) {
            ;
        } else {
            digitalWrite(_mosi, val & (1<<bit) ? HIGH : LOW);
        }

        for (uint8_t i = 0; i < del; i++) {
            asm volatile("nop");
        }

        digitalWrite(_sck, _ckp ? HIGH : LOW);

        for (uint8_t i = 0; i < del; i++) {
            asm volatile("nop");
        }

        if (_cke) {
            digitalWrite(_mosi, val & (1<<bit) ? HIGH : LOW);
        } else {
            ;
        }

        for (uint8_t i = 0; i < del; i++) {
            asm volatile("nop");
        }
    }
    return out;
}
<|endoftext|>


<commit_before>// REQUIRES: static-analyzer
// RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s
extern void *malloc(unsigned long);
extern void free(void *);

void f() {
  int *p = new int(42);
  delete p;
  delete p;
  // CHECK: warning: Attempt to delete released memory [clang-analyzer-cplusplus.NewDelete]
}

void g() {
  void *q = malloc(132);
  free(q);
  free(q);
  // CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]
}
<commit_msg>Revert rCTE349288 'Fix a lit test failure after MallocChecker changes'<commit_after>// REQUIRES: static-analyzer
// RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s
extern void *malloc(unsigned long);
extern void free(void *);

void f() {
  int *p = new int(42);
  delete p;
  delete p;
  // CHECK: warning: Attempt to free released memory [clang-analyzer-cplusplus.NewDelete]
}

void g() {
  void *q = malloc(132);
  free(q);
  free(q);
  // CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]
}
<|endoftext|>


<commit_before>#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <iostream>

namespace py = pybind11;

template<class I, class T, class F>
void gauss_seidel_orig(const I Ap[], const int Ap_size,
                   const I Aj[], const int Aj_size,
                   const T Ax[], const int Ax_size,
                         T  x[], const int  x_size,
                   const T  b[], const int  b_size,
                   const I row_start,
                   const I row_stop,
                   const I row_step)
{
    for(I i = row_start; i != row_stop; i += row_step) {
        I start = Ap[i];
        I end   = Ap[i+1];
        T rsum = 0;
        T diag = 0;

        for(I jj = start; jj < end; jj++){
            I j = Aj[jj];
            if (i == j)
                diag  = Ax[jj];
            else
                rsum += Ax[jj]*x[j];
        }

        if (diag != (F) 0.0){
            x[i] = (b[i] - rsum)/diag;
        }
    }
}

template<class I, class T, class F>
void gauss_seidel1(py::array &Ap,
                  const py::array &Aj,
                  const py::array &Ax,
                        py::array  &x,
                  const py::array  &b,
                  const I row_start,
                  const I row_stop,
                  const I row_step)
{
    auto rrAp = Ap.unchecked<I,1>();
    auto rrAj = Aj.unchecked<I,1>();
    auto rrAx = Ax.unchecked<T,1>();
    auto  rrx =  x.mutable_unchecked<T,1>();
    auto  rrb =  b.unchecked<T,1>();

    const I *_Ap;
    const I *_Aj;
    const T *_Ax;
          T *_x;
    const T *_b;

    _Ap = rrAp.data(0);
    _Aj = rrAj.data(0);
    _Ax = rrAx.data(0);
     _x =  rrx.mutable_data(0);
     _b =  rrb.data(0);

    gauss_seidel_orig<I,T,F>(_Ap, Ap.size(),
                  _Aj, Aj.size(),
                  _Ax, Ax.size(),
                   _x,  x.size(),
                   _b,  b.size(),
                   row_start,
                   row_stop,
                   row_step);
}

template<class T>
void tmp(py::array &v)
{
    auto rr = v.unchecked<T,1>();
    const T *vv;
    vv = rr.data(0);
}

template<class I, class T, class F>
void gauss_seidel2(py::array &Apraw,
                   py::array &Ajraw,
                   py::array &Axraw,
                   py::array &xraw,
                   py::array &braw,
                   const I row_start,
                   const I row_stop,
                   const I row_step)
{
    auto rrAp = Apraw.unchecked<I,1>();
    auto rrAj = Ajraw.unchecked<I,1>();
    auto rrAx = Axraw.unchecked<T,1>();
    auto  rrx =  xraw.mutable_unchecked<T,1>();
    auto  rrb =  braw.unchecked<T,1>();

    const I *Ap;
    const I *Aj;
    const T *Ax;
          T *x;
    const T *b;

    Ap = rrAp.data(0);
    Aj = rrAj.data(0);
    Ax = rrAx.data(0);
     x =  rrx.mutable_data(0);
     b =  rrb.data(0);

    for(I i = row_start; i != row_stop; i += row_step) {
        I start = Ap[i];
        I end   = Ap[i+1];
        T rsum = 0;
        T diag = 0;

        for(I jj = start; jj < end; jj++){
            I j = Aj[jj];
            if (i == j)
                diag  = Ax[jj];
            else
                rsum += Ax[jj]*x[j];
        }

        if (diag != (F) 0.0){
            x[i] = (b[i] - rsum)/diag;
        }
    }
}

template<class I, class T, class F>
void gauss_seidel3(py::array &Apraw,
                   py::array &Ajraw,
                   py::array &Axraw,
                   py::array &xraw,
                   py::array &braw,
                   const I row_start,
                   const I row_stop,
                   const I row_step)
{
    auto rrAp = Apraw.unchecked<I,1>();
    auto rrAj = Ajraw.unchecked<I,1>();
    auto rrAx = Axraw.unchecked<T,1>();
    auto  rrx =  xraw.mutable_unchecked<T,1>();
    auto  rrb =  braw.unchecked<T,1>();
}

PYBIND11_PLUGIN(relaxation_wrap) {
    py::module m("relaxation_wrap", "pybind11 example plugin");

    m.def("gauss_seidel_proto1", gauss_seidel1<int, double, double>, "Gauss-Seidel");
    m.def("gauss_seidel_proto2", gauss_seidel2<int, double, double>, "Gauss-Seidel");
    m.def("gauss_seidel_proto3", gauss_seidel3<int, double, double>, "Gauss-Seidel");
    //m.def("gauss_seidel_proto", tmp<double>, "Gauss-Seidel");

    return m.ptr();
}
<commit_msg>remove old wrap example<commit_after><|endoftext|>


<commit_before>#define OVERRIDE_MATRIX_MULT true

#include <thread>
#include <future>
#include "../lib/matrix.hpp"
#include "../lib/pool.hpp"
#include "../lib/image.hpp"
#include "../lib/promise-polyfill.hpp"
#include "../lib/queue.hpp"

/* 1a */
matrix operator*(const matrix &x, const matrix &y) {
  if (x.cols != y.rows) {
    throw std::invalid_argument("Invalid arguments");
  }

  matrix z;
  z.create(x.rows, y.cols);

  //Flatten the loops so we can fairly chunk up the work (assume the
  //picture isn't the same width as it is height!)
  parallel_for(0u, x.rows * y.cols, [&](int k) {
    unsigned i = k / y.cols, j = k % y.cols;
    int zz = 0;
    for (unsigned k = 0; k < x.cols; k++) {
      zz += x(i, k) * y(k, j);
    }
    z(i, j) = zz;
  });
  return z;
}

/*
 * 2. parallel_for uses the queue_work function instead of create_thread.
 * a. Why?
 * - Parallel for loops are typically used in data problems which require the
 * - computation of some value over a loop. As such, these are often short lived
 * - and cause blocks in control flow. To mitigate the delay and increase the
 * - benefit of using parallel_for, the work is pushed into the pool so that thread
 * - creation is not experienced (which takes time), additionally, since the computation
 * - is most likely computationally expensive, the pool will only schedule the work
 * - when threads are available instead of maxing out the system and causing system lag.
 *
 * b. Give an example of when should you use create_thread instead of queue_work
 * to execute work asynchronously?
 * - Create thread should always be used for work which is *long running* or blocking.
 * - Reason being is that long running work (or threads which will be alive the entire
 * - program life) will utilize all the threads provisioned to the pool and will cease
 * - execution of other work (e.g. a worker thread that works on a concurrent queue).
 * - Knowing this, simply spawn a new thread!
 */

/* 3 */
//Consider the following program
int mainEx() {
  int value = 32;
  queue_work([&] {
    value -= 17;
    printf("%d\n", value);
  });
  return value;
}

/*
* 3a.  What is the result of this program?  (Hint: its not always the same).
* - The result of this program varies depending on how quickly the queued
* - works starts in relation to the execution of the remaining code (pop stack
* - [removing queue_work return], push `value`, and return stack[0]/int).
*
* Possible results:
* 1. mainEx returns 32
* 2. mainEx returns 15
* 3. mainEx returns 15 and prints 15
*/

/* 3b - Correct the defect. */
int mainExFixed() {
  int value = 32;
  auto f = queue_work([&] {
    value -= 17;
    printf("%d\n", value);
  });
  f.wait();//Wait for the async work to complete so our value is consistent every time
  return value;
}

/* 4 completed */
void conv(matrix &x, const matrix &k) {
  matrix y;
  y.create(x.rows + k.rows, x.cols + k.cols);

  const unsigned xR = x.rows, xC = x.cols;
  parallel_for(0u, xR * xC, [&](auto i) {
    auto row = i % xR, col = i / xR;
    auto yrow = row + k.rows / 2;
    auto ycol = col + k.cols / 2;
    y(yrow, ycol) = x(row, col);
  });

  std::atomic<int> weight(0);
  const unsigned kR = k.rows, kC = k.cols;
  parallel_for(0u, kR * kC, [&](int i) {
    auto row = i % kR, col = i / kR;
    weight += k(row, col);
  });

  parallel_for(0u, xR * xC, [&](int i) {
    auto row = i % xR, col = i / xR;
    int t = 0;
    auto yrow = row;
    for (int krow = k.rows - 1; krow >= 0; krow--, yrow++) {
      auto ycol = col;
      for (int kcol = k.cols - 1; kcol >= 0; kcol--, ycol++) {
        t += y(yrow, ycol) * k(krow, kcol);
      }
    }
    if (weight != 0) {
      t /= weight;
    }
    x(row, col) = t;
  });
}

int binomial_coefficient(int n, int k) {
  if (n <= 1 || k == 0) {
    return 1;
  } else {
    return binomial_coefficient(n - 1, k - 1) * n / k;
  }
}

matrix binomial(int n) {
  if ((n & 1) == 0) {
    throw std::invalid_argument("n must be odd");
  }

  matrix x, y;
  x.create(1, n);
  y.create(n, 1);

  for (int i = 0; i < n / 2; i++) {
    x(0, i) = x(0, n - i - 1) = binomial_coefficient(n - 1, i);
    y(i, 0) = y(n - i - 1, 0) = binomial_coefficient(n - 1, i);
  }

  x(0, n / 2) = binomial_coefficient(n - 1, n / 2);
  y(n / 2, 0) = binomial_coefficient(n - 1, n / 2);

  return y * x;
}

concurrent_queue<matrix> pipeline;
std::future<matrix> blur_image_async(matrix x) {
  return std::async(std::launch::async, [](matrix bmp) {
    matrix kernel = binomial(3);
    conv(bmp, kernel);
    return std::move(bmp);
  }, std::move(x));
}

int main_q4() {
  auto pipeline_thread = std::thread([] {
    for (;;) {
      auto x = pipeline.pop();
      auto b = blur_image_async(std::move(x)).share();
      Promise::then(b, [](auto f) {
        matrix h = histogram(f.get());
      }).wait();
    }
  });
  Promise::then(load_image_async("image.png").share(), [](auto f) {
    pipeline.push(f.get());
  }).wait();
  pipeline_thread.join();
  return 0;
}
/* 4 end */

/*
* 5a. How does a semaphore differ from mutex?
* - A semaphore differs from a mutex in that it is not a mutual exclusion lock,
* - a semaphore, unlike a mutex, can be aquired multiple times (depending on how
* - the sempahore is created) unlike a mutex which is strictly locked or unlocked.
* - Additionally, a semaphore lives in the file system and is not restrictied to the
* - process in which it was created (like a mutex), which makes it useful to lock
* - access to things like shared memory pools across processes.
*
* 5b. Describe the operation of a bar (sitting down, ordering a drink) in terms
* of a semaphore and mutex.
*/

int main(int argc, char **argv) {
  return 0;
}
<commit_msg>Answer 5b<commit_after>#define OVERRIDE_MATRIX_MULT true

#include <thread>
#include <future>
#include "../lib/matrix.hpp"
#include "../lib/pool.hpp"
#include "../lib/image.hpp"
#include "../lib/promise-polyfill.hpp"
#include "../lib/queue.hpp"

/* 1a */
matrix operator*(const matrix &x, const matrix &y) {
  if (x.cols != y.rows) {
    throw std::invalid_argument("Invalid arguments");
  }

  matrix z;
  z.create(x.rows, y.cols);

  //Flatten the loops so we can fairly chunk up the work (assume the
  //picture isn't the same width as it is height!)
  parallel_for(0u, x.rows * y.cols, [&](int k) {
    unsigned i = k / y.cols, j = k % y.cols;
    int zz = 0;
    for (unsigned k = 0; k < x.cols; k++) {
      zz += x(i, k) * y(k, j);
    }
    z(i, j) = zz;
  });
  return z;
}

/*
 * 2. parallel_for uses the queue_work function instead of create_thread.
 * a. Why?
 * - Parallel for loops are typically used in data problems which require the
 * - computation of some value over a loop. As such, these are often short lived
 * - and cause blocks in control flow. To mitigate the delay and increase the
 * - benefit of using parallel_for, the work is pushed into the pool so that thread
 * - creation is not experienced (which takes time), additionally, since the computation
 * - is most likely computationally expensive, the pool will only schedule the work
 * - when threads are available instead of maxing out the system and causing system lag.
 *
 * b. Give an example of when should you use create_thread instead of queue_work
 * to execute work asynchronously?
 * - Create thread should always be used for work which is *long running* or blocking.
 * - Reason being is that long running work (or threads which will be alive the entire
 * - program life) will utilize all the threads provisioned to the pool and will cease
 * - execution of other work (e.g. a worker thread that works on a concurrent queue).
 * - Knowing this, simply spawn a new thread!
 */

/* 3 */
//Consider the following program
int mainEx() {
  int value = 32;
  queue_work([&] {
    value -= 17;
    printf("%d\n", value);
  });
  return value;
}

/*
* 3a.  What is the result of this program?  (Hint: its not always the same).
* - The result of this program varies depending on how quickly the queued
* - works starts in relation to the execution of the remaining code (pop stack
* - [removing queue_work return], push `value`, and return stack[0]/int).
*
* Possible results:
* 1. mainEx returns 32
* 2. mainEx returns 15
* 3. mainEx returns 15 and prints 15
*/

/* 3b - Correct the defect. */
int mainExFixed() {
  int value = 32;
  auto f = queue_work([&] {
    value -= 17;
    printf("%d\n", value);
  });
  f.wait();//Wait for the async work to complete so our value is consistent every time
  return value;
}

/* 4 completed */
void conv(matrix &x, const matrix &k) {
  matrix y;
  y.create(x.rows + k.rows, x.cols + k.cols);

  const unsigned xR = x.rows, xC = x.cols;
  parallel_for(0u, xR * xC, [&](auto i) {
    auto row = i % xR, col = i / xR;
    auto yrow = row + k.rows / 2;
    auto ycol = col + k.cols / 2;
    y(yrow, ycol) = x(row, col);
  });

  std::atomic<int> weight(0);
  const unsigned kR = k.rows, kC = k.cols;
  parallel_for(0u, kR * kC, [&](int i) {
    auto row = i % kR, col = i / kR;
    weight += k(row, col);
  });

  parallel_for(0u, xR * xC, [&](int i) {
    auto row = i % xR, col = i / xR;
    int t = 0;
    auto yrow = row;
    for (int krow = k.rows - 1; krow >= 0; krow--, yrow++) {
      auto ycol = col;
      for (int kcol = k.cols - 1; kcol >= 0; kcol--, ycol++) {
        t += y(yrow, ycol) * k(krow, kcol);
      }
    }
    if (weight != 0) {
      t /= weight;
    }
    x(row, col) = t;
  });
}

int binomial_coefficient(int n, int k) {
  if (n <= 1 || k == 0) {
    return 1;
  } else {
    return binomial_coefficient(n - 1, k - 1) * n / k;
  }
}

matrix binomial(int n) {
  if ((n & 1) == 0) {
    throw std::invalid_argument("n must be odd");
  }

  matrix x, y;
  x.create(1, n);
  y.create(n, 1);

  for (int i = 0; i < n / 2; i++) {
    x(0, i) = x(0, n - i - 1) = binomial_coefficient(n - 1, i);
    y(i, 0) = y(n - i - 1, 0) = binomial_coefficient(n - 1, i);
  }

  x(0, n / 2) = binomial_coefficient(n - 1, n / 2);
  y(n / 2, 0) = binomial_coefficient(n - 1, n / 2);

  return y * x;
}

concurrent_queue<matrix> pipeline;
std::future<matrix> blur_image_async(matrix x) {
  return std::async(std::launch::async, [](matrix bmp) {
    matrix kernel = binomial(3);
    conv(bmp, kernel);
    return std::move(bmp);
  }, std::move(x));
}

int main_q4() {
  auto pipeline_thread = std::thread([] {
    for (;;) {
      auto x = pipeline.pop();
      auto b = blur_image_async(std::move(x)).share();
      Promise::then(b, [](auto f) {
        matrix h = histogram(f.get());
      }).wait();
    }
  });
  Promise::then(load_image_async("image.png").share(), [](auto f) {
    pipeline.push(f.get());
  }).wait();
  pipeline_thread.join();
  return 0;
}
/* 4 end */

/*
* 5a. How does a semaphore differ from mutex?
* - A semaphore differs from a mutex in that it is not a mutual exclusion lock,
* - a semaphore, unlike a mutex, can be aquired multiple times (depending on how
* - the sempahore is created) unlike a mutex which is strictly locked or unlocked.
* - Additionally, a semaphore lives in the file system and is not restrictied to the
* - process in which it was created (like a mutex), which makes it useful to lock
* - access to things like shared memory pools across processes.
*
* 5b. Describe the operation of a bar (sitting down, ordering a drink) in terms
* of a semaphore and mutex.
* = Semaphore:
* - A bar has `n` number of seats, so a semapore is constructed accordingly.
* - The semaphore (or a bar seat) can be aquired up to `n` times before parties
* - begin waiting for a seat at the bar. Meaning, each person can reserve a seat
* - by sitting (aquiring) it and then leaving (releasing) the seat, where then
* - the fastest person to react can aquire the released seat. This experiences
* - contention when the semaphore is fully aquired, but not at the same level as a mutex.
*
* = Mutex:
* - The bar has a single seat and the bar tender refuses to serve anyone who is
* - not sitting at that seat. The seat can be locked (sat in) and then unlocked
* - (individual leaves). When the seat is unlocked, the fastest person to react
* - can then sit (lock) in the seat. This means that after the seat is taken,
* - every new person who wishes to have service must wait, which creates contention
* - in the form of a large blob of people (many threads waiting in the kernel on
* - the lock).
*/

int main(int argc, char **argv) {
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pyuno_util.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:54:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#include <osl/thread.h>

#include <typelib/typedescription.hxx>

#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>

#include <com/sun/star/beans/XMaterialHolder.hpp>

#include "pyuno_impl.hxx"

using rtl::OUStringToOString;
using rtl::OUString;
using rtl::OString;
using rtl::OStringBuffer;
using rtl::OUStringBuffer;

using com::sun::star::uno::TypeDescription;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Any;
using com::sun::star::uno::Type;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::TypeClass;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::XComponentContext;
using com::sun::star::lang::XSingleServiceFactory;
using com::sun::star::script::XTypeConverter;
using com::sun::star::beans::XMaterialHolder;

#define USTR_ASCII(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) )
namespace pyuno
{
PyRef ustring2PyUnicode( const OUString & str )
{
    PyRef ret;
#if Py_UNICODE_SIZE == 2
    ret = PyRef( PyUnicode_FromUnicode( str.getStr(), str.getLength() ), SAL_NO_ACQUIRE );
#else
    OString sUtf8(OUStringToOString(str, RTL_TEXTENCODING_UTF8));
    ret = PyRef( PyUnicode_DecodeUTF8( sUtf8.getStr(), sUtf8.getLength(), NULL) , SAL_NO_ACQUIRE );
#endif
    return ret;
}

PyRef ustring2PyString( const OUString &str )
{
    OString o = OUStringToOString( str, osl_getThreadTextEncoding() );
    return PyRef( PyString_FromString( o.getStr() ), SAL_NO_ACQUIRE );
}

OUString pyString2ustring( PyObject *pystr )
{
    OUString ret;
    if( PyUnicode_Check( pystr ) )
    {
#if Py_UNICODE_SIZE == 2
    ret = OUString( (sal_Unicode * ) PyUnicode_AS_UNICODE( pystr ) );
#else
    PyObject* pUtf8 = PyUnicode_AsUTF8String(pystr);
    ret = OUString(PyString_AsString(pUtf8), PyString_Size(pUtf8), RTL_TEXTENCODING_UTF8);
    Py_DECREF(pUtf8);
#endif
    }
    else
    {
        char *name = PyString_AsString(pystr );
        ret = OUString( name, strlen(name), osl_getThreadTextEncoding() );
    }
    return ret;
}

PyRef getObjectFromUnoModule( const Runtime &runtime, const char * func )
    throw ( RuntimeException )
{
    PyRef object(PyDict_GetItemString( runtime.getImpl()->cargo->getUnoModule().get(), (char*)func ) );
    if( !object.is() )
    {
        OUStringBuffer buf;
        buf.appendAscii( "couldn't find core function " );
        buf.appendAscii( func );
        throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());
    }
    return object;
}

}
<commit_msg>INTEGRATION: CWS pyunofixes2 (1.3.10); FILE MERGED 2006/01/07 21:36:43 jbu 1.3.10.2: RESYNC: (1.3-1.4); FILE MERGED 2005/09/09 18:43:07 jbu 1.3.10.1: #i54416#,#i47270# added logging support for pyuno + refcounting bug for __members__ variable fixed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pyuno_util.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-03-22 10:52:11 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#include <time.h>
#include <osl/thread.h>

#include <typelib/typedescription.hxx>

#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/time.h>

#include <com/sun/star/beans/XMaterialHolder.hpp>

#include "pyuno_impl.hxx"

using rtl::OUStringToOString;
using rtl::OUString;
using rtl::OString;
using rtl::OStringBuffer;
using rtl::OUStringBuffer;

using com::sun::star::uno::TypeDescription;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Any;
using com::sun::star::uno::Type;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::TypeClass;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::XComponentContext;
using com::sun::star::lang::XSingleServiceFactory;
using com::sun::star::script::XTypeConverter;
using com::sun::star::beans::XMaterialHolder;

#define USTR_ASCII(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) )
namespace pyuno
{
PyRef ustring2PyUnicode( const OUString & str )
{
    PyRef ret;
#if Py_UNICODE_SIZE == 2
    ret = PyRef( PyUnicode_FromUnicode( str.getStr(), str.getLength() ), SAL_NO_ACQUIRE );
#else
    OString sUtf8(OUStringToOString(str, RTL_TEXTENCODING_UTF8));
    ret = PyRef( PyUnicode_DecodeUTF8( sUtf8.getStr(), sUtf8.getLength(), NULL) , SAL_NO_ACQUIRE );
#endif
    return ret;
}

PyRef ustring2PyString( const OUString &str )
{
    OString o = OUStringToOString( str, osl_getThreadTextEncoding() );
    return PyRef( PyString_FromString( o.getStr() ), SAL_NO_ACQUIRE );
}

OUString pyString2ustring( PyObject *pystr )
{
    OUString ret;
    if( PyUnicode_Check( pystr ) )
    {
#if Py_UNICODE_SIZE == 2
    ret = OUString( (sal_Unicode * ) PyUnicode_AS_UNICODE( pystr ) );
#else
    PyObject* pUtf8 = PyUnicode_AsUTF8String(pystr);
    ret = OUString(PyString_AsString(pUtf8), PyString_Size(pUtf8), RTL_TEXTENCODING_UTF8);
    Py_DECREF(pUtf8);
#endif
    }
    else
    {
        char *name = PyString_AsString(pystr );
        ret = OUString( name, strlen(name), osl_getThreadTextEncoding() );
    }
    return ret;
}

PyRef getObjectFromUnoModule( const Runtime &runtime, const char * func )
    throw ( RuntimeException )
{
    PyRef object(PyDict_GetItemString( runtime.getImpl()->cargo->getUnoModule().get(), (char*)func ) );
    if( !object.is() )
    {
        OUStringBuffer buf;
        buf.appendAscii( "couldn't find core function " );
        buf.appendAscii( func );
        throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());
    }
    return object;
}

//------------------------------------------------------------------------------------
// Logging
//------------------------------------------------------------------------------------

bool isLog( RuntimeCargo * cargo, sal_Int32 loglevel )
{
    return cargo && cargo->logFile && loglevel <= cargo->logLevel;
}

void log( RuntimeCargo * cargo, sal_Int32 level, const rtl::OUString &logString )
{
    log( cargo, level, OUStringToOString( logString, osl_getThreadTextEncoding() ).getStr() );
}

void log( RuntimeCargo * cargo, sal_Int32 level, const char *str )
{
    if( isLog( cargo, level ) )
    {
        static const char *strLevel[] = { "NONE", "CALL", "ARGS" };

        TimeValue systemTime;
        TimeValue localTime;
        oslDateTime localDateTime;

        osl_getSystemTime( &systemTime );
        osl_getLocalTimeFromSystemTime( &systemTime, &localTime );
        osl_getDateTimeFromTimeValue( &localTime, &localDateTime );

        fprintf( cargo->logFile,
                 "%4i-%02i-%02i %02i:%02i:%02i,%03i [%s,tid %i]: %s\n",
                 localDateTime.Year,
                 localDateTime.Month,
                 localDateTime.Day,
                 localDateTime.Hours,
                 localDateTime.Minutes,
                 localDateTime.Seconds,
                 localDateTime.NanoSeconds/1000000,
                 strLevel[level],
                 (sal_Int32) osl_getThreadIdentifier( 0),
                 str );
    }
}

void logException( RuntimeCargo *cargo, const char *intro,
                   sal_Int64 ptr, const rtl::OUString &aFunctionName,
                   const void * data, const com::sun::star::uno::Type & type )
{
    if( isLog( cargo, LogLevel::CALL ) )
    {
        rtl::OUStringBuffer buf( 128 );
        buf.appendAscii( intro );
        buf.append( ptr , 16);
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("].") );
        buf.append( aFunctionName );
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " = " ) );
        buf.append(
            val2str( data, type.getTypeLibType(), VAL2STR_MODE_SHALLOW ) );
        log( cargo,LogLevel::CALL, buf.makeStringAndClear() );
    }

}

void logReply(
    RuntimeCargo *cargo,
    const char *intro,
    sal_Int64 ptr,
    const rtl::OUString & aFunctionName,
    const Any &returnValue,
    const Sequence< Any > & aParams )
{
    rtl::OUStringBuffer buf( 128 );
    buf.appendAscii( intro );
    buf.append( (sal_Int64) ptr, 16);
    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("].") );
    buf.append( aFunctionName );
    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("()=") );
    if( isLog( cargo, LogLevel::ARGS ) )
    {
        buf.append(
            val2str( returnValue.getValue(), returnValue.getValueTypeRef(), VAL2STR_MODE_SHALLOW) );
        for( int i = 0; i < aParams.getLength() ; i ++ )
        {
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", " ) );
            buf.append(
                val2str( aParams[i].getValue(), aParams[i].getValueTypeRef(), VAL2STR_MODE_SHALLOW) );
        }
    }
    log( cargo,LogLevel::CALL, buf.makeStringAndClear() );

}

void logCall( RuntimeCargo *cargo, const char *intro,
          sal_Int64 ptr, const rtl::OUString & aFunctionName, const Sequence< Any > & aParams )
{
    rtl::OUStringBuffer buf( 128 );
    buf.appendAscii( intro );
    buf.append( (sal_Int64) ptr, 16);
    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("].") );
    buf.append( aFunctionName );
    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("(") );
    if( isLog( cargo, LogLevel::ARGS ) )
    {
        for( int i = 0; i < aParams.getLength() ; i ++ )
        {
            if( i > 0 )
                buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", " ) );
            buf.append(
                val2str( aParams[i].getValue(), aParams[i].getValueTypeRef(), VAL2STR_MODE_SHALLOW) );
        }
    }
    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(")") );
    log( cargo,LogLevel::CALL, buf.makeStringAndClear() );
}

}
<|endoftext|>


<commit_before><commit_msg>Use SparseState instead of std::vector. Cleaning dead code. Feature #3510158.<commit_after><|endoftext|>


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

#include "searchLineEdit.h"

#include <QtCore/QPropertyAnimation>
#include <QtGui/QIcon>
#include <QtWidgets/QAction>
#include <QtWidgets/QMenu>
#include <QtWidgets/QStyle>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QLineEdit>

using namespace qReal::ui;

SearchLineEdit::SearchLineEdit(QWidget *parent, bool borderEnabled)
	: QFrame(parent)
	, mOptionsButton(initButton(QIcon(":/widgets/icons/find.svg"), QString()))
	, mClearButton(initButton(style()->standardIcon(QStyle::SP_LineEditClearButton), tr("Clear text")))
	, mCaseInsensitive(new QAction(tr("Case insensitive"), this))
	, mCaseSensitive(new QAction(tr("Case sensitive"), this))
	, mRegularExpression(new QAction(tr("Regular expression"), this))
	, mCurrentOption(SearchOptions::CaseInsensitive)
{
	QHBoxLayout * const layout = new QHBoxLayout(this);
	layout->setContentsMargins(2, 2, 2, 2);
	layout->setSpacing(2);

	mLineEdit = new QLineEdit(this);
	connect(mLineEdit, &QLineEdit::textChanged, this, &SearchLineEdit::onTextChanged);
	mLineEdit->setPlaceholderText(tr("Enter search text..."));
	mLineEdit->setStyleSheet("border: 0");

	makeContextMenu();
	mOptionsButton->setPopupMode(QToolButton::InstantPopup);
	mOptionsButton->setFixedSize(16, 12);
	mCaseInsensitive->trigger();

	connect(mClearButton, &QAbstractButton::clicked, mLineEdit, &QLineEdit::clear);
	mClearButton->setFixedSize(16, 16);
	mClearButton->hide();

	layout->addWidget(mOptionsButton);
	layout->addWidget(mLineEdit);
	layout->addWidget(mClearButton);

	setBorderEnabled(borderEnabled);
}

void SearchLineEdit::setBorderEnabled(bool enabled)
{
	if (enabled) {
		setStyleSheet("QFrame { background: white; border: 1px solid black; border-radius: 2px; }");
	} else {
		setStyleSheet("QFrame { background: white; }");
	}
}

void SearchLineEdit::setLineEditColor(const QColor &color)
{
	mLineEdit->setStyleSheet(QString("QLineEdit {background: %1}").arg(color.name(QColor::HexArgb)));
}

void SearchLineEdit::focusMe()
{
	mLineEdit->setFocus(Qt::ShortcutFocusReason);
}

void SearchLineEdit::setSearchOption(const SearchLineEdit::SearchOptions &option)
{
	mCurrentOption = option;
}

void SearchLineEdit::makeSearchOptionsSelectable(bool selectable)
{
	mOptionsButton->setEnabled(selectable);
}

void SearchLineEdit::setPlaceHolderTextToLineEdit(const QString &text)
{
	mLineEdit->setPlaceholderText(text);
}

QString SearchLineEdit::getText() const
{
	return mLineEdit->text();
}

void SearchLineEdit::clearText()
{
	mLineEdit->clear();
}

QToolButton *SearchLineEdit::initButton(const QIcon &icon, const QString &toolTip)
{
	QToolButton * const result = new QToolButton(this);
	result->setIcon(icon);
	result->setToolTip(toolTip);
	result->setStyleSheet("QToolButton { border: 0; } QToolButton:menu-indicator { image: none; }");
	return result;
}

void SearchLineEdit::onTextChanged(const QString &text)
{
	mClearButton->setVisible(!text.isEmpty());
	notifyTextChanged();
}

void SearchLineEdit::makeContextMenu()
{
	connect(mCaseSensitive, &QAction::triggered, [=]() {
		mCurrentOption = SearchOptions::CaseSensitive;
		notifyTextChanged();
	});
	connect(mCaseInsensitive, &QAction::triggered, [=]() {
		mCurrentOption = SearchOptions::CaseInsensitive;
		notifyTextChanged();
	});
	connect(mRegularExpression, &QAction::triggered, [=]() {
		mCurrentOption = SearchOptions::RegularExpression;
		notifyTextChanged();
	});

	QActionGroup * const group = new QActionGroup(this);
	group->setExclusive(true);
	group->addAction(mCaseInsensitive);
	group->addAction(mCaseSensitive);
	group->addAction(mRegularExpression);

	for (QAction * const action : group->actions()) {
		action->setCheckable(true);
	}

	QMenu * const menu = new QMenu(this);
	menu->addActions(group->actions());
	mOptionsButton->setMenu(menu);
}

void SearchLineEdit::notifyTextChanged()
{
	emit textChanged(regexpFromText(mLineEdit->text(), mCurrentOption));
}

QRegExp SearchLineEdit::regexpFromText(const QString &text, SearchOptions option) const
{
	if (option == SearchOptions::RegularExpression) {
		return QRegExp(text);
	}

	const QStringList parts = text.split(QRegExp("\\s+"), QString::SkipEmptyParts);
	QRegExp result(parts.join("|"));
	result.setCaseSensitivity(option == SearchOptions::CaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
	return result;
}
<commit_msg>fix search options<commit_after>/* Copyright 2015 QReal Research Group, Dmitry Mordvinov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "searchLineEdit.h"

#include <QtCore/QPropertyAnimation>
#include <QtGui/QIcon>
#include <QtWidgets/QAction>
#include <QtWidgets/QMenu>
#include <QtWidgets/QStyle>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QLineEdit>

using namespace qReal::ui;

SearchLineEdit::SearchLineEdit(QWidget *parent, bool borderEnabled)
	: QFrame(parent)
	, mOptionsButton(initButton(QIcon(":/widgets/icons/find.svg"), QString()))
	, mClearButton(initButton(style()->standardIcon(QStyle::SP_LineEditClearButton), tr("Clear text")))
	, mCaseInsensitive(new QAction(tr("Case insensitive"), this))
	, mCaseSensitive(new QAction(tr("Case sensitive"), this))
	, mRegularExpression(new QAction(tr("Regular expression"), this))
	, mCurrentOption(SearchOptions::CaseInsensitive)
{
	QHBoxLayout * const layout = new QHBoxLayout(this);
	layout->setContentsMargins(2, 2, 2, 2);
	layout->setSpacing(2);

	mLineEdit = new QLineEdit(this);
	connect(mLineEdit, &QLineEdit::textChanged, this, &SearchLineEdit::onTextChanged);
	mLineEdit->setPlaceholderText(tr("Enter search text..."));
	mLineEdit->setStyleSheet("border: 0");

	makeContextMenu();
	mOptionsButton->setPopupMode(QToolButton::InstantPopup);
	mOptionsButton->setFixedSize(16, 12);
	mCaseInsensitive->trigger();

	connect(mClearButton, &QAbstractButton::clicked, mLineEdit, &QLineEdit::clear);
	mClearButton->setFixedSize(16, 16);
	mClearButton->hide();

	layout->addWidget(mOptionsButton);
	layout->addWidget(mLineEdit);
	layout->addWidget(mClearButton);

	setBorderEnabled(borderEnabled);
}

void SearchLineEdit::setBorderEnabled(bool enabled)
{
	if (enabled) {
		setStyleSheet("QFrame { background: white; border: 1px solid black; border-radius: 2px; }");
	} else {
		setStyleSheet("QFrame { background: white; }");
	}
}

void SearchLineEdit::setLineEditColor(const QColor &color)
{
	mLineEdit->setStyleSheet(QString("QLineEdit {background: %1}").arg(color.name(QColor::HexArgb)));
}

void SearchLineEdit::focusMe()
{
	mLineEdit->setFocus(Qt::ShortcutFocusReason);
}

void SearchLineEdit::setSearchOption(const SearchLineEdit::SearchOptions &option)
{
	mCurrentOption = option;
}

void SearchLineEdit::makeSearchOptionsSelectable(bool selectable)
{
	mOptionsButton->setEnabled(selectable);
}

void SearchLineEdit::setPlaceHolderTextToLineEdit(const QString &text)
{
	mLineEdit->setPlaceholderText(text);
}

QString SearchLineEdit::getText() const
{
	return mLineEdit->text();
}

void SearchLineEdit::clearText()
{
	mLineEdit->clear();
}

QToolButton *SearchLineEdit::initButton(const QIcon &icon, const QString &toolTip)
{
	QToolButton * const result = new QToolButton(this);
	result->setIcon(icon);
	result->setToolTip(toolTip);
	result->setStyleSheet("QToolButton { border: 0; } QToolButton:menu-indicator { image: none; }");
	return result;
}

void SearchLineEdit::onTextChanged(const QString &text)
{
	mClearButton->setVisible(!text.isEmpty());
	notifyTextChanged();
}

void SearchLineEdit::makeContextMenu()
{
	connect(mCaseSensitive, &QAction::triggered, [=]() {
		mCurrentOption = SearchOptions::CaseSensitive;
		notifyTextChanged();
	});

	connect(mCaseInsensitive, &QAction::triggered, [=]() {
		mCurrentOption = SearchOptions::CaseInsensitive;
		notifyTextChanged();
	});

	connect(mRegularExpression, &QAction::triggered, [=]() {
		mCurrentOption = SearchOptions::RegularExpression;
		notifyTextChanged();
	});

	QActionGroup * const group = new QActionGroup(this);
	group->setExclusive(true);
	group->addAction(mCaseInsensitive);
	group->addAction(mCaseSensitive);
	group->addAction(mRegularExpression);

	for (QAction * const action : group->actions()) {
		action->setCheckable(true);
	}

	QMenu * const menu = new QMenu(this);
	menu->addActions(group->actions());
	mOptionsButton->setMenu(menu);
}

void SearchLineEdit::notifyTextChanged()
{
	emit textChanged(regexpFromText(mLineEdit->text(), mCurrentOption));
}

QRegExp SearchLineEdit::regexpFromText(const QString &text, SearchOptions option) const
{
	QRegExp result(text);

	switch (option) {
		case SearchOptions::RegularExpression:
			return result;
		case SearchOptions::CaseInsensitive:
			result.setPatternSyntax(QRegExp::FixedString);
			result.setCaseSensitivity(Qt::CaseInsensitive);
			return result;
		case SearchOptions::CaseSensitive:
			result.setPatternSyntax(QRegExp::FixedString);
			result.setCaseSensitivity(Qt::CaseSensitive);
			return result;
	}
}
<|endoftext|>


<commit_before><commit_msg>Shuffle: fix hint<commit_after><|endoftext|>


<commit_before><commit_msg>adding TC/699-DIV2-500.cc<commit_after><|endoftext|>


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

#include "flow_graph/instruction_provider.h"

#include "absl/memory/memory.h"

#include "reil/aarch64.h"

#define GOOGLE_STRIP_LOG 1
#include "glog/logging.h"

namespace reil {
uint64_t InstructionProvider::NextNativeInstruction(uint64_t address) {
  uint64_t next_address = 0;

  if (memory_image_.executable(address)) {
    absl::Span<const uint8_t> bytes = memory_image_.Read(address);
    next_address = NextNativeInstruction(address, bytes);
  }

  return next_address;
}

std::shared_ptr<reil::NativeInstruction> InstructionProvider::NativeInstruction(
    uint64_t address) {
  std::shared_ptr<reil::NativeInstruction> ni = nullptr;

  auto cache_iter = cache_.find(address);
  if (cache_iter != cache_.end()) {
    ni = cache_iter->second.lock();
  }

  if (!ni) {
    if (memory_image_.executable(address)) {
      absl::Span<const uint8_t> bytes = memory_image_.Read(address);
      ni = std::make_shared<reil::NativeInstruction>(std::move(NativeInstruction(address, bytes)));
      cache_[address] = ni;
      cache__[cache__index_++ % cache__.size()] = ni;
    }
  }

  return ni;
}

Node InstructionProvider::NextInstruction(const Node& node) {
  auto ni = NativeInstruction(node.address);
  if ((uint64_t)node.offset + 1 < ni->reil.size()) {
    return Node(node.address, node.offset + 1);
  } else {
    return Node(NextNativeInstruction(node.address));
  }
}

reil::Instruction InstructionProvider::Instruction(const Node& node) {
  auto ni = NativeInstruction(node.address);
  DCHECK(node.offset < ni->reil.size());
  return ni->reil[node.offset];
}

InstructionProvider::InstructionProvider(const MemoryImage& memory_image,
                                   enum TranslationFlags flags)
    : memory_image_(memory_image), flags_(flags) {}

InstructionProvider::~InstructionProvider() {}

class AArch64InstructionProvider : public InstructionProvider {
 protected:
  uint64_t NextNativeInstruction(uint64_t address,
                                 absl::Span<const uint8_t> bytes) override;
  reil::NativeInstruction NativeInstruction(uint64_t address,
                                      absl::Span<const uint8_t> bytes) override;

 public:
  AArch64InstructionProvider(const MemoryImage& memory_image,
                          enum TranslationFlags flags)
      : InstructionProvider(memory_image, flags) {}
};

uint64_t AArch64InstructionProvider::NextNativeInstruction(
    uint64_t address, absl::Span<const uint8_t> bytes) {
  return address + 4;
}

reil::NativeInstruction AArch64InstructionProvider::NativeInstruction(
    uint64_t address, absl::Span<const uint8_t> bytes) {
  return reil::aarch64::TranslateInstruction(address, bytes.data(),
                                             bytes.size(), flags_);
}

std::unique_ptr<InstructionProvider> InstructionProvider::Create(
    const MemoryImage& memory_image, enum TranslationFlags flags) {
  if (memory_image.architecture_name() == "aarch64") {
    return absl::make_unique<AArch64InstructionProvider>(memory_image, flags);
  } else {
    LOG(FATAL) << "Unsupported architecture";
  }
}
}  // namespace reil<commit_msg>Removing unneccessary move.<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "flow_graph/instruction_provider.h"

#include "absl/memory/memory.h"

#include "reil/aarch64.h"

#define GOOGLE_STRIP_LOG 1
#include "glog/logging.h"

namespace reil {
uint64_t InstructionProvider::NextNativeInstruction(uint64_t address) {
  uint64_t next_address = 0;

  if (memory_image_.executable(address)) {
    absl::Span<const uint8_t> bytes = memory_image_.Read(address);
    next_address = NextNativeInstruction(address, bytes);
  }

  return next_address;
}

std::shared_ptr<reil::NativeInstruction> InstructionProvider::NativeInstruction(
    uint64_t address) {
  std::shared_ptr<reil::NativeInstruction> ni = nullptr;

  auto cache_iter = cache_.find(address);
  if (cache_iter != cache_.end()) {
    ni = cache_iter->second.lock();
  }

  if (!ni) {
    if (memory_image_.executable(address)) {
      absl::Span<const uint8_t> bytes = memory_image_.Read(address);
      ni = std::make_shared<reil::NativeInstruction>(NativeInstruction(address, bytes));
      cache_[address] = ni;
      cache__[cache__index_++ % cache__.size()] = ni;
    }
  }

  return ni;
}

Node InstructionProvider::NextInstruction(const Node& node) {
  auto ni = NativeInstruction(node.address);
  if ((uint64_t)node.offset + 1 < ni->reil.size()) {
    return Node(node.address, node.offset + 1);
  } else {
    return Node(NextNativeInstruction(node.address));
  }
}

reil::Instruction InstructionProvider::Instruction(const Node& node) {
  auto ni = NativeInstruction(node.address);
  DCHECK(node.offset < ni->reil.size());
  return ni->reil[node.offset];
}

InstructionProvider::InstructionProvider(const MemoryImage& memory_image,
                                   enum TranslationFlags flags)
    : memory_image_(memory_image), flags_(flags) {}

InstructionProvider::~InstructionProvider() {}

class AArch64InstructionProvider : public InstructionProvider {
 protected:
  uint64_t NextNativeInstruction(uint64_t address,
                                 absl::Span<const uint8_t> bytes) override;
  reil::NativeInstruction NativeInstruction(uint64_t address,
                                      absl::Span<const uint8_t> bytes) override;

 public:
  AArch64InstructionProvider(const MemoryImage& memory_image,
                          enum TranslationFlags flags)
      : InstructionProvider(memory_image, flags) {}
};

uint64_t AArch64InstructionProvider::NextNativeInstruction(
    uint64_t address, absl::Span<const uint8_t> bytes) {
  return address + 4;
}

reil::NativeInstruction AArch64InstructionProvider::NativeInstruction(
    uint64_t address, absl::Span<const uint8_t> bytes) {
  return reil::aarch64::TranslateInstruction(address, bytes.data(),
                                             bytes.size(), flags_);
}

std::unique_ptr<InstructionProvider> InstructionProvider::Create(
    const MemoryImage& memory_image, enum TranslationFlags flags) {
  if (memory_image.architecture_name() == "aarch64") {
    return absl::make_unique<AArch64InstructionProvider>(memory_image, flags);
  } else {
    LOG(FATAL) << "Unsupported architecture";
  }
}
}  // namespace reil<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CPlotApp.h"
#include "Document.h"
#include "../Persistence/Serializer.h"
#include "MainWindow.h"
#include "SideView.h"
#include <propkey.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

IMPLEMENT_DYNCREATE(Document, CDocument)

Document::Document()
: plot(rns)
{
}

Document::~Document()
{
}

BOOL Document::OnNewDocument()
{
	if (!CDocument::OnNewDocument()) return FALSE;

	plot.clear();
	rns.clear();

	return TRUE;
}

void Document::Serialize(CArchive &ar)
{
	MainWindow* w = (MainWindow*)AfxGetMainWnd();
	SideView *sv = w ? &w->GetSideView() : NULL;

	if (ar.IsStoring())
	{
		FileWriter fw(ar.GetFile());
		Serializer  w(fw);
		rns.save(w);
		plot.save(w);
		BoxState b; b.all = -1;
		if (sv) b = sv->GetBoxState();
		if (w.version() >= FILE_VERSION_1_8) w.uint32_(b.all);
		w.marker_("EOF.");
	}
	else
	{
		FileReader   fr(ar.GetFile());
		Deserializer s(fr);
		plot.clear(); // TODO: don't modify on fail
		rns.clear();
		rns.load(s);
		plot.load(s);
		BoxState b; b.all = -1;
		if (s.version() >= FILE_VERSION_1_8) s.uint32_(b.all);
		s.marker_("EOF.");
		assert(s.done());
		if (sv) sv->SetBoxState(b);
	}
}
<commit_msg>handle serialization errors better<commit_after>#include "stdafx.h"
#include "CPlotApp.h"
#include "Document.h"
#include "../Persistence/Serializer.h"
#include "MainWindow.h"
#include "SideView.h"
#include <propkey.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

IMPLEMENT_DYNCREATE(Document, CDocument)

Document::Document()
: plot(rns)
{
}

Document::~Document()
{
}

BOOL Document::OnNewDocument()
{
	if (!CDocument::OnNewDocument()) return FALSE;

	plot.clear();
	rns.clear();

	return TRUE;
}

void Document::Serialize(CArchive &ar)
{
	MainWindow* w = (MainWindow*)AfxGetMainWnd();
	SideView *sv = w ? &w->GetSideView() : NULL;

	try
	{
		if (ar.IsStoring())
		{
			FileWriter fw(ar.GetFile());
			Serializer  w(fw);
			rns.save(w);
			plot.save(w);
			BoxState b; b.all = -1;
			if (sv) b = sv->GetBoxState();
			if (w.version() >= FILE_VERSION_1_8) w.uint32_(b.all);
			w.marker_("EOF.");
		}
		else
		{
			FileReader   fr(ar.GetFile());
			Deserializer s(fr);
			plot.clear(); // TODO: don't modify on fail
			rns.clear();
			rns.load(s);
			plot.load(s);
			BoxState b; b.all = -1;
			if (s.version() >= FILE_VERSION_1_8) s.uint32_(b.all);
			s.marker_("EOF.");
			assert(s.done());
			if (sv) sv->SetBoxState(b);
		}
	}
	catch (const std::exception &ex)
	{
		MessageBox(NULL, CString(ex.what()), _T("Error"), MB_OK | MB_ICONERROR);
		THROW(new CArchiveException);
	}
	catch (...)
	{
		MessageBox(NULL, _T("Unexpected exception"), _T("Error"), MB_OK | MB_ICONERROR);
		THROW(new CArchiveException);
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: EditBase.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: fs $ $Date: 2002-12-02 09:56:30 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FORMS_EDITBASE_HXX_
#define _FORMS_EDITBASE_HXX_

#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif
#ifndef _DATE_HXX
#include <tools/date.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif

#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_
#include <com/sun/star/awt/XFocusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XKEYLISTENER_HPP_
#include <com/sun/star/awt/XKeyListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XCHANGEBROADCASTER_HPP_
#include <com/sun/star/form/XChangeBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

// persistence flags for use with the version id
#define PF_HANDLE_COMMON_PROPS  0x8000
    // Derived classes which use their own persistence methods (read/write) and have an own
    // version handling therein may want to clear this flag in getPersistenceFlags.
    // If done so, this class will write an version without a call to writeCommonEditProperties.
#define PF_FAKE_FORMATTED_FIELD 0x4000
    // .... hmmm .... a fake, as the name suggests. see OFormattedFieldWrapper
#define PF_RESERVED_2           0x2000
#define PF_RESERVED_3           0x1000
#define PF_RESERVED_4           0x0800
#define PF_RESERVED_5           0x0400
#define PF_RESERVED_6           0x0200
#define PF_RESERVED_7           0x0100

#define PF_SPECIAL_FLAGS        0xFF00

//.........................................................................
namespace frm
{

//==================================================================
//= OEditBaseModel
//==================================================================
class OEditBaseModel :  public OBoundControlModel
{
    sal_Int16                   m_nLastReadVersion;

protected:
// [properties]         fuer all Editierfelder
    ::com::sun::star::uno::Any  m_aDefault;
    ::rtl::OUString             m_aDefaultText;             // default value
    sal_Bool                    m_bEmptyIsNull : 1;         // empty string will be interepreted as NULL when committing
    sal_Bool                    m_bFilterProposal : 1;      // use a list of possible value in filtermode
// [properties]

    sal_Int16   getLastReadVersion() const { return m_nLastReadVersion; }

public:
    DECLARE_DEFAULT_XTOR( OEditBaseModel );

    // XPersistObject
    virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;
    virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue,
                                          sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
                                        throw(::com::sun::star::lang::IllegalArgumentException);
    virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception);

    // XPropertyState
    virtual ::com::sun::star::beans::PropertyState getPropertyStateByHandle(sal_Int32 nHandle);
    virtual void setPropertyToDefaultByHandle(sal_Int32 nHandle);
    virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 nHandle ) const;

protected:
    // new properties common to all edit models should be handled with the following two methods
    void SAL_CALL readCommonEditProperties(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream);
    void SAL_CALL writeCommonEditProperties(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream);
    void defaultCommonEditProperties();

    virtual sal_Int16 getPersistenceFlags() const;
        // derived classes may use this if they want this base class to write additinal version flags
        // (one of the PF_.... constants). After ::read they may ask for that flags with getLastReadVersion
};

//.........................................................................
}
//.........................................................................

#endif // _FORMS_EDITBASE_HXX_

<commit_msg>INTEGRATION: CWS formcelllinkage (1.5.92); FILE MERGED 2003/10/01 09:18:23 fs 1.5.92.1: #i18994# merging the changes from the CWS fs002<commit_after>/*************************************************************************
 *
 *  $RCSfile: EditBase.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2003-10-21 08:57:29 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FORMS_EDITBASE_HXX_
#define _FORMS_EDITBASE_HXX_

#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif
#ifndef _DATE_HXX
#include <tools/date.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif

#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_
#include <com/sun/star/awt/XFocusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XKEYLISTENER_HPP_
#include <com/sun/star/awt/XKeyListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XCHANGEBROADCASTER_HPP_
#include <com/sun/star/form/XChangeBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

// persistence flags for use with the version id
#define PF_HANDLE_COMMON_PROPS  0x8000
    // Derived classes which use their own persistence methods (read/write) and have an own
    // version handling therein may want to clear this flag in getPersistenceFlags.
    // If done so, this class will write an version without a call to writeCommonEditProperties.
#define PF_FAKE_FORMATTED_FIELD 0x4000
    // .... hmmm .... a fake, as the name suggests. see OFormattedFieldWrapper
#define PF_RESERVED_2           0x2000
#define PF_RESERVED_3           0x1000
#define PF_RESERVED_4           0x0800
#define PF_RESERVED_5           0x0400
#define PF_RESERVED_6           0x0200
#define PF_RESERVED_7           0x0100

#define PF_SPECIAL_FLAGS        0xFF00

//.........................................................................
namespace frm
{

//==================================================================
//= OEditBaseModel
//==================================================================
class OEditBaseModel :  public OBoundControlModel
{
    sal_Int16                   m_nLastReadVersion;

protected:
// [properties]         fuer all Editierfelder
    ::com::sun::star::uno::Any  m_aDefault;
    ::rtl::OUString             m_aDefaultText;             // default value
    sal_Bool                    m_bEmptyIsNull : 1;         // empty string will be interepreted as NULL when committing
    sal_Bool                    m_bFilterProposal : 1;      // use a list of possible value in filtermode
// [properties]

    sal_Int16   getLastReadVersion() const { return m_nLastReadVersion; }

public:
    DECLARE_DEFAULT_BOUND_XTOR( OEditBaseModel );

    // XPersistObject
    virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;
    virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue,
                                          sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
                                        throw(::com::sun::star::lang::IllegalArgumentException);
    virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception);

    // XPropertyState
    virtual ::com::sun::star::beans::PropertyState getPropertyStateByHandle(sal_Int32 nHandle);
    virtual void setPropertyToDefaultByHandle(sal_Int32 nHandle);
    virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 nHandle ) const;

protected:
    // new properties common to all edit models should be handled with the following two methods
    void SAL_CALL readCommonEditProperties(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream);
    void SAL_CALL writeCommonEditProperties(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream);
    void defaultCommonEditProperties();

    virtual sal_Int16 getPersistenceFlags() const;
        // derived classes may use this if they want this base class to write additinal version flags
        // (one of the PF_.... constants). After ::read they may ask for that flags with getLastReadVersion
};

//.........................................................................
}
//.........................................................................

#endif // _FORMS_EDITBASE_HXX_

<|endoftext|>


<commit_before>#include "stdafx.h"

#include "Guild.h"
#include <ATF/global.hpp>
#include <ATF/CItemStoreManager.hpp>

namespace GameServer
{
    namespace Fixes
    {
        void CGuild::load()
        {
            enable_hook(&ATF::CGuild::ManageAcceptORRefuseGuildBattle, &CGuild::ManageAcceptORRefuseGuildBattle);
            enable_hook(&ATF::CPlayer::pc_GuildRoomEnterRequest, &CGuild::pc_GuildRoomEnterRequest);
            enable_hook(&ATF::CPlayer::pc_GuildRoomOutRequest, &CGuild::pc_GuildRoomOutRequest);
            enable_hook(&ATF::CPlayer::pc_GuildManageRequest, &CGuild::pc_GuildManageRequest);
            enable_hook(&ATF::CGuild::ManageExpulseMember, &CGuild::ManageExpulseMember);
        }

        void CGuild::unload()
        {
            cleanup_all_hook();
        }

        ModuleName_t CGuild::get_name()
        {
            static const ModuleName_t name = "fix_Guild";
            return name;
        }

        char WINAPIV CGuild::ManageAcceptORRefuseGuildBattle(
            ATF::CGuild * pObj,
            bool bAccept,
            ATF::Info::CGuildManageAcceptORRefuseGuildBattle80_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            static const int dwCostBattleGold = 5000;

            char result = 0;
            do
            {
                if (pObj->m_GuildBattleSugestMatter.eState != ATF::_guild_battle_suggest_matter::APPLY_BATTLE_REQUEST_SUGGEST)
                {
                    result = 111;
                    break;
                }

                if (bAccept)
                {
                    if (pObj->m_dTotalGold < dwCostBattleGold)
                    {
                        result = 116;
                        break;
                    }

                    result = ATF::CGuildBattleController::Instance()->Add(
                        pObj->m_GuildBattleSugestMatter.pkSrc,
                        pObj->m_GuildBattleSugestMatter.pkDest,
                        pObj->m_GuildBattleSugestMatter.dwStartTime,
                        pObj->m_GuildBattleSugestMatter.dwNumber,
                        pObj->m_GuildBattleSugestMatter.dwMapIdx);

                    if (result)
                    {
                        if (result == 112)
                            result = 119;

                        pObj->m_GuildBattleSugestMatter.pkSrc->PushDQSInGuildBattleCost();
                        pObj->m_GuildBattleSugestMatter.pkSrc->SendMsg_ApplyGuildBattleResultInform(result, pObj->m_wszName);
                    }
                    else
                    {
                        pObj->PushDQSDestGuildOutputGuildBattleCost();
                        if (ATF::CHonorGuild::Instance()->CheckHonorGuild(
                            pObj->m_GuildBattleSugestMatter.pkSrc->m_byRace,
                            pObj->m_GuildBattleSugestMatter.pkSrc->m_dwSerial))
                        {
                            ATF::CMoneySupplyMgr::Instance()->UpdateHonorGuildMoneyData(1, pObj->m_byRace, dwCostBattleGold);
                        }
                    }
                }
                else
                {
                    pObj->m_GuildBattleSugestMatter.pkSrc->SendMsg_GuildBattleRefused(pObj->m_wszName);
                    pObj->m_GuildBattleSugestMatter.pkSrc->PushDQSInGuildBattleCost();
                }

                pObj->m_GuildBattleSugestMatter.pkSrc->m_GuildBattleSugestMatter.Clear();
                pObj->m_GuildBattleSugestMatter.Clear();
            } while (false);

            return result;
        }

        void WINAPIV CGuild::pc_GuildRoomEnterRequest(
            ATF::CPlayer * pPlayer,
            ATF::_guildroom_enter_request_clzo * pProtocol,
            ATF::Info::CPlayerpc_GuildRoomEnterRequest1755_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            auto fnFindNpc = [pPlayer](ATF::CMapItemStoreList* pMapItemStoreList)->bool
            {
                for (int j = 0; j < pMapItemStoreList->m_nItemStoreNum; ++j)
                {
                    auto& pItemStore = pMapItemStoreList->m_ItemStore[j];
                    if (!pItemStore.m_bLive)
                        continue;

                    auto pPosStore = pItemStore.GetStorePos();
                    for (auto button : pItemStore.m_pRec->m_nNpc_Class)
                    {
                        if (button != 44)
                            continue;

                        if (ATF::Global::Get3DSqrt(pPosStore, pPlayer->m_fCurPos) < 100.0)
                        {
                            return true;
                        }
                    }
                }

                return false;
            };

            char byRetCode = 0;
            char bySubRetCode = 3;
            char byMapIndex = 0;
            int nRoomType = 0;
            unsigned __int16 wMapLayer = 0;
            float pfStartPos[3];

            do
            {
                if (pPlayer->GetCurSecNum() == -1 || pPlayer->m_bMapLoading)
                {
                    byRetCode = 5;
                    break;
                }

                if (pPlayer->IsRidingUnit())
                {
                    byRetCode = 6;
                    break;
                }

                if (pPlayer->m_byStandType == 1)
                {
                    byRetCode = 7;
                    break;
                }

                if (!pPlayer->m_Param.m_pGuild)
                {
                    byRetCode = 1;
                    break;
                }

                auto pGuild = pPlayer->m_Param.m_pGuild;
                if (pProtocol->dwGuildSerial != pGuild->m_dwSerial)
                {
                    byRetCode = 1;
                    break;
                }

                auto pGuildRoomSystem = ATF::CGuildRoomSystem::GetInstance();
                if (!pGuildRoomSystem->IsRoomRented(pGuild->m_dwSerial))
                {
                    byRetCode = 2;
                    break;
                }

                bySubRetCode = pGuildRoomSystem->RoomIn(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial);
                if (bySubRetCode)
                {
                    byRetCode = 3;
                    break;
                }

                ATF::CMapData *pMap = nullptr;
                char byRoomType;
                if (!pGuildRoomSystem->GetMapPos(pGuild->m_dwSerial, pfStartPos, pMap, &wMapLayer, &byRoomType))
                {
                    pGuildRoomSystem->RoomOut(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial);
                    byRetCode = 4;
                    break;
                }

                if (pPlayer->m_byStoneMapMoveInfo == 1)
                {
                    pPlayer->m_byStoneMapMoveInfo = 2;
                }
                else if (pPlayer->m_byStoneMapMoveInfo == 2)
                {
                    byRetCode = 5;
                    break;
                }
                else
                {
                    auto nSerial = pPlayer->m_pCurMap->GetMapCode();
                    auto pItemStoreMngInstance = ATF::CItemStoreManager::Instance();
                    auto pItemStoreList = pItemStoreMngInstance->GetMapItemStoreListBySerial(nSerial);
                    if (!pItemStoreList)
                    {
                        byRetCode = 5;
                        break;
                    }

                    if (!fnFindNpc(pItemStoreList))
                    {
                        byRetCode = 5;
                        break;
                    }
                }

                // SUCESS
                byRetCode = 10;
                pMap = pGuildRoomSystem->GetMapData(pPlayer->m_Param.GetRaceCode(), byRoomType);
                pPlayer->OutOfMap(pMap, wMapLayer, 3, pfStartPos);
                byMapIndex = pMap->m_pMapSet->m_dwIndex;
                pGuildRoomSystem->GetRestTime(pGuild->m_dwSerial, &nRoomType);
            } while (false);

            pPlayer->SendMsg_GuildRoomEnterResult(
                byRetCode,
                bySubRetCode,
                byMapIndex,
                wMapLayer,
                pfStartPos,
                nRoomType);
        }

        void WINAPIV CGuild::pc_GuildRoomOutRequest(
            ATF::CPlayer * pPlayer,
            ATF::_guildroom_out_request_clzo * pProtocol,
            ATF::Info::CPlayerpc_GuildRoomOutRequest1757_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            char byResult = 0;

            do
            {
                if (pPlayer->GetCurSecNum() == -1 || pPlayer->m_bMapLoading)
                {
                    byResult = 4;
                    break;
                }

                if (pPlayer->IsRidingUnit())
                {
                    byResult = 5;
                    break;
                }

                if (pPlayer->m_byStandType == 1)
                {
                    byResult = 6;
                    break;
                }

                if (!pPlayer->m_Param.m_pGuild)
                {
                    byResult = 1;
                    break;
                }

                auto pGuild = pPlayer->m_Param.m_pGuild;
                if (pProtocol->dwGuildSerial != pGuild->m_dwSerial)
                {
                    byResult = 1;
                    break;
                }

                auto pGuildRoomSystem = ATF::CGuildRoomSystem::GetInstance();
                if (!pGuildRoomSystem->IsRoomRented(pGuild->m_dwSerial))
                {
                    byResult = 2;
                    break;
                }

                if (!pGuildRoomSystem->RoomIn(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial))
                {
                    byResult = 1;
                    break;
                }

                if (!pGuildRoomSystem->SetPlayerOut(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial))
                {
                    byResult = 2;
                    break;
                }
            } while (false);

            if (byResult != 0)
                pPlayer->SendMsg_GuildRoomOutResult(byResult, 0, 0, nullptr);
        }

        char WINAPIV CGuild::ManageExpulseMember(
            ATF::CGuild * pGuild,
            unsigned int dwMemberSerial,
            ATF::Info::CGuildManageExpulseMember84_ptr next)
        {
            auto pInstance = ATF::GUILD_BATTLE::CNormalGuildBattleManager::Instance();
            LPVOID pBattle = pInstance->GetBattleByGuildSerial(pGuild->m_dwSerial);
            if (pBattle)
            {
                return 0x6e;
            }

            return next(pGuild, dwMemberSerial);
        }

        void WINAPIV CGuild::pc_GuildManageRequest(
            ATF::CPlayer* pPlayer,
            char byType,
            unsigned int dwDst,
            unsigned int dwObj1,
            unsigned int dwObj2,
            unsigned int dwObj3,
            ATF::Info::CPlayerpc_GuildManageRequest1745_ptr next)
        {
            if (pPlayer->m_Param.m_pGuild)
            {
                next(pPlayer, byType, dwDst, dwObj1, dwObj2, dwObj3);
            }
            else
            {
                pPlayer->SendMsg_GuildManageResult(-53);
            }
        }
    }
}
<commit_msg>Updated fix guild room enter<commit_after>#include "stdafx.h"

#include "Guild.h"
#include <ATF/global.hpp>
#include <ATF/CItemStoreManager.hpp>

namespace GameServer
{
    namespace Fixes
    {
        void CGuild::load()
        {
            enable_hook(&ATF::CGuild::ManageAcceptORRefuseGuildBattle, &CGuild::ManageAcceptORRefuseGuildBattle);
            enable_hook(&ATF::CPlayer::pc_GuildRoomEnterRequest, &CGuild::pc_GuildRoomEnterRequest);
            enable_hook(&ATF::CPlayer::pc_GuildRoomOutRequest, &CGuild::pc_GuildRoomOutRequest);
            enable_hook(&ATF::CPlayer::pc_GuildManageRequest, &CGuild::pc_GuildManageRequest);
            enable_hook(&ATF::CGuild::ManageExpulseMember, &CGuild::ManageExpulseMember);
        }

        void CGuild::unload()
        {
            cleanup_all_hook();
        }

        ModuleName_t CGuild::get_name()
        {
            static const ModuleName_t name = "fix_Guild";
            return name;
        }

        char WINAPIV CGuild::ManageAcceptORRefuseGuildBattle(
            ATF::CGuild * pObj,
            bool bAccept,
            ATF::Info::CGuildManageAcceptORRefuseGuildBattle80_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            static const int dwCostBattleGold = 5000;

            char result = 0;
            do
            {
                if (pObj->m_GuildBattleSugestMatter.eState != ATF::_guild_battle_suggest_matter::APPLY_BATTLE_REQUEST_SUGGEST)
                {
                    result = 111;
                    break;
                }

                if (bAccept)
                {
                    if (pObj->m_dTotalGold < dwCostBattleGold)
                    {
                        result = 116;
                        break;
                    }

                    result = ATF::CGuildBattleController::Instance()->Add(
                        pObj->m_GuildBattleSugestMatter.pkSrc,
                        pObj->m_GuildBattleSugestMatter.pkDest,
                        pObj->m_GuildBattleSugestMatter.dwStartTime,
                        pObj->m_GuildBattleSugestMatter.dwNumber,
                        pObj->m_GuildBattleSugestMatter.dwMapIdx);

                    if (result)
                    {
                        if (result == 112)
                            result = 119;

                        pObj->m_GuildBattleSugestMatter.pkSrc->PushDQSInGuildBattleCost();
                        pObj->m_GuildBattleSugestMatter.pkSrc->SendMsg_ApplyGuildBattleResultInform(result, pObj->m_wszName);
                    }
                    else
                    {
                        pObj->PushDQSDestGuildOutputGuildBattleCost();
                        if (ATF::CHonorGuild::Instance()->CheckHonorGuild(
                            pObj->m_GuildBattleSugestMatter.pkSrc->m_byRace,
                            pObj->m_GuildBattleSugestMatter.pkSrc->m_dwSerial))
                        {
                            ATF::CMoneySupplyMgr::Instance()->UpdateHonorGuildMoneyData(1, pObj->m_byRace, dwCostBattleGold);
                        }
                    }
                }
                else
                {
                    pObj->m_GuildBattleSugestMatter.pkSrc->SendMsg_GuildBattleRefused(pObj->m_wszName);
                    pObj->m_GuildBattleSugestMatter.pkSrc->PushDQSInGuildBattleCost();
                }

                pObj->m_GuildBattleSugestMatter.pkSrc->m_GuildBattleSugestMatter.Clear();
                pObj->m_GuildBattleSugestMatter.Clear();
            } while (false);

            return result;
        }

        void WINAPIV CGuild::pc_GuildRoomEnterRequest(
            ATF::CPlayer * pPlayer,
            ATF::_guildroom_enter_request_clzo * pProtocol,
            ATF::Info::CPlayerpc_GuildRoomEnterRequest1755_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            auto fnFindNpc = [pPlayer](ATF::CMapItemStoreList* pMapItemStoreList)->bool
            {
                for (int j = 0; j < pMapItemStoreList->m_nItemStoreNum; ++j)
                {
                    auto& pItemStore = pMapItemStoreList->m_ItemStore[j];
                    if (!pItemStore.m_bLive)
                        continue;

                    auto pPosStore = pItemStore.GetStorePos();
                    for (auto button : pItemStore.m_pRec->m_nNpc_Class)
                    {
                        if (button != 44)
                            continue;

                        if (ATF::Global::Get3DSqrt(pPosStore, pPlayer->m_fCurPos) < 100.0)
                        {
                            return true;
                        }
                    }
                }

                return false;
            };

            char byRetCode = 0;
            char bySubRetCode = 3;
            char byMapIndex = 0;
            int nRoomType = 0;
            unsigned __int16 wMapLayer = 0;
            float pfStartPos[3];

            do
            {
                if (pPlayer->GetCurSecNum() == -1 || pPlayer->m_bMapLoading)
                {
                    byRetCode = 5;
                    break;
                }

                if (pPlayer->IsRidingUnit())
                {
                    byRetCode = 6;
                    break;
                }

                if (pPlayer->m_byStandType == 1)
                {
                    byRetCode = 7;
                    break;
                }

                if (!pPlayer->m_Param.m_pGuild)
                {
                    byRetCode = 1;
                    break;
                }

                auto pGuild = pPlayer->m_Param.m_pGuild;
                if (pProtocol->dwGuildSerial != pGuild->m_dwSerial)
                {
                    byRetCode = 1;
                    break;
                }

                auto pGuildRoomSystem = ATF::CGuildRoomSystem::GetInstance();
                if (!pGuildRoomSystem->IsRoomRented(pGuild->m_dwSerial))
                {
                    byRetCode = 2;
                    break;
                }

                bySubRetCode = pGuildRoomSystem->RoomIn(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial);
                if (bySubRetCode)
                {
                    byRetCode = 3;
                    break;
                }

                ATF::CMapData *pMap = nullptr;
                char byRoomType;
                if (!pGuildRoomSystem->GetMapPos(pGuild->m_dwSerial, pfStartPos, pMap, &wMapLayer, &byRoomType))
                {
                    pGuildRoomSystem->RoomOut(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial);
                    byRetCode = 4;
                    break;
                }

                auto nSerial = pPlayer->m_pCurMap->GetMapCode();
                auto pItemStoreMngInstance = ATF::CItemStoreManager::Instance();
                auto pItemStoreList = pItemStoreMngInstance->GetMapItemStoreListBySerial(nSerial);
                if (!pItemStoreList)
                {
                    byRetCode = 5;
                    break;
                }

                if (!fnFindNpc(pItemStoreList))
                {
                    byRetCode = 5;
                    break;
                }

                // SUCESS
                byRetCode = 10;
                pMap = pGuildRoomSystem->GetMapData(pPlayer->m_Param.GetRaceCode(), byRoomType);
                pPlayer->OutOfMap(pMap, wMapLayer, 3, pfStartPos);
                byMapIndex = pMap->m_pMapSet->m_dwIndex;
                pGuildRoomSystem->GetRestTime(pGuild->m_dwSerial, &nRoomType);
            } while (false);

            pPlayer->SendMsg_GuildRoomEnterResult(
                byRetCode,
                bySubRetCode,
                byMapIndex,
                wMapLayer,
                pfStartPos,
                nRoomType);
        }

        void WINAPIV CGuild::pc_GuildRoomOutRequest(
            ATF::CPlayer * pPlayer,
            ATF::_guildroom_out_request_clzo * pProtocol,
            ATF::Info::CPlayerpc_GuildRoomOutRequest1757_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            char byResult = 0;

            do
            {
                if (pPlayer->GetCurSecNum() == -1 || pPlayer->m_bMapLoading)
                {
                    byResult = 4;
                    break;
                }

                if (pPlayer->IsRidingUnit())
                {
                    byResult = 5;
                    break;
                }

                if (pPlayer->m_byStandType == 1)
                {
                    byResult = 6;
                    break;
                }

                if (!pPlayer->m_Param.m_pGuild)
                {
                    byResult = 1;
                    break;
                }

                auto pGuild = pPlayer->m_Param.m_pGuild;
                if (pProtocol->dwGuildSerial != pGuild->m_dwSerial)
                {
                    byResult = 1;
                    break;
                }

                auto pGuildRoomSystem = ATF::CGuildRoomSystem::GetInstance();
                if (!pGuildRoomSystem->IsRoomRented(pGuild->m_dwSerial))
                {
                    byResult = 2;
                    break;
                }

                if (!pGuildRoomSystem->RoomIn(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial))
                {
                    byResult = 1;
                    break;
                }

                if (!pGuildRoomSystem->SetPlayerOut(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial))
                {
                    byResult = 2;
                    break;
                }
            } while (false);

            if (byResult != 0)
                pPlayer->SendMsg_GuildRoomOutResult(byResult, 0, 0, nullptr);
        }

        char WINAPIV CGuild::ManageExpulseMember(
            ATF::CGuild * pGuild,
            unsigned int dwMemberSerial,
            ATF::Info::CGuildManageExpulseMember84_ptr next)
        {
            auto pInstance = ATF::GUILD_BATTLE::CNormalGuildBattleManager::Instance();
            LPVOID pBattle = pInstance->GetBattleByGuildSerial(pGuild->m_dwSerial);
            if (pBattle)
            {
                return 0x6e;
            }

            return next(pGuild, dwMemberSerial);
        }

        void WINAPIV CGuild::pc_GuildManageRequest(
            ATF::CPlayer* pPlayer,
            char byType,
            unsigned int dwDst,
            unsigned int dwObj1,
            unsigned int dwObj2,
            unsigned int dwObj3,
            ATF::Info::CPlayerpc_GuildManageRequest1745_ptr next)
        {
            if (pPlayer->m_Param.m_pGuild)
            {
                next(pPlayer, byType, dwDst, dwObj1, dwObj2, dwObj3);
            }
            else
            {
                pPlayer->SendMsg_GuildManageResult(-53);
            }
        }
    }
}
<|endoftext|>