text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#pragma once

#include <bond/core/config.h>

#include "io_manager_tag.h"
#include "lazy_bonded.h"
#include "serialization.h"

#include <bond/core/bonded.h>

#ifdef _MSC_VER
    #pragma warning (push)
    // warning C4100: unreferenced formal parameter
    //
    // warning C4291: no matching operator delete found; memory will not be
    // freed if initialization throws an exception
    //
    // warning C4702: unreachable code
    #pragma warning (disable: 4100 4291 4702)
#endif

#include <grpcpp/grpcpp.h>
#include <grpcpp/impl/codegen/async_unary_call.h>
#include <grpcpp/impl/codegen/status.h>
#include <grpcpp/impl/codegen/server_context.h>

#ifdef _MSC_VER
    #pragma warning (pop)
#endif

#include <boost/assert.hpp>
#include <boost/smart_ptr/intrusive_ptr.hpp>

#include <atomic>
#include <utility>

namespace bond { namespace ext { namespace grpc { namespace detail
{
    /// @brief Implementation class that holds the state associated with a
    /// single async, unary call.
    ///
    /// Potentually three different objects participate in shared ownership
    /// of instances of this class: the user-facing \ref unary_call and \ref
    /// shared_unary_call objects, as well as this object itself.
    ///
    /// To ensure that this instance stays alive while sending a response,
    /// unary_call_impl creates itself with a ref count of 1, opposed to the
    /// usual 0 that many boost::intrusive_ptr implementations use. When the
    /// notification that the response has been sent is dequeued from the
    /// completion queue, %invoke() calls %Release() on itself, decrementing
    /// the ref count, and allowing the remaining unary_call and
    /// shared_unary_call objects, if any, to control lifetime.
    class unary_call_impl final : io_manager_tag
    {
    public:
        unary_call_impl() = default;

        const ::grpc::ServerContext& context() const noexcept
        {
            return _context;
        }

        ::grpc::ServerContext& context() noexcept
        {
            return _context;
        }

        ::grpc::ByteBuffer& request_buffer() noexcept
        {
            return _requestBuffer;
        }

        ::grpc::ServerAsyncResponseWriter<::grpc::ByteBuffer>& responder() noexcept
        {
            return _responder;
        }

        template <typename T = Void>
        void Finish(const T& response = {})
        {
            Finish(bonded<T>{ boost::ref(response) });
        }

        template <typename T>
        void Finish(const bonded<T>& response)
        {
            bool wasResponseSent = _responseSentFlag.test_and_set();
            if (!wasResponseSent)
            {
                _responder.Finish(Serialize(response), ::grpc::Status::OK, tag());
            }
        }

        void Finish(const ::grpc::Status& status)
        {
            bool wasResponseSent = _responseSentFlag.test_and_set();
            if (!wasResponseSent)
            {
                _responder.FinishWithError(status, tag());
            }
        }

    private:
        void invoke(bool /* ok */) override
        {
            // The response has been sent, so we no longer need to keep
            // ourselves alive: release the implicit initial refcount that
            // this instance was constructed with.
            Release();
        }

        void AddRef() noexcept
        {
            _refCount.fetch_add(1, std::memory_order_relaxed);
        }

        void Release()
        {
            if (_refCount.fetch_sub(1, std::memory_order_acq_rel) == 1)
            {
                delete this;
            }
        }

        void TryFinishWithError()
        {
            if (_refCount.load(std::memory_order::memory_order_acquire) == 2)
            {
                // The last user reference has just gone away, but Finish was
                // not called. In this case, we are responsible for sending
                // an error response and decrementing the final ref
                // count. Finish with ::grpc::Status will schedule the send of the
                // error response, and notification of completion of the
                // send via invoke() will decrement the final ref count.
                // Since we hold the ref count ourselves, we will not
                // get deleted until we're done sending.
                //
                // Even when multiple threads enter this case, at most one
                // will succeed in sending error, thanks to _responseSentFlag.

                Finish({ ::grpc::StatusCode::INTERNAL, "An internal server error has occurred." });
            }
        }

        friend void intrusive_ptr_add_ref(unary_call_impl* call) noexcept
        {
            call->AddRef();
        }

        friend void intrusive_ptr_release(unary_call_impl* call)
        {
            call->TryFinishWithError();
            call->Release();
        }

        // A pointer to the context is passed to _responder when
        // constructing it, so this needs to be declared before _responder.
        ::grpc::ServerContext _context{};
        ::grpc::ServerAsyncResponseWriter<::grpc::ByteBuffer> _responder{ &_context };
        ::grpc::ByteBuffer _requestBuffer;
        std::atomic_flag _responseSentFlag = ATOMIC_FLAG_INIT; // Tracks whether any response has been sent yet.
        // The ref count intentionally starts at 1, because this instance
        // needs to keep itself alive until the response has finished being
        // sent, regardless of whether there are any outstanding user
        // references still alive.
        std::atomic<size_t> _refCount{ 1 };
    };

    template <typename Request, typename Response>
    class unary_call_base;

    template <typename Base>
    class unary_call_impl_base;

    template <typename Base>
    class unary_call_input_base;

    template <typename Base>
    class unary_call_result_base;

    template <template <typename> class Base, typename Request, typename Response>
    class unary_call_impl_base<Base<unary_call_base<Request, Response>>>
    {
    protected:
        unary_call_base<Request, Response>& as_ucb() noexcept
        {
            return static_cast<unary_call_base<Request, Response>&>(
                static_cast<Base<unary_call_base<Request, Response>>&>(*this));
        }

        const unary_call_base<Request, Response>& as_ucb() const noexcept
        {
            return static_cast<const unary_call_base<Request, Response>&>(
                static_cast<const Base<unary_call_base<Request, Response>>&>(*this));
        }
    };

    template <typename Request, typename Response>
    class unary_call_input_base<unary_call_base<Request, Response>>
        : public unary_call_impl_base<unary_call_input_base<unary_call_base<Request, Response>>>
    {
    public:
        /// @brief Get the request message for this call.
        const bonded<Request>& request() const
        {
            return _request.get();
        }

        /// @brief Get the request message for this call.
        bonded<Request>& request()
        {
            return _request.get();
        }

    protected:
        unary_call_input_base() = default;

        explicit unary_call_input_base(unary_call_impl& impl)
            : _request{ impl.request_buffer() }
        {}

    private:
        lazy_bonded<Request> _request;
    };

    template <typename Response>
    class unary_call_input_base<unary_call_base<void, Response>>
    {
    protected:
        unary_call_input_base() = default;

        explicit unary_call_input_base(unary_call_impl& /*impl*/)
        {}
    };

    template <typename Request, typename Response>
    class unary_call_result_base<unary_call_base<Request, Response>>
        : public unary_call_impl_base<unary_call_result_base<unary_call_base<Request, Response>>>
    {
    public:
        /// @brief Responds to the client with the given message.
        ///
        /// Only the first call to \p Finish will be honored.
        void Finish(const Response& msg = {})
        {
            this->as_ucb().impl().Finish(msg);
        }

        /// @brief Responds to the client with the given message.
        ///
        /// Only the first call to \p Finish will be honored.
        void Finish(const bonded<Response>& msg)
        {
            this->as_ucb().impl().Finish(msg);
        }

        /// @brief Responds to the client with the given status and no message.
        ///
        /// Only the first call to \p Finish will be honored.
        void Finish(const ::grpc::Status& status)
        {
            this->as_ucb().impl().Finish(status);
        }

    protected:
        unary_call_result_base() = default;

        explicit unary_call_result_base(unary_call_impl& /*impl*/)
        {}
    };

    template <typename Request>
    class unary_call_result_base<unary_call_base<Request, void>>
        : public unary_call_impl_base<unary_call_result_base<unary_call_base<Request, void>>>
    {
    public:
        /// @brief Responds to the client with empty message.
        ///
        /// Only the first call to \p Finish will be honored.
        void Finish()
        {
            this->as_ucb().impl().Finish();
        }

        /// @brief Responds to the client with the given status and no message.
        ///
        /// Only the first call to \p Finish will be honored.
        void Finish(const ::grpc::Status& status)
        {
            this->as_ucb().impl().Finish(status);
        }

    protected:
        unary_call_result_base() = default;

        explicit unary_call_result_base(unary_call_impl& /*impl*/)
        {}
    };

    template <typename Request>
    class unary_call_result_base<unary_call_base<Request, bond::reflection::nothing>>
        : public unary_call_impl_base<unary_call_result_base<unary_call_base<Request, bond::reflection::nothing>>>
    {
    protected:
        unary_call_result_base() = default;

        explicit unary_call_result_base(unary_call_impl& impl)
        {
            impl.Finish();
        }
    };

    /// @brief Detail class that helps implement \ref unary_call and \ref
    /// shared_unary_call.
    template <typename Request, typename Response>
    class unary_call_base
        : public unary_call_input_base<unary_call_base<Request, Response>>,
          public unary_call_result_base<unary_call_base<Request, Response>>
    {
    public:
        unary_call_base() = default;

        explicit unary_call_base(boost::intrusive_ptr<unary_call_impl> impl)
            : unary_call_base::unary_call_input_base(*impl),
              unary_call_base::unary_call_result_base(*impl),
              _impl(std::move(impl))
        {}

        explicit operator bool() const noexcept
        {
            return static_cast<bool>(_impl);
        }

        void swap(unary_call_base& rhs) noexcept
        {
            using std::swap;
            swap(_impl, rhs._impl);
        }

        /// @brief Get the server context for this call.
        const ::grpc::ServerContext& context() const noexcept
        {
            return impl().context();
        }

        /// @brief Get the server context for this call.
        ::grpc::ServerContext& context() noexcept
        {
            return impl().context();
        }

    private:
        friend class unary_call_input_base<unary_call_base>;
        friend class unary_call_result_base<unary_call_base>;

        unary_call_impl& impl() noexcept
        {
            BOOST_ASSERT(_impl);
            return *_impl;
        }

        const unary_call_impl& impl() const noexcept
        {
            BOOST_ASSERT(_impl);
            return *_impl;
        }

        boost::intrusive_ptr<unary_call_impl> _impl;
    };

} } } } //namespace bond::ext::grpc::detail


text:
/**
 *  @file
 */
#define _LIB_LIBCARRDM_LOCK_C 1
#include "libcarrdm-lock.h"

///////////////
//           //
//  Headers  //
//           //
///////////////
#ifdef CARRDM_PMARK
#pragma mark - Headers
#endif

#include <assert.h>
#include <pthread.h>

#ifdef USE_OSSPINLOCK
#   include <libkern/OSAtomic.h>
#endif

#include "libcarrdm-base.h"

//////////////////
//              //
//  Data Types  //
//              //
//////////////////
#ifdef CARRDM_PMARK
#pragma mark - Data Types
#endif

#ifdef USE_PTHREAD_SPINLOCK
typedef pthread_spinlock_t carrdm_spinlock_t;
#elif USE_OSSPINLOCK
typedef OSSpinLock carrdm_spinlock_t;
#else
typedef pthread_mutex_t carrdm_spinlock_t;
#endif
typedef pthread_mutex_t carrdm_mutex_t;

struct carrdm_lock_data_struct
{
   union
   {
      carrdm_magic   magic;
      carrdm_base    base;
   } sup;
   uint64_t             lock_count;
   pthread_t            lock_thread;
   carrdm_spinlock_t    lock_meta_lock;
   carrdm_mutex_t       lock_lock;
};

typedef struct carrdm_reallock_struct carrdm_reallock;

struct carrdm_reallock_struct
{
   union
   {
      carrdm_magic   magic;
      carrdm_base    base;
   } sup;
   uint64_t             lock_recursive;
   uint64_t             lock_count;
   pthread_t            lock_thread;
   carrdm_spinlock_t    lock_meta_lock;
   carrdm_mutex_t       lock_lock;
};

//////////////////
//              //
//  Prototypes  //
//              //
//////////////////
#ifdef CARRDM_PMARK
#pragma mark - Prototypes
#endif

void carrdm_baselock_destroy(void * objref);

void   carrdm_mutex_destroy(carrdm_mutex_t * mutex);
int    carrdm_mutex_init(carrdm_mutex_t * mutex);
void   carrdm_mutex_lock(carrdm_mutex_t * mutex);
int    carrdm_mutex_trylock(carrdm_mutex_t * mutex);
void   carrdm_mutex_unlock(carrdm_mutex_t * mutex);

void                    carrdm_reallock_destroy(void * objref);
carrdm_reallock       * carrdm_reallock_initialize(void * ptr);

void   carrdm_spin_destroy(carrdm_spinlock_t * spinlock);
int    carrdm_spin_init(carrdm_spinlock_t * spinlock);
void   carrdm_spin_lock(carrdm_spinlock_t * spinlock);
int    carrdm_spin_trylock(carrdm_spinlock_t * spinlock);
void   carrdm_spin_unlock(carrdm_spinlock_t * spinlock);

/////////////////
//             //
//  Variables  //
//             //
/////////////////
#ifdef CARRDM_PMARK
#pragma mark - Variables
#endif

carrdm_definition carrdm_baselock_def =
{
   sizeof(carrdm_definition),    // def_size
   CARRDM_API_CURRENT,           // def_api_current
   CARRDM_API_REVISION,          // def_api_revision
   CARRDM_API_AGE,               // def_api_age
   CARRDM_API_CURRENT,           // obj_api_current
   CARRDM_API_REVISION,          // obj_api_revision
   CARRDM_API_AGE,               // obj_api_age
   NULL,                         // obj_data
   0LLU,                         // obj_data_size
   &carrdm_base_def,             // super_def
   CARRDM_TYPE_BASELOCK,         // type
   sizeof(carrdm_baselock),      // size
   carrdm_baselock_destroy,      // destroy
   NULL,                         // getter
   NULL,                         // setter
   NULL,                         // is_object
   NULL                          // duplicate
};

carrdm_definition carrdm_reallock_def =
{
   sizeof(carrdm_definition),    // def_size
   CARRDM_API_CURRENT,           // def_api_current
   CARRDM_API_REVISION,          // def_api_revision
   CARRDM_API_AGE,               // def_api_age
   CARRDM_API_CURRENT,           // obj_api_current
   CARRDM_API_REVISION,          // obj_api_revision
   CARRDM_API_AGE,               // obj_api_age
   NULL,                         // obj_data
   0LLU,                         // obj_data_size
   &carrdm_base_def,             // super_def
   CARRDM_TYPE_BASELOCK,         // type
   sizeof(carrdm_reallock),      // size
   carrdm_reallock_destroy,      // destroy
   NULL,                         // getter
   NULL,                         // setter
   NULL,                         // is_object
   NULL                          // duplicate
};

carrdm_definition carrdm_reclock_def =
{
   sizeof(carrdm_definition),    // def_size
   CARRDM_API_CURRENT,           // def_api_current
   CARRDM_API_REVISION,          // def_api_revision
   CARRDM_API_AGE,               // def_api_age
   CARRDM_API_CURRENT,           // obj_api_current
   CARRDM_API_REVISION,          // obj_api_revision
   CARRDM_API_AGE,               // obj_api_age
   NULL,                         // obj_data
   0LLU,                         // obj_data_size
   &carrdm_baselock_def,         // super_def
   CARRDM_TYPE_RECLOCK,          // type
   sizeof(carrdm_reclock),       // size
   NULL,                         // destroy
   NULL,                         // getter
   NULL,                         // setter
   NULL,                         // is_object
   NULL                          // duplicate
};

////////////////////////
//                    //
//  Inline Functions  //
//                    //
////////////////////////
#ifdef CARRDM_PMARK
#pragma mark - Inline Functions
#endif

extern inline carrdm_baselock       * carrdm_baselock_cast(void * objref);
extern inline const carrdm_baselock * carrdm_baselock_ccast(const void * objref);
extern inline carrdm_reclock        * carrdm_reclock_cast(void * objref);
extern inline const carrdm_reclock  * carrdm_reclock_ccast(const void * objref);

/////////////////
//             //
//  Functions  //
//             //
/////////////////
#ifdef CARRDM_PMARK
#pragma mark - Baselock Objref Functions
#endif

void carrdm_baselock_destroy(void * ptr)
{
   carrdm_baselock * objref = ptr;

   assert(carrdm_is_def(objref, &carrdm_baselock_def) == CARRDM_TRUE);

   if (objref->reallock != NULL)
      carrdm_release(objref->reallock);
   objref->reallock = NULL;

   return;
}

carrdm_baselock * carrdm_baselock_initialize(void * ptr)
{
   void            * mem;
   carrdm_baselock * objref;

   if ((mem = carrdm_alloc(ptr, &carrdm_baselock_def)) == NULL)
      return(NULL);
   if ((objref = (carrdm_baselock *)carrdm_base_initialize(mem)) == NULL)
   {
      if (ptr == NULL)
         carrdm_release(mem);
      return(NULL);
   };

   if ((objref->reallock = carrdm_reallock_initialize(NULL)) == NULL)
   {
      carrdm_destroy(objref);
      return(NULL);
   };

   return(objref);
}

/////////////////
//             //
//  Functions  //
//             //
/////////////////
#ifdef CARRDM_PMARK
#pragma mark - Core Lock Functions
#endif

int carrdm_lock(void * ptr)
{
   carrdm_baselock * baselock = ptr;
   carrdm_reallock * reallock;
   pthread_t         thread;

   assert(carrdm_is_def(baselock, &carrdm_baselock_def) == CARRDM_TRUE);
   reallock = baselock->reallock;

   if (reallock->lock_recursive == CARRDM_FALSE)
   {
      carrdm_mutex_lock(&reallock->lock_lock);
      return(0);
   };

   thread = pthread_self();

   carrdm_spin_lock(&reallock->lock_meta_lock);
   if ((pthread_equal(thread, reallock->lock_thread) != 0) && (reallock->lock_count != 0))
   {
      reallock->lock_count++;
      carrdm_spin_unlock(&reallock->lock_meta_lock);
      return(0);
   };
   carrdm_spin_unlock(&reallock->lock_meta_lock);

   carrdm_mutex_lock(&reallock->lock_lock);

   carrdm_spin_lock(&reallock->lock_meta_lock);
   reallock->lock_thread = pthread_self();
   reallock->lock_count++;
   carrdm_spin_unlock(&reallock->lock_meta_lock);

   return(0);
}

int carrdm_trylock(void * ptr)
{
   carrdm_baselock * baselock = ptr;
   carrdm_reallock * reallock;
   int               err;
   pthread_t         thread;

   assert(carrdm_is_def(baselock, &carrdm_baselock_def) == CARRDM_TRUE);
   reallock = baselock->reallock;

   if (reallock->lock_recursive == CARRDM_TRUE)
      return(carrdm_mutex_trylock(&reallock->lock_lock));

   thread = pthread_self();

   carrdm_spin_lock(&reallock->lock_meta_lock);
   if ((err = carrdm_mutex_trylock(&reallock->lock_lock)) != 0)
   {
      if ((pthread_equal(thread, reallock->lock_thread) != 0) && (reallock->lock_count != 0))
      {
         reallock->lock_count++;
         err = 0;
      };
   }
   else
   {
      reallock->lock_thread = thread;
      reallock->lock_count++;
   };
   carrdm_spin_unlock(&reallock->lock_meta_lock);

   return(err);
}

int carrdm_unlock(void * ptr)
{
   carrdm_baselock * baselock = ptr;
   carrdm_reallock * reallock;

   assert(carrdm_is_def(baselock, &carrdm_baselock_def) == CARRDM_TRUE);
   reallock = baselock->reallock;

   if (reallock->lock_recursive == CARRDM_FALSE)
   {
      carrdm_mutex_unlock(&reallock->lock_lock);
      return(0);
   };

   carrdm_spin_lock(&reallock->lock_meta_lock);
   if (reallock->lock_count != 0)
      reallock->lock_count--;
   if (reallock->lock_count == 0)
   {
      carrdm_spin_unlock(&reallock->lock_meta_lock);
      carrdm_mutex_unlock(&reallock->lock_lock);
      return(0);
   };
   carrdm_spin_unlock(&reallock->lock_meta_lock);
   return(0);
}

/////////////////
//             //
//  Functions  //
//             //
/////////////////
#ifdef CARRDM_PMARK
#pragma mark - Reallock Objref Functions
#endif

void carrdm_reallock_destroy(void * ptr)
{
   carrdm_reallock * objref = ptr;

   assert(carrdm_is_def(objref, &carrdm_reallock_def) == CARRDM_TRUE);

   carrdm_spin_destroy(&objref->lock_meta_lock);
   carrdm_mutex_destroy(&objref->lock_lock);

   return;
}

carrdm_reallock * carrdm_reallock_initialize(void * ptr)
{
   void            * mem;
   carrdm_reallock * objref;

   if ((mem = carrdm_alloc(ptr, &carrdm_reallock_def)) == NULL)
      return(NULL);
   if ((objref = (carrdm_reallock *)carrdm_base_initialize(mem)) == NULL)
   {
      if (ptr == NULL)
         carrdm_release(mem);
      return(NULL);
   };

   carrdm_spin_init(&objref->lock_meta_lock);
   carrdm_mutex_init(&objref->lock_lock);

   return(objref);
}

/////////////////
//             //
//  Functions  //
//             //
/////////////////
#ifdef CARRDM_PMARK
#pragma mark - Reclock Objref Functions
#endif

carrdm_reclock * carrdm_reclock_initialize(void * ptr)
{
   carrdm_reclock  * objref;
   carrdm_reallock * reallock;

   if ((ptr = carrdm_alloc(ptr, &carrdm_reclock_def)) == NULL)
      return(NULL);

   if ((objref = (carrdm_reclock *)carrdm_baselock_initialize(ptr)) == NULL)
   {
      carrdm_destroy(ptr);
      return(NULL);
   };

   reallock                 = objref->sup.baselock.reallock;
   reallock->lock_recursive = CARRDM_TRUE;

   return(objref);
}

///////////////////////
//                   //
//  Low-level Locks  //
//                   //
///////////////////////
#ifdef CARRDM_PMARK
#pragma mark - Low-level Locks
#endif

#ifdef USE_PTHREAD_SPINLOCK
void carrdm_spin_destroy(carrdm_spinlock_t * spinlock) { pthread_spin_destroy(spinlock); }
int  carrdm_spin_init(carrdm_spinlock_t * spinlock)    { return(pthread_spin_init(spinlock, NULL)); }
void carrdm_spin_lock(carrdm_spinlock_t * spinlock)    { pthread_spin_lock(spinlock); }
int  carrdm_spin_trylock(carrdm_spinlock_t * spinlock) { return(pthread_spin_trylock(spinlock)); }
void carrdm_spin_unlock(carrdm_spinlock_t * spinlock)  { pthread_spin_unlock(spinlock); }
#elif USE_OSSPINLOCK
#include <libkern/OSAtomic.h>
void carrdm_spin_destroy(carrdm_spinlock_t * spinlock) { assert(spinlock != NULL); }
int  carrdm_spin_init(carrdm_spinlock_t * spinlock)    { *spinlock = OS_SPINLOCK_INIT; return(0); }
void carrdm_spin_lock(carrdm_spinlock_t * spinlock)    { OSSpinLockLock(spinlock); }
int  carrdm_spin_trylock(carrdm_spinlock_t * spinlock) { return(OSSpinLockTry(spinlock)); }
void carrdm_spin_unlock(carrdm_spinlock_t * spinlock)  { OSSpinLockUnlock(spinlock); }
#else
void carrdm_spin_destroy(carrdm_spinlock_t * spinlock) { pthread_mutex_destroy(spinlock); }
int  carrdm_spin_init(carrdm_spinlock_t * spinlock)    { return(pthread_mutex_init(spinlock, NULL)); }
void carrdm_spin_lock(carrdm_spinlock_t * spinlock)    { pthread_mutex_lock(spinlock); }
int  carrdm_spin_trylock(carrdm_spinlock_t * spinlock) { return(pthread_mutex_trylock(spinlock)); }
void carrdm_spin_unlock(carrdm_spinlock_t * spinlock)  { pthread_mutex_unlock(spinlock); }
#endif
void carrdm_mutex_destroy(carrdm_mutex_t * mutex) { pthread_mutex_destroy(mutex); }
int  carrdm_mutex_init(carrdm_mutex_t * mutex)    { return(pthread_mutex_init(mutex, NULL)); }
void carrdm_mutex_lock(carrdm_mutex_t * mutex)    { pthread_mutex_lock(mutex); }
int  carrdm_mutex_trylock(carrdm_mutex_t * mutex) { return(pthread_mutex_trylock(mutex)); }
void carrdm_mutex_unlock(carrdm_mutex_t * mutex)  { pthread_mutex_unlock(mutex); }

/* end of source */

redpajama_set_name: RedPajamaGithub


text:
package gov.nih.nci.cacis.nav;

import java.io.InputStream;

/**
 * @author Joshua Phillips
 * @since May 10, 2011
 *
 */
public interface XDSDocumentResolver {

    /**
     * Resolves a document ID to an InputStream
     *
     * @param documentId the document ID
     * @return the InputStream
     * @throws XDSDocumentResolutionException on error
     */
    InputStream resolve(String documentId) throws XDSDocumentResolutionException;

    /**
     *
     * @return the ID of the document registry
     */
    String getRecommendedRegistry();
}


text:
function torch.group(sorted, index, tensor, samegrp, desc)
   if not torch.isTensor(tensor) then
      desc = tensor
      samegrp = index
      tensor = sorted
      index = nil
      sorted = nil
   end
   assert(torch.isTensor(tensor), 'expecting torch.Tensor for arg 3')

   local sorted = sorted or tensor.new()
   assert(torch.type(tensor) == torch.type(sorted), 'expecting torch.Tensor for arg 1 as same type as arg 2')

   samegrp = samegrp or function(start_val, val)
      return start_val == val
   end
   assert(torch.type(samegrp) == 'function', 'expecting function for arg 4')

   index = index or torch.LongTensor()
   assert(torch.type(index) == 'torch.LongTensor', 'expecting torch.LongTensor for arg 2')

   if desc == nil then
      desc = false
   end
   sorted:sort(index, tensor, desc)

   local start_idx, start_val = 1, sorted[1]
   local idx = 1
   local groups = {}
   sorted:apply(function(val)
      if not samegrp(start_val, val) then
         groups[start_val] = {
            idx=index:narrow(1, start_idx, idx-start_idx),
            val=sorted:narrow(1, start_idx, idx-start_idx)
         }
         start_val = val
         start_idx = idx
      end

      idx = idx + 1

      if idx-1 == sorted:size(1) then
         groups[start_val] = {
            idx=index:narrow(1, start_idx, idx-start_idx),
            val=sorted:narrow(1, start_idx, idx-start_idx)
         }
      end

   end)

   return groups, sorted, index
end


text:
package org.onosproject.store.primitives.resources.impl;

import org.onosproject.store.service.DocumentPath;
import org.onosproject.store.service.Versioned;

import com.google.common.base.MoreObjects;

/**
 * Result of a document tree node update operation.
 * <p>
 * Both old and new values are accessible along with a status of update.
 *
 * @param <V> value type
 */
public class DocumentTreeUpdateResult<V> {

    public enum Status {
        /**
         * Indicates a successful update.
         */
        OK,

        /**
         * Indicates a noop i.e. existing and new value are both same.
         */
        NOOP,

        /**
         * Indicates a failed update due to a write lock.
         */
        WRITE_LOCK,

        /**
         * Indicates a failed update due to a invalid path.
         */
        INVALID_PATH,

        /**
         * Indicates a failed update due to a illegal modification attempt.
         */
        ILLEGAL_MODIFICATION,
    }

    private final DocumentPath path;
    private final Status status;
    private final Versioned<V> oldValue;
    private final Versioned<V> newValue;

    public DocumentTreeUpdateResult(DocumentPath path,
            Status status,
            Versioned<V> newValue,
            Versioned<V> oldValue) {
        this.status = status;
        this.path = path;
        this.newValue = newValue;
        this.oldValue = oldValue;
    }

    public static <V> DocumentTreeUpdateResult<V> invalidPath(DocumentPath path) {
        return new DocumentTreeUpdateResult<>(path, Status.INVALID_PATH, null, null);
    }

    public static <V> DocumentTreeUpdateResult<V> illegalModification(DocumentPath path) {
        return new DocumentTreeUpdateResult<>(path, Status.ILLEGAL_MODIFICATION, null, null);
    }

    public Status status() {
        return status;
    }

    public DocumentPath path() {
        return path;
    }

    public Versioned<V> oldValue() {
        return oldValue;
    }

    public Versioned<V> newValue() {
        return this.newValue;
    }

    public boolean updated() {
        return status == Status.OK;
    }

    public boolean created() {
        return updated() && oldValue == null;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(getClass())
                .add("path", path)
                .add("status", status)
                .add("newValue", newValue)
                .add("oldValue", oldValue)
                .toString();
    }
}


text:
<!DOCTYPE html>

Test


text:
package id.satusatudua.sigap.service;

import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.NotificationCompat;

import id.satusatudua.sigap.R;
import id.satusatudua.sigap.SigapApp;
import id.zelory.benih.util.BenihUtils;

/**
 * Created on : November 23, 2015
 * Author     : zetbaitsu
 * Name       : Zetra
 * Email      : zetra@mail.ugm.ac.id
 * GitHub     : https://github.com/zetbaitsu
 * LinkedIn   : https://id.linkedin.com/in/zetbaitsu
 */
public class LocationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (!BenihUtils.isMyServiceRunning(context, LocationService.class)) {
            context.startService(new Intent(context, LocationService.class));
        }

        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean anyLocationProv = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        anyLocationProv |= locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!anyLocationProv) {
            Notification notification = new NotificationCompat.Builder(context)
                    .setContentTitle("Sigap")
                    .setContentText("Fitur lokasi tidak aktif.")
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setOngoing(true)
                    .setAutoCancel(true)
                    .setStyle(new android.support
                            .v4.app.NotificationCompat
                            .BigTextStyle()
                                      .bigText("Aktifkan fitur lokasi agar Sigap bisa berjalan dengan baik."))
                    .build();

            NotificationManagerCompat.from(SigapApp.pluck().getApplicationContext()).notify(25061993, notification);
        } else {
            NotificationManagerCompat.from(SigapApp.pluck().getApplicationContext()).cancel(25061993);
        }
    }
}


text:
import boto3
import hashlib
import logging
import math
import os
import xxhash
from botocore.exceptions import ClientError
from itertools import repeat
from multiprocessing import Manager, Pool, Queue
from random import randrange

from supersync.metadatastore import MetaDataStore
from supersync.s3wrapper import S3Wrapper

logger = logging.getLogger('supersync')

KB = 1024
MB = KB * KB
GB = MB * KB

def hash_part(speed, chunk):
    if speed == 'default':
        hash1 = hashlib.sha3_512(chunk).hexdigest()
        hash2 = hashlib.blake2b(chunk).hexdigest()
    if speed == 'fast':
        hash1 = xxhash.xxh64(chunk).hexdigest()
        hash2 = '-'
    return (hash1,hash2)

def process_part(
        local,
        dest,
        chunk_size,
        local_size,
        part_count,
        part_number,
        upload_id,
        profile,
        table_name,
        queue,
        speed,
        hash_type1,
        hash_type2):
    pid = os.getpid()
    part_number = part_number + 1
    metadata = MetaDataStore(profile,table_name,speed,check_table=False)
    s3_wrapper = S3Wrapper(profile,local,dest)
    with open(local,'rb') as file_object:
        file_object.seek((part_number - 1) * chunk_size)
        chunk = file_object.read(chunk_size)
        lower = (part_number - 1) * chunk_size
        upper = ((part_number * chunk_size) - 1) if part_number < part_count else (local_size - 1)
        content_range = '{}-{}'.format(lower,upper)
        hash1,hash2 = hash_part(speed,chunk)
        logger.debug('{}: Part {}/{} {}: {}'.format(pid,part_number,part_count,hash_type1,hash1))
        logger.debug('{}: Part {}/{} {}: {}'.format(pid,part_number,part_count,hash_type2,hash2))
        item = metadata.get_dynamo_item(hash1,hash2)
        if item:
            index = 0
            if len(item['locations']['L']) > 1:
                index = randrange(0,(len(item['locations']['L']) - 1))
            first_location = item['locations']['L'][index]['M']
            source_bucket = first_location['bucket']['S']
            source_key = first_location['key']['S']
            source_version = first_location['version']['S']
            source_part_number = first_location['part']['N']
            source_range = first_location['content_range']['S']
            resp = s3_wrapper.copy_part(
                source_bucket,
                source_key,
                source_version,
                source_part_number,
                source_range,
                part_number,
                upload_id
            )
            etag = resp['CopyPartResult']['ETag']
        else:
            resp = s3_wrapper.upload_part(
               chunk,
               part_number,
               upload_id,
               chunk_size
            )
            logger.debug('{}: Upload Part: {}'.format(pid,resp))
            etag = resp['ETag']
        queue.put(
            {
                'ETag': etag,
                'PartNumber': part_number,
                hash_type1: hash1,
                hash_type2: hash2,
                'content_range': content_range
            }
        )

class S3SuperSync(object):

    def __init__(self,profile,table_name,local,dest,concurrency,speed):
        self.profile = profile
        self.speed = speed
        self.hash_type1, self.hash_type2 = self._get_hash_types(speed)
        self.metadata = MetaDataStore(profile,table_name,speed,concurrency)
        self.s3 = S3Wrapper(profile,local,dest)
        self.concurrency = concurrency
        self.local = self.s3.local
        self.dest = self.s3.dest
        self.local_size = os.path.getsize(self.local)
        logger.debug(self.local_size)
        self.chunk_size = self._get_chunk_size()
        self.part_count = self._get_part_count()

    def sync(self):
        upload_id = self.s3.start_multipart_upload()
        parts = self._chunk_file(upload_id)
        upload = self.s3.complete_multipart_upload(upload_id,parts)
        version = upload['VersionId']
        self.metadata.push_dynamo_metadata(
            parts,
            self.s3.bucket,
            self.s3.key,
            version,
            upload_id
        )
        logger.info('Uploaded: {} --> {}'.format(self.local,self.dest))

    def _get_chunk_size(self):
        prior_chunk_size = self.s3.get_object_chunk_size()
        if prior_chunk_size:
            chunk_size = prior_chunk_size
            logger.debug('Prior object found, part size: {}MB'.format(chunk_size/MB))
        else:
            chunk_size = 8 * MB
            logger.debug('Prior object not found, trying part size: {}MB'.format(chunk_size/MB))
        while self.local_size / chunk_size > 10000:
            logger.debug('Part size {}MB too small'.format(str(chunk_size/MB)))
            chunk_size = chunk_size * 2
        logger.debug('Part size determined: {}MB'.format(str(chunk_size/MB)))
        return chunk_size

    def _get_hash_types(self, speed):
        if speed == 'default':
            return ('sha3','blake2')
        elif speed == 'fast':
            return ('xxhash','blank')
        else:
            raise('Unknown Speed Setting')

    def _get_part_count(self):
        unrounded = self.local_size / self.chunk_size
        rounded = int(math.ceil(unrounded))
        logger.debug('Number of parts determined: {}'.format(rounded))
        return rounded

    def _lazy_load_helper(self, file_object):
        while True:
            data = file_object.read(self.chunk_size)
            if not data:
                break
            yield data

    def _queue_get_all(self,queue):
        items = []
        while len(items) < self.part_count:
            items.append(queue.get())
        return items

    def _chunk_file(self,upload_id):
        manager = Manager()
        queue = manager.Queue()
        with Pool(self.concurrency) as pool:
            pool.starmap(
                process_part,
                zip(
                    repeat(self.local),
                    repeat(self.dest),
                    repeat(self.chunk_size),
                    repeat(self.local_size),
                    repeat(self.part_count),
                    range(self.part_count),
                    repeat(upload_id),
                    repeat(self.profile),
                    repeat(self.metadata.table_name),
                    repeat(queue),
                    repeat(self.speed),
                    repeat(self.hash_type1),
                    repeat(self.hash_type2)
                )
            )
            logger.debug('Parts processed, pool not closed')
        logger.debug('Parts processed, waiting for queue items')
        return self._queue_get_all(queue)


text:
name: Brent Fox
title: Chef
description:  Sic tempus fugit esperanto hiccup estrogen. Glorious baklava ex librus hup hey ad infinitum
socialmedia:
  twitter: '#'
  facebook: '#'
  linkedin: '#'
image: http://placehold.it/750x450
---


text:
import {combineReducers} from 'redux';
import kmsReducer from './kms';
import vaultReducer from './vault';
import appReducer from './app';
import {RESET_STORE_AT_KEY} from '../actions/app';

const appReducers = combineReducers({
  kms: kmsReducer,
  app: appReducer,
  vault: vaultReducer
});

export default (state, action) => {
  if (action.type === RESET_STORE_AT_KEY) {
    const key = action.payload.key;
    const initialState = action.payload.initialState;

    return {
      ...state,
      [key]: initialState
    };
  }

  return appReducers(state, action);
};