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

#include "log.hpp"
#include <sstream>
#include <ctime>
#include <iomanip>

namespace nlp {
    block::block(std::string p_str) : m_str{std::move(p_str)} {}
    std::string & block::value() {
        return m_str;
    }
    std::string const & block::value() const {
        return m_str;
    }
    log::log() {
    }
    log::log(log && p_other) {
        p_other.m_owned = false;
    }
    log::~log() {
        std::cout << std::endl;
    }
    log && log::operator<<(block && p_block) && {
        throw;
    }
}
<commit_msg>Fixed warning caused by pull request.<commit_after>//////////////////////////////////////////////////////////////////////////////
// NoLifePony - Pony Card Game                                              //
// Copyright © 2014 Peter Atashian                                          //
//                                                                          //
// This program is free software: you can redistribute it and/or modify     //
// it under the terms of the GNU Affero General Public License as           //
// published by the Free Software Foundation, either version 3 of the       //
// License, or (at your option) any later version.                          //
//                                                                          //
// This program is distributed in the hope that it will be useful,          //
// but WITHOUT ANY WARRANTY; without even the implied warranty of           //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
// GNU Affero General Public License for more details.                      //
//                                                                          //
// You should have received a copy of the GNU Affero General Public License //
// along with this program.  If not, see <http://www.gnu.org/licenses/>.    //
//////////////////////////////////////////////////////////////////////////////

#include "log.hpp"
#include <sstream>
#include <ctime>
#include <iomanip>

namespace nlp {
    block::block(std::string p_str) : m_str{std::move(p_str)} {}
    std::string & block::value() {
        return m_str;
    }
    std::string const & block::value() const {
        return m_str;
    }
    log::log() {
    }
    log::log(log && p_other) {
        p_other.m_owned = false;
    }
    log::~log() {
        std::cout << std::endl;
    }
    log && log::operator<<(block &&) && {
        throw;
    }
}
<|endoftext|>


<commit_before>#pragma once
#include <cstdio>
namespace nls{
        #ifdef DEBUG
                #ifdef USE_PRETTY_FUNCTION
                        #define ___FUNC___ __PRETTY_FUNCTION__
                #else
                        #define ___FUNC___ __FUNCTION__
                #endif
                #define DBG_TRACE(format,...) fprintf(stdout,"file:%s line:%d func:%s msg:" format "\n", __FILE__,__LINE__,___FUNC___, ##__VA_ARGS__)
        #else
                #define DBG_TRACE(a,...) ((void)0)
        #endif
}
<commit_msg>new debug format.<commit_after>#pragma once
#include <cstdio>
namespace nls{
        #ifdef DEBUG
                #ifdef USE_PRETTY_FUNCTION
                        #define ___FUNC___ __PRETTY_FUNCTION__
                #else
                        #define ___FUNC___ __FUNCTION__
                #endif
                #define DBG_TRACE(format,...) fprintf(stdout,"[\"%s\":%d][%s][" format "]\n", __FILE__,__LINE__,___FUNC___, ##__VA_ARGS__)
        #else
                #define DBG_TRACE(a,...) ((void)0)
        #endif
}
<|endoftext|>


<commit_before>#pragma once

#include <type_traits>
#include <functional>
#include <algorithm>
#include <utility>
#include <cstddef>
#include <vector>
#include <memory>
#include <list>
#include "event.hpp"

namespace uvw {

/**
 * @brief Event emitter base class.
 *
 * Almost everything in `uvw` is an event emitter.

 * This is the base class from which resources and loops inherit.
 */
template<typename T>
class Emitter {
    struct BaseHandler {
        virtual ~BaseHandler() noexcept = default;
        virtual bool empty() const noexcept = 0;
        virtual void clear() noexcept = 0;
    };

    template<typename E>
    struct Handler final: BaseHandler {
        using Listener = std::function<void(E &, T &)>;
        using Element = std::pair<bool, Listener>;
        using ListenerList = std::list<Element>;
        using Connection = typename ListenerList::iterator;

        bool empty() const noexcept override {
            auto pred = [](auto &&element){ return element.first; };

            return std::all_of(onceL.cbegin(), onceL.cend(), pred) &&
                    std::all_of(onL.cbegin(), onL.cend(), pred);
        }

        void clear() noexcept override {
            auto func = [](auto &&element){ element.first = true; };
            std::for_each(onceL.begin(), onceL.end(), func);
            std::for_each(onL.begin(), onL.end(), func);
        }

        Connection once(Listener f) {
            return onceL.emplace(onceL.cend(), false, std::move(f));
        }

        Connection on(Listener f) {
            return onL.emplace(onL.cbegin(), false, std::move(f));
        }

        void erase(Connection conn) noexcept {
            conn->first = true;
        }

        void publish(E event, T &ref) {
            ListenerList currentL;
            onceL.swap(currentL);

            auto func = [&event, &ref](auto &&element) {
                return element.first ? void() : element.second(event, ref);
            };

            std::for_each(onL.rbegin(), onL.rend(), func);
            std::for_each(currentL.rbegin(), currentL.rend(), func);

            onL.remove_if([](auto &&element){ return element.first; });
        }

    private:
        ListenerList onceL{};
        ListenerList onL{};
    };

    template<typename E>
    Handler<E> & handler() noexcept {
        static_assert(std::is_base_of<Event<E>, E>::value, "!");

        std::size_t type = E::type();

        if(!(type < handlers.size())) {
            handlers.resize(type+1);
        }

        if(!handlers[type]) {
           handlers[type] = std::make_unique<Handler<E>>();
        }

        return static_cast<Handler<E>&>(*handlers[type]);
    }

protected:
    template<typename E>
    void publish(E event) {
        handler<E>().publish(std::move(event), *static_cast<T*>(this));
    }

public:
    template<typename E>
    using Listener = typename Handler<E>::Listener;

    /**
     * @brief Connection type for a given event type.
     *
     * Given an event type `E`, `Connection<E>` is the type of the connection
     * object returned by the event emitter whenever a listener for the given
     * type is registered.
     */
    template<typename E>
    struct Connection: private Handler<E>::Connection {
        template<typename> friend class Emitter;

        Connection() = default;
        Connection(const Connection &) = default;
        Connection(Connection &&) = default;

        Connection(typename Handler<E>::Connection conn)
            : Handler<E>::Connection{std::move(conn)}
        { }

        Connection & operator=(const Connection &) = default;
        Connection & operator=(Connection &&) = default;
    };

    virtual ~Emitter() noexcept {
        static_assert(std::is_base_of<Emitter<T>, T>::value, "!");
    }

    /**
     * @brief Registers a long-lived listener with the event emitter.
     *
     * This method can be used to register a listener that is meant to be
     * invoked more than once for the given event type.

     * The Connection object returned by the method can be freely discarded. It
     * can be used later to disconnect the listener, if needed.
     *
     * Listener is usually defined as a callable object assignable to a
     * `std::function<void(const E &, T &)`, where `E` is the type of the event
     * and `T` is the type of the resource.
     *
     * @param f A valid listener to be registered.
     * @return Connection object to be used later to disconnect the listener.
     */
    template<typename E>
    Connection<E> on(Listener<E> f) {
        return handler<E>().on(std::move(f));
    }

    /**
     * @brief Registers a short-lived listener with the event emitter.
     *
     * This method can be used to register a listener that is meant to be
     * invoked only once for the given event type.

     * The Connection object returned by the method can be freely discarded. It
     * can be used later to disconnect the listener, if needed.
     *
     * Listener is usually defined as a callable object assignable to a
     * `std::function<void(const E &, T &)`, where `E` is the type of the event
     * and `T` is the type of the resource.
     *
     * @param f Avalid listener to be registered.
     * @return Connection object to be used later to disconnect the listener.
     */
    template<typename E>
    Connection<E> once(Listener<E> f) {
        return handler<E>().once(std::move(f));
    }

    /**
     * @brief Disconnects a listener from the event emitter.
     * @param conn A valid Connection object
     */
    template<typename E>
    void erase(Connection<E> conn) noexcept {
        handler<E>().erase(std::move(conn));
    }

    /**
     * @brief Disconnects all the listeners for the given event type.
     */
    template<typename E>
    void clear() noexcept {
        handler<E>().clear();
    }

    /**
     * @brief Disconnects all the listeners.
     */
    void clear() noexcept {
        std::for_each(handlers.begin(), handlers.end(),
                      [](auto &&handler){ if(handler) { handler->clear(); } });
    }

    /**
     * @brief Checks if there are listeners registered for the specific event.
     * @return True if there are no listeners registered for the specific event,
     * false otherwise.
     */
    template<typename E>
    bool empty() const noexcept {
        std::size_t type = E::type();

        return (!(type < handlers.size()) ||
                !handlers[type] ||
                static_cast<Handler<E>&>(*handlers[type]).empty());
    }

    /**
     * @brief Checks if there are listeners registered with the event emitter.
     * @return True if there are no listeners registered with the event emitter,
     * false otherwise.
     */
    bool empty() const noexcept {
        return std::all_of(handlers.cbegin(), handlers.cend(),
                           [](auto &&handler){ return !handler || handler->empty(); });
    }

private:
    std::vector<std::unique_ptr<BaseHandler>> handlers{};
};

}
<commit_msg>bug fixing<commit_after>#pragma once

#include <type_traits>
#include <functional>
#include <algorithm>
#include <utility>
#include <cstddef>
#include <vector>
#include <memory>
#include <list>
#include "event.hpp"

namespace uvw {

/**
 * @brief Event emitter base class.
 *
 * Almost everything in `uvw` is an event emitter.

 * This is the base class from which resources and loops inherit.
 */
template<typename T>
class Emitter {
    struct BaseHandler {
        virtual ~BaseHandler() noexcept = default;
        virtual bool empty() const noexcept = 0;
        virtual void clear() noexcept = 0;
    };

    template<typename E>
    struct Handler final: BaseHandler {
        using Listener = std::function<void(E &, T &)>;
        using Element = std::pair<bool, Listener>;
        using ListenerList = std::list<Element>;
        using Connection = typename ListenerList::iterator;

        bool empty() const noexcept override {
            auto pred = [](auto &&element){ return element.first; };

            return std::all_of(onceL.cbegin(), onceL.cend(), pred) &&
                    std::all_of(onL.cbegin(), onL.cend(), pred);
        }

        void clear() noexcept override {
            if(publishing) {
                auto func = [](auto &&element){ element.first = true; };
                std::for_each(onceL.begin(), onceL.end(), func);
                std::for_each(onL.begin(), onL.end(), func);
            } else {
                onceL.clear();
                onL.clear();
            }
        }

        Connection once(Listener f) {
            return onceL.emplace(onceL.cend(), false, std::move(f));
        }

        Connection on(Listener f) {
            return onL.emplace(onL.cbegin(), false, std::move(f));
        }

        void erase(Connection conn) noexcept {
            conn->first = true;

            if(!publishing) {
                auto pred = [](auto &&element){ return element.first; };
                onceL.remove_if(pred);
                onL.remove_if(pred);
            }
        }

        void publish(E event, T &ref) {
            ListenerList currentL;
            onceL.swap(currentL);

            auto func = [&event, &ref](auto &&element) {
                return element.first ? void() : element.second(event, ref);
            };

            publishing = true;

            std::for_each(onL.rbegin(), onL.rend(), func);
            std::for_each(currentL.rbegin(), currentL.rend(), func);

            publishing = false;

            onL.remove_if([](auto &&element){ return element.first; });
        }

    private:
        bool publishing{false};
        ListenerList onceL{};
        ListenerList onL{};
    };

    template<typename E>
    Handler<E> & handler() noexcept {
        static_assert(std::is_base_of<Event<E>, E>::value, "!");

        std::size_t type = E::type();

        if(!(type < handlers.size())) {
            handlers.resize(type+1);
        }

        if(!handlers[type]) {
           handlers[type] = std::make_unique<Handler<E>>();
        }

        return static_cast<Handler<E>&>(*handlers[type]);
    }

protected:
    template<typename E>
    void publish(E event) {
        handler<E>().publish(std::move(event), *static_cast<T*>(this));
    }

public:
    template<typename E>
    using Listener = typename Handler<E>::Listener;

    /**
     * @brief Connection type for a given event type.
     *
     * Given an event type `E`, `Connection<E>` is the type of the connection
     * object returned by the event emitter whenever a listener for the given
     * type is registered.
     */
    template<typename E>
    struct Connection: private Handler<E>::Connection {
        template<typename> friend class Emitter;

        Connection() = default;
        Connection(const Connection &) = default;
        Connection(Connection &&) = default;

        Connection(typename Handler<E>::Connection conn)
            : Handler<E>::Connection{std::move(conn)}
        { }

        Connection & operator=(const Connection &) = default;
        Connection & operator=(Connection &&) = default;
    };

    virtual ~Emitter() noexcept {
        static_assert(std::is_base_of<Emitter<T>, T>::value, "!");
    }

    /**
     * @brief Registers a long-lived listener with the event emitter.
     *
     * This method can be used to register a listener that is meant to be
     * invoked more than once for the given event type.

     * The Connection object returned by the method can be freely discarded. It
     * can be used later to disconnect the listener, if needed.
     *
     * Listener is usually defined as a callable object assignable to a
     * `std::function<void(const E &, T &)`, where `E` is the type of the event
     * and `T` is the type of the resource.
     *
     * @param f A valid listener to be registered.
     * @return Connection object to be used later to disconnect the listener.
     */
    template<typename E>
    Connection<E> on(Listener<E> f) {
        return handler<E>().on(std::move(f));
    }

    /**
     * @brief Registers a short-lived listener with the event emitter.
     *
     * This method can be used to register a listener that is meant to be
     * invoked only once for the given event type.

     * The Connection object returned by the method can be freely discarded. It
     * can be used later to disconnect the listener, if needed.
     *
     * Listener is usually defined as a callable object assignable to a
     * `std::function<void(const E &, T &)`, where `E` is the type of the event
     * and `T` is the type of the resource.
     *
     * @param f Avalid listener to be registered.
     * @return Connection object to be used later to disconnect the listener.
     */
    template<typename E>
    Connection<E> once(Listener<E> f) {
        return handler<E>().once(std::move(f));
    }

    /**
     * @brief Disconnects a listener from the event emitter.
     * @param conn A valid Connection object
     */
    template<typename E>
    void erase(Connection<E> conn) noexcept {
        handler<E>().erase(std::move(conn));
    }

    /**
     * @brief Disconnects all the listeners for the given event type.
     */
    template<typename E>
    void clear() noexcept {
        handler<E>().clear();
    }

    /**
     * @brief Disconnects all the listeners.
     */
    void clear() noexcept {
        std::for_each(handlers.begin(), handlers.end(),
                      [](auto &&handler){ if(handler) { handler->clear(); } });
    }

    /**
     * @brief Checks if there are listeners registered for the specific event.
     * @return True if there are no listeners registered for the specific event,
     * false otherwise.
     */
    template<typename E>
    bool empty() const noexcept {
        std::size_t type = E::type();

        return (!(type < handlers.size()) ||
                !handlers[type] ||
                static_cast<Handler<E>&>(*handlers[type]).empty());
    }

    /**
     * @brief Checks if there are listeners registered with the event emitter.
     * @return True if there are no listeners registered with the event emitter,
     * false otherwise.
     */
    bool empty() const noexcept {
        return std::all_of(handlers.cbegin(), handlers.cend(),
                           [](auto &&handler){ return !handler || handler->empty(); });
    }

private:
    std::vector<std::unique_ptr<BaseHandler>> handlers{};
};

}
<|endoftext|>


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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/distributed_runtime/rpc/grpc_remote_worker.h"

#include <utility>

#include "grpcpp/generic/generic_stub.h"
#include "grpcpp/grpcpp.h"
#include "tensorflow/core/common_runtime/process_util.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_client_cq_tag.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_state.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_worker_service_impl.h"
#include "tensorflow/core/distributed_runtime/tensor_coding.h"
#include "tensorflow/core/distributed_runtime/worker_cache_logger.h"
#include "tensorflow/core/distributed_runtime/worker_interface.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/tracing.h"
#include "tensorflow/core/protobuf/transport_options.pb.h"
#include "tensorflow/core/protobuf/worker.pb.h"

namespace tensorflow {

const int kMaxWorkerRpcRetries = 10;

class GrpcRemoteWorker : public WorkerInterface {
 public:
  explicit GrpcRemoteWorker(SharedGrpcChannelPtr channel,
                            ::grpc::CompletionQueue* completion_queue,
                            thread::ThreadPool* callback_threadpool,
                            WorkerCacheLogger* logger, const string& target)
      : channel_(std::move(channel)),
        stub_(channel_),
        cq_(completion_queue),
        callback_threadpool_(callback_threadpool),
        getstatus_(Method(GrpcWorkerMethod::kGetStatus)),
        createworkersession_(Method(GrpcWorkerMethod::kCreateWorkerSession)),
        deleteworkersession_(Method(GrpcWorkerMethod::kDeleteWorkerSession)),
        registergraph_(Method(GrpcWorkerMethod::kRegisterGraph)),
        deregistergraph_(Method(GrpcWorkerMethod::kDeregisterGraph)),
        rungraph_(Method(GrpcWorkerMethod::kRunGraph)),
        cleanupgraph_(Method(GrpcWorkerMethod::kCleanupGraph)),
        cleanupall_(Method(GrpcWorkerMethod::kCleanupAll)),
        recvtensor_(Method(GrpcWorkerMethod::kRecvTensor)),
        recvbuf_(Method(GrpcWorkerMethod::kRecvBuf)),
        logging_(Method(GrpcWorkerMethod::kLogging)),
        tracing_(Method(GrpcWorkerMethod::kTracing)),
        completegroup_(Method(GrpcWorkerMethod::kCompleteGroup)),
        instancesource_(Method(GrpcWorkerMethod::kCompleteInstance)),
        getstepsequence_(Method(GrpcWorkerMethod::kGetStepSequence)),
        markrecvfinished_(Method(GrpcWorkerMethod::kMarkRecvFinished)),
        logger_(logger),
        target_(target) {}

  ~GrpcRemoteWorker() override {}

  void GetStatusAsync(const GetStatusRequest* request,
                      GetStatusResponse* response, bool fail_fast,
                      StatusCallback done) override {
    IssueRequest(request, response, getstatus_, std::move(done), nullptr,
                 fail_fast);
  }

  void CreateWorkerSessionAsync(const CreateWorkerSessionRequest* request,
                                CreateWorkerSessionResponse* response,
                                StatusCallback done) override {
    IssueRequest(request, response, createworkersession_, std::move(done));
  }

  void DeleteWorkerSessionAsync(CallOptions* call_opts,
                                const DeleteWorkerSessionRequest* request,
                                DeleteWorkerSessionResponse* response,
                                StatusCallback done) override {
    IssueRequest(request, response, deleteworkersession_, std::move(done),
                 call_opts);
  }

  void RegisterGraphAsync(const RegisterGraphRequest* request,
                          RegisterGraphResponse* response,
                          StatusCallback done) override {
    IssueRequest(request, response, registergraph_, std::move(done));
  }

  void DeregisterGraphAsync(const DeregisterGraphRequest* request,
                            DeregisterGraphResponse* response,
                            StatusCallback done) override {
    IssueRequest(request, response, deregistergraph_, std::move(done));
  }

  void RunGraphAsync(CallOptions* call_opts, const RunGraphRequest* request,
                     RunGraphResponse* response, StatusCallback done) override {
    IssueRequest(request, response, rungraph_, std::move(done), call_opts);
  }
  void RunGraphAsync(CallOptions* call_opts, RunGraphRequestWrapper* request,
                     MutableRunGraphResponseWrapper* response,
                     StatusCallback done) override {
    IssueRequest(&request->ToProto(), get_proto_from_wrapper(response),
                 rungraph_, std::move(done), call_opts);
  }

  void CleanupGraphAsync(const CleanupGraphRequest* request,
                         CleanupGraphResponse* response,
                         StatusCallback done) override {
    IssueRequest(request, response, cleanupgraph_, std::move(done));
  }

  void CleanupAllAsync(const CleanupAllRequest* request,
                       CleanupAllResponse* response,
                       StatusCallback done) override {
    IssueRequest(request, response, cleanupall_, std::move(done));
  }

  void RecvBufAsync(CallOptions* call_opts, const RecvBufRequest* request,
                    RecvBufResponse* response, StatusCallback done) override {
    int64 start_usec = Env::Default()->NowMicros();
    // Type-specialized logging for this method.
    bool logging_active = logger_->LoggingActive() || VLOG_IS_ON(2);

    auto callback = [this, request, response, done, start_usec,
                     logging_active](Status s) {
      if (logging_active) {
        if (logger_->LoggingActive()) {
          int64 end_usec = Env::Default()->NowMicros();
          int64 step_id = request->step_id();
          RecvBufRespExtra extra;
          response->transport_options().UnpackTo(&extra);
          int64 num_bytes = 0;
          for (const auto& chunk : extra.tensor_content()) {
            num_bytes += chunk.size();
          }
          int64 send_start_usec = start_usec;
          // Prefer start time reported by the sender, if available.
          if (response->send_start_micros()) {
            send_start_usec = std::max(
                start_usec, static_cast<int64>(response->send_start_micros()));
            send_start_usec = std::min(send_start_usec, end_usec - 1);
          }
          const string& key = request->buf_rendezvous_key();
          logger_->RecordDataTransfer(
              step_id, send_start_usec, end_usec, key, request->src_device(),
              request->dst_device(), num_bytes, "", "RecvBuf");
        }
        VLOG(2) << "done callback, req: " << request->DebugString()
                << " response " << response->DebugString();
      }

      // Note done() can delete this worker object, so we need to call done()
      // last.
      if (response->require_ack()) {
        IssueMarkRecvFinishedRequest(request->request_id());
      }
      done(s);
    };

    IssueRequest(request, response, recvbuf_, callback, call_opts);
  }

  void CompleteGroupAsync(CallOptions* call_opts,
                          const CompleteGroupRequest* request,
                          CompleteGroupResponse* response,
                          StatusCallback done) override {
    IssueRequest(request, response, completegroup_, std::move(done), call_opts,
                 /*fail_fast=*/false);
  }

  void CompleteInstanceAsync(CallOptions* call_opts,
                             const CompleteInstanceRequest* request,
                             CompleteInstanceResponse* response,
                             StatusCallback done) override {
    IssueRequest(request, response, instancesource_, std::move(done),
                 call_opts);
  }

  void GetStepSequenceAsync(const GetStepSequenceRequest* request,
                            GetStepSequenceResponse* response,
                            StatusCallback done) override {
    IssueRequest(request, response, getstepsequence_, std::move(done));
  }

  void RecvTensorAsync(CallOptions* call_opts, const RecvTensorRequest* request,
                       TensorResponse* response, StatusCallback done) override {
    VLOG(1) << "RecvTensorAsync req: " << request->DebugString();
    int64 start_usec = Env::Default()->NowMicros();
    // Type-specialized logging for this method.
    bool logging_active = logger_->LoggingActive() || VLOG_IS_ON(2);

    auto callback = [this, request, response, done, start_usec,
                     logging_active](Status s) {
      if (logging_active) {
        if (logger_->LoggingActive()) {
          int64 end_usec = Env::Default()->NowMicros();
          int64 step_id = request->step_id();
          int64 bytes = response->tensor().TotalBytes();
          int64 send_start_usec = start_usec;
          // If a send start time was reported by the other side, use
          // that instead.  Maybe we should mark the display if we're using
          // our local time instead of the remote start time?
          if (response->metadata().send_start_micros()) {
            // send_start_micros is the timestamp taken when the
            // remote machine began to send the RecvTensor response.
            // Due to clock skew between source and dest machines, it
            // is possible that send_start_micros can be larger than
            // end_usec or less than start_usec.
            //
            // To respect causality, we enforce the invariants that
            // the RecvTensor response can not have been sent before
            // the RecvTensor request, and must have been sent before
            // it was received.
            send_start_usec = std::max(
                start_usec,
                static_cast<int64>(response->metadata().send_start_micros()));
            send_start_usec = std::min(send_start_usec, end_usec - 1);
          }
          const string& key = request->rendezvous_key();
          std::vector<string> key_parts = str_util::Split(key, ';');
          if (key_parts.size() != 5) {
            LOG(WARNING) << "Bad key: " << key;
          } else {
            logger_->RecordRecvTensor(step_id, send_start_usec, end_usec,
                                      key_parts[3],  // tensor name
                                      key_parts[0],  // src_device
                                      key_parts[2],  // dst_device
                                      bytes);
          }
        }
        VLOG(2) << "done callback, req: " << request->DebugString()
                << " response " << response->metadata().DebugString();
      }

      // Note done() can delete this worker object, so we need to call done()
      // last.
      if (response->metadata().require_ack()) {
        IssueMarkRecvFinishedRequest(request->request_id());
      }
      done(s);
    };

    IssueRequest(request, response, recvtensor_, callback, call_opts);
  }

  void LoggingAsync(const LoggingRequest* request, LoggingResponse* response,
                    StatusCallback done) override {
    IssueRequest(request, response, logging_, done);
  }

  void TracingAsync(const TracingRequest* request, TracingResponse* response,
                    StatusCallback done) override {
    IssueRequest(request, response, tracing_, done);
  }

 private:
  // Utility method for issuing a generic asynchronous request. The
  // given callback, `done`, will be called when the RPC completes.
  void IssueRequest(const protobuf::Message* request,
                    protobuf::Message* response, const ::grpc::string& method,
                    StatusCallback done, CallOptions* call_opts = nullptr,
                    bool fail_fast = true) {
    new RPCState<protobuf::Message>(
        &stub_, cq_, method, *request, response, std::move(done), call_opts,
        callback_threadpool_, /*max_retries=*/0, fail_fast, &target_);
  }

  void IssueRequest(const protobuf::Message* request, TensorResponse* response,
                    const ::grpc::string& method, StatusCallback done,
                    CallOptions* call_opts = nullptr) {
    new RPCState<TensorResponse>(&stub_, cq_, method, *request, response,
                                 std::move(done), call_opts,
                                 callback_threadpool_, /*max_retries=*/0,
                                 /*fail_fast=*/true, &target_);
  }

  void IssueMarkRecvFinishedRequest(int64 request_id) {
    VLOG(2) << "Send MarkRecvFinishedRequest for request " << request_id;
    MarkRecvFinishedRequest request;
    request.set_request_id(request_id);

    MarkRecvFinishedResponse* response = new MarkRecvFinishedResponse();
    auto done = [response](Status status) { delete response; };
    IssueRequest(&request, response, markrecvfinished_, done);
  }

  // Helper function for initializing the RpcMethod objects below.
  const char* Method(GrpcWorkerMethod id) { return GrpcWorkerMethodName(id); }

  SharedGrpcChannelPtr channel_;
  ::grpc::GenericStub stub_;
  ::grpc::CompletionQueue* cq_;
  thread::ThreadPool* callback_threadpool_;

  const ::grpc::string getstatus_;
  const ::grpc::string createworkersession_;
  const ::grpc::string deleteworkersession_;
  const ::grpc::string registergraph_;
  const ::grpc::string deregistergraph_;
  const ::grpc::string rungraph_;
  const ::grpc::string cleanupgraph_;
  const ::grpc::string cleanupall_;
  const ::grpc::string recvtensor_;
  const ::grpc::string recvbuf_;
  const ::grpc::string logging_;
  const ::grpc::string tracing_;
  const ::grpc::string completegroup_;
  const ::grpc::string instancesource_;
  const ::grpc::string getstepsequence_;
  const ::grpc::string markrecvfinished_;

  // Support for logging.
  WorkerCacheLogger* logger_;
  const string target_;

  TF_DISALLOW_COPY_AND_ASSIGN(GrpcRemoteWorker);
};

WorkerInterface* NewGrpcRemoteWorker(SharedGrpcChannelPtr channel,
                                     ::grpc::CompletionQueue* completion_queue,
                                     thread::ThreadPool* callback_threadpool,
                                     WorkerCacheLogger* logger,
                                     const string& target) {
  return new GrpcRemoteWorker(std::move(channel), completion_queue,
                              callback_threadpool, logger, target);
}

}  // namespace tensorflow
<commit_msg>Make GRPC retries configurable.<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/distributed_runtime/rpc/grpc_remote_worker.h"

#include <utility>

#include "grpcpp/generic/generic_stub.h"
#include "grpcpp/grpcpp.h"
#include "tensorflow/core/common_runtime/process_util.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_client_cq_tag.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_state.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_worker_service_impl.h"
#include "tensorflow/core/distributed_runtime/tensor_coding.h"
#include "tensorflow/core/distributed_runtime/worker_cache_logger.h"
#include "tensorflow/core/distributed_runtime/worker_interface.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/tracing.h"
#include "tensorflow/core/protobuf/transport_options.pb.h"
#include "tensorflow/core/protobuf/worker.pb.h"
#include "tensorflow/core/util/env_var.h"

namespace tensorflow {

class GrpcRemoteWorker : public WorkerInterface {
 public:
  explicit GrpcRemoteWorker(SharedGrpcChannelPtr channel,
                            ::grpc::CompletionQueue* completion_queue,
                            thread::ThreadPool* callback_threadpool,
                            WorkerCacheLogger* logger, const string& target)
      : channel_(std::move(channel)),
        stub_(channel_),
        cq_(completion_queue),
        callback_threadpool_(callback_threadpool),
        getstatus_(Method(GrpcWorkerMethod::kGetStatus)),
        createworkersession_(Method(GrpcWorkerMethod::kCreateWorkerSession)),
        deleteworkersession_(Method(GrpcWorkerMethod::kDeleteWorkerSession)),
        registergraph_(Method(GrpcWorkerMethod::kRegisterGraph)),
        deregistergraph_(Method(GrpcWorkerMethod::kDeregisterGraph)),
        rungraph_(Method(GrpcWorkerMethod::kRunGraph)),
        cleanupgraph_(Method(GrpcWorkerMethod::kCleanupGraph)),
        cleanupall_(Method(GrpcWorkerMethod::kCleanupAll)),
        recvtensor_(Method(GrpcWorkerMethod::kRecvTensor)),
        recvbuf_(Method(GrpcWorkerMethod::kRecvBuf)),
        logging_(Method(GrpcWorkerMethod::kLogging)),
        tracing_(Method(GrpcWorkerMethod::kTracing)),
        completegroup_(Method(GrpcWorkerMethod::kCompleteGroup)),
        instancesource_(Method(GrpcWorkerMethod::kCompleteInstance)),
        getstepsequence_(Method(GrpcWorkerMethod::kGetStepSequence)),
        markrecvfinished_(Method(GrpcWorkerMethod::kMarkRecvFinished)),
        logger_(logger),
        target_(target) {}

  ~GrpcRemoteWorker() override {}

  void GetStatusAsync(const GetStatusRequest* request,
                      GetStatusResponse* response, bool fail_fast,
                      StatusCallback done) override {
    IssueRequest(request, response, getstatus_, std::move(done), nullptr,
                 fail_fast);
  }

  void CreateWorkerSessionAsync(const CreateWorkerSessionRequest* request,
                                CreateWorkerSessionResponse* response,
                                StatusCallback done) override {
    IssueRequest(request, response, createworkersession_, std::move(done));
  }

  void DeleteWorkerSessionAsync(CallOptions* call_opts,
                                const DeleteWorkerSessionRequest* request,
                                DeleteWorkerSessionResponse* response,
                                StatusCallback done) override {
    IssueRequest(request, response, deleteworkersession_, std::move(done),
                 call_opts);
  }

  void RegisterGraphAsync(const RegisterGraphRequest* request,
                          RegisterGraphResponse* response,
                          StatusCallback done) override {
    IssueRequest(request, response, registergraph_, std::move(done));
  }

  void DeregisterGraphAsync(const DeregisterGraphRequest* request,
                            DeregisterGraphResponse* response,
                            StatusCallback done) override {
    IssueRequest(request, response, deregistergraph_, std::move(done));
  }

  void RunGraphAsync(CallOptions* call_opts, const RunGraphRequest* request,
                     RunGraphResponse* response, StatusCallback done) override {
    IssueRequest(request, response, rungraph_, std::move(done), call_opts);
  }
  void RunGraphAsync(CallOptions* call_opts, RunGraphRequestWrapper* request,
                     MutableRunGraphResponseWrapper* response,
                     StatusCallback done) override {
    IssueRequest(&request->ToProto(), get_proto_from_wrapper(response),
                 rungraph_, std::move(done), call_opts);
  }

  void CleanupGraphAsync(const CleanupGraphRequest* request,
                         CleanupGraphResponse* response,
                         StatusCallback done) override {
    IssueRequest(request, response, cleanupgraph_, std::move(done));
  }

  void CleanupAllAsync(const CleanupAllRequest* request,
                       CleanupAllResponse* response,
                       StatusCallback done) override {
    IssueRequest(request, response, cleanupall_, std::move(done));
  }

  void RecvBufAsync(CallOptions* call_opts, const RecvBufRequest* request,
                    RecvBufResponse* response, StatusCallback done) override {
    int64 start_usec = Env::Default()->NowMicros();
    // Type-specialized logging for this method.
    bool logging_active = logger_->LoggingActive() || VLOG_IS_ON(2);

    auto callback = [this, request, response, done, start_usec,
                     logging_active](Status s) {
      if (logging_active) {
        if (logger_->LoggingActive()) {
          int64 end_usec = Env::Default()->NowMicros();
          int64 step_id = request->step_id();
          RecvBufRespExtra extra;
          response->transport_options().UnpackTo(&extra);
          int64 num_bytes = 0;
          for (const auto& chunk : extra.tensor_content()) {
            num_bytes += chunk.size();
          }
          int64 send_start_usec = start_usec;
          // Prefer start time reported by the sender, if available.
          if (response->send_start_micros()) {
            send_start_usec = std::max(
                start_usec, static_cast<int64>(response->send_start_micros()));
            send_start_usec = std::min(send_start_usec, end_usec - 1);
          }
          const string& key = request->buf_rendezvous_key();
          logger_->RecordDataTransfer(
              step_id, send_start_usec, end_usec, key, request->src_device(),
              request->dst_device(), num_bytes, "", "RecvBuf");
        }
        VLOG(2) << "done callback, req: " << request->DebugString()
                << " response " << response->DebugString();
      }

      // Note done() can delete this worker object, so we need to call done()
      // last.
      if (response->require_ack()) {
        IssueMarkRecvFinishedRequest(request->request_id());
      }
      done(s);
    };

    IssueRequest(request, response, recvbuf_, callback, call_opts);
  }

  void CompleteGroupAsync(CallOptions* call_opts,
                          const CompleteGroupRequest* request,
                          CompleteGroupResponse* response,
                          StatusCallback done) override {
    IssueRequest(request, response, completegroup_, std::move(done), call_opts,
                 /*fail_fast=*/false);
  }

  void CompleteInstanceAsync(CallOptions* call_opts,
                             const CompleteInstanceRequest* request,
                             CompleteInstanceResponse* response,
                             StatusCallback done) override {
    IssueRequest(request, response, instancesource_, std::move(done),
                 call_opts);
  }

  void GetStepSequenceAsync(const GetStepSequenceRequest* request,
                            GetStepSequenceResponse* response,
                            StatusCallback done) override {
    IssueRequest(request, response, getstepsequence_, std::move(done));
  }

  void RecvTensorAsync(CallOptions* call_opts, const RecvTensorRequest* request,
                       TensorResponse* response, StatusCallback done) override {
    VLOG(1) << "RecvTensorAsync req: " << request->DebugString();
    int64 start_usec = Env::Default()->NowMicros();
    // Type-specialized logging for this method.
    bool logging_active = logger_->LoggingActive() || VLOG_IS_ON(2);

    auto callback = [this, request, response, done, start_usec,
                     logging_active](Status s) {
      if (logging_active) {
        if (logger_->LoggingActive()) {
          int64 end_usec = Env::Default()->NowMicros();
          int64 step_id = request->step_id();
          int64 bytes = response->tensor().TotalBytes();
          int64 send_start_usec = start_usec;
          // If a send start time was reported by the other side, use
          // that instead.  Maybe we should mark the display if we're using
          // our local time instead of the remote start time?
          if (response->metadata().send_start_micros()) {
            // send_start_micros is the timestamp taken when the
            // remote machine began to send the RecvTensor response.
            // Due to clock skew between source and dest machines, it
            // is possible that send_start_micros can be larger than
            // end_usec or less than start_usec.
            //
            // To respect causality, we enforce the invariants that
            // the RecvTensor response can not have been sent before
            // the RecvTensor request, and must have been sent before
            // it was received.
            send_start_usec = std::max(
                start_usec,
                static_cast<int64>(response->metadata().send_start_micros()));
            send_start_usec = std::min(send_start_usec, end_usec - 1);
          }
          const string& key = request->rendezvous_key();
          std::vector<string> key_parts = str_util::Split(key, ';');
          if (key_parts.size() != 5) {
            LOG(WARNING) << "Bad key: " << key;
          } else {
            logger_->RecordRecvTensor(step_id, send_start_usec, end_usec,
                                      key_parts[3],  // tensor name
                                      key_parts[0],  // src_device
                                      key_parts[2],  // dst_device
                                      bytes);
          }
        }
        VLOG(2) << "done callback, req: " << request->DebugString()
                << " response " << response->metadata().DebugString();
      }

      // Note done() can delete this worker object, so we need to call done()
      // last.
      if (response->metadata().require_ack()) {
        IssueMarkRecvFinishedRequest(request->request_id());
      }
      done(s);
    };

    IssueRequest(request, response, recvtensor_, callback, call_opts);
  }

  void LoggingAsync(const LoggingRequest* request, LoggingResponse* response,
                    StatusCallback done) override {
    IssueRequest(request, response, logging_, done);
  }

  void TracingAsync(const TracingRequest* request, TracingResponse* response,
                    StatusCallback done) override {
    IssueRequest(request, response, tracing_, done);
  }

 private:
  // Utility method for issuing a generic asynchronous request. The
  // given callback, `done`, will be called when the RPC completes.
  void IssueRequest(const protobuf::Message* request,
                    protobuf::Message* response, const ::grpc::string& method,
                    StatusCallback done, CallOptions* call_opts = nullptr,
                    bool fail_fast = true) {
    new RPCState<protobuf::Message>(
        &stub_, cq_, method, *request, response, std::move(done), call_opts,
        callback_threadpool_, MaxRetries(), fail_fast, &target_);
  }

  void IssueRequest(const protobuf::Message* request, TensorResponse* response,
                    const ::grpc::string& method, StatusCallback done,
                    CallOptions* call_opts = nullptr) {
    new RPCState<TensorResponse>(&stub_, cq_, method, *request, response,
                                 std::move(done), call_opts,
                                 callback_threadpool_, MaxRetries(),
                                 /*fail_fast=*/true, &target_);
  }

  void IssueMarkRecvFinishedRequest(int64 request_id) {
    VLOG(2) << "Send MarkRecvFinishedRequest for request " << request_id;
    MarkRecvFinishedRequest request;
    request.set_request_id(request_id);

    MarkRecvFinishedResponse* response = new MarkRecvFinishedResponse();
    auto done = [response](Status status) { delete response; };
    IssueRequest(&request, response, markrecvfinished_, done);
  }

  // Helper function for initializing the RpcMethod objects below.
  const char* Method(GrpcWorkerMethod id) { return GrpcWorkerMethodName(id); }

  // Helper function for configuring max GRPC retries. Defaults to 0 (no
  // retries).
  const int64 MaxRetries() {
    int64 max_retries = -1;
    TF_CHECK_OK(ReadInt64FromEnvVar("GRPC_MAX_RETRIES", 0, &max_retries));
    return max_retries;
  }

  SharedGrpcChannelPtr channel_;
  ::grpc::GenericStub stub_;
  ::grpc::CompletionQueue* cq_;
  thread::ThreadPool* callback_threadpool_;

  const ::grpc::string getstatus_;
  const ::grpc::string createworkersession_;
  const ::grpc::string deleteworkersession_;
  const ::grpc::string registergraph_;
  const ::grpc::string deregistergraph_;
  const ::grpc::string rungraph_;
  const ::grpc::string cleanupgraph_;
  const ::grpc::string cleanupall_;
  const ::grpc::string recvtensor_;
  const ::grpc::string recvbuf_;
  const ::grpc::string logging_;
  const ::grpc::string tracing_;
  const ::grpc::string completegroup_;
  const ::grpc::string instancesource_;
  const ::grpc::string getstepsequence_;
  const ::grpc::string markrecvfinished_;

  // Support for logging.
  WorkerCacheLogger* logger_;
  const string target_;

  TF_DISALLOW_COPY_AND_ASSIGN(GrpcRemoteWorker);
};

WorkerInterface* NewGrpcRemoteWorker(SharedGrpcChannelPtr channel,
                                     ::grpc::CompletionQueue* completion_queue,
                                     thread::ThreadPool* callback_threadpool,
                                     WorkerCacheLogger* logger,
                                     const string& target) {
  return new GrpcRemoteWorker(std::move(channel), completion_queue,
                              callback_threadpool, logger, target);
}

}  // namespace tensorflow
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////
//
// CoinVault
//
// versioninfo.cpp
//
// Copyright (c) 2013 Eric Lombrozo
//
// All Rights Reserved.

#include "versioninfo.h"
#include "../BuildInfo.h"

// Definitions
const int VERSIONPADDINGRIGHT = 20;
const int VERSIONPADDINGBOTTOM = 30;

const QString VERSIONTEXT("Version 0.4.8 beta");

const QString commitHash(COMMIT_HASH);
const QString shortCommitHash(QString(COMMIT_HASH).left(6));

// Accessors
int getVersionPaddingRight() { return VERSIONPADDINGRIGHT; }
int getVersionPaddingBottom() { return VERSIONPADDINGBOTTOM; }

const QString& getVersionText() { return VERSIONTEXT; }

const QString& getCommitHash() { return commitHash; }
const QString& getShortCommitHash() { return shortCommitHash; }
<commit_msg>v0.4.9<commit_after>///////////////////////////////////////////////////////////////////
//
// CoinVault
//
// versioninfo.cpp
//
// Copyright (c) 2013 Eric Lombrozo
//
// All Rights Reserved.

#include "versioninfo.h"
#include "../BuildInfo.h"

// Definitions
const int VERSIONPADDINGRIGHT = 20;
const int VERSIONPADDINGBOTTOM = 30;

const QString VERSIONTEXT("Version 0.4.9 beta");

const QString commitHash(COMMIT_HASH);
const QString shortCommitHash(QString(COMMIT_HASH).left(6));

// Accessors
int getVersionPaddingRight() { return VERSIONPADDINGRIGHT; }
int getVersionPaddingBottom() { return VERSIONPADDINGBOTTOM; }

const QString& getVersionText() { return VERSIONTEXT; }

const QString& getCommitHash() { return commitHash; }
const QString& getShortCommitHash() { return shortCommitHash; }
<|endoftext|>


<commit_before>/** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */
#include "wallOverlap.h"

#include <cmath> // isfinite
#include <sstream>

#include "utils/AABB.h" // for debug output svg html
#include "utils/SVG.h"

namespace cura
{

WallOverlapComputation::WallOverlapComputation(Polygons& polygons, int line_width)
: overlap_linker(polygons, line_width)
, line_width(line_width)
{

}

float WallOverlapComputation::getFlow(Point& from, Point& to)
{
    using Point2LinkIt = PolygonProximityLinker::Point2Link::iterator;

    if (!overlap_linker.isLinked(from))
    { // [from] is not linked
        return 1;
    }
    const std::pair<Point2LinkIt, Point2LinkIt> to_links = overlap_linker.getLinks(to);
    if (to_links.first == to_links.second)
    { // [to] is not linked
        return 1;
    }

    int64_t overlap_area = 0;
    // note that we don't need to loop over all from_links, because they are handled in the previous getFlow(.) call (or in the very last)
    for (Point2LinkIt it = to_links.first; it != to_links.second; ++it)
    {
        const ProximityPointLink& to_link = it->second;
        ListPolyIt to_it = to_link.a;
        ListPolyIt to_other_it = to_link.b;
        if (to_link.a.p() != to)
        {
            assert(to_link.b.p() == to && "Either part of the link should be the point in the link!");
            std::swap(to_it, to_other_it);
        }
        ListPolyIt from_it = to_it.prev();
        assert(from_it.p() == from && "From location doesn't seem to be connected to destination location!");

        ListPolyIt to_other_next_it = to_other_it.next(); // move towards [from]; the lines on the other side move in the other direction
        //           to  from
        //   o<--o<--T<--F
        //   |       :   :
        //   v       :   :
        //   o-->o-->o-->o
        //           ,   ,
        //           ;   to_other_next
        //           to other

        // handle multiple points  linked to [to]
        //   o<<<T<<<F
        //     / |
        //    /  |
        //   o>>>o>>>o
        //   ,   ,
        //   ;   to other next
        //   to other
        overlap_area += handlePotentialOverlap(to_link, to_other_next_it, to_it);

        // handle multiple points  linked to [to_other]
        //   o<<<T<<<F
        //       |  /
        //       | /
        //   o>>>o>>>o
        overlap_area += handlePotentialOverlap(to_link, to_other_it, from_it);

        // handle normal case where the segment from-to overlaps with another segment
        //   o<<<T<<<F
        //       |   |
        //       |   |
        //   o>>>o>>>o
        //       ,   ,
        //       ;   to other next
        //       to other
        overlap_area += handlePotentialOverlap(to_link, to_other_next_it, from_it);
    }

    int64_t normal_area = vSize(from - to) * line_width;
    float ratio = float(normal_area - overlap_area) / normal_area;
    if (ratio > 1.0)
    {
        return 1.0;
    }
    if (ratio < 0.0)
    {
        return 0;
    }
    return ratio;
}

int64_t WallOverlapComputation::handlePotentialOverlap(const ProximityPointLink& link_a, const ListPolyIt from_it, const ListPolyIt to_it)
{
    const ProximityPointLink* link_b = overlap_linker.getLink(from_it, to_it);
    if (!link_b)
    {
        return 0;
    }
    if (!getIsPassed(link_a)|| !getIsPassed(*link_b))
    { // check whether the segment is already passed
        setIsPassed(link_a);
        setIsPassed(*link_b);
        return 0;
    }
    // mark the segment as passed
    setIsPassed(link_a);
    setIsPassed(*link_b);
    return getApproxOverlapArea(link_a, *link_b);
}

int64_t WallOverlapComputation::getApproxOverlapArea(const ProximityPointLink& from, const ProximityPointLink& to)
{
    return getApproxOverlapArea(from.a.p(), from.b.p(), from.dist, to.a.p(), to.b.p(), to.dist);
}

int64_t WallOverlapComputation::getApproxOverlapArea(const Point from_a, const Point from_b, const int64_t from_dist, const Point to_a, const Point to_b, const int64_t to_dist)
{
    const Point from_middle = from_a + from_b; // dont divide by two just yet
    const Point to_middle = to_a + to_b; // dont divide by two just yet

    const int64_t dist_2 = vSize(from_middle - to_middle);

    const int64_t average_dists_2 = line_width * 2 - from_dist - to_dist; // dont divide by two just yet

    const int64_t area = dist_2 * average_dists_2 / 4; // divide by 2 two times: once for the middles and once for the average_dists
    return area;
}

bool WallOverlapComputation::getIsPassed(const ProximityPointLink& link)
{
    return passed_links.count(link) > 0;
}

void WallOverlapComputation::setIsPassed(const ProximityPointLink& link)
{
    passed_links.emplace(link);
}

}//namespace cura
<commit_msg>lil rename (CURA-1911)<commit_after>/** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */
#include "wallOverlap.h"

#include <cmath> // isfinite
#include <sstream>

#include "utils/AABB.h" // for debug output svg html
#include "utils/SVG.h"

namespace cura
{

WallOverlapComputation::WallOverlapComputation(Polygons& polygons, int line_width)
: overlap_linker(polygons, line_width)
, line_width(line_width)
{

}

float WallOverlapComputation::getFlow(Point& from, Point& to)
{
    using Point2LinkIt = PolygonProximityLinker::Point2Link::iterator;

    if (!overlap_linker.isLinked(from))
    { // [from] is not linked
        return 1;
    }
    const std::pair<Point2LinkIt, Point2LinkIt> to_links = overlap_linker.getLinks(to);
    if (to_links.first == to_links.second)
    { // [to] is not linked
        return 1;
    }

    int64_t overlap_area = 0;
    // note that we don't need to loop over all from_links, because they are handled in the previous getFlow(.) call (or in the very last)
    for (Point2LinkIt to_link_it = to_links.first; to_link_it != to_links.second; ++to_link_it)
    {
        const ProximityPointLink& to_link = to_link_it->second;
        ListPolyIt to_it = to_link.a;
        ListPolyIt to_other_it = to_link.b;
        if (to_link.a.p() != to)
        {
            assert(to_link.b.p() == to && "Either part of the link should be the point in the link!");
            std::swap(to_it, to_other_it);
        }
        ListPolyIt from_it = to_it.prev();
        assert(from_it.p() == from && "From location doesn't seem to be connected to destination location!");

        ListPolyIt to_other_next_it = to_other_it.next(); // move towards [from]; the lines on the other side move in the other direction
        //           to  from
        //   o<--o<--T<--F
        //   |       :   :
        //   v       :   :
        //   o-->o-->o-->o
        //           ,   ,
        //           ;   to_other_next
        //           to other

        // handle multiple points  linked to [to]
        //   o<<<T<<<F
        //     / |
        //    /  |
        //   o>>>o>>>o
        //   ,   ,
        //   ;   to other next
        //   to other
        overlap_area += handlePotentialOverlap(to_link, to_other_next_it, to_it);

        // handle multiple points  linked to [to_other]
        //   o<<<T<<<F
        //       |  /
        //       | /
        //   o>>>o>>>o
        overlap_area += handlePotentialOverlap(to_link, to_other_it, from_it);

        // handle normal case where the segment from-to overlaps with another segment
        //   o<<<T<<<F
        //       |   |
        //       |   |
        //   o>>>o>>>o
        //       ,   ,
        //       ;   to other next
        //       to other
        overlap_area += handlePotentialOverlap(to_link, to_other_next_it, from_it);
    }

    int64_t normal_area = vSize(from - to) * line_width;
    float ratio = float(normal_area - overlap_area) / normal_area;
    if (ratio > 1.0)
    {
        return 1.0;
    }
    if (ratio < 0.0)
    {
        return 0;
    }
    return ratio;
}

int64_t WallOverlapComputation::handlePotentialOverlap(const ProximityPointLink& link_a, const ListPolyIt from_it, const ListPolyIt to_it)
{
    const ProximityPointLink* link_b = overlap_linker.getLink(from_it, to_it);
    if (!link_b)
    {
        return 0;
    }
    if (!getIsPassed(link_a)|| !getIsPassed(*link_b))
    { // check whether the segment is already passed
        setIsPassed(link_a);
        setIsPassed(*link_b);
        return 0;
    }
    // mark the segment as passed
    setIsPassed(link_a);
    setIsPassed(*link_b);
    return getApproxOverlapArea(link_a, *link_b);
}

int64_t WallOverlapComputation::getApproxOverlapArea(const ProximityPointLink& from, const ProximityPointLink& to)
{
    return getApproxOverlapArea(from.a.p(), from.b.p(), from.dist, to.a.p(), to.b.p(), to.dist);
}

int64_t WallOverlapComputation::getApproxOverlapArea(const Point from_a, const Point from_b, const int64_t from_dist, const Point to_a, const Point to_b, const int64_t to_dist)
{
    const Point from_middle = from_a + from_b; // dont divide by two just yet
    const Point to_middle = to_a + to_b; // dont divide by two just yet

    const int64_t dist_2 = vSize(from_middle - to_middle);

    const int64_t average_dists_2 = line_width * 2 - from_dist - to_dist; // dont divide by two just yet

    const int64_t area = dist_2 * average_dists_2 / 4; // divide by 2 two times: once for the middles and once for the average_dists
    return area;
}

bool WallOverlapComputation::getIsPassed(const ProximityPointLink& link)
{
    return passed_links.count(link) > 0;
}

void WallOverlapComputation::setIsPassed(const ProximityPointLink& link)
{
    passed_links.emplace(link);
}

}//namespace cura
<|endoftext|>


<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

#include "RhoProfiler.h"
#include "logging/RhoLog.h"
#include "common/RhoTime.h"
#include <map>

namespace rho {
class CProfiler
{
    DEFINE_LOGCLASS;

    class CCounter
    {
        common::CTimeInterval m_startTime;
        bool m_bWasStarted;
    public:
        CCounter(bool bStart=true) : m_bWasStarted(false){
            if ( bStart )
                start();
        }

        virtual bool isGlobal()const{ return false;}

        virtual void start(){ m_startTime = common::CTimeInterval::getCurrentTime(); m_bWasStarted = true; }
        virtual common::CTimeInterval stop(){
            if ( m_startTime.isEmpty() )
                return m_startTime;

            common::CTimeInterval res = common::CTimeInterval::getCurrentTime()-m_startTime;
            m_startTime = common::CTimeInterval();
            return res;
        }
        virtual common::CTimeInterval flush(){ return stop(); }

        bool isWasStarted()const{ return m_bWasStarted;}
    };

    class CGlobalCounter : public CCounter
    {
        common::CTimeInterval m_sumGlobal;
    public:
        CGlobalCounter() : CCounter(false){ }
        virtual bool isGlobal()const{ return true;}

        virtual common::CTimeInterval stop(){
            m_sumGlobal += CCounter::stop();

            return m_sumGlobal;
        }
        virtual common::CTimeInterval flush(){
            common::CTimeInterval res = stop();
            m_sumGlobal = common::CTimeInterval();
            return res;
        }

    };

    std::map<String,CCounter*> m_mapCounters;
public:
    CProfiler(){}
    ~CProfiler(){}

    void startCounter(const char* szCounterName);
    void startCreatedCounter(const char* szCounterName);
    void stopCounter(const char* szCounterName, bool bDestroy =false);
    void createCounter(const char* szCounterName);
    void destroyCounter(const char* szCounterName);
    void flushCounter(const char* szCounterName, const char* msg);

};
IMPLEMENT_LOGCLASS(CProfiler,"PROFILER");

void CProfiler::startCounter(const char* szCounterName)
{
    CCounter* pCounter = m_mapCounters[szCounterName];
    if ( !pCounter || !pCounter->isWasStarted() )
        LOG(INFO) + szCounterName + " : START";

    if ( !pCounter )
        m_mapCounters[szCounterName] = new CCounter();
    else
        pCounter->start();
}

void CProfiler::startCreatedCounter(const char* szCounterName)
{
    CCounter* pCounter = m_mapCounters[szCounterName];
    if ( !pCounter )
        return;

    if ( !pCounter->isWasStarted() )
        LOG(INFO) + szCounterName + " : START";

    pCounter->start();
}

void CProfiler::stopCounter(const char* szCounterName, bool bDestroy /*=false*/)
{
    CCounter* pCounter = m_mapCounters[szCounterName];
    if ( !pCounter ){
        //LOG(ERROR) + szCounterName + " : Cannot find counter.";
        return;
    }

    if ( bDestroy || !pCounter->isGlobal() )
    {
        common::CTimeInterval oInterval = pCounter->stop();
        LOG(INFO) + szCounterName + " (" + oInterval.toString() + ") : STOP";

        m_mapCounters.erase(szCounterName);
    }else
        pCounter->stop();

}

void CProfiler::flushCounter(const char* szCounterName, const char* msg)
{
    CCounter* pCounter = m_mapCounters[szCounterName];
    if ( !pCounter ){
        LOG(ERROR) + szCounterName + " : Cannot find counter.";
        return;
    }

    common::CTimeInterval oInterval = pCounter->flush();
    LOG(INFO) + szCounterName + (msg && *msg ? " - " : "" ) + (msg && *msg ? msg : "" ) +
        " (" + oInterval.toString() + ") : STOP";
}

void CProfiler::createCounter(const char* szCounterName)
{
    m_mapCounters[szCounterName] = new CGlobalCounter();
}

void CProfiler::destroyCounter(const char* szCounterName)
{
    stopCounter( szCounterName, true );
}

}

static rho::CProfiler g_oProfiler;
extern "C"{

void rhoStartProfilerCounter(const char* file, int line, const char* szCounterName )
{
    g_oProfiler.startCounter(szCounterName);
}

void rhoStartProfilerCreatedCounter(const char* file, int line, const char* szCounterName )
{
    g_oProfiler.startCreatedCounter(szCounterName);
}

void rhoStopProfilerCounter(const char* file, int line, const char* szCounterName )
{
    g_oProfiler.stopCounter(szCounterName);
}

void rhoCreateProfilerCounter(const char* file, int line, const char* szCounterName )
{
    g_oProfiler.createCounter(szCounterName);
}

void rhoDestroyProfilerCounter(const char* file, int line, const char* szCounterName )
{
    g_oProfiler.destroyCounter(szCounterName);
}

void rhoFlushProfilerCounter(const char* file, int line, const char* szCounterName, const char* msg )
{
    g_oProfiler.flushCounter(szCounterName, msg );
}

}
<commit_msg>profiler: flsuh counter should not stop it<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

#include "RhoProfiler.h"
#include "logging/RhoLog.h"
#include "common/RhoTime.h"
#include <map>

namespace rho {
class CProfiler
{
    DEFINE_LOGCLASS;

    class CCounter
    {
        common::CTimeInterval m_startTime;
        bool m_bWasStarted;
    public:
        CCounter(bool bStart=true) : m_bWasStarted(false){
            if ( bStart )
                start();
        }

        virtual bool isGlobal()const{ return false;}

        virtual void start(){ m_startTime = common::CTimeInterval::getCurrentTime(); m_bWasStarted = true; }
        virtual common::CTimeInterval stop()
        {
            if ( m_startTime.isEmpty() )
                return m_startTime;

            common::CTimeInterval res = common::CTimeInterval::getCurrentTime()-m_startTime;
            m_startTime = common::CTimeInterval();
            return res;
        }
        virtual common::CTimeInterval flush()
        {
            if ( m_startTime.isEmpty() )
                return m_startTime;

            common::CTimeInterval res = common::CTimeInterval::getCurrentTime()-m_startTime;
            m_startTime = common::CTimeInterval::getCurrentTime();
            return res;
        }

        bool isWasStarted()const{ return m_bWasStarted;}
    };

    class CGlobalCounter : public CCounter
    {
        common::CTimeInterval m_sumGlobal;
    public:
        CGlobalCounter() : CCounter(false){ }
        virtual bool isGlobal()const{ return true;}

        virtual common::CTimeInterval stop()
        {
            m_sumGlobal += CCounter::stop();

            return m_sumGlobal;
        }
        virtual common::CTimeInterval flush()
        {
            m_sumGlobal += CCounter::flush();
            common::CTimeInterval res = m_sumGlobal;
            m_sumGlobal = common::CTimeInterval();
            return res;
        }

    };

    std::map<String,CCounter*> m_mapCounters;
public:
    CProfiler(){}
    ~CProfiler(){}

    void startCounter(const char* szCounterName);
    void startCreatedCounter(const char* szCounterName);
    void stopCounter(const char* szCounterName, bool bDestroy =false);
    void createCounter(const char* szCounterName);
    void destroyCounter(const char* szCounterName);
    void flushCounter(const char* szCounterName, const char* msg);

};
IMPLEMENT_LOGCLASS(CProfiler,"PROFILER");

void CProfiler::startCounter(const char* szCounterName)
{
    CCounter* pCounter = m_mapCounters[szCounterName];
    if ( !pCounter || !pCounter->isWasStarted() )
        LOG(INFO) + szCounterName + " : START";

    if ( !pCounter )
        m_mapCounters[szCounterName] = new CCounter();
    else
        pCounter->start();
}

void CProfiler::startCreatedCounter(const char* szCounterName)
{
    CCounter* pCounter = m_mapCounters[szCounterName];
    if ( !pCounter )
        return;

    if ( !pCounter->isWasStarted() )
        LOG(INFO) + szCounterName + " : START";

    pCounter->start();
}

void CProfiler::stopCounter(const char* szCounterName, bool bDestroy /*=false*/)
{
    CCounter* pCounter = m_mapCounters[szCounterName];
    if ( !pCounter ){
        //LOG(ERROR) + szCounterName + " : Cannot find counter.";
        return;
    }

    if ( bDestroy || !pCounter->isGlobal() )
    {
        common::CTimeInterval oInterval = pCounter->stop();
        LOG(INFO) + szCounterName + " (" + oInterval.toString() + ") : STOP";

        m_mapCounters.erase(szCounterName);
    }else
        pCounter->stop();

}

void CProfiler::flushCounter(const char* szCounterName, const char* msg)
{
    CCounter* pCounter = m_mapCounters[szCounterName];
    if ( !pCounter ){
        LOG(ERROR) + szCounterName + " : Cannot find counter.";
        return;
    }

    common::CTimeInterval oInterval = pCounter->flush();
    LOG(INFO) + szCounterName + (msg && *msg ? " - " : "" ) + (msg && *msg ? msg : "" ) +
        " (" + oInterval.toString() + ") : STOP";
}

void CProfiler::createCounter(const char* szCounterName)
{
    m_mapCounters[szCounterName] = new CGlobalCounter();
}

void CProfiler::destroyCounter(const char* szCounterName)
{
    stopCounter( szCounterName, true );
}

}

static rho::CProfiler g_oProfiler;
extern "C"{

void rhoStartProfilerCounter(const char* file, int line, const char* szCounterName )
{
    g_oProfiler.startCounter(szCounterName);
}

void rhoStartProfilerCreatedCounter(const char* file, int line, const char* szCounterName )
{
    g_oProfiler.startCreatedCounter(szCounterName);
}

void rhoStopProfilerCounter(const char* file, int line, const char* szCounterName )
{
    g_oProfiler.stopCounter(szCounterName);
}

void rhoCreateProfilerCounter(const char* file, int line, const char* szCounterName )
{
    g_oProfiler.createCounter(szCounterName);
}

void rhoDestroyProfilerCounter(const char* file, int line, const char* szCounterName )
{
    g_oProfiler.destroyCounter(szCounterName);
}

void rhoFlushProfilerCounter(const char* file, int line, const char* szCounterName, const char* msg )
{
    g_oProfiler.flushCounter(szCounterName, msg );
}

}
<|endoftext|>


<commit_before>#include "shutteranimationcomponent.h"

#include <QtDeclarative/qdeclarative.h>
#include <QGraphicsView>
#include <QGraphicsPathItem>
#include "shutterslice.h"
#include <QDebug>
#include <QTimeLine>
#include <QtCore/qmath.h>
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <QtConcurrentRun>

ShutterAnimationComponent::ShutterAnimationComponent(QDeclarativeItem *parent):
        QDeclarativeItem(parent)
{
    // By default, QDeclarativeItem does not draw anything. If you subclass
    // QDeclarativeItem to create a visual item, you will need to uncomment the
    // following line:

    // setFlag(ItemHasNoContents, false);
    setVisible(false);
    connect(&animationGroup, SIGNAL(finished()), this, SLOT(animationEnded()));
}

ShutterAnimationComponent::~ShutterAnimationComponent()
{
}

qreal ShutterAnimationComponent::size()
{
    return m_size;
}

void ShutterAnimationComponent::setSize(qreal size)
{
    m_size = size;
    emit sizeChanged();
}

void ShutterAnimationComponent::componentComplete()
{
    QGraphicsItem *base = this;
    base->setFlag(QGraphicsItem::ItemClipsChildrenToShape,true);

    qreal d = qMax(base->boundingRect().width(),base->boundingRect().height());
    qreal r = d/2.0;
    r *= 1.4;

    qreal incrementAngle = 36;

    qreal b = r;
    QPolygonF poly;
    poly << QPointF(0,0) << QPointF(0,r) << QPointF(b,r) << QPointF(0,0);

  //  QPixmap px = QPixmap(":/images/camera-bg-triangle.png").scaled(b,r,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);

    QPropertyAnimation *anim = new QPropertyAnimation(this,"angle");
    anim->setDuration(3500);
    anim->setKeyValueAt(0,90.0);
    anim->setKeyValueAt(0.15, 0.0);
    anim->setKeyValueAt(0.8, 0.0);
    anim->setKeyValueAt(1,90.0);
    animationGroup.addAnimation(anim);
    int i=0;
    for (qreal angle = 0.0; angle < 360; angle += incrementAngle, i++) {

        // Could be QRectF
        QGraphicsPolygonItem *polyItem = new QGraphicsPolygonItem(poly,this);
        polyItem->setPen(QPen(Qt::white));
        polyItem->setBrush(QColor("gray"));

//        QGraphicsPixmapItem *polyItem = new QGraphicsPixmapItem(px,this);
       ShutterSlice *sh= new ShutterSlice(r,angle,polyItem,boundingRect());
       shList.append(sh);

    }
}

void ShutterAnimationComponent::start()
{
    setVisible(true);
    animationGroup.start();

}

void ShutterAnimationComponent::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
    Q_UNUSED(oldGeometry);
    foreach(ShutterSlice* slice, shList)
    {
        slice->setRect(newGeometry);
    }
}

void ShutterAnimationComponent::animationEnded()
{
    setVisible(false);
}
void ShutterAnimationComponent::setAngle(qreal angle)
{
foreach (ShutterSlice *slice, shList) {
    slice->setAngle(angle);

}
}
<commit_msg>Color fix<commit_after>#include "shutteranimationcomponent.h"

#include <QtDeclarative/qdeclarative.h>
#include <QGraphicsView>
#include <QGraphicsPathItem>
#include "shutterslice.h"
#include <QDebug>
#include <QTimeLine>
#include <QtCore/qmath.h>
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <QtConcurrentRun>

ShutterAnimationComponent::ShutterAnimationComponent(QDeclarativeItem *parent):
        QDeclarativeItem(parent)
{
    // By default, QDeclarativeItem does not draw anything. If you subclass
    // QDeclarativeItem to create a visual item, you will need to uncomment the
    // following line:

    // setFlag(ItemHasNoContents, false);
    setVisible(false);
    connect(&animationGroup, SIGNAL(finished()), this, SLOT(animationEnded()));
}

ShutterAnimationComponent::~ShutterAnimationComponent()
{
}

qreal ShutterAnimationComponent::size()
{
    return m_size;
}

void ShutterAnimationComponent::setSize(qreal size)
{
    m_size = size;
    emit sizeChanged();
}

void ShutterAnimationComponent::componentComplete()
{
    QGraphicsItem *base = this;
    base->setFlag(QGraphicsItem::ItemClipsChildrenToShape,true);

    qreal d = qMax(base->boundingRect().width(),base->boundingRect().height());
    qreal r = d/2.0;
    r *= 1.4;

    qreal incrementAngle = 36;

    qreal b = r;
    QPolygonF poly;
    poly << QPointF(0,0) << QPointF(0,r) << QPointF(b,r) << QPointF(0,0);

  //  QPixmap px = QPixmap(":/images/camera-bg-triangle.png").scaled(b,r,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);

    QPropertyAnimation *anim = new QPropertyAnimation(this,"angle");
    anim->setDuration(3500);
    anim->setKeyValueAt(0,90.0);
    anim->setKeyValueAt(0.15, 0.0);
    anim->setKeyValueAt(0.8, 0.0);
    anim->setKeyValueAt(1,90.0);
    animationGroup.addAnimation(anim);
    int i=0;
    for (qreal angle = 0.0; angle < 360; angle += incrementAngle, i++) {

        // Could be QRectF
        QGraphicsPolygonItem *polyItem = new QGraphicsPolygonItem(poly,this);
        polyItem->setPen(QPen(Qt::black));
        polyItem->setBrush(QColor("gray").darker().darker());

//        QGraphicsPixmapItem *polyItem = new QGraphicsPixmapItem(px,this);
       ShutterSlice *sh= new ShutterSlice(r,angle,polyItem,boundingRect());
       shList.append(sh);

    }
}

void ShutterAnimationComponent::start()
{
    setVisible(true);
    animationGroup.start();

}

void ShutterAnimationComponent::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
    Q_UNUSED(oldGeometry);
    foreach(ShutterSlice* slice, shList)
    {
        slice->setRect(newGeometry);
    }
}

void ShutterAnimationComponent::animationEnded()
{
    setVisible(false);
}
void ShutterAnimationComponent::setAngle(qreal angle)
{
foreach (ShutterSlice *slice, shList) {
    slice->setAngle(angle);

}
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.18.68); FILE MERGED 2006/03/17 16:12:47 pl 1.18.68.3: #i55991# removed warnings for windows platform 2005/11/04 17:25:00 pl 1.18.68.2: #i55991# removed warnings for linux/solaris 2005/10/21 17:31:14 pl 1.18.68.1: #i55991# removed warnings for linux platform<commit_after><|endoftext|>


<commit_before>#define FUSE_USE_VERSION 26

#include <fuse.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <cstdlib>

#include <sstream>
#include <string>
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

void strip_quotes(string&,const string,string);
queue<string> adb_push(string, string);
queue<string> adb_pull(string, string);
queue<string> adb_shell(string);
queue<string> shell(string);
queue<string> exec_command(string);
vector<string> make_array(string);

vector<string> make_array(string data){
    vector<string> result;
    string delimiters = " ";
    string::size_type lastPos = data.find_first_not_of(delimiters, 0);
    string::size_type pos     = data.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        result.push_back(data.substr(lastPos, pos - lastPos));
        lastPos = data.find_first_not_of(delimiters, pos);
        pos = data.find_first_of(delimiters, lastPos);
    }
    return result;
}

queue<string> shell(string command)
{
    string actual_command;
    strip_quotes(command,"\\","\\\\");
    strip_quotes(command,"'","\\'");
    strip_quotes(command,"`","\\`");
    actual_command.append(command);

    return exec_command(actual_command);
}

queue<string> adb_shell(string command)
{
    string actual_command;
    strip_quotes(command,"\\","\\\\");
    strip_quotes(command,"'","\\'");
    strip_quotes(command,"`","\\`");
    actual_command = "adb shell '";
    actual_command.append(command);
    actual_command.append("'");

    return exec_command(actual_command);
}

queue<string> adb_pull(string remote_source, string local_destination)
{
    string actual_command;
    strip_quotes(remote_source,"\\","\\\\");
    strip_quotes(remote_source,"'","\\'");
    strip_quotes(remote_source,"`","\\`");
    strip_quotes(local_destination,"\\","\\\\");
    strip_quotes(local_destination,"'","\\'");
    strip_quotes(local_destination,"`","\\`");
    actual_command = "adb pull '";
    actual_command.append(remote_source);
    actual_command.append("' '");
    actual_command.append(local_destination);
    actual_command.append("'");

    return exec_command(actual_command);
}

queue<string> adb_push(string local_source, string remote_destination)
{
    string actual_command;
    strip_quotes(remote_destination,"\\","\\\\");
    strip_quotes(remote_destination,"'","\\'");
    strip_quotes(remote_destination,"`","\\`");
    strip_quotes(local_source,"\\","\\\\");
    strip_quotes(local_source,"'","\\'");
    strip_quotes(local_source,"`","\\`");
    actual_command = "adb push '";
    actual_command.append(local_source);
    actual_command.append("' '");
    actual_command.append(remote_destination);
    actual_command.append("'");

    return exec_command(actual_command);
}

queue<string> exec_command(string command)
{
    queue<string> output;
    FILE *fp = popen(command.c_str(), "r" );

    char buff[1000];
    string tmp_string;
    while ( fgets( buff, sizeof buff, fp ) != NULL && !feof(fp) )
    {
        tmp_string.assign(buff);
        tmp_string.erase(tmp_string.size()-2);
        output.push(tmp_string);
    }

    pclose( fp );

    return output;
}

void strip_quotes( string &source, const string find, string replace ) {

	size_t j;
	for ( ; (j = source.find( find )) != string::npos ; ) {
		source.replace( j, find.length(), replace );
	}
}
int xtoi(const char* xs, unsigned int* result)
{
 size_t szlen = strlen(xs);
 int i, xv, fact;

 if (szlen > 0)
 {
  // Converting more than 32bit hexadecimal value?
  if (szlen>8) return 2; // exit

  // Begin conversion here
  *result = 0;
  fact = 1;

  // Run until no more character to convert
  for(i=szlen-1; i>=0 ;i--)
  {
   if (isxdigit(*(xs+i)))
   {
    if (*(xs+i)>=97)
    {
     xv = ( *(xs+i) - 97) + 10;
    }
    else if ( *(xs+i) >= 65)
    {
     xv = (*(xs+i) - 65) + 10;
    }
    else
    {
     xv = *(xs+i) - 48;
    }
    *result += (xv * fact);
    fact *= 16;
   }
   else
   {
    // Conversion was abnormally terminated
    // by non hexadecimal digit, hence
    // returning only the converted with
    // an error value 4 (illegal hex character)
    return 4;
   }
  }
 }

 // Nothing to convert
 return 1;
}
static int adb_getattr(const char *path, struct stat *stbuf)
{
    int res = 0;
    memset(stbuf, 0, sizeof(struct stat));

    string path_string;
    path_string.assign(path);

    queue<string> output;
    string command = "stat -t \"";
    command.append(path_string);
    command.append("\"");
    cout << command<<"\n";
    output = adb_shell(command);
    vector<string> output_chunk = make_array(output.front());
    if (output_chunk.size() < 13){
        return -ENOENT;
    }
    /*
    stat -t Explained:
    file name (%n)
    total size (%s)
    number of blocks (%b)
    raw mode in hex (%f)
    UID of owner (%u)
    GID of file (%g)
    device number in hex (%D)
    inode number (%i)
    number of hard links (%h)
    major devide type in hex (%t)
    minor device type in hex (%T)
    last access time as seconds since the Unix Epoch (%X)
    last modification as seconds since the Unix Epoch (%Y)
    last change as seconds since the Unix Epoch (%Z)
    I/O block size (%o)
    */
    //stbuf->st_dev = atoi(output_chunk[1].c_str());     /* ID of device containing file */
    stbuf->st_ino = atoi(output_chunk[7].c_str());     /* inode number */
    unsigned int raw_mode;
    xtoi(output_chunk[3].c_str(),&raw_mode);
    stbuf->st_mode = raw_mode;    /* protection */
    stbuf->st_nlink = 1;   /* number of hard links */
    stbuf->st_uid = atoi(output_chunk[4].c_str());     /* user ID of owner */
    stbuf->st_gid = atoi(output_chunk[5].c_str());     /* group ID of owner */

    unsigned int device_id;
    xtoi(output_chunk[6].c_str(),&device_id);
    stbuf->st_rdev = device_id;    // device ID (if special file)

    stbuf->st_size = atoi(output_chunk[1].c_str());    /* total size, in bytes */
    stbuf->st_blksize = atoi(output_chunk[14].c_str()); /* blocksize for filesystem I/O */
    stbuf->st_blocks = atoi(output_chunk[2].c_str());  /* number of blocks allocated */
    stbuf->st_atime = atol(output_chunk[11].c_str());   /* time of last access */
    stbuf->st_mtime = atol(output_chunk[12].c_str());   /* time of last modification */
    stbuf->st_ctime = atol(output_chunk[13].c_str());   /* time of last status change */

    return res;
}

static int adb_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
			 off_t offset, struct fuse_file_info *fi)
{
	(void) offset;
	(void) fi;
    string path_string;
    path_string.assign(path);

    queue<string> output;
    string command = "ls -1a \"";
    command.append(path_string);
    command.append("\"");
    output = adb_shell(command);

    while (output.size() > 0){
        filler(buf, output.front().c_str(), NULL, 0);
        output.pop();
    }

	return 0;
}

static int adb_open(const char *path, struct fuse_file_info *fi)
{

    if((fi->flags & 3) != O_RDONLY)
        return -EACCES;

    return 0;
}

static int adb_read(const char *path, char *buf, size_t size, off_t offset,
                      struct fuse_file_info *fi)
{
    return -ENOENT;
}

static struct fuse_operations adbfs_oper;

int main(int argc, char *argv[])
{
    memset(&adbfs_oper, sizeof(adbfs_oper), 0);
    adbfs_oper.readdir= adb_readdir;
    adbfs_oper.getattr= adb_getattr;
    adbfs_oper.open= adb_open;
    adbfs_oper.read= adb_read;
	return fuse_main(argc, argv, &adbfs_oper, NULL);
}
<commit_msg>added write support<commit_after>#define FUSE_USE_VERSION 26

#include <fuse.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
#include <queue>
#include <vector>
#include <map>

using namespace std;

struct fileCache{
    time_t timestamp;
    queue<string> statOutput;
};

void string_replacer(string&,const string,string);
queue<string> adb_push(string, string);
queue<string> adb_pull(string, string);
queue<string> adb_shell(string);
queue<string> shell(string);
queue<string> exec_command(string);
vector<string> make_array(string);
map<string,fileCache> fileData;

vector<string> make_array(string data){
    vector<string> result;
    string delimiters = " ";
    string::size_type lastPos = data.find_first_not_of(delimiters, 0);
    string::size_type pos     = data.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        result.push_back(data.substr(lastPos, pos - lastPos));
        lastPos = data.find_first_not_of(delimiters, pos);
        pos = data.find_first_of(delimiters, lastPos);
    }
    return result;
}

queue<string> shell(string command)
{
    string actual_command;
    string_replacer(command,"\\","\\\\");
    string_replacer(command,"'","\\'");
    string_replacer(command,"`","\\`");
    actual_command.append(command);

    return exec_command(actual_command);
}

queue<string> adb_shell(string command)
{
    string actual_command;
    string_replacer(command,"\\","\\\\");
    string_replacer(command,"'","\\'");
    string_replacer(command,"`","\\`");
    actual_command = "adb shell ";
    actual_command.append(command);
    //actual_command.append("'");

    return exec_command(actual_command);
}

queue<string> adb_pull(string remote_source, string local_destination)
{
    string actual_command;
    string_replacer(remote_source,"\\","\\\\");
    string_replacer(remote_source,"'","\\'");
    string_replacer(remote_source,"`","\\`");
    string_replacer(local_destination,"\\","\\\\");
    string_replacer(local_destination,"'","\\'");
    string_replacer(local_destination,"`","\\`");
    actual_command = "adb pull '";
    actual_command.append(remote_source);
    actual_command.append("' '");
    actual_command.append(local_destination);
    actual_command.append("'");

    return exec_command(actual_command);
}

queue<string> adb_push(string local_source, string remote_destination)
{
    string actual_command;
    string_replacer(remote_destination,"\\","\\\\");
    string_replacer(remote_destination,"'","\\'");
    string_replacer(remote_destination,"`","\\`");
    string_replacer(local_source,"\\","\\\\");
    string_replacer(local_source,"'","\\'");
    string_replacer(local_source,"`","\\`");
    actual_command = "adb push '";
    actual_command.append(local_source);
    actual_command.append("' '");
    actual_command.append(remote_destination);
    actual_command.append("'");

    return exec_command(actual_command);
}

queue<string> exec_command(string command)
{
    queue<string> output;
    FILE *fp = popen(command.c_str(), "r" );

    char buff[1000];
    string tmp_string;
    while ( fgets( buff, sizeof buff, fp ) != NULL && !feof(fp) )
    {
        tmp_string.assign(buff);
        tmp_string.erase(tmp_string.size()-2);
        output.push(tmp_string);
    }

    pclose( fp );

    return output;
}

void string_replacer( string &source, const string find, string replace ) {
	size_t j;
	for ( ; (j = source.find( find,j)) != string::npos ; ) {
		source.replace( j, find.length(), replace );
        j = j + replace.length();
	}
}

int xtoi(const char* xs, unsigned int* result)
{
 size_t szlen = strlen(xs);
 int i, xv, fact;

 if (szlen > 0)
 {
  // Converting more than 32bit hexadecimal value?
  if (szlen>8) return 2; // exit

  // Begin conversion here
  *result = 0;
  fact = 1;

  // Run until no more character to convert
  for(i=szlen-1; i>=0 ;i--)
  {
   if (isxdigit(*(xs+i)))
   {
    if (*(xs+i)>=97)
    {
     xv = ( *(xs+i) - 97) + 10;
    }
    else if ( *(xs+i) >= 65)
    {
     xv = (*(xs+i) - 65) + 10;
    }
    else
    {
     xv = *(xs+i) - 48;
    }
    *result += (xv * fact);
    fact *= 16;
   }
   else
   {
    // Conversion was abnormally terminated
    // by non hexadecimal digit, hence
    // returning only the converted with
    // an error value 4 (illegal hex character)
    return 4;
   }
  }
 }

 // Nothing to convert
 return 1;
}
static int adb_getattr(const char *path, struct stat *stbuf)
{
    int res = 0;
    memset(stbuf, 0, sizeof(struct stat));
    queue<string> output;
    string path_string;
    path_string.assign(path);
    string_replacer(path_string," ","\\ ");

    if (fileData.find(path_string) ==  fileData.end() || fileData[path_string].timestamp + 30 > time(NULL)){
        string command = "stat -t \"";
        command.append(path_string);
        command.append("\"");
        cout << command<<"\n";
        output = adb_shell(command);
        fileData[path_string].statOutput = output;
        fileData[path_string].timestamp = time(NULL);
    }else{
        output = fileData[path_string].statOutput;
        cout << "from cache " << output.front() <<"\n";
    }
    vector<string> output_chunk = make_array(output.front());
    if (output_chunk.size() < 13){
        return -ENOENT;
    }
    while (output_chunk.size() > 15){
        output_chunk.erase( output_chunk.begin());
    }
    /*
    stat -t Explained:
    file name (%n)
    total size (%s)
    number of blocks (%b)
    raw mode in hex (%f)
    UID of owner (%u)
    GID of file (%g)
    device number in hex (%D)
    inode number (%i)
    number of hard links (%h)
    major devide type in hex (%t)
    minor device type in hex (%T)
    last access time as seconds since the Unix Epoch (%X)
    last modification as seconds since the Unix Epoch (%Y)
    last change as seconds since the Unix Epoch (%Z)
    I/O block size (%o)
    */
    //stbuf->st_dev = atoi(output_chunk[1].c_str());     /* ID of device containing file */
    stbuf->st_ino = atoi(output_chunk[7].c_str());     /* inode number */
    unsigned int raw_mode;
    xtoi(output_chunk[3].c_str(),&raw_mode);
    stbuf->st_mode = raw_mode;    /* protection */
    stbuf->st_nlink = 1;   /* number of hard links */
    stbuf->st_uid = atoi(output_chunk[4].c_str());     /* user ID of owner */
    stbuf->st_gid = atoi(output_chunk[5].c_str());     /* group ID of owner */

    unsigned int device_id;
    xtoi(output_chunk[6].c_str(),&device_id);
    stbuf->st_rdev = device_id;    // device ID (if special file)

    stbuf->st_size = atoi(output_chunk[1].c_str());    /* total size, in bytes */
    stbuf->st_blksize = atoi(output_chunk[14].c_str()); /* blocksize for filesystem I/O */
    stbuf->st_blocks = atoi(output_chunk[2].c_str());  /* number of blocks allocated */
    stbuf->st_atime = atol(output_chunk[11].c_str());   /* time of last access */
    stbuf->st_mtime = atol(output_chunk[12].c_str());   /* time of last modification */
    stbuf->st_ctime = atol(output_chunk[13].c_str());   /* time of last status change */

    return res;
}

static int adb_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
			 off_t offset, struct fuse_file_info *fi)
{
	(void) offset;
	(void) fi;
    string path_string;
    path_string.assign(path);
    string_replacer(path_string," ","\\ ");

    queue<string> output;
    string command = "ls -1a \"";
    command.append(path_string);
    command.append("\"");
    output = adb_shell(command);

    while (output.size() > 0){
        filler(buf, output.front().c_str(), NULL, 0);
        output.pop();
    }

	return 0;
}

static int adb_open(const char *path, struct fuse_file_info *fi)
{
    string path_string;
    string local_path_string;
    path_string.assign(path);
    local_path_string.assign("/tmp/adbfs");
    local_path_string.append(path_string);
    string_replacer(local_path_string," ","\\ ");

    queue<string> output;
    string command = "stat -t \"";
    command.append(path_string);
    command.append("\"");
    cout << command<<"\n";
    output = adb_shell(command);
    vector<string> output_chunk = make_array(output.front());
    if (output_chunk.size() < 13){
        return -ENOENT;
    }

    adb_pull(path_string,local_path_string);

    return 0;
}

static int adb_read(const char *path, char *buf, size_t size, off_t offset,
                      struct fuse_file_info *fi)
{
    int fd;
    int res;
    string local_path_string;
    local_path_string.assign("/tmp/adbfs");
    local_path_string.append(path);

    fd = open(local_path_string.c_str(), O_RDONLY);

    if(fd == -1)
        return -errno;

    res = pread(fd, buf, size, offset);
        if(res == -1)
            res = -errno;

    return size;
}

static int adb_access(const char *path, int mask) {
    //###cout << "###access[path=" << path << "]" <<  endl;
    return 0;
}

static struct fuse_operations adbfs_oper;

int main(int argc, char *argv[])
{
    memset(&adbfs_oper, sizeof(adbfs_oper), 0);
    adbfs_oper.readdir= adb_readdir;
    adbfs_oper.getattr= adb_getattr;
    adbfs_oper.access= adb_access;
    adbfs_oper.open= adb_open;
    adbfs_oper.read= adb_read;
	return fuse_main(argc, argv, &adbfs_oper, NULL);
}
<|endoftext|>