text:
#ifndef _BF_RT_SERVER_HPP_
#define _BF_RT_SERVER_HPP_

#include <bf_rt/proto/bf_rt_server.h>
#include <bf_rt/bf_rt_common.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#ifdef __cplusplus
extern "C" {
#endif
#include <bf_pal/dev_intf.h>
#ifdef __cplusplus
}
#endif

#ifdef PTF_ENABLED
#include <ptf_server_impl.hpp>
#endif

#include <bfruntime.grpc.pb.h>
#include <google/rpc/status.grpc.pb.h>
#include <google/rpc/code.grpc.pb.h>
#include <grpc++/grpc++.h>
#include <mutex>
#include <condition_variable>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cstdint>
#include <chrono>

#include <bf_rt/bf_rt_init.hpp>
#include <bf_rt/bf_rt_info.hpp>
#include <bf_rt/bf_rt_table.hpp>
#include <bf_rt/bf_rt_session.hpp>
#include <bf_rt/bf_rt_table_attributes.hpp>
#include <bf_rt/bf_rt_table_operations.hpp>

namespace bfrt {
namespace server {

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::Status;
using grpc::StatusCode;

using device_id_t = bf_dev_id_t;

using StreamChannelReaderWriter =
    ServerReaderWriter<bfrt_proto::StreamMessageResponse,
                       bfrt_proto::StreamMessageRequest>;

struct bfRtInfoNotFoundException : public std::exception {
  const char *what() const throw() { return "BfRtInfo Not Found"; }
};
struct fwdConfigError : public std::exception {
  const char *what() const throw() { return "Failed to set fwd config"; }
};
struct lockAcquireAgainError : public std::exception {
  const char *what() const throw() { return "Failed to acquire lock"; }
};

enum class ForwardingConfigState {
  INITIAL,
  WARM_INIT_STARTED,
  WARM_INIT_FINISHED
};

inline Status to_grpc_status(const bf_status_t &bf_status_from,
                             const std::string &msg_str_from) {
  switch (bf_status_from) {
    case BF_SUCCESS:
      return Status();
    case BF_NOT_READY:
    case BF_TABLE_LOCKED:
    case BF_DEVICE_LOCKED:
    case BF_IN_USE:
      return Status(StatusCode::UNAVAILABLE, msg_str_from);
    case BF_NO_SYS_RESOURCES:
    case BF_NO_SPACE:
    case BF_MAX_SESSIONS_EXCEEDED:
    case BF_STS_MAX:
    case BF_IO:
      return Status(StatusCode::RESOURCE_EXHAUSTED, msg_str_from);
    case BF_INVALID_ARG:
      return Status(StatusCode::INVALID_ARGUMENT, msg_str_from);
    case BF_ALREADY_EXISTS:
    case BF_ENTRY_REFERENCES_EXIST:
      return Status(StatusCode::ALREADY_EXISTS, msg_str_from);
    case BF_OBJECT_NOT_FOUND:
    case BF_SESSION_NOT_FOUND:
    case BF_TABLE_NOT_FOUND:
      return Status(StatusCode::NOT_FOUND, msg_str_from);
    case BF_NOT_SUPPORTED:
    case BF_NOT_IMPLEMENTED:
    case BF_TXN_NOT_SUPPORTED:
      return Status(StatusCode::UNIMPLEMENTED, msg_str_from);
    case BF_INTERNAL_ERROR:
      return Status(StatusCode::INTERNAL, msg_str_from);
    case BF_INIT_ERROR:
      return Status(StatusCode::ABORTED, msg_str_from);
    case BF_UNEXPECTED:
    case BF_HW_UPDATE_FAILED:
    case BF_HW_COMM_FAIL:
    case BF_NO_LEARN_CLIENTS:
    case BF_IDLE_UPDATE_IN_PROGRESS:
    case BF_EAGAIN:
      return Status(StatusCode::UNKNOWN, msg_str_from);
  }
  return Status(StatusCode::UNKNOWN, msg_str_from);
}

// Warning: This macro RETURNS grpc_error on non-success
// but just ignores and CONTINUES it is success
#define check_and_return(bf_status, ...)                 \
  do {                                                   \
    if (bf_status == BF_SUCCESS) {                       \
      break;                                             \
    }                                                    \
    std::string prnt_str;                                \
    char buf[1024];                                      \
    std::snprintf(buf, 1024, __VA_ARGS__);               \
    LOG_ERROR("BF_RT_SERVER:%s:%d %s %s",                \
              __func__,                                  \
              __LINE__,                                  \
              buf,                                       \
              bf_err_str(bf_status));                    \
    prnt_str = buf;                                      \
    prnt_str += " ";                                     \
    prnt_str += bf_err_str(bf_status);                   \
    Status status = to_grpc_status(bf_status, prnt_str); \
    if (!status.ok()) {                                  \
      return status;                                     \
    }                                                    \
  } while (0)

// Warning: This macro RETURNS grpc_error on non-success
// but just ignores and CONTINUES it is success. Doesn't change
// the grpc::Status error message
#define grpc_check_and_return(grpc_status, ...)                    \
  do {                                                             \
    std::string prnt_str;                                          \
    if (!grpc_status.ok()) {                                       \
      char buf[1024];                                              \
      std::snprintf(buf, 1024, __VA_ARGS__);                       \
      LOG_ERROR("BF_RT_SERVER:%s:%d %s", __func__, __LINE__, buf); \
      return grpc_status;                                          \
    }                                                              \
  } while (0)

// Forward declare
class ConnectionData;

// This class implements the interface of the Service exposed by the grpc
// server
class BfRuntimeServiceImpl : public bfrt_proto::BfRuntime::Service {
 private:
  Status GetForwardingPipelineConfig(
      ServerContext *context,
      const bfrt_proto::GetForwardingPipelineConfigRequest *request,
      bfrt_proto::GetForwardingPipelineConfigResponse *response) override;

  Status SetForwardingPipelineConfig(
      ServerContext *context,
      const bfrt_proto::SetForwardingPipelineConfigRequest *request,
      bfrt_proto::SetForwardingPipelineConfigResponse *response) override;

  Status Write(ServerContext *context,
               const bfrt_proto::WriteRequest *request,
               bfrt_proto::WriteResponse *response) override;

  Status Read(ServerContext *context,
              const bfrt_proto::ReadRequest *request,
              ServerWriter<bfrt_proto::ReadResponse> *writer) override;

  Status StreamChannel(ServerContext *context,
                       StreamChannelReaderWriter *stream) override;
};

// This is a helper class to manage the stream that a client open when
// connecting to the server. Please note that it is essential for the
// client to open a bi_directional stream so as to get notified about
// idle time, learn and other callbacks. In addition, the stream also serves
// as a hearbeat and is used by the server to detect when a client
// connection drops so that the server can cleanup the client state
class StreamWrapper {
 public:
  static std::unique_ptr<StreamWrapper> make(StreamChannelReaderWriter *stream);
  StreamChannelReaderWriter *stream() const { return stream_; }

 private:
  StreamWrapper(StreamChannelReaderWriter *stream) : stream_(stream) {}
  StreamChannelReaderWriter *stream_{nullptr};
};

/**
 * @brief This class creates and stores an entire device's config in form of
 * set_programs(prog_name, set_pipeline_profiles(profile_name,
 *set_pipe_scope()))
 * An object of this class can be constructed by 2 methods ->
 * 1. By passing in a protobuf of SetForwardingPipelineConfigRequest
 * 2. By passing in a device ID where we read from the current config on
 * the device and create this object.
 *
 * The object only contains metadata of DeviceConfig. The actual file contents
 * are not stored and are flushed to/ read from device directly via helpers
 * present
 */
class DeviceForwardingConfig {
 public:
  class ProgramConfig {
   public:
    class P4Pipeline {
     public:
      P4Pipeline(const std::string &profile_name,
                 const std::string &context_json_path,
                 const std::string &binary_path,
                 const std::set<bf_dev_pipe_t> pipe_scope)
          : profile_name_(profile_name),
            context_json_path_(context_json_path),
            binary_path_(binary_path),
            pipe_scope_(pipe_scope){};
      bool operator<(const P4Pipeline &anotherPipeline) const;
      const std::string profile_name_;
      const std::string context_json_path_;
      const std::string binary_path_;
      const std::set<bf_dev_pipe_t> pipe_scope_;
    };
    ProgramConfig(const std::string &prog_name,
                  const std::string &bfrt_info_path,
                  const std::set<P4Pipeline> &p4_pipelines)
        : prog_name_(prog_name),
          p4_bfrt_path_(bfrt_info_path),
          p4_pipelines_(p4_pipelines) {}
    bool operator<(const ProgramConfig &anotherProgram) const;
    const std::string prog_name_;
    const std::string p4_bfrt_path_;
    const std::set<P4Pipeline> p4_pipelines_;
  };

  DeviceForwardingConfig(
      const bfrt_proto::SetForwardingPipelineConfigRequest &request);
  DeviceForwardingConfig(const bf_dev_id_t &device_id);

  virtual ~DeviceForwardingConfig() = default;
  const bf_dev_id_t &deviceIdGet() const { return device_id_; }
  Status getDeviceProfile(bf_device_profile_t *device_profile);
  Status saveToDisk(
      const bfrt_proto::SetForwardingPipelineConfigRequest &request);
  Status readFromDisk(
      bfrt_proto::GetForwardingPipelineConfigResponse *response);

 private:
  const bf_dev_id_t device_id_;
  std::vector<std::string> fixed_info_path_vec_;
  std::set<ProgramConfig> programs_;
};

/**
 * @brief This class contains details about a bound program with
 * a client connection binds to. A client can be alive without binding
 * but it can only GetForwardingPipeline and SetForwardingPipeline right
 * now. It cannot Read/Write
 */
class BoundProgram {
 public:
  BoundProgram(const bf_rt_id_t &device_id, const std::string &p4_name);
  virtual ~BoundProgram() = default;

  const std::string &p4NameGet() const { return p4_name_; }
  const BfRtInfo *bfRtInfoGet() const { return bfrt_info_; }
  const bf_dev_id_t &deviceIdGet() const { return device_id_; }

 private:
  const bf_dev_id_t device_id_;
  const BfRtInfo *bfrt_info_;
  const std::string p4_name_;
};

/**
 * @brief Contains and manages a device fwd config. This only takes
 * care in case of a SetFwd master. This class helps separate out
 * Device config from what program a client is bound to. An instance
 * of it is present as a public member of ConnectionData so as to keep
 * things simple.
 */
class ConfigManager {
 public:
  ConfigManager() : fwd_config_state_(ForwardingConfigState::INITIAL){};
  Status verify(const DeviceForwardingConfig &device_forwarding_config) const;
  Status warmInitBegin(
      std::unique_ptr<DeviceForwardingConfig> device_forwarding_config,
      const bfrt_proto::SetForwardingPipelineConfigRequest &request);
  Status get(const bf_dev_id_t &device_id,
             bfrt_proto::GetForwardingPipelineConfigResponse *response) const;
  Status warmInitEnd();

 private:
  std::unique_ptr<DeviceForwardingConfig> device_forwarding_config_;
  ForwardingConfigState fwd_config_state_;
};

// Contains whether certain notifications are enabled
class Notifications {
 public:
  Notifications(bool enable_learn,
                bool enable_idletimeout,
                bool enable_port_status_change)
      : enable_learn_(enable_learn),
        enable_idletimeout_(enable_idletimeout),
        enable_port_status_change_(enable_port_status_change){};
  bool enable_learn_ = false;
  bool enable_idletimeout_ = false;
  bool enable_port_status_change_ = false;
};

// This is a helper class that stores all the data pertaining to a particular
// client connection on a device.
class ConnectionData {
 public:
  ConnectionData(const uint32_t &client_id,
                 const Notifications &notifications,
                 std::shared_ptr<BfRtSession> session,
                 ServerContext *context,
                 StreamChannelReaderWriter *stream);

  ConnectionData(const uint32_t &client_id,
                 std::shared_ptr<BfRtSession> session);

  ~ConnectionData() {
    // Complete operations. The session will be destroyed by itself
    // once the shared_ptr goes away
    session_->sessionCompleteOperations();
  }

  uint32_t clientIdGet() const { return client_id_; }
  const std::shared_ptr<BfRtSession> &sessionGet() const { return session_; }

  Status boundProgramGet(const BoundProgram **bound_program) const;
  void boundProgramSet(std::unique_ptr<BoundProgram> bound_program) {
    std::lock_guard<std::mutex> lock(bound_config_mutex_);
    bound_program_ = std::move(bound_program);
  }
  void boundProgramReset() {
    std::lock_guard<std::mutex> lock(bound_config_mutex_);
    bound_program_ = nullptr;
  }

  void sendStreamMessage(bfrt_proto::StreamMessageResponse &response) const;
  void insertTableIdInList(const bf_rt_id_t &table_id);
  bool removeIfPresentTableIdFromList(const bf_rt_id_t &table_id);
  std::condition_variable &getCV() { return operation_cv; }
  std::mutex &getMutex() { return operation_mtx; }
  uint8_t getTimeoutLimit() const { return timeout_limit_for_operation_cb; }
  void cancel() { server_context_->TryCancel(); }

  std::mutex &getStreamChannelRWMutex() const { return stream_channel_rw_mtx; }
  void setStreamChannelRWValidFlag(const bool &val) {
    std::lock_guard<std::mutex> stream_lock(getStreamChannelRWMutex());
    is_stream_channel_rw_valid = val;
  }
  bool getStreamChannelRWValidFlag() const {
    return is_stream_channel_rw_valid;
  }
  const Notifications &getNotifications() const { return notifications_; }
  const bool &isIndependent() const { return is_independent_; }
  void setSubscribeForIndependentClient(const Notifications &notifications,
                                        ServerContext *context,
                                        StreamChannelReaderWriter *stream);

  ConfigManager config_manager;

 private:
  uint32_t client_id_;
  Notifications notifications_;
  std::shared_ptr<BfRtSession> session_;
  ServerContext *server_context_;
  std::unique_ptr<BoundProgram> bound_program_;

  std::unique_ptr<StreamWrapper> connection_{nullptr};
  bool is_independent_ = false;

  // The cb registered with the sync operations will insert table ids (for
  // which the operation has been completed) into this list and the thread
  // which initiated the operation will be waiting for the table id (for
  // which it initiated the operation) to appear in this list
  std::unordered_set<bf_rt_id_t> operation_cb_sync_list;
  std::condition_variable operation_cv;
  std::mutex operation_mtx;
  // This is the max time that a thread will wait for the operation callback
  // to complete before returning to the client
  uint8_t timeout_limit_for_operation_cb{5}; /*seconds*/

  // The following mutex and flag is required to ensure the sanity of the
  // StreamChannelReaderWriter stream (which is managed by grpc and a pointer
  // to which is cached in connection_data object) before we write anything to
  // it OR read anything from it
  mutable std::mutex stream_channel_rw_mtx;
  // mutex to protect bound config
  mutable std::mutex bound_config_mutex_;
  bool is_stream_channel_rw_valid{true};
};

// This class contains all information regarding a GRPC connection
class ServerData {
 public:
  ServerData(std::string server_name, std::string address);

 private:
  std::string server_name_;
  std::string address_;
  int port_;
  BfRuntimeServiceImpl service_;
#ifdef PTF_ENABLED
  ptf::server::ptfServiceImpl ptfservice_;
#endif

  ServerBuilder builder_;
  std::unique_ptr<Server> server_;
};

/**
 * @brief Scope guard class to maintain a lock
 * for SetFwdPipe.Write lock is only taken when SetFwdPipe
 * is done. The read lock is taken by every Read/Write RPC
 * and the callbacks in order to avoid stepping over a SetFwdConfig
 * process
 *
 * Automatically released when goes out of scope.
 * The object creation still goes through even if the lock
 * acquire fails, but a boolean check on the object will return
 * false.
 */
class SetFwdConfigLockGuard {
 public:
  SetFwdConfigLockGuard(pthread_rwlock_t *set_fwd_rw_lock, const bool &is_write)
      : set_fwd_rw_lock_() {
    int success = 1;
    if (set_fwd_rw_lock != NULL) {
      if (is_write) {
        success = pthread_rwlock_wrlock(set_fwd_rw_lock);
      } else {
        success = pthread_rwlock_tryrdlock(set_fwd_rw_lock);
      }
      if (success == 0) {
        acquired_ = true;
        set_fwd_rw_lock_ = set_fwd_rw_lock;
      }
    }
  }
  ~SetFwdConfigLockGuard() {
    if (acquired_) {
      pthread_rwlock_unlock(set_fwd_rw_lock_);
    }
  }
  operator bool() const { return acquired_; }

 private:
  bool acquired_ = false;
  pthread_rwlock_t *set_fwd_rw_lock_;
  SetFwdConfigLockGuard() = delete;
};

class BfRtServer {
 public:
  static BfRtServer &getInstance(
      std::unique_ptr<ServerData> server_data = nullptr);
  BfRtServer(BfRtServer const &) = delete;
  void operator=(BfRtServer const &) = delete;
  // locks mutex
  Status getConnection(const uint32_t &client_id,
                       std::shared_ptr<const ConnectionData> *connection) const;
  // locks mutex
  Status getConnection(const uint32_t &client_id,
                       std::shared_ptr<ConnectionData> *connection) const;
  // locks mutex
  Status addConnection(const uint32_t &client_id,
                       const bfrt_proto::Subscribe &subscribe,
                       ServerContext *context,
                       StreamChannelReaderWriter *stream);
  Status addConnection(const uint32_t &client_id);
  // locks mutex
  Status forwardingConfigSet(
      const uint32_t &client_id,
      const bfrt_proto::SetForwardingPipelineConfigRequest *request);
  // locks mutex
  Status forwardingConfigBind(
      const uint32_t &client_id,
      const bfrt_proto::SetForwardingPipelineConfigRequest *request);
  // locks mutex
  void cleanupConnection(const uint32_t &client_id);
  // locks mutex
  Status clientListGet(std::vector<uint32_t> *client_id_list) const;
  Status sendSetForwardingPipelineConfigResponse(
      bfrt_proto::SetForwardingPipelineConfigResponseType response_status);
  Status refreshConnections(const bf_dev_id_t &device_id);
  pthread_rwlock_t *setFwdRwLockget() { return &set_fwd_rw_lock_; }

 private:
  explicit BfRtServer(std::unique_ptr<ServerData> server_data);
  static BfRtServer *bfrt_server_obj;
  std::unique_ptr<ServerData> server_data_{nullptr};
  // Client id to Connection data map and its mutex
  mutable std::mutex m{};
  std::map<uint32_t, std::shared_ptr<ConnectionData>>
      client_id_to_connection_data_map{};

  // RW lock for SetForwarding
  pthread_rwlock_t set_fwd_rw_lock_ = PTHREAD_RWLOCK_INITIALIZER;
};

// This class contains logic to convert multiple
// grpc::Status to one smushed grpc::Status.
//
// More details at
// https://s3-us-west-2.amazonaws.com/p4runtime/docs/v1.0.0-rc3/P4Runtime-Spec.html#sec-error-reporting-messages
class BfRtServerErrorReporter {
 public:
  BfRtServerErrorReporter(std::string default_msg)
      : default_msg_(default_msg){};

  using StatusMsg = ::google::rpc::Status;
  using Code = ::google::rpc::Code;

  // Stores all error messages in the reporter
  // $1 grpc::status (convert to) bfrt_proto::Error
  // $2 push $1 in a stack only if it was an error, else ignore
  void push_back(const Status &status) {
    if (!status.ok()) {
      bfrt_proto::Error error;
      error.set_canonical_code(status.error_code());
      error.set_message(status.error_message());
      error.set_space("");
      errors.emplace_back(index, error);
    }
    index++;
  }

  // Smushes all bfrt_proto::Error in 'any details' field of
  // ::google::rpc::Code. Then the ::google::rpc::Code message
  // is serialized into the "error_details" field of grpc::Status
  //
  // $1 Iterate over the stack if not empty and add to "details"
  //  in ::google::rpc::Code the current bfrt_proto::Error
  // $2 If for a certain missing index, there was no error present,
  //  then add to "details" a success bfrt_proto::Error msg
  // $3 Convert the ::google::rpc::Code to grpc::Status and return it
  Status get_status() const {
    StatusMsg status_msg;
    if (errors.empty()) {
      status_msg.set_code(Code::OK);
    } else {
      bfrt_proto::Error success;
      success.set_code(Code::OK);
      status_msg.set_code(Code::UNKNOWN);
      status_msg.set_message(default_msg_);
      size_t cur_index = 0;
      for (const auto &p : errors) {
        for (; cur_index++ < p.first;) {
          auto success_any = status_msg.add_details();
          success_any->PackFrom(success);
        }
        auto error_any = status_msg.add_details();
        error_any->PackFrom(p.second);
      }
    }
    Status ret_status;
    SetErrorDetails(status_msg, &ret_status);
    return ret_status;
  }

 private:
  // Copied from
  // https://github.com/grpc/grpc/blob/master/src/cpp/util/error_details.cc
  // Cannot use libgrpc++_error_details due to linkage issues
  static Status SetErrorDetails(const ::google::rpc::Status &from,
                                grpc::Status *to) {
    if (to == nullptr) {
      return Status(StatusCode::FAILED_PRECONDITION, "");
    }
    StatusCode code = StatusCode::UNKNOWN;
    if (from.code() >= StatusCode::OK && from.code() <= StatusCode::DATA_LOSS) {
      code = static_cast<StatusCode>(from.code());
    }
    *to = Status(code, from.message(), from.SerializeAsString());
    return Status::OK;
  }
  std::vector<std::pair<size_t, bfrt_proto::Error>> errors{};
  size_t index{0};
  std::string default_msg_{""};
};

}  // namespace server

}  // namespace bfrt

#endif  //_BF_RT_SERVER_HPP_


text:
package org.cfeclipse.cfml;

import org.cfeclipse.cfml.editors.CFMLEditor;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPart;

public class EditorPartListener implements IPartListener {

	public EditorPartListener() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void partActivated(IWorkbenchPart part) {
		if(part instanceof CFMLEditor){

			CFMLEditor openEditor =(CFMLEditor)part;
			openEditor.setStatusLine();
		}
	}

	public void partBroughtToTop(IWorkbenchPart part) {
		if(part instanceof CFMLEditor){

			CFMLEditor openEditor =(CFMLEditor)part;
			openEditor.setStatusLine();
		}

	}

	public void partClosed(IWorkbenchPart part) {

	}

	public void partDeactivated(IWorkbenchPart part) {

	}

	public void partOpened(IWorkbenchPart part) {
		if(part instanceof CFMLEditor){

			CFMLEditor openEditor =(CFMLEditor)part;
			openEditor.setStatusLine();
		}

	}

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Torrent.Gui
{
    interface IOService
    {
        string OpenFile(string filter);
        string SaveFile();
        string OpenFolder(string title);
        void ShowErrorMessage(string title, string content);
    }
}


text:
namespace boost {
namespace asio {
namespace detail {

class signal_op
  : public operation
{
public:
  // The error code to be passed to the completion handler.
  boost::system::error_code ec_;

  // The signal number to be passed to the completion handler.
  int signal_number_;

protected:
  signal_op(func_type func)
    : operation(func),
      signal_number_(0)
  {
  }
};

} // namespace detail
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_DETAIL_SIGNAL_OP_HPP


text:
<?php

namespace Monetise\Wallet\Balance;

use Monetise\Money\Money\MoneyInterface;
use Monetise\Money\Money\MoneyObject;

/**
 * Class BalanceTrait
 */
trait BalanceTrait
{
    /**
     * @var MoneyInterface
     */
    protected $accountBalance;

    /**
     * @var MoneyInterface
     */
    protected $availableBalance;

    /**
     * @var array
     */
    protected $pendingTransactions = [];

    /**
     * @return MoneyInterface
     */
    public function getAccountBalance()
    {
        if (!$this->accountBalance) {
            $this->accountBalance = new MoneyObject;
        }
        return $this->accountBalance;
    }

    /**
     * @param MoneyInterface $accountBalance
     * @return $this
     */
    public function setAccountBalance(MoneyInterface $accountBalance)
    {
        $this->accountBalance = $accountBalance;
        return $this;
    }

    /**
     * @return MoneyInterface
     */
    public function getAvailableBalance()
    {
        if (!$this->availableBalance) {
            $this->availableBalance = new MoneyObject;
        }
        return $this->availableBalance;
    }

    /**
     * @param MoneyInterface $availableBalance
     * @return $this
     */
    public function setAvailableBalance(MoneyInterface $availableBalance)
    {
        $this->availableBalance = $availableBalance;
        return $this;
    }

    /**
     * @return array
     */
    public function getPendingTransactions()
    {
        return $this->pendingTransactions;
    }

    /**
     * @param array $pendingTransactions
     * @return $this
     */
    public function setPendingTransactions(array $pendingTransactions)
    {
        $this->pendingTransactions = $pendingTransactions;
        return $this;
    }
}


text:
package cdn

import (
	"context"
	"time"

	"github.com/rockbears/log"

	"github.com/ovh/cds/engine/cdn/item"
	"github.com/ovh/cds/engine/cdn/storage"
	"github.com/ovh/cds/engine/gorpmapper"
	"github.com/ovh/cds/sdk"
	"github.com/ovh/cds/sdk/cdn"
)

func (s *Service) sendToBufferWithRetry(ctx context.Context, hms []handledMessage) error {
	if len(hms) == 0 {
		return nil
	}

	// Browse all messages
	for _, hm := range hms {
		var itemType sdk.CDNItemType
		if hm.Signature.Service != nil {
			itemType = sdk.CDNTypeItemServiceLog
		} else {
			itemType = sdk.CDNTypeItemStepLog
		}
		currentLog := buildMessage(hm)
		cpt := 0
		for {
			if err := s.storeLogs(ctx, itemType, hm.Signature, hm.IsTerminated, currentLog); err != nil {
				if sdk.ErrorIs(err, sdk.ErrLocked) && cpt < 10 {
					cpt++
					time.Sleep(250 * time.Millisecond)
					continue
				}
				return err
			}
			break
		}
	}
	return nil
}

func (s *Service) storeLogs(ctx context.Context, itemType sdk.CDNItemType, signature cdn.Signature, terminated bool, content string) error {
	it, err := s.loadOrCreateItem(ctx, itemType, signature)
	if err != nil {
		return err
	}

	var t0 = it.Created.UnixNano() / 1000000 // convert to ms
	var t1 = signature.Timestamp / 1000000

	ctx = context.WithValue(ctx, storage.FieldAPIRef, it.APIRefHash)

	iu, err := s.loadOrCreateItemUnitBuffer(ctx, it.ID, itemType)
	if err != nil {
		return err
	}

	// In case where the item was marked as complete we don't allow append of other logs
	if it.Status == sdk.CDNStatusItemCompleted {
		log.Warn(ctx, "cdn:storeLogs: a log was received for item %s but status in already complete", it.ID)
		return nil
	}

	bufferUnit := s.Units.LogsBuffer()
	countLine, err := bufferUnit.Card(*iu)
	if err != nil {
		return err
	}

	// Add the number of millisecond since creation
	ms := t1 - t0
	if ms < 0 {
		ms = 0
	}

	// Build the score from the "countLine" as the interger part and "ms" as floating part
	if err := bufferUnit.Add(*iu, uint(countLine), uint(ms), content); err != nil {
		return err
	}

	// Send an event in WS broker to refresh streams on current item
	s.GoRoutines.Exec(ctx, "storeLogsPublishWSEvent", func(ctx context.Context) {
		s.publishWSEvent(*iu)
	})

	// If we have all lines or buffer is full and we received the last line
	if terminated {
		tx, err := s.mustDBWithCtx(ctx).Begin()
		if err != nil {
			return sdk.WithStack(err)
		}

		defer tx.Rollback() // nolint
		if err := s.completeItem(ctx, tx, *iu); err != nil {
			return err
		}
		if err := tx.Commit(); err != nil {
			return sdk.WithStack(err)
		}

		s.Units.PushInSyncQueue(ctx, it.ID, it.Created)
	}

	return nil
}

func (s *Service) loadOrCreateItem(ctx context.Context, itemType sdk.CDNItemType, signature cdn.Signature) (*sdk.CDNItem, error) {
	// Build cds api ref
	apiRef, err := sdk.NewCDNApiRef(itemType, signature)
	if err != nil {
		return nil, err
	}
	hashRef, err := apiRef.ToHash()
	if err != nil {
		return nil, err
	}

	it, err := item.LoadByAPIRefHashAndType(ctx, s.Mapper, s.mustDBWithCtx(ctx), hashRef, itemType)
	if err != nil {
		if !sdk.ErrorIs(err, sdk.ErrNotFound) {
			return nil, err
		}
		// Insert data
		it = &sdk.CDNItem{
			APIRef:     apiRef,
			Type:       itemType,
			APIRefHash: hashRef,
			Status:     sdk.CDNStatusItemIncoming,
			Created:    time.Unix(0, signature.Timestamp),
		}

		tx, err := s.mustDBWithCtx(ctx).Begin()
		if err != nil {
			return nil, sdk.WithStack(err)
		}
		defer tx.Rollback() // nolint

		ctx = context.WithValue(ctx, storage.FieldAPIRef, it.APIRefHash)

		if errInsert := item.Insert(ctx, s.Mapper, tx, it); errInsert == nil {
			if err := tx.Commit(); err != nil {
				return nil, sdk.WithStack(err)
			}
			log.Info(ctx, "storeLogs> new item %s has been stored", it.ID)

			return it, nil
		} else if !sdk.ErrorIs(errInsert, sdk.ErrConflictData) {
			return nil, errInsert
		}

		// reload if item already exist
		it, err = item.LoadByAPIRefHashAndType(ctx, s.Mapper, s.mustDBWithCtx(ctx), hashRef, itemType)
		if err != nil {
			return nil, err
		}
	}

	return it, nil
}

func (s *Service) loadOrCreateItemUnitBuffer(ctx context.Context, itemID string, itemType sdk.CDNItemType) (*sdk.CDNItemUnit, error) {
	bufferUnit := s.Units.GetBuffer(itemType)
	unit, err := storage.LoadUnitByName(ctx, s.Mapper, s.mustDBWithCtx(ctx), bufferUnit.Name())
	if err != nil {
		return nil, err
	}

	it, err := item.LoadByID(ctx, s.Mapper, s.mustDBWithCtx(ctx), itemID, gorpmapper.GetOptions.WithDecryption)
	if err != nil {
		return nil, err
	}

	itemUnit, err := storage.LoadItemUnitByUnit(ctx, s.Mapper, s.mustDBWithCtx(ctx), unit.ID, itemID, gorpmapper.GetOptions.WithDecryption)
	if err != nil {
		if !sdk.ErrorIs(err, sdk.ErrNotFound) {
			return nil, err
		}

		itemUnit, err = s.Units.NewItemUnit(ctx, bufferUnit, it)
		if err != nil {
			return nil, err
		}

		tx, err := s.mustDBWithCtx(ctx).Begin()
		if err != nil {
			return nil, sdk.WithStack(err)
		}
		defer tx.Rollback() // nolint

		if errInsert := storage.InsertItemUnit(ctx, s.Mapper, tx, itemUnit); errInsert == nil {
			if err := tx.Commit(); err != nil {
				return nil, sdk.WithStack(err)
			}
			return itemUnit, nil
		} else if !sdk.ErrorIs(errInsert, sdk.ErrConflictData) {
			return nil, errInsert
		}

		itemUnit, err = storage.LoadItemUnitByUnit(ctx, s.Mapper, s.mustDBWithCtx(ctx), unit.ID, itemID, gorpmapper.GetOptions.WithDecryption)
		if err != nil {
			return nil, sdk.WrapError(err, "unable to load item unit %s/%s", unit.ID, itemID)
		}
	}

	return itemUnit, nil
}


text:
/**
 * Language module contains everything related to language-specific operations:
 * * Translating prompts
 * * Translating functions
 * * Date format localizations
 */
import { __extends, __read, __spread } from "tslib";
/**
 * ============================================================================
 * IMPORTS
 * ============================================================================
 * @hidden
 */
import { BaseObjectEvents } from "../Base";
import { Adapter } from "./Adapter";
import * as $array from "./Array";
import * as $type from "./Type";
import en from "../../../lang/en";
import { options } from "../Options";
;
;
/**
 * Handles all language-related tasks, like loading and storing translations,
 * translating prompts, lists of prompts and even functions.
 *
 * Almost every object in amCharts4 universe will have a `language` property,
 * which can be accessed for prompt translation.
 *
 * @see {@link ILanguageAdapters} for a list of available Adapters
 * @todo Make prompt keys case-insensitive
 * @important
 */
var Language = /** @class */ (function (_super) {
    __extends(Language, _super);
    /**
     * Constructor
     */
    function Language() {
        var _this = _super.call(this) || this;
        /**
         * Adapter.
         */
        _this.adapter = new Adapter(_this);
        /**
         * Current locale.
         */
        _this._locale = en;
        /**
         * Default locale. A locale to fall back to if none is specified, or
         * if there's no translation for the prompt for the current language.
         */
        _this._defaultLocale = en;
        _this.className = "Language";
        // Set default language if necessary
        if ($type.hasValue(options.defaultLocale)) {
            _this.locale = options.defaultLocale;
        }
        _this.applyTheme();
        return _this;
    }
    /**
     * Returns locale that is currently used.
     *
     * @param locale  Force locale. Will use current language if not set.
     * @return Locale
     */
    Language.prototype.getLocale = function (locale) {
        if (locale == null) {
            locale = this._locale;
        }
        return this.adapter.apply("locale", {
            locale: locale
        }).locale;
    };
    /**
     * Returns the translation of the string.
     *
     * If the translation is empty, it will return untranslated prompt.
     *
     * Third parameter and up are strings that can be used to replace "%X"
     * placeholders in prompt.
     *
     * E.g.:
     *
     * ```TypeScript
     * // Results in "This is a first translation test"
     * chart.language.translate("This is a %1 translation %2", null, "first", "test");
     * ```
     * ```JavaScriptScript
     * // Results in "This is a first translation test"
     * chart.language.translate("This is a %1 translation %2", null, "first", "test");
     * ```
     *
     * @param  prompt   A string to translate
     * @param  locale   Force translation into specific locale, e.g. fr_FR
     * @param  rest     Parameters to replace in string
     * @return          Translation
     */
    Language.prototype.translate = function (prompt, locale) {
        var rest = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            rest[_i - 2] = arguments[_i];
        }
        // Get langauge
        locale = this.getLocale(locale);
        // Init translation
        var translation = prompt;
        // Get translations for the locale
        var translations = this.getTranslations(locale);
        var value = translations[prompt];
        // Try to look for the translation
        if (value === null) {
            value = "";
        }
        else if ($type.hasValue(value)) {
            // It might be an empty string
            if (value) {
                translation = value;
            }
        }
        else if (locale !== this._defaultLocale) {
            // Try to look in default language
            return this.translate.apply(this, __spread([prompt, this._defaultLocale], rest));
        }
        // Replace %1, %2, etc params
        if (rest.length) {
            for (var len = rest.length, i = 0; i < len; ++i) {
                translation = translation.split("%" + (i + 1)).join(rest[i]);
            }
        }
        // Return the translation
        return this.adapter.apply("translate", {
            translation: translation,
            locale: locale
        }).translation;
    };
    /**
     * Non-type-checked translation.
     *
     * Can be used by plugins and other code that may have their own non-standard
     * translation prompts.
     *
     * @since 4.5.5
     * @param  prompt   A string to translate
     * @param  locale   Force translation into specific locale, e.g. fr_FR
     * @param  rest     Parameters to replace in string
     * @return          Translation
     */
    Language.prototype.translateAny = function (prompt, locale) {
        var rest = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            rest[_i - 2] = arguments[_i];
        }
        return this.translate(prompt, locale);
    };
    /**
     * Translates prompt.
     *
     * If translation is empty, it will return empty string, which is a different
     * behavior than that of regular `translate`.
     *
     * @param prompt   A string to translate
     * @param locale   Force translation into specific locale, e.g. fr_FR
     * @param ...rest  Parameters to replace in string
     * @return Translation
     */
    Language.prototype.translateEmpty = function (prompt, locale) {
        var rest = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            rest[_i - 2] = arguments[_i];
        }
        var translation = this.translate.apply(this, __spread([prompt, locale], rest));
        return translation == prompt ? "" : translation;
    };
    /**
     * Translates a function.
     *
     * This method will return a function reference, but will not run it. It's
     * up to the caller script to run the function.
     *
     * @param prompt  A function id to translate
     * @param locale  Force translation into specific locale. e.g. fr_FR
     * @return A language-specific version of the function
     * @todo Apply adapter
     */
    Language.prototype.translateFunc = function (prompt, locale) {
        // Get langauge
        locale = this.getLocale(locale);
        // Get translations for the locale
        var translations = this.getTranslations(locale);
        var value = translations[prompt];
        // Try to look for the translation
        if (value != null) {
            return value;
        }
        // Try to look in default language
        if (locale !== this._defaultLocale) {
            return this.translateFunc(prompt, this._defaultLocale);
        }
        // Fail - return empty function
        return function () {
            return "";
        };
    };
    /**
     * Translates a list of prompts in one go.
     *
     * @param list    An array of strings to translate
     * @param locale  Force translation into specific locale. e.g. fr_FR
     * @return An array of translated strings in the same order as source list
     */
    Language.prototype.translateAll = function (list, locale) {
        var _this = this;
        // Translate all items in the list
        if (!this.isDefault()) {
            return $array.map(list, function (x) { return _this.translate(x, locale); });
        }
        else {
            return list;
        }
    };
    /**
     * Returns `true` if the currently selected locale is a default locale.
     *
     * @return `true` if locale is default; `false` if it is not.
     */
    Language.prototype.isDefault = function () {
        return this._defaultLocale === this._locale;
    };
    Object.defineProperty(Language.prototype, "locale", {
        /**
         * @return Locale definition
         */
        get: function () {
            return this._locale;
        },
        /**
         * Current locale.
         *
         * @param value  Locale definition (translations)
         */
        set: function (value) {
            if (this._locale != value) {
                this._locale = value;
                if (this.events.isEnabled("localechanged")) {
                    var event_1 = {
                        type: "localechanged",
                        locale: value,
                        target: this
                    };
                    this.events.dispatchImmediately("localechanged", event_1);
                }
            }
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Returns translations for a given locale.
     *
     * @ignore
     * @deprecated
     * @param locale  Locale
     * @return Translations
     */
    Language.prototype.getTranslations = function (locale) {
        return this.adapter.apply("translations", {
            translations: locale,
            locale: locale
        }).translations;
    };
    return Language;
}(BaseObjectEvents));
export { Language };
//# sourceMappingURL=Language.js.map


text:
<?php

namespace ErpNET\App\Models\Doctrine\Repositories;

use Doctrine\ORM\Query;
use ErpNET\App\Models\RepositoryLayer\SharedOrderTypeRepositoryInterface;

/**
 * Class SharedOrderTypeRepositoryDoctrine
 * @package namespace ErpNET\App\Models\Doctrine\Repositories;
 */
class SharedOrderTypeRepositoryDoctrine extends BaseEntityRepository implements SharedOrderTypeRepositoryInterface
{
    /**
     * @var array
     */
    protected $fillable = [
        'tipo',
        'descricao',
    ];
}


text:
hs-pi-upload
============

A simple HTTP server implemented in Haskell, which offers a convenient
upload form for large and/or many files. The server can be compiled
and run on a Raspberry Pi.

The upload form is useful e.g. to collect photos and videos from
friends and family after a trip or wedding. Further details are given
in a
[blog post](https://doering.io/posts/2015-10-23-happstack-upload-on-raspberry-pi.html).

The server and frontend are based on:

* [Happstack Lite](http://www.happstack.com/page/view-page-slug/9/happstack-lite)
* [Resumable.js](http://www.resumablejs.com/)


text:
<?php

use Phinx\Migration\AbstractMigration;

class Newsletter extends AbstractMigration
{

    public function change()
    {
        $this->table('newsletter', ['id' => false])
            ->addColumn('email', 'text')
            ->addColumn('created_at', 'timestamp', ['default' => 'CURRENT_TIMESTAMP'])
            ->create();
    }
}


text:
zirkon.validator.check_default module
=====================================

.. include:: ../macros.txt

.. testsetup::

    from zirkon.validator.check_default import *

.. automodule:: zirkon.validator.check_default
    :members:
    :undoc-members:
    :show-inheritance:


text:
namespace Nest
{
	public class StatsMetric : IMetricAggregation
	{
		public long Count { get; set; }
		public double? Min { get; set; }
		public double? Max { get; set; }
		public double? Average { get; set; }
		public double? Sum { get; set; }
	}
}


text:
<?php
declare(strict_types=1);

namespace Search\Model\Filter;

use Cake\ORM\Table;

class Exists extends Base
{
    /**
     * Default configuration.
     *
     * @var array
     */
    protected $_defaultConfig = [
        'mode' => 'OR',
        'nullValue' => null, // Set to empty string for required fields
    ];

    /**
     * Check if a value is truthy/falsy and pass as condition aware of NULLable.
     *
     * @return bool
     */
    public function process(): bool
    {
        $value = $this->value();
        if (!is_scalar($value) || $value === '') {
            return false;
        }

        $bool = (bool)$value;

        $nullValue = $this->getConfig('nullValue');
        $comparison = ' !=';
        if (!$bool) {
            $comparison = '';
        }
        if ($nullValue === null) {
            $comparison = ' IS NOT';
            if (!$bool) {
                $comparison = ' IS';
            }
        }

        if (!$this->manager()->getRepository() instanceof Table) {
            foreach ($this->fields() as $field) {
                $this->getQuery()->where([
                    $field . $comparison => $nullValue,
                ]);
            }

            return true;
        }

        $conditions = [];
        foreach ($this->fields() as $field) {
            $conditions[] = [$field . $comparison => $nullValue];
        }

        $this->getQuery()->andWhere([$this->getConfig('mode') => $conditions]);

        return true;
    }
}


text:
require 'spec_helper'

require 'rackstash/filter/rename'

RSpec.describe Rackstash::Filter::Rename do
  let(:event) {
    {
      'foo' => 'foo value',
      'bar' => 'bar value'
    }
  }

  def filter!(spec)
    described_class.new(spec).call(event)
  end

  it 'renames existing fields' do
    filter!('foo' => 'awesome')
    expect(event).to eql 'awesome' => 'foo value', 'bar' => 'bar value'
  end

  it 'it ignores missing fields' do
    filter!('unknown' => 'ohnoes')
    expect(event).to eql 'foo' => 'foo value', 'bar' => 'bar value'
  end

  it 'stringifies spec values' do
    filter!(foo: :bam)
    expect(event).to eql 'bam' => 'foo value', 'bar' => 'bar value'
  end

  it 'overwrites conflicting keys' do
    filter!('foo' => 'bar')
    expect(event).to eql 'bar' => 'foo value'
  end

  it 'returns the given event object' do
    expect(filter!('bar' => 'baz')).to equal event
  end
end


text:
![Couchbase Bytes Read][1]

## Overview

Identify busy buckets, track cache miss ratios, and more. This Agent check collects metrics like:

- Hard disk and memory used by data
- Current connections
- Total objects
- Operations per second
- Disk write queue size

And many more.

## Setup

### Installation

The Couchbase check is included in the [Datadog Agent][2] package, so you don't need to install anything else on your Couchbase nodes.

### Configuration

<!-- xxx tabs xxx -->
<!-- xxx tab "Host" xxx -->

#### Host

To configure this check for an Agent running on a host:

##### Metric collection

1. Edit the `couchbase.d/conf.yaml` file in the `conf.d/` folder at the root of your [Agent's configuration directory][3] to start collecting your Couchbase data. See the [sample couchbase.d/conf.yaml][4] for all available configuration options.

   ```yaml
   init_config:

   instances:
     ## @param server - string - required
     ## The server's url.
     #
     - server: http://localhost:8091
   ```

2. [Restart the Agent][5].

#### Log collection

_Available for Agent versions >6.0_

1. Collecting logs is disabled by default in the Datadog Agent, you need to enable it in `datadog.yaml`:

   ```yaml
   logs_enabled: true
   ```

2. Add this configuration block to your `couchbase.d/conf.yaml` file to start collecting your Couchbase Logs:

   ```yaml
   logs:
     - type: file
       path: /opt/couchbase/var/lib/couchbase/logs/couchdb.log
       source: couchdb
   ```

    Change the `path` and `service` parameter values and configure them for your environment. See the [sample couchbase.d/conf.yaml][4] for all available configuration options.

3. [Restart the Agent][5].

<!-- xxz tab xxx -->
<!-- xxx tab "Containerized" xxx -->

#### Containerized

For containerized environments, see the [Autodiscovery Integration Templates][6] for guidance on applying the parameters below.

##### Metric collection

| Parameter            | Value                                |
| -------------------- | ------------------------------------ |
| `<INTEGRATION_NAME>` | `couchbase`                          |
| `<INIT_CONFIG>`      | blank or `{}`                        |
| `<INSTANCE_CONFIG>`  | `{"server": "http://%%host%%:8091"}` |

<!-- xxz tab xxx -->
<!-- xxz tabs xxx -->

### Validation

[Run the Agent's `status` subcommand][7] and look for `couchbase` under the Checks section.

## Data Collected

### Metrics

See [metadata.csv][8] for a list of metrics provided by this integration.

### Events

The Couchbase check emits an event to Datadog each time the cluster is rebalanced.

### Service Checks

See [service_checks.json][9] for a list of service checks provided by this integration.

## Troubleshooting

Need help? Contact [Datadog support][10].

## Further Reading

- [Monitor key Couchbase metrics][11].

[1]: https://raw.githubusercontent.com/DataDog/integrations-core/master/couchbase/images/couchbase_graph.png
[2]: https://app.datadoghq.com/account/settings#agent
[3]: https://docs.datadoghq.com/agent/guide/agent-configuration-files/#agent-configuration-directory
[4]: https://github.com/DataDog/integrations-core/blob/master/couchbase/datadog_checks/couchbase/data/conf.yaml.example
[5]: https://docs.datadoghq.com/agent/guide/agent-commands/#start-stop-and-restart-the-agent
[6]: https://docs.datadoghq.com/agent/kubernetes/integrations/
[7]: https://docs.datadoghq.com/agent/guide/agent-commands/#agent-status-and-information
[8]: https://github.com/DataDog/integrations-core/blob/master/couchbase/metadata.csv
[9]: https://github.com/DataDog/integrations-core/blob/master/couchbase/assets/service_checks.json
[10]: https://docs.datadoghq.com/help/
[11]: https://www.datadoghq.com/blog/monitoring-couchbase-performance-datadog


text:
import { Observable } from '../../internal/Observable';
import { timeoutWith } from '../../internal/patching/operator/timeoutWith';

Observable.prototype.timeoutWith = timeoutWith;

declare module '../../internal/Observable' {
  interface Observable<T> {
    timeoutWith: typeof timeoutWith;
  }
}


text: console.log("running network console logging tests");


text:
package com.vaadin.tests.components.formlayout;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.vaadin.testbench.elements.ButtonElement;
import com.vaadin.tests.tb3.SingleBrowserTest;

public class HtmlCaptionInFormLayoutTest extends SingleBrowserTest {
    @Test
    public void testHtmlCaptions() {
        openTestURL();

        List<WebElement> captions = getDriver().findElements(
                By.cssSelector(".v-formlayout-captioncell span"));

        Assert.assertEquals("Should be two formlayout captions", 2,
                captions.size());

        Assert.assertEquals("Contains HTML", captions.get(0).getText());
        Assert.assertEquals("Contains HTML", captions.get(1).getText());
    }

    @Test
    public void testHtmlCaptionToggle() {
        openTestURL();

        $(ButtonElement.class).caption("Toggle").first().click();

        List<WebElement> captions = getDriver().findElements(
                By.cssSelector(".v-formlayout-captioncell span"));

        Assert.assertEquals("Should be two formlayout captions", 2,
                captions.size());

        Assert.assertEquals("Contains HTML", captions.get(0).getText());
        Assert.assertEquals("Contains HTML", captions.get(1).getText());
    }

}


text:
'------------------------------------------------------------------------------
' <auto-generated>
'     This code was generated by a tool.
'     Runtime Version:4.0.30319.18444
'
'     Changes to this file may cause incorrect behavior and will be lost if
'     the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------

Option Strict On
Option Explicit On

Imports System

Namespace My.Resources

    'This class was auto-generated by the StronglyTypedResourceBuilder
    'class via a tool like ResGen or Visual Studio.
    'To add or remove a member, edit your .ResX file then rerun ResGen
    'with the /str option, or rebuild your VS project.
    '''
    '''  A strongly-typed resource class, for looking up localized strings, etc.
    '''
    <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"),  _
     Global.System.Diagnostics.DebuggerNonUserCodeAttribute(),  _
     Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(),  _
     Global.Microsoft.VisualBasic.HideModuleNameAttribute()>  _
    Friend Module Resources

        Private resourceMan As Global.System.Resources.ResourceManager

        Private resourceCulture As Global.System.Globalization.CultureInfo

        '''
        '''  Returns the cached ResourceManager instance used by this class.
        '''
        <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)>  _
        Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
            Get
                If Object.ReferenceEquals(resourceMan, Nothing) Then
                    Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("BasicBrowser.Resources", GetType(Resources).Assembly)
                    resourceMan = temp
                End If
                Return resourceMan
            End Get
        End Property

        '''
        '''  Overrides the current thread's CurrentUICulture property for all
        '''  resource lookups using this strongly typed resource class.
        '''
        <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)>  _
        Friend Property Culture() As Global.System.Globalization.CultureInfo
            Get
                Return resourceCulture
            End Get
            Set
                resourceCulture = value
            End Set
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _1371833355_go_home() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("1371833355_go-home", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _1387139872_window_new() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("1387139872_window-new", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _1387140136_process_stop() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("1387140136_process-stop", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _1387146817_tab_new() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("1387146817_tab-new", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _1391271803_view_refresh() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("1391271803_view-refresh", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _1391271889_emblem_unreadable() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("1391271889_emblem-unreadable", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _1391274345_go_next() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("1391274345_go-next", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _1391274420_go_previous() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("1391274420_go-previous", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _16x16_bookmark_add() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("16x16_bookmark_add", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _16x16_bookmark_remove() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("16x16_bookmark_remove", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property _16x16_quit() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("16x16_quit", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property Exit2() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("Exit2", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property go_right_d() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("go_right_d", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property Help() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("Help", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property Info() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("Info", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
        '''
        Friend ReadOnly Property SourceCodeIcon() As System.Drawing.Icon
            Get
                Dim obj As Object = ResourceManager.GetObject("SourceCodeIcon", resourceCulture)
                Return CType(obj,System.Drawing.Icon)
            End Get
        End Property

        '''
        '''  Looks up a localized resource of type System.Drawing.Bitmap.
        '''
        Friend ReadOnly Property SourceCodeIconBitmap() As System.Drawing.Bitmap
            Get
                Dim obj As Object = ResourceManager.GetObject("SourceCodeIconBitmap", resourceCulture)
                Return CType(obj,System.Drawing.Bitmap)
            End Get
        End Property
    End Module
End Namespace


text:
module Wombat
  module Services
    class Duplicity < Wombat::Services::Base
      module Protocols
        class Webdav < Wombat::Services::Duplicity::Protocols::Base
          class << self
            attr_accessor :ssl
          end

          def self.display_name
            'WebDAV'
          end

          def self.proto
            ssl ? 'webdavs' : 'webdav'
          end

          def configure_protocol
            @config[:host_path] = ui.ask(
              'WebDAV host and path, where backups will be stored (for example, for box.com it is dav.box.com/dav)',
              required: true
            )

            @config[:username] = ui.ask('WebDAV username', required: true)
            @config[:password] = ui.ask('WebDAV password', password: true)
            self.class.ssl = ui.ask('Use SSL', boolean: true)
          end

          def path
            "#{self.class.proto}://#{@config[:username]}:#{@config[:password]}@#{@config[:host_path]}/"
              .sub(%r{/+$}, '/')
          end
        end
      end
    end
  end
end


text:
import './Links';
import './Navigation';
import './Authentication';


text:
{% extends "layout.html" %}

{% block page_title %}
  Sprint {{sprint}} - Funding
{% endblock %}

{% block inside_header %}

{% endblock %}

{% block after_header %}
{% include "sprint/"+sprint+"/includes/header.html" %}
{% endblock %}

{% block content %}

  {% include "includes/link-back.html" %}

                Good Content Ltd
               About your agreement

This agreement creates a legal contract between Good Content Ltd and the Skills Funding Agency (SFA). It allows SFA to pay your training providers for apprenticeships.

You need to make sure you have authority from your organisation before you accept this agreement. Contact Sarah.Thompson@Content.com if you're not sure whether you have authority to accept this agreement.

Only levy payers can continue

By continuing you confirm that your organisation, or its connected organisations, submits or will submit apprenticeship levy payments to HMRC.

        Continue to your agreement

      {% include "includes/link-back.html" %}

{% endblock %}


text:
package net.xenqtt.proxy;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.xenqtt.SimpleBroker;
import net.xenqtt.message.ConnAckMessage;
import net.xenqtt.message.ConnectMessage;
import net.xenqtt.message.DisconnectMessage;
import net.xenqtt.message.MessageHandler;
import net.xenqtt.message.MqttChannel;
import net.xenqtt.message.MqttMessage;
import net.xenqtt.message.PubAckMessage;
import net.xenqtt.message.PubCompMessage;
import net.xenqtt.message.PubMessage;
import net.xenqtt.message.PubRecMessage;
import net.xenqtt.message.PubRelMessage;
import net.xenqtt.message.SubAckMessage;
import net.xenqtt.message.SubscribeMessage;
import net.xenqtt.message.UnsubAckMessage;
import net.xenqtt.message.UnsubscribeMessage;

/**
 * {@link SimpleBroker} extension that handles creating/managing {@link ProxySession sessions}.
 */
public class ProxyBroker extends SimpleBroker implements MessageHandler {

	private final String brokerUri;

	private final Map<String, ProxySession> proxySessionByClientId = new HashMap<String, ProxySession>();

	private final int maxInFlightBrokerMessages;

	/**
	 * @param brokerUri
	 *            The URI of the broker the proxy should connect to
	 * @param port
	 *            The port for the server to listen on. 0 will choose an arbitrary available port which you can get from {@link #getPort()} after calling
	 *            {@link #init()}.
	 * @param maxInFlightBrokerMessages
	 *            Maximum number of messages that may be in-flight to the broker at a time
	 */
	public ProxyBroker(String brokerUri, int port, int maxInFlightBrokerMessages) {
		super(0, port);
		this.brokerUri = brokerUri;
		this.maxInFlightBrokerMessages = maxInFlightBrokerMessages;
	}

	/**
	 * Initializes the broker
	 */
	public void init() {

		super.init(this, "ProxyServer");
	}

	/**
	 * @see net.xenqtt.SimpleBroker#shutdown(long)
	 */
	@Override
	public boolean shutdown(long millis) {

		for (ProxySession session : proxySessionByClientId.values()) {
			session.shutdown();
		}

		return super.shutdown(millis);
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#connect(net.xenqtt.message.MqttChannel, net.xenqtt.message.ConnectMessage)
	 */
	@Override
	public void connect(MqttChannel channel, ConnectMessage message) throws Exception {

		String clientId = message.getClientId();
		ProxySession session = proxySessionByClientId.get(clientId);
		if (session == null) {
			session = newProxySession(brokerUri, message, maxInFlightBrokerMessages);
			session.init();
			proxySessionByClientId.put(clientId, session);
		}

		manager.detachChannel(channel);

		if (!session.newConnection(channel, message)) {
			proxySessionByClientId.remove(clientId);
			session.shutdown();
			connect(channel, message);
			return;
		}

		shutdownClosedSessions();
	}

	/**
	 * Unit tests override to inject mock {@link ProxySession sessions}
	 *
	 * @return A new {@link ProxySession} instance
	 */
	ProxySession newProxySession(String brokerUri, ConnectMessage message, int maxInFlightBrokerMessages) {
		return new ProxySession(brokerUri, message, maxInFlightBrokerMessages);
	}

	private void shutdownClosedSessions() {

		Iterator<ProxySession> iter = proxySessionByClientId.values().iterator();
		while (iter.hasNext()) {
			ProxySession session = iter.next();
			if (session.isClosed()) {
				session.shutdown();
				iter.remove();
			}
		}
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#connAck(net.xenqtt.message.MqttChannel, net.xenqtt.message.ConnAckMessage)
	 */
	@Override
	public void connAck(MqttChannel channel, ConnAckMessage message) throws Exception {
		// Should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#publish(net.xenqtt.message.MqttChannel, net.xenqtt.message.PubMessage)
	 */
	@Override
	public void publish(MqttChannel channel, PubMessage message) throws Exception {
		// Should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#pubAck(net.xenqtt.message.MqttChannel, net.xenqtt.message.PubAckMessage)
	 */
	@Override
	public void pubAck(MqttChannel channel, PubAckMessage message) throws Exception {
		// Should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#pubRec(net.xenqtt.message.MqttChannel, net.xenqtt.message.PubRecMessage)
	 */
	@Override
	public void pubRec(MqttChannel channel, PubRecMessage message) throws Exception {
		// Should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#pubRel(net.xenqtt.message.MqttChannel, net.xenqtt.message.PubRelMessage)
	 */
	@Override
	public void pubRel(MqttChannel channel, PubRelMessage message) throws Exception {
		// Should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#pubComp(net.xenqtt.message.MqttChannel, net.xenqtt.message.PubCompMessage)
	 */
	@Override
	public void pubComp(MqttChannel channel, PubCompMessage message) throws Exception {
		// Should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#subscribe(net.xenqtt.message.MqttChannel, net.xenqtt.message.SubscribeMessage)
	 */
	@Override
	public void subscribe(MqttChannel channel, SubscribeMessage message) throws Exception {
		// Should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#subAck(net.xenqtt.message.MqttChannel, net.xenqtt.message.SubAckMessage)
	 */
	@Override
	public void subAck(MqttChannel channel, SubAckMessage message) throws Exception {
		// Should never happen
	}

	@Override
	public void unsubscribe(MqttChannel channel, UnsubscribeMessage message) throws Exception {
		// Should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#unsubAck(net.xenqtt.message.MqttChannel, net.xenqtt.message.UnsubAckMessage)
	 */
	@Override
	public void unsubAck(MqttChannel channel, UnsubAckMessage message) throws Exception {
		// Should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#disconnect(net.xenqtt.message.MqttChannel, net.xenqtt.message.DisconnectMessage)
	 */
	@Override
	public void disconnect(MqttChannel channel, DisconnectMessage message) throws Exception {
		// Should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#channelOpened(net.xenqtt.message.MqttChannel)
	 */
	@Override
	public void channelOpened(MqttChannel channel) {
		// ignore
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#channelClosed(net.xenqtt.message.MqttChannel, java.lang.Throwable)
	 */
	@Override
	public void channelClosed(MqttChannel channel, Throwable cause) {
		// ignore
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#channelAttached(net.xenqtt.message.MqttChannel)
	 */
	@Override
	public void channelAttached(MqttChannel channel) {
		// this should never happen
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#channelDetached(net.xenqtt.message.MqttChannel)
	 */
	@Override
	public void channelDetached(MqttChannel channel) {
		// ignore
	}

	/**
	 * @see net.xenqtt.message.MessageHandler#messageSent(net.xenqtt.message.MqttChannel, net.xenqtt.message.MqttMessage)
	 */
	@Override
	public void messageSent(MqttChannel channel, MqttMessage message) {
		// ignore
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>TibiaAPI: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css">
<link href="doxygen.css" rel="stylesheet" type="text/css">

Main Page

Packages

Classes

Files

Class List

Class Hierarchy

Class Members

Tibia.Objects.Vip Member List
This is the complete list of members for Tibia.Objects.Vip, including all inherited members.

Icon	Tibia.Objects.Vip

Id	Tibia.Objects.Vip

Name	Tibia.Objects.Vip

Status	Tibia.Objects.Vip

<address style="text-align: right;">Generated on Tue Jul 7 18:50:10 2009 for TibiaAPI by

 1.5.9 </address>


text:
/**
* @author Vera Y. Petrashkova
* @version $Revision$
*/

package org.apache.harmony.crypto.tests.javax.crypto.serialization;

import javax.crypto.NoSuchPaddingException;

import org.apache.harmony.testframework.serialization.SerializationTest;

/**
 * Test for NuSuchPaddingException serialization
 *
 */

public class NoSuchPaddingExceptionTest extends SerializationTest {

    public static String[] msgs = {
            "New message",
            "Long message for Exception. Long message for Exception. Long message for Exception." };

    protected Object[] getData() {
        return new Object[] { new NoSuchPaddingException(),
                new NoSuchPaddingException(null), new NoSuchPaddingException(msgs[1]) };
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

public class QuadTree<T> where T : IBoundable
{
    public const int DefaultMaxDepth = 5;

    public readonly int MaxDepth;

    private Node<T> root;

    public QuadTree(int width, int height, int maxDepth = DefaultMaxDepth)
    {
        this.root = new Node<T>(0, 0, width, height);
        this.Bounds = this.root.Bounds;
        this.MaxDepth = maxDepth;
    }

    public int Count { get; private set; }

    public Rectangle Bounds { get; private set; }

    public void ForEachDfs(Action<List<T>, int, int> action)
    {
        this.ForEachDfs(this.root, action);
    }

    public bool Insert(T item)
    {
        if (!item.Bounds.IsInside(this.Bounds))
        {
            return false;
        }

        int depth = 1;

        var currentNode = this.root;
        while (currentNode.Children != null)
        {
            var quadrant = GetQuadrant(currentNode, item.Bounds);
            if (quadrant == -1)
            {
                break;
            }
            currentNode = currentNode.Children[quadrant];
            depth++;
        }

        currentNode.Items.Add(item);
        this.Split(currentNode, depth);
        this.Count++;

        return true;
    }

    private void Split(Node<T> node, int nodeDepth)
    {
        if (!(node.ShouldSplit && nodeDepth < MaxDepth))
        {
            return;
        }

        var leftWidth = node.Bounds.Width / 2;
        var rightWidth = node.Bounds.Width - leftWidth;
        var topHeight = node.Bounds.Height / 2;
        var bottomHeight = node.Bounds.Height - topHeight;

        node.Children = new Node<T>[4];

        node.Children[0] = new Node<T>(node.Bounds.MidX, node.Bounds.Y1, rightWidth, topHeight);
        node.Children[1] = new Node<T>(node.Bounds.X1, node.Bounds.Y1, leftWidth, topHeight);
        node.Children[2] = new Node<T>(node.Bounds.X1, node.Bounds.MidY, leftWidth, bottomHeight);
        node.Children[3] = new Node<T>(node.Bounds.MidX, node.Bounds.MidY, rightWidth, bottomHeight);

        for (int i = 0; i < node.Items.Count; i++)
        {
            var item = node.Items[i];
            var quadrant = GetQuadrant(node, item.Bounds);
            if (quadrant != -1)
            {
                node.Items.Remove(item);
                node.Children[quadrant].Items.Add(item);
                i--;
            }
        }

        foreach (var child in node.Children)
        {
            Split(child, nodeDepth + 1);
        }
    }

    private int GetQuadrant(Node<T> node, Rectangle bounds)
    {
        var verticalMidpoint = node.Bounds.MidX;
        var horizontalMidpoint = node.Bounds.MidY;

        var inTopQuadrant = node.Bounds.Y1 <= bounds.Y1 && bounds.Y2 <= horizontalMidpoint;
        var inBottomQuadrant = horizontalMidpoint <= bounds.Y1 && bounds.Y2 <= node.Bounds.Y2;
        var inLeftQuadrant = node.Bounds.X1 <= bounds.X1 && bounds.X2 <= verticalMidpoint;
        var inRightQuadrant = verticalMidpoint <= bounds.X1 && bounds.X2 <= node.Bounds.X2;

        if (inLeftQuadrant)
        {
            if (inTopQuadrant)
            {
                return 1;
            }
            else if (inBottomQuadrant)
            {
                return 2;
            }
        }
        else if (inRightQuadrant)
        {
            if (inTopQuadrant)
            {
                return 0;
            }
            else if (inBottomQuadrant)
            {
                return 3;
            }
        }

        return -1;
    }

    public List<T> Report(Rectangle bounds)
    {
        var collisionCandidates = new List<T>();

        GetCollisionCandidates(this.root, bounds, collisionCandidates);

        return collisionCandidates;
    }

    private void GetCollisionCandidates(Node<T> node, Rectangle bounds, List<T> result)
    {
        var quadrant = GetQuadrant(node, bounds);

        if (quadrant == -1)
        {
            GetSubtreeContents(node, bounds, result);
        }
        else
        {
            if (node.Children != null)
            {
                GetCollisionCandidates(node.Children[quadrant], bounds, result);
            }

            result.AddRange(node.Items);
        }
    }

    private void GetSubtreeContents(Node<T> node, Rectangle bounds, List<T> result)
    {
        if (node.Children != null)
        {
            foreach (var child in node.Children)
            {
                if (child.Bounds.Intersects(bounds))
                {
                    GetSubtreeContents(child, bounds, result);
                }
            }
        }

        result.AddRange(node.Items);
    }

    private void ForEachDfs(Node<T> node, Action<List<T>, int, int> action, int depth = 1, int quadrant = 0)
    {
        if (node == null)
        {
            return;
        }

        if (node.Items.Any())
        {
            action(node.Items, depth, quadrant);
        }

        if (node.Children != null)
        {
            for (int i = 0; i < node.Children.Length; i++)
            {
                ForEachDfs(node.Children[i], action, depth + 1, i);
            }
        }
    }
}


text:
<?php
namespace App\Modules\General\Database\Seeds;

use Illuminate\Database\Seeder;

use DB;
use Schema;

class StatusesSeeder extends Seeder {

	public function run()
	{
		// Uncomment the below to wipe the table clean before populating
		DB::table('statuses')->truncate();

		$seeds = array(
			array(
				'name'					=> 'Enabled',
				'description'			=> 'Enabled'
			),
			array(
				'name'					=> 'Diabled',
				'description'			=> 'Diabled'
			)
		);

		// Uncomment the below to run the seeder
		DB::table('statuses')->insert($seeds);
	}

}


text:
<?php

namespace Realex\HttpAdapter;

use Realex\Realex;

use Buzz\Browser;

/**
 * @author Shane O'Grady <shane.ogrady@gmail.com>
 */
class BuzzHttpAdapter implements HttpAdapterInterface
{

    /**
     * @var Browser
     */
    protected $browser;

    /**
     * @param Browser $browser Browser object
     */
    public function __construct(Browser $browser = null)
    {
        $this->browser = null === $browser ? new Browser() : $browser;
    }

    /**
     * {@inheritDoc}
     */
    public function postRequest($content)
    {
        $result = $this->browser->post(Realex::REMOTE_ENDPOINT, array("User-Agent" => Realex::USER_AGENT), $content);
        $response  = $result->getContent();

        return $response;
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'buzz';
    }
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.imscv.robotapp.fragment.DiscoverFragment">

    <!-- TODO: Update blank com.david.wechatsample.fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="DiscoverFragment" />

</FrameLayout>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Lingnan Univ. Sci. Bull. 2:69. 1930

#### Original name
null

### Remarks
null


text:
from PySide.QtGui import *
from PySide.QtCore import *

class Factorial(QObject):
    xChanged = Signal(int)
    def __init__(self):
        super(Factorial, self).__init__()
        self.xval = -1
        self.facval = 1
    def getX(self):
        return self.xval
    def setX(self, x):
        if self.xval == x:
            return
        self.xval = x
        self.xChanged.emit(x)
    x = Property(int, getX, setX)
    def getFact(self):
        return self.facval
    def setFact(self, fac):
        self.facval = fac
    fac = Property(int, getFact, setFact)

class FactorialLoopTransition(QSignalTransition):
    def __init__(self, fact):
        super(FactorialLoopTransition, self).__init__(fact, SIGNAL('xChanged(int)'))
        self.fact = fact
    def eventTest(self, e):
        if not super(FactorialLoopTransition, self).eventTest(e):
            return False
        return e.arguments()[0] > 1
    def onTransition(self, e):
        x = e.arguments()[0]
        fac = self.fact.fac
        self.fact.fac = x * fac
        self.fact.x = x - 1

class FactorialDoneTransition(QSignalTransition):
    def __init__(self, fact):
        super(FactorialDoneTransition, self).__init__(fact, SIGNAL('xChanged(int)'))
        self.fact = fact
    def eventTest(self, e):
        if not super(FactorialDoneTransition, self).eventTest(e):
            return False
        return e.arguments()[0] <= 1
    def onTransition(self, e):
        print(self.fact.fac)

if __name__ == '__main__':
    import sys
    app = QCoreApplication(sys.argv)
    factorial = Factorial()
    machine = QStateMachine()

    compute = QState(machine)
    compute.assignProperty(factorial, 'fac', 1)
    compute.assignProperty(factorial, 'x', 6)
    compute.addTransition(FactorialLoopTransition(factorial))

    done = QFinalState(machine)
    doneTransition = FactorialDoneTransition(factorial)
    doneTransition.setTargetState(done)
    compute.addTransition(doneTransition)

    machine.setInitialState(compute)
    machine.finished.connect(app.quit)
    machine.start()

    sys.exit(app.exec_())


text:
var ProgressBar = require("../progress");
var Swipeable = require("react-swipeable");

var CarouselLoop = React.createClass({
	displayName: "CarouselLoop",
	propTypes: {
		autoPlay: React.PropTypes.number,
		visibleItemCount: React.PropTypes.number,
		children: React.PropTypes.node
	},
	getDefaultProps() {
		return {
			autoPlay: 0
		}
	},
	getInitialState() {
		return {
			activeGroup: 0,
			autoPlayTimestamp: Date.now(),
			currentTimestamp: Date.now(),
			lastDirection: undefined,
			anchorIndex: 0
		}
	},
	componentDidMount() {
		if (this.props.autoPlay) {
			this.setProgress(this.props, this.state);
			this.next();
		}
	},
	componentDidUpdate(prevProps, prevState) {
		if ((this.state.currentTimestamp == this.state.autoPlayTimestamp) && (prevState.activeGroup != this.state.activeGroup)) {
			this.setProgress(this.props, this.state);
		}
	},
	componentWillUnmount() {
		clearInterval(this._interval);
	},
	buildControl(props, state) {

		let _next = (
			this.next(true)}>

				);
		let _prev = (
			this.prev(true)}>

				);

		let circleList = this.getGroupedItemIndex(props, state).map((group, index)=> {
			var _className = cx({
				circle: true,
				active: index == this.state.activeGroup
			});
			return (
				this.navigate(index)}>
			)

		});

		let controlList = React.Children.count(props.children) > props.visibleItemCount ? [_prev,
			{circleList}, _next] : null;

		return controlList;
	},
	buildProgressBar(props, state) {
		var transitionDuration = (state.currentTimestamp == state.autoPlayTimestamp) ? 0 : props.autoPlay;
		//console.log(transitionDuration);
		return (props.autoPlay && (React.Children.count(props.children) > 1)) ? (
			<ProgressBar percent={this.getAutoPlayTimePercent(props,state)}
									 transitionDuration={props.autoPlay && transitionDuration}></ProgressBar>
		) : null;
	},
	getAutoPlayTimePercent(props, state) {
		//console.log(100 * (state.currentTimestamp - state.autoPlayTimestamp) / props.autoPlay);
		return 100 * (state.currentTimestamp - state.autoPlayTimestamp) / props.autoPlay;
	},
	setActiveGroup(index, direction) {
		var groupCount = this.getGroupCount(this.props, this.state);
		let childCount = React.Children.count(this.props.children);
		let groupedIndex = this.getGroupedItemIndex(this.props, this.state);

		var _targetIndex = index;
		let _newAnchorIndex = this.state.anchorIndex;

		if (index >= groupCount) {
			_targetIndex = 0;
			_newAnchorIndex = groupedIndex.last().last() + 1;
			_newAnchorIndex = _newAnchorIndex > (childCount - 1) ? 0 : _newAnchorIndex;
		} else if (index < 0) {
			_targetIndex = groupCount - 1;
			_newAnchorIndex = groupedIndex.first().first() + groupCount * (childCount - this.props.visibleItemCount);
		}

		//console.log(_targetIndex,_newAnchorIndex);

		var timeStamp = Date.now();

		this.setState({
			prevIndex: this.state.activeGroup,
			activeGroup: _targetIndex,
			autoPlayTimestamp: timeStamp,
			currentTimestamp: timeStamp,
			lastDirection: direction,
			anchorIndex: _newAnchorIndex
		});
	},
	getGroupedItemIndex(props, state) {
		let {visibleItemCount} = props;
		let childCount = React.Children.count(props.children);
		let groupCount = this.getGroupCount(props, state);
		return Immutable.Range(0, groupCount).toList().map((groupNumber, index)=> {
			if (childCount <= visibleItemCount) {
				return Immutable.Range(0, childCount);
			} else {
				return Immutable.Range(visibleItemCount * groupNumber + state.anchorIndex, visibleItemCount * (groupNumber + 1) + state.anchorIndex).toList();
			}
		}).map((itemGroup, index)=> {
			return itemGroup.map((itemIndex, idx)=> {
				//console.log(itemIndex);
				if (itemIndex >= childCount) {
					return (itemIndex - childCount) % childCount;
				} else if (itemIndex < 0) {
					return (itemIndex + childCount) % childCount;
				} else {
					return itemIndex;
				}
			})
		});
	},
	setProgress(props, state) {
		if (props.autoPlay) {
			setTimeout(()=> {
				this.setState({
					currentTimestamp: state.autoPlayTimestamp + props.autoPlay
				})
			}, 10);

		}
	},
	navigate(index) {
		if (index != this.state.activeGroup) {
			clearInterval(this._interval);
			this.setActiveGroup(index);
			this.next();
		}
	},
	next(force) {
		clearInterval(this._interval);
		if (!force && !!this.props.autoPlay) {
			this._interval = setInterval(()=> {
				this.setActiveGroup(this.state.activeGroup + 1, "right");
			}, this.props.autoPlay);
		} else {
			this.setActiveGroup(this.state.activeGroup + 1, "right");
			//this.next();
		}
	},
	prev(force) {
		clearInterval(this._interval);
		if (!force && !!this.props.autoPlay) {
			clearInterval(this._interval);
			this._interval = setInterval(()=> {
				this.setActiveGroup(this.state.activeGroup - 1, "left");
			}, this.props.autoPlay);
		} else {
			this.setActiveGroup(this.state.activeGroup - 1, "left");
			//this.prev();
		}
	},
	onSwipingRight: $.debounce(200, function () {
		this.prev(true);
	}),
	onSwipingLeft: $.debounce(200, function () {
		this.next(true);
	}),
	buildTransitionName(props, state) {
		let groupCount = this.getGroupCount(props, state);
		let tailToHead = (state.activeGroup == 0 && state.prevIndex + 1 == groupCount && state.lastDirection == "right");
		let headToTail = (state.activeGroup + 1 == groupCount && state.prevIndex == 0 && state.lastDirection == "left");
		if (headToTail || tailToHead) {
			return cx({
				"carousel-animation": tailToHead,
				"carousel-animation-reverse": headToTail
			})
		} else {
			return cx({
				"carousel-animation": (state.activeGroup > state.prevIndex),
				"carousel-animation-reverse": (state.activeGroup < state.prevIndex)
			})
		}

	},
	getGroupCount(props, state) {
		let {visibleItemCount} = props;
		let childCount = React.Children.count(props.children);
		return Math.ceil(childCount / visibleItemCount);
	},
	getActiveGroupItem(props, state) {
		let {activeGroup} = state;
		let {visibleItemCount} = props;
		let childCount = React.Children.count(props.children);
		let groupCount = Math.ceil(childCount / visibleItemCount);
		let groupedIndex = this.getGroupedItemIndex(props, state);
		let childArray = React.Children.toArray(props.children);
		let lastCombinedItemList = [];

		lastCombinedItemList = groupedIndex.get(activeGroup).map((index)=> {
			return childArray[index]
		});

		return lastCombinedItemList.filter((val)=>!!val);

	},
	buildChildren(props, state) {
		var _resultChild;
		try {
			_resultChild = React.Children.only(props.children)
		} catch (e) {
			_resultChild = (

					{
						this.getActiveGroupItem(props, state).toJS().map((child, index)=> {
							return child ? React.cloneElement(child, {
								width: child.props.width ? child.props.width : 100 / props.visibleItemCount + "%",
								left: (index) * 100 / props.visibleItemCount + "%",
							}) : null
						})
					}

			)
		}
		return _resultChild;
	},
	buildCarousel(props, state) {
		//console.log(this.buildTransitionName(props,state));
		let _className = cx({
			"b-carousel b-carousel--multiple": true,
			[props.className]: !!props.className
		});
		return React.Children.count(props.children) ? (

				{this.buildProgressBar(props, state)}

				<ReactCSSTransitionGroup component={Swipeable}
																 onSwipingLeft={this.onSwipingLeft}
																 onSwipingRight={this.onSwipingRight}
																 delta={100}
																 className="item-container"
																 transitionAppear={true}
																 transitionEnter={true}
																 transitionLeave={true}
																 transitionAppearTimeout={1000}
																 transitionEnterTimeout={1000} transitionLeaveTimeout={1000}
																 transitionName={this.buildTransitionName(props,state)}>
					{this.buildChildren(props, state)}
				</ReactCSSTransitionGroup>

					{this.buildControl(props, state)}

		) : null;
	},
	render() {
		return this.buildCarousel(this.props, this.state);
	}
});

CarouselLoop.Item = React.createClass({
	displayName: "CarouselMultiple.Item",
	propTypes: {
		width: React.PropTypes.string
	},
	render() {
		let _style = {
			width: this.props.width,
			left: this.props.left
		};

		return (

				{this.props.children}

		)
	}
});

module.exports = CarouselLoop;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="AnimatedGradientTextView">
        <attr name="colors" format="reference"/>
        <attr name="simultaneousColors" format="integer"/>
        <attr name="angle" format="integer"/>
        <attr name="speed" format="integer"/>
        <attr name="maxFPS" format="integer"/>
        <attr name="customFont" format="string"/>
    </declare-styleable>

    <array name="default_gradient_colors">
        <item>@color/materialRed</item>
        <item>@color/materialPink</item>
        <item>@color/materialPurple</item>
        <item>@color/materialDeepPurple</item>
        <item>@color/materialIndigo</item>
        <item>@color/materialBlue</item>
    </array>
</resources>


text:
package com.sequenceiq.cloudbreak.cloud.gcp.model;

import com.fasterxml.jackson.annotation.JsonProperty;

public class ZoneDefinitionView {

    @JsonProperty("id")
    private String id;

    @JsonProperty("kind")
    private String kind;

    @JsonProperty("creationTimestamp")
    private String creationTimestamp;

    @JsonProperty("name")
    private String name;

    @JsonProperty("description")
    private String description;

    @JsonProperty("status")
    private String status;

    @JsonProperty("region")
    private String region;

    @JsonProperty("selfLink")
    private String selfLink;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getKind() {
        return kind;
    }

    public void setKind(String kind) {
        this.kind = kind;
    }

    public String getCreationTimestamp() {
        return creationTimestamp;
    }

    public void setCreationTimestamp(String creationTimestamp) {
        this.creationTimestamp = creationTimestamp;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public String getSelfLink() {
        return selfLink;
    }

    public void setSelfLink(String selfLink) {
        this.selfLink = selfLink;
    }
}


text:
#region license

#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;

namespace DMagic.Part_Modules
{
	public class DMBreakablePart : DMModuleScienceAnimate
	{
		protected List<GameObject> breakableObjects = new List<GameObject>();
		private Transform baseTransform;
		private Transform forwardTransform;

		[KSPField(isPersistant = true)]
		public bool broken;
		[KSPField]
		public bool breakable = true;
		[KSPField]
		public float breakingForce = 5;
		//[KSPField(guiActive = true)]
		//public string BForce = "";
		[KSPField]
		public bool fixable = true;
		[KSPField]
		public int fixLevel = 1;
		[KSPField]
		public string baseTransfromName = "";
		[KSPField]
		public string forwardTransformName = "";
		[KSPField]
		public float componentDrag = 1f;
		[KSPField]
		public float componentMass = 0.1f;

		public override void OnStart(PartModule.StartState state)
		{
			base.OnStart(state);

			if (!string.IsNullOrEmpty(baseTransfromName))
				baseTransform = part.FindModelTransform(baseTransfromName);

			if (!string.IsNullOrEmpty(forwardTransformName))
				forwardTransform = part.FindModelTransform(forwardTransformName);

			if (broken)
			{
				setTransformState(false);
				base.Events["retractEvent"].active = base.IsDeployed && showEndEvent;
				base.Events["deployEvent"].active = false;
			}

			Events["fixPart"].active = fixable && breakable && broken;
			Events["fixPart"].unfocusedRange = interactionRange;
		}

		public override string GetInfo()
		{
			string info = base.GetInfo();

			if (breakable)
			{
				info += string.Format("Breakable: {0}\n", RUIutils.GetYesNoUIString(fixable));

				info += string.Format("Fixable: {0}\n", RUIutils.GetYesNoUIString(fixable));

				if (fixable)
					info += string.Format("Engineer Level To Fix: {0}\n", fixLevel);
			}

			return info;
		}

		public override void OnFixedUpdate()
		{
			base.OnFixedUpdate();

			if (!breakable)
				return;

			//BForce = breakingForce.ToString("F2");

			if (broken)
				return;

			checkForces();
		}

		public override bool canConduct()
		{
			if (broken)
			{
				failMessage = "This instrument is broken; the experiment can't be conducted";
				return false;
			}

			return base.canConduct();
		}

		public override void deployEvent()
		{
			base.deployEvent();

			if (broken && !oneWayAnimation)
				base.Events["retractEvent"].active = true;
		}

		protected virtual void setTransformState(bool on)
		{
			if (!breakable)
				return;

			if (baseTransform == null)
				return;

			if (baseTransform.gameObject == null)
				return;

			baseTransform.gameObject.SetActive(on);
		}

		private void checkForces()
		{
			if (!HighLogic.LoadedSceneIsFlight)
				return;

			if (vessel == null)
				return;

			if (vessel.atmDensity <= 0)
				return;

			if (!IsDeployed)
				return;

			if (forwardTransform == null)
				return;

			if (anim != null)
			{
				if (anim.IsPlaying(animationName))
					return;
			}

			if (vessel.HoldPhysics)
				return;

			if (shieldedState())
				return;

			float velocity = Mathf.Abs(Vector3.Dot(vessel.srf_velocity.normalized, forwardTransform.forward.normalized));
			if (velocity < 0.0001f)
				velocity = 0.0001f;
			float pressure = velocity * (float)(part.dynamicPressurekPa + part.submergedDynamicPressurekPa);
			if (pressure > breakingForce)
			{
				DMUtils.Logging("Breakable Part {0} - Breaking Force Exceded", part.name);
				onBreak();
			}
		}

		//Handle FAR shielded state; from RemoteTech:
		//https://github.com/RemoteTechnologiesGroup/RemoteTech/blob/develop/src/RemoteTech/Modules/ModuleRTAntenna.cs#L427-L481
		private bool shieldedState()
		{
			PartModule FARPartModule = GetFARModule();

			if (FARPartModule != null)
			{
				try
				{
					FieldInfo fi = FARPartModule.GetType().GetField("isShielded");
					return (bool)(fi.GetValue(FARPartModule));
				}
				catch (Exception e)
				{
					DMUtils.Logging("GetShieldedState: {0}", e);
				}
			}

			return part.ShieldedFromAirstream;
		}

		private PartModule GetFARModule()
		{
			if (part.Modules.Contains("FARBasicDragModel"))
			{
				return part.Modules["FARBasicDragModel"];
			}
			else if (part.Modules.Contains("FARWingAerodynamicModel"))
			{
				return part.Modules["FARWingAerodynamicModel"];
			}
			else if (part.Modules.Contains("FARControlSys"))
			{
				return part.Modules["FARControlSys"];
			}
			else
			{
				return null;
			}
		}

		//[KSPEvent(guiActive = true, active = true, guiName = "Break")]
		//public void breakStuff()
		//{
		//	onBreak();
		//}

		//[KSPEvent(guiActive = true, active = true)]
		//public void breakAdd()
		//{
		//	breakingForce += 0.05f;
		//}

		//[KSPEvent(guiActive = true, active = true)]
		//public void breakMinus()
		//{
		//	breakingForce -= 0.05f;
		//}

		private void breakObjects()
		{
			if (broken)
				return;

			if (part.packed)
				return;

			DMUtils.DebugLog("Breaking Objects...");

			getGameObjects();

			for (int i = 0; i < breakableObjects.Count; i++)
			{
				GameObject o = breakableObjects[i];

				if (o == null)
					continue;

				Rigidbody r = o.AddComponent<Rigidbody>();

				if (r == null)
					continue;

				DMUtils.DebugLog("Breaking Object [{0}]...", o.name);

				Rigidbody partRigid = part.GetComponent<Rigidbody>();

				Vector3 randomAngular = new Vector3((float)DMUtils.rand.NextDouble() * 3, (float)DMUtils.rand.NextDouble() * 3, (float)DMUtils.rand.NextDouble() * 3);
				DMUtils.DebugLog("Random Angular: [{0:F4}]", randomAngular);
				DMUtils.DebugLog("Old Angular: [{0:F4}]", r.angularVelocity);
				r.angularVelocity = partRigid.angularVelocity + randomAngular;
				DMUtils.DebugLog("New Angular: [{0:F4}]", r.angularVelocity);
				Vector3 randomVel = new Vector3(((float)DMUtils.rand.NextDouble() * 8) - 4, ((float)DMUtils.rand.NextDouble() * 8) - 4, ((float)DMUtils.rand.NextDouble() * 8) - 4);
				DMUtils.DebugLog("Random Velocity: [{0:F4}]", randomVel);
				Vector3 localCOM = vessel.findWorldCenterOfMass() - partRigid.worldCenterOfMass;
				DMUtils.DebugLog("Old Velocity: [{0:F4}]", r.velocity);
				r.velocity = partRigid.velocity + randomVel + Vector3.Cross(localCOM, r.angularVelocity);
				DMUtils.DebugLog("New Velocity: [{0:F4}]", r.velocity);
				r.mass = componentMass;
				r.useGravity = false;
				o.transform.parent = null;
				physicalObject p = o.AddComponent<physicalObject>();
				r.drag = componentDrag;

				var colliders = o.GetComponentsInChildren<Collider>();

				if (colliders.Length <= 0)
					continue;

				for (int j = 0; j < colliders.Length; j++)
				{
					Collider c = colliders[j];

					if (c == null)
						continue;

					if (!c.enabled)
						continue;

					DMUtils.DebugLog("Setting Collider [{0}] Inactive", c.name);

					c.enabled = false;
				}
			}

			StartCoroutine(breakablePartsRemove());

			if (IsDeployed && oneShot && !oneWayAnimation)
			{
				isLocked = false;
				base.Events["retractEvent"].active = true;
			}
		}

		private IEnumerator breakablePartsRemove()
		{
			yield return new WaitForSeconds(0.75f);

			setTransformState(false);
		}

		protected virtual void getGameObjects()
		{
			getChildren(baseTransform);
		}

		private void getChildren(Transform t)
		{
			if (t == null)
				return;

			for (int i = 0; i < t.childCount; i++)
			{
				Transform tChild = t.GetChild(i);

				if (tChild == null)
					continue;

				GameObject obj = tChild.gameObject;

				if (obj == null)
					continue;

				if (obj.GetComponent<MeshRenderer>() == null && obj.GetComponent<SkinnedMeshRenderer>() == null)
					continue;

				breakableObjects.Add(obj);

				getChildren(tChild);
			}
		}

		[KSPEvent(guiActive = false, guiActiveUnfocused = true, externalToEVAOnly = true, guiName = "Fix", active = false)]
		public void fixPart()
		{
			if (!fixable)
				return;

			if (!breakable)
				return;

			if (!broken)
			{
				Events["fixPart"].active = false;
				return;
			}

			Vessel v = FlightGlobals.ActiveVessel;

			if (v == null)
				return;

			if (!v.isEVA)
				return;

			if (v.parts[0] == null)
				return;

			if (v.parts[0].protoModuleCrew.Count <= 0)
				return;

			if (v.parts[0].protoModuleCrew[0].experienceTrait.TypeName != "Engineer")
			{
				ScreenMessages.PostScreenMessage(string.Format("An engineer of at least level [{0}] is required to repair this instrument.", fixLevel), 6f, ScreenMessageStyle.UPPER_CENTER);
				return;
			}

			if (v.parts[0].protoModuleCrew[0].experienceLevel < fixLevel)
			{
				ScreenMessages.PostScreenMessage(string.Format("An engineer of at least level [{0}] is required to repair this instrument.", fixLevel), 6f, ScreenMessageStyle.UPPER_CENTER);
				return;
			}

			onFix();
		}

		protected virtual void onBreak()
		{
			breakObjects();

			broken = true;

			if (fixable)
				Events["fixPart"].active = true;
		}

		protected virtual void onFix()
		{
			broken = false;

			setTransformState(true);

			Events["fixPart"].active = false;
		}
	}
}