text:
#include <eosio/trace_api/trace_api_plugin.hpp>

#include <eosio/trace_api/abi_data_handler.hpp>
#include <eosio/trace_api/request_handler.hpp>
#include <eosio/trace_api/chain_extraction.hpp>
#include <eosio/trace_api/store_provider.hpp>

#include <eosio/trace_api/configuration_utils.hpp>

#include <eosio/resource_monitor_plugin/resource_monitor_plugin.hpp>

#include <boost/signals2/connection.hpp>

using namespace eosio::trace_api;
using namespace eosio::trace_api::configuration_utils;
using boost::signals2::scoped_connection;

namespace {
   appbase::abstract_plugin& plugin_reg = app().register_plugin<trace_api_plugin>();

   const std::string logger_name("trace_api");
   fc::logger _log;

   std::string to_detail_string(const std::exception_ptr& e) {
      try {
         std::rethrow_exception(e);
      } catch (fc::exception& er) {
         return er.to_detail_string();
      } catch (const std::exception& e) {
         fc::exception fce(
               FC_LOG_MESSAGE(warn, "std::exception: ${what}: ", ("what", e.what())),
               fc::std_exception_code,
               BOOST_CORE_TYPEID(e).name(),
               e.what());
         return fce.to_detail_string();
      } catch (...) {
         fc::unhandled_exception ue(
               FC_LOG_MESSAGE(warn, "unknown: ",),
               std::current_exception());
         return ue.to_detail_string();
      }
   }

   void log_exception( const exception_with_context& e, fc::log_level level ) {
      if( _log.is_enabled( level ) ) {
         auto detail_string = to_detail_string(std::get<0>(e));
         auto context = fc::log_context( level, std::get<1>(e), std::get<2>(e), std::get<3>(e) );
         _log.log(fc::log_message( context, detail_string ));
      }
   }

   /**
    * The exception_handler provided to the extraction sub-system throws `yield_exception` as a signal that
    * Something has gone wrong and the extraction process needs to terminate immediately
    *
    * This templated method is used to wrap signal handlers for `chain_controller` so that the plugin-internal
    * `yield_exception` can be translated to a `chain::controller_emit_signal_exception`.
    *
    * The goal is that the currently applied block will be rolled-back before the shutdown takes effect leaving
    * the system in a better state for restart.
    */
   template<typename F>
   void emit_killer(F&& f) {
      try {
         f();
      } catch (const yield_exception& ) {
         EOS_THROW(chain::controller_emit_signal_exception, "Trace API encountered an Error which it cannot recover from.  Please resolve the error and relaunch the process")
      }
   }

   template<typename Store>
   struct shared_store_provider {
      shared_store_provider(const std::shared_ptr<Store>& store)
      :store(store)
      {}

      template <typename BlockTrace>
      void append( const BlockTrace& trace ) {
         store->append(trace);
      }

      void append_lib( uint32_t new_lib ) {
         store->append_lib(new_lib);
      }

      get_block_t get_block(uint32_t height, const yield_function& yield) {
         return store->get_block(height, yield);
      }

      std::shared_ptr<Store> store;
   };
}

namespace eosio {

/**
 * A common source for information shared between the extraction process and the RPC process
 */
struct trace_api_common_impl {
   static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
      auto cfg_options = cfg.add_options();
      cfg_options("trace-dir", bpo::value<bfs::path>()->default_value("traces"),
                  "the location of the trace directory (absolute path or relative to application data dir)");
      cfg_options("trace-slice-stride", bpo::value<uint32_t>()->default_value(10'000),
                  "the number of blocks each \"slice\" of trace data will contain on the filesystem");
      cfg_options("trace-minimum-irreversible-history-blocks", boost::program_options::value<int32_t>()->default_value(-1),
                  "Number of blocks to ensure are kept past LIB for retrieval before \"slice\" files can be automatically removed.\n"
                  "A value of -1 indicates that automatic removal of \"slice\" files will be turned off.");
      cfg_options("trace-minimum-uncompressed-irreversible-history-blocks", boost::program_options::value<int32_t>()->default_value(-1),
                  "Number of blocks to ensure are uncompressed past LIB. Compressed \"slice\" files are still accessible but may carry a performance loss on retrieval\n"
                  "A value of -1 indicates that automatic compression of \"slice\" files will be turned off.");
   }

   void plugin_initialize(const appbase::variables_map& options) {
      auto dir_option = options.at("trace-dir").as<bfs::path>();
      if (dir_option.is_relative())
         trace_dir = app().data_dir() / dir_option;
      else
         trace_dir = dir_option;
      if (auto resmon_plugin = app().find_plugin<resource_monitor_plugin>())
        resmon_plugin->monitor_directory(trace_dir);

      slice_stride = options.at("trace-slice-stride").as<uint32_t>();

      const int32_t blocks = options.at("trace-minimum-irreversible-history-blocks").as<int32_t>();
      EOS_ASSERT(blocks >= -1, chain::plugin_config_exception,
                 "\"trace-minimum-irreversible-history-blocks\" must be greater to or equal to -1.");
      if (blocks > manual_slice_file_value) {
         minimum_irreversible_history_blocks = blocks;
      }

      const int32_t uncompressed_blocks = options.at("trace-minimum-uncompressed-irreversible-history-blocks").as<int32_t>();
      EOS_ASSERT(uncompressed_blocks >= -1, chain::plugin_config_exception,
                 "\"trace-minimum-uncompressed-irreversible-history-blocks\" must be greater to or equal to -1.");

      if (uncompressed_blocks > manual_slice_file_value) {
         minimum_uncompressed_irreversible_history_blocks = uncompressed_blocks;
      }

      store = std::make_shared<store_provider>(
         trace_dir,
         slice_stride,
         minimum_irreversible_history_blocks,
         minimum_uncompressed_irreversible_history_blocks,
         compression_seek_point_stride
      );
   }

   void plugin_startup() {
      store->start_maintenance_thread([](const std::string& msg ){
         fc_dlog( _log, msg );
      });
   }

   void plugin_shutdown() {
      store->stop_maintenance_thread();
   }

   // common configuration paramters
   boost::filesystem::path trace_dir;
   uint32_t slice_stride = 0;

   std::optional<uint32_t> minimum_irreversible_history_blocks;
   std::optional<uint32_t> minimum_uncompressed_irreversible_history_blocks;

   static constexpr int32_t manual_slice_file_value = -1;
   static constexpr uint32_t compression_seek_point_stride = 6 * 1024 * 1024; // 6 MiB strides for clog seek points

   std::shared_ptr<store_provider> store;
};

/**
 * Interface with the RPC process
 */
struct trace_api_rpc_plugin_impl : public std::enable_shared_from_this<trace_api_rpc_plugin_impl>
{
   trace_api_rpc_plugin_impl( const std::shared_ptr<trace_api_common_impl>& common )
   :common(common) {}

   static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
      auto cfg_options = cfg.add_options();
      cfg_options("trace-rpc-abi", bpo::value<vector<string>>()->composing(),
                  "ABIs used when decoding trace RPC responses.\n"
                  "There must be at least one ABI specified OR the flag trace-no-abis must be used.\n"
                  "ABIs are specified as \"Key=Value\" pairs in the form <account-name>=<abi-def>\n"
                  "Where <abi-def> can be:\n"
                  "   an absolute path to a file containing a valid JSON-encoded ABI\n"
                  "   a relative path from `data-dir` to a file containing a valid JSON-encoded ABI\n"
                  );
      cfg_options("trace-no-abis",
            "Use to indicate that the RPC responses will not use ABIs.\n"
            "Failure to specify this option when there are no trace-rpc-abi configuations will result in an Error.\n"
            "This option is mutually exclusive with trace-rpc-api"
      );
   }

   void plugin_initialize(const appbase::variables_map& options) {
      std::shared_ptr<abi_data_handler> data_handler = std::make_shared<abi_data_handler>([](const exception_with_context& e){
         log_exception(e, fc::log_level::debug);
      });

      if( options.count("trace-rpc-abi") ) {
         EOS_ASSERT(options.count("trace-no-abis") == 0, chain::plugin_config_exception,
                    "Trace API is configured with ABIs however trace-no-abis is set");
         const std::vector<std::string> key_value_pairs = options["trace-rpc-abi"].as<std::vector<std::string>>();
         for (const auto& entry : key_value_pairs) {
            try {
               auto kv = parse_kv_pairs(entry);
               auto account = chain::name(kv.first);
               auto abi = abi_def_from_file(kv.second, app().data_dir());
               data_handler->add_abi(account, abi);
            } catch (...) {
               elog("Malformed trace-rpc-abi provider: \"${val}\"", ("val", entry));
               throw;
            }
         }
      } else {
         EOS_ASSERT(options.count("trace-no-abis") != 0, chain::plugin_config_exception,
                    "Trace API is not configured with ABIs and trace-no-abis is not set");
      }

      req_handler = std::make_shared<request_handler_t>(
         shared_store_provider<store_provider>(common->store),
         abi_data_handler::shared_provider(data_handler)
      );
   }

   fc::time_point calc_deadline( const fc::microseconds& max_serialization_time ) {
      fc::time_point deadline = fc::time_point::now();
      if( max_serialization_time > fc::microseconds::maximum() - deadline.time_since_epoch() ) {
         deadline = fc::time_point::maximum();
      } else {
         deadline += max_serialization_time;
      }
      return deadline;
   }

   void plugin_startup() {
      auto& http = app().get_plugin<http_plugin>();
      fc::microseconds max_response_time = http.get_max_response_time();

      http.add_async_handler("/v1/trace_api/get_block",
            [wthis=weak_from_this(), max_response_time](std::string, std::string body, url_response_callback cb)
      {
         auto that = wthis.lock();
         if (!that) {
            return;
         }

         auto block_number = ([&body]() -> std::optional<uint32_t> {
            if (body.empty()) {
               return {};
            }

            try {
               auto input = fc::json::from_string(body);
               auto block_num = input.get_object()["block_num"].as_uint64();
               if (block_num > std::numeric_limits<uint32_t>::max()) {
                  return {};
               }
               return block_num;
            } catch (...) {
               return {};
            }
         })();

         if (!block_number) {
            error_results results{400, "Bad or missing block_num"};
            cb( 400, fc::variant( results ));
            return;
         }

         try {

            const auto deadline = that->calc_deadline( max_response_time );
            auto resp = that->req_handler->get_block_trace(*block_number, [deadline]() { FC_CHECK_DEADLINE(deadline); });
            if (resp.is_null()) {
               error_results results{404, "Block trace missing"};
               cb( 404, fc::variant( results ));
            } else {
               cb( 200, std::move(resp) );
            }
         } catch (...) {
            http_plugin::handle_exception("trace_api", "get_block", body, cb);
         }
      });
   }

   void plugin_shutdown() {
   }

   std::shared_ptr<trace_api_common_impl> common;

   using request_handler_t = request_handler<shared_store_provider<store_provider>, abi_data_handler::shared_provider>;
   std::shared_ptr<request_handler_t> req_handler;
};

struct trace_api_plugin_impl {
   trace_api_plugin_impl( const std::shared_ptr<trace_api_common_impl>& common )
   :common(common) {}

   static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
      auto cfg_options = cfg.add_options();
   }

   void plugin_initialize(const appbase::variables_map& options) {
      auto log_exceptions_and_shutdown = [](const exception_with_context& e) {
         log_exception(e, fc::log_level::error);
         app().quit();
         throw yield_exception("shutting down");
      };
      extraction = std::make_shared<chain_extraction_t>(shared_store_provider<store_provider>(common->store), log_exceptions_and_shutdown);

      auto& chain = app().find_plugin<chain_plugin>()->chain();

      applied_transaction_connection.emplace(
         chain.applied_transaction.connect([this](std::tuple<const chain::transaction_trace_ptr&, const chain::packed_transaction_ptr&> t) {
            emit_killer([&](){
               extraction->signal_applied_transaction(std::get<0>(t), std::get<1>(t));
            });
         }));

      block_start_connection.emplace(
            chain.block_start.connect([this](uint32_t block_num) {
               emit_killer([&](){
                  extraction->signal_block_start(block_num);
               });
            }));

      accepted_block_connection.emplace(
         chain.accepted_block.connect([this](const chain::block_state_ptr& p) {
            emit_killer([&](){
               extraction->signal_accepted_block(p);
            });
         }));

      irreversible_block_connection.emplace(
         chain.irreversible_block.connect([this](const chain::block_state_ptr& p) {
            emit_killer([&](){
               extraction->signal_irreversible_block(p);
            });
         }));

   }

   void plugin_startup() {
      common->plugin_startup();
   }

   void plugin_shutdown() {
      common->plugin_shutdown();
   }

   std::shared_ptr<trace_api_common_impl> common;

   using chain_extraction_t = chain_extraction_impl_type<shared_store_provider<store_provider>>;
   std::shared_ptr<chain_extraction_t> extraction;

   std::optional<scoped_connection>                            applied_transaction_connection;
   std::optional<scoped_connection>                            block_start_connection;
   std::optional<scoped_connection>                            accepted_block_connection;
   std::optional<scoped_connection>                            irreversible_block_connection;
};

trace_api_plugin::trace_api_plugin()
{}

trace_api_plugin::~trace_api_plugin()
{}

void trace_api_plugin::set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
   trace_api_common_impl::set_program_options(cli, cfg);
   trace_api_plugin_impl::set_program_options(cli, cfg);
   trace_api_rpc_plugin_impl::set_program_options(cli, cfg);
}

void trace_api_plugin::plugin_initialize(const appbase::variables_map& options) {
   auto common = std::make_shared<trace_api_common_impl>();
   common->plugin_initialize(options);

   my = std::make_shared<trace_api_plugin_impl>(common);
   my->plugin_initialize(options);

   rpc = std::make_shared<trace_api_rpc_plugin_impl>(common);
   rpc->plugin_initialize(options);
}

void trace_api_plugin::plugin_startup() {
   handle_sighup(); // setup logging

   my->plugin_startup();
   rpc->plugin_startup();
}

void trace_api_plugin::plugin_shutdown() {
   my->plugin_shutdown();
   rpc->plugin_shutdown();
}

void trace_api_plugin::handle_sighup() {
   fc::logger::update( logger_name, _log );
}

trace_api_rpc_plugin::trace_api_rpc_plugin()
{}

trace_api_rpc_plugin::~trace_api_rpc_plugin()
{}

void trace_api_rpc_plugin::set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
   trace_api_common_impl::set_program_options(cli, cfg);
   trace_api_rpc_plugin_impl::set_program_options(cli, cfg);
}

void trace_api_rpc_plugin::plugin_initialize(const appbase::variables_map& options) {
   auto common = std::make_shared<trace_api_common_impl>();
   common->plugin_initialize(options);

   rpc = std::make_shared<trace_api_rpc_plugin_impl>(common);
   rpc->plugin_initialize(options);
}

void trace_api_rpc_plugin::plugin_startup() {
   rpc->plugin_startup();
}

void trace_api_rpc_plugin::plugin_shutdown() {
   rpc->plugin_shutdown();
}

void trace_api_rpc_plugin::handle_sighup() {
   fc::logger::update( logger_name, _log );
}

}


text:
namespace PhotoArtSystem.CloudStorages.CloudinaryApi
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Threading.Tasks;
    using Bytes2you.Validation;
    using CloudinaryDotNet;
    using CloudinaryDotNet.Actions;
    using Common.Constants;
    using Common.Providers.Contracts;
    using Contracts;

    public class CloudinaryCloudStorage : IImageCloudStorage
    {
        private const int DefaultWidth = 100;
        private const int DefaultHeight = 100;
        private const string DefaultCropMode = "fill";
        private const string DefaultOutputFormat = "jpg";

        private readonly Cloudinary cloud;
        private readonly Account account;

        public CloudinaryCloudStorage(ICloudStorageConfigurationProvider config)
        {
            this.account = new Account(
                config.ImageUploadName,
                config.ImageUploadApiKey,
                config.ImageUploadApiSecret);
            this.cloud = new Cloudinary(this.account);
        }

        public async Task<string> UploadFile(
            Stream stream,
            string fileName,
            string fileType,
            int width,
            int height,
            string cropMode,
            string outputFormat)
        {
            Guard.WhenArgument(
                stream,
                GlobalConstants.StreamRequiredExceptionMessage).IsNull().Throw();
            Guard.WhenArgument(
                fileName,
                GlobalConstants.FileNameRequiredExceptionMessage).IsNullOrWhiteSpace().Throw();
            Guard.WhenArgument(
                fileType,
                GlobalConstants.FileTypeRequiredExceptionMessage).IsNullOrWhiteSpace().Throw();
            Guard.WhenArgument(
                width,
                GlobalConstants.ImageWidthRequiredExceptionMessage).IsLessThanOrEqual(0).Throw();
            Guard.WhenArgument(
                height,
                GlobalConstants.ImageHeightRequiredExceptionMessage).IsLessThanOrEqual(0).Throw();

            if (!stream.CanRead)
            {
                throw new ArgumentException(GlobalConstants.StreamRequiredExceptionMessage);
            }

            if (width == 0)
            {
                width = DefaultWidth;
            }

            if (height == 0)
            {
                height = DefaultHeight;
            }

            if (string.IsNullOrWhiteSpace(cropMode))
            {
                cropMode = DefaultCropMode;
            }

            if (string.IsNullOrWhiteSpace(outputFormat))
            {
                outputFormat = DefaultOutputFormat;
            }

            var imageUploadParams = new ImageUploadParams
            {
                File = new FileDescription(fileName, stream),
                Transformation = new Transformation()
                                            .Width(width)
                                            .Height(height)
                                            .Crop(cropMode)
                                            .FetchFormat(outputFormat),
                PublicId = fileName
            };

            ImageUploadResult result = null;

            try
            {
                result = await this.cloud.UploadAsync(imageUploadParams);
            }
            catch (Exception)
            {
                // Log stuff
            }

            return result?.Uri?.AbsoluteUri;
        }

        public async Task<bool> DeleteFile(string fileName)
        {
            Guard.WhenArgument(
                fileName,
                GlobalConstants.FileNameRequiredExceptionMessage).IsNullOrWhiteSpace().Throw();

            var delParams = new DelResParams()
            {
                PublicIds = new List<string>() { fileName },
                Invalidate = true
            };

            DelResResult delResult = null;

            try
            {
                delResult = await this.cloud.DeleteResourcesAsync(delParams);
            }
            catch (Exception)
            {
                // Log stuff
            }

            return delResult.StatusCode == HttpStatusCode.OK;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe RandomSet do

  describe '.generate' do

    it "should require a template argument" do
      expect{ RandomSet.generate }
        .to raise_error(ArgumentError, "template required")
    end

    it "should not accept more than two arguments" do
      expect{ RandomSet.generate :one, :two, :template }
        .to raise_error(ArgumentError, "too many arguments (1..2 expected)")
    end

    it "should create a template from the last argument and call its generate with the rest of the arguments" do
      template = double(:template)
      expect(RandomSet::Template).to receive(:new).with(:template).and_return(template)

      result = double(:result)
      expect(template).to receive(:generate).with(10).and_return(result)
      expect(RandomSet.generate 10, :template).to be(result)
    end

  end

end


text:
package com.go.tea;

import java.util.Date;

public final class PackageInfo {
    // The following fields are automatically assigned by PackageInfoCreator.
    private static final String BASE_DIRECTORY = null;
    private static final String REPOSITORY = null;
    private static final String USERNAME = null;
    private static final String BUILD_MACHINE = null;
    private static final String GROUP = null;
    private static final String PROJECT = null;
    private static final String BUILD_LOCATION = null;
    private static final String PRODUCT = "Tea";
    private static final String PRODUCT_VERSION = "3.2.x";
    private static final String BUILD_NUMBER = null;
    private static final Date BUILD_DATE = null;

    /**
     * Prints all the PackageInfo properties to standard out.
     */
    public static void main(String[] args) {
        System.out.println("Base Directory: " + getBaseDirectory());
        System.out.println("Repository: " + getRepository());
        System.out.println("Username: " + getUsername());
        System.out.println("Build Machine: " + getBuildMachine());
        System.out.println("Group: " + getGroup());
        System.out.println("Project: " + getProject());
        System.out.println("Build Location: " + getBuildLocation());
        System.out.println("Product: " + getProduct());
        System.out.println("Product Version: " + getProductVersion());
        System.out.println("Build Number: " + getBuildNumber());
        System.out.println("Build Date: " + getBuildDate());
        System.out.println();
        System.out.println("Specification Title: " + getSpecificationTitle());
        System.out.println("Specification Version: " + getSpecificationVersion());
        System.out.println("Specification Vendor: " + getSpecificationVendor());
        System.out.println("Implementation Title: " + getImplementationTitle());
        System.out.println("Implementation Version: " + getImplementationVersion());
        System.out.println("Implementation Vendor: " + getImplementationVendor());
    }

    public static String getSpecificationTitle() {
        return PRODUCT;
    }

    public static String getSpecificationVersion() {
        return PRODUCT_VERSION;
    }

    public static String getSpecificationVendor() {
        return "WDIG";
    }

    public static String getImplementationTitle() {
        return PRODUCT;
    }

    public static String getImplementationVersion() {
        if (BUILD_NUMBER != null) {
            if (getSpecificationVersion() != null) {
                return getSpecificationVersion() + '.' + BUILD_NUMBER;
            }
            else {
                return BUILD_NUMBER;
            }
        }
        else {
            return getSpecificationVersion();
        }
    }

    public static String getImplementationVendor() {
        if (GROUP != null) {
            return getSpecificationVendor() + ' ' + GROUP;
        }
        else {
            return getSpecificationVendor();
        }
    }

    public static String getBaseDirectory() {
        return BASE_DIRECTORY;
    }

    public static String getRepository() {
        return REPOSITORY;
    }

    public static String getUsername() {
        return USERNAME;
    }

    public static String getBuildMachine() {
        return BUILD_MACHINE;
    }

    public static String getGroup() {
        return GROUP;
    }

    public static String getProject() {
        return PROJECT;
    }

    public static String getBuildLocation() {
        return BUILD_LOCATION;
    }

    public static String getProduct() {
        return PRODUCT;
    }

    public static String getProductVersion() {
        return PRODUCT_VERSION;
    }

    public static String getBuildNumber() {
        return BUILD_NUMBER;
    }

    public static Date getBuildDate() {
        return BUILD_DATE;
    }
}


text:
<?php

namespace Openl10n\Domain\Resource\Application\Action;

use Openl10n\Domain\Resource\Model\Resource;

class UpdateResourceAction
{
    protected $resource;
    protected $pathname;

    public function __construct(Resource $resource)
    {
        $this->resource = $resource;
        $this->pathname = (string) $resource->getPathname();
    }

    public function getResource()
    {
        return $this->resource;
    }

    public function getPathname()
    {
        return $this->pathname;
    }

    public function setPathname($pathname)
    {
        $this->pathname = $pathname;

        return $this;
    }
}


text:
<?php

namespace Elcodi\Component\CartCoupon\Applicator;

use Elcodi\Component\Cart\Entity\Interfaces\CartInterface;
use Elcodi\Component\CartCoupon\Applicator\Interfaces\CartCouponApplicatorInterface;
use Elcodi\Component\Coupon\Entity\Interfaces\CouponInterface;
use Elcodi\Component\Currency\Entity\Interfaces\MoneyInterface;
use Elcodi\Component\Currency\Entity\Money;
use Elcodi\Component\Currency\Wrapper\CurrencyWrapper;

/**
 * Class CartCouponApplicatorCollector.
 */
class CartCouponApplicatorCollector
{
    /**
     * @var CartCouponApplicatorInterface[]
     *
     * Cart Coupon Applicators
     */
    private $cartCouponApplicators = [];

    /**
     * @var CurrencyWrapper
     *
     * Currency Wrapper
     */
    private $currencyWrapper;

    /**
     * Construct method.
     *
     * @param CurrencyWrapper $currencyWrapper Currency wrapper
     */
    public function __construct(CurrencyWrapper $currencyWrapper)
    {
        $this->currencyWrapper = $currencyWrapper;
    }

    /**
     * Add Cart Coupon Applicator.
     *
     * @param CartCouponApplicatorInterface $cartCouponApplicator Cart Coupon Applicator
     */
    public function addCartCouponApplicator(CartCouponApplicatorInterface $cartCouponApplicator)
    {
        $this->cartCouponApplicators[] = $cartCouponApplicator;
    }

    /**
     * Calculate coupon absolute value.
     *
     * @param CartInterface   $cart   Cart
     * @param CouponInterface $coupon Coupon
     *
     * @return MoneyInterface Absolute value for this coupon in this cart
     */
    public function getCouponAbsoluteValue(
        CartInterface $cart,
        CouponInterface $coupon
    ) {
        $currency = $this
            ->currencyWrapper
            ->get();

        $couponPrice = Money::create(
            0,
            $currency
        );

        foreach ($this->cartCouponApplicators as $cartCouponApplicator) {
            if ($cartCouponApplicator->canBeApplied(
                $cart,
                $coupon
            )) {
                return $cartCouponApplicator->getCouponAbsoluteValue(
                    $cart,
                    $coupon
                );
            }
        }

        return $couponPrice;
    }
}


text:
<?php

class Object_Class_Data_Link extends Object_Class_Data {

    /**
     * Static type of this element
     *
     * @var string
     */
    public $fieldtype = "link";

    /**
     * Type for the column to query
     *
     * @var string
     */
    public $queryColumnType = "text";

    /**
     * Type for the column
     *
     * @var string
     */
    public $columnType = "text";

    /**
     * Type for the generated phpdoc
     *
     * @var string
     */
    public $phpdocType = "Object_Data_Link";

    /**
     * @see Object_Class_Data::getDataForResource
     * @param Object_Data_Link $data
     * @param null|Object_Abstract $object
     * @return string
     */
    public function getDataForResource($data, $object = null) {
        if($data instanceof Object_Data_Link and isset($data->object)){
            unset($data->object);
        }

        if($data) {
            try {
                $this->checkValidity($data, true);
            } catch (Exception $e) {
                $data->setInternalType(null);
                $data->setInternal(null);
            }
        }

        return Pimcore_Tool_Serialize::serialize($data);
    }

    /**
     * @see Object_Class_Data::getDataFromResource
     * @param string $data
     * @return Object_Data_Link
     */
    public function getDataFromResource($data) {
        $link = Pimcore_Tool_Serialize::unserialize($data);

        if ($link instanceof Object_Data_Link) {
            if ($link->isEmpty()) {
                return false;
            }

            try {
                $this->checkValidity($data, true);
            } catch (Exception $e) {
                $data->setInternalType(null);
                $data->setInternal(null);
            }
        }

        return $link;
    }

    /**
     * @see Object_Class_Data::getDataForQueryResource
     * @param string $data
     * @param null|Object_Abstract $object
     * @return string
     */
    public function getDataForQueryResource($data, $object = null) {
        return Pimcore_Tool_Serialize::serialize($data);
    }

    /**
     * @see Object_Class_Data::getDataForEditmode
     * @param string $data
     * @param null|Object_Abstract $object
     * @return string
     */
    public function getDataForEditmode($data, $object = null) {
        if (!$data instanceof Object_Data_Link) {
            return false;
        }
        $data->path = $data->getPath();
        return $data;
    }

    /**
     * @see Object_Class_Data::getDataFromEditmode
     * @param string $data
     * @param null|Object_Abstract $object
     * @return string
     */
    public function getDataFromEditmode($data, $object = null) {

        $link = new Object_Data_Link();
        $link->setValues($data);

        if ($link->isEmpty()) {
            return false;
        }
        return $link;
    }

    /**
     * @see Object_Class_Data::getVersionPreview
     * @param string $data
     * @return string
     */
    public function getVersionPreview($data) {
        return $data;
    }

    /**
     * Checks if data is valid for current data field
     *
     * @param mixed $data
     * @param boolean $omitMandatoryCheck
     * @throws Exception
     */
    public function checkValidity($data, $omitMandatoryCheck = false){
        if ($data) {
            if ($data instanceof Object_Data_Link) {
                if (intval($data->getInternal()) > 0) {
                    if ($data->getInternalType() == "document") {
                        $doc = Document::getById($data->getInternal());
                        if (!$doc instanceof Document) {
                            throw new Exception("invalid internal link, referenced document with id [" . $data->getInternal() . "] does not exist");
                        }
                    }
                    else if ($data->getInternalType() == "asset") {
                        $asset = Asset::getById($data->getInternal());
                        if (!$asset instanceof Asset) {
                            throw new Exception("invalid internal link, referenced asset with id [" . $data->getInternal() . "] does not exist");
                        }
                    }
                }
            }
        }
    }

    /**
     * @param mixed $data
     */
    public function resolveDependencies($data) {
        $dependencies = array();

        if ($data instanceof Object_Data_Link and $data->getInternal()) {

            if (intval($data->getInternal()) > 0) {
                if ($data->getInternalType() == "document") {

                    if ($doc = Document::getById($data->getInternal())) {

                        $key = "document_" . $doc->getId();
                        $dependencies[$key] = array(
                            "id" => $doc->getId(),
                            "type" => "document"
                        );
                    }
                }
                else if ($data->getInternalType() == "asset") {
                    if ($asset = Asset::getById($data->getInternal())) {
                        $key = "asset_" . $asset->getId();

                        $dependencies[$key] = array(
                            "id" => $asset->getId(),
                            "type" => "asset"
                        );
                    }
                }
            }
        }

        return $dependencies;
    }

    /**
     * @param mixed $data
     * @param Object_Concrete $ownerObject
     * @param array $blockedTags
     */
    public function getCacheTags($data, $ownerObject, $tags = array()) {

        $tags = is_array($tags) ? $tags : array();

        if ($data instanceof Object_Data_Link and $data->getInternal()) {

            if (intval($data->getInternal()) > 0) {
                if ($data->getInternalType() == "document") {

                    if ($doc = Document::getById($data->getInternal())) {
                        if (!array_key_exists($doc->getCacheTag(), $tags)) {
                            $tags = $doc->getCacheTags($tags);
                        }
                    }
                }
                else if ($data->getInternalType() == "asset") {
                    if ($asset = Asset::getById($data->getInternal())) {
                        if (!array_key_exists($asset->getCacheTag(), $tags)) {
                            $tags = $asset->getCacheTags($tags);
                        }
                    }
                }
            }
        }

        return $tags;
    }

    /**
     * converts object data to a simple string value or CSV Export
     * @abstract
     * @param Object_Abstract $object
     * @return string
     */
    public function getForCsvExport($object) {
        $key = $this->getName();
        $getter = "get".ucfirst($key);
        if ($object->$getter() instanceof Object_Data_Link) {
            return base64_encode(Pimcore_Tool_Serialize::serialize($object->$getter()));
        } else return null;
    }

    /**
     * fills object field data values from CSV Import String
     * @param string $importValue
     * @return Object_Class_Data_Link
     */
    public function getFromCsvImport($importValue) {
        $value = Pimcore_Tool_Serialize::unserialize(base64_decode($importValue));
        if ($value instanceof Object_Data_Link) {
            return $value;
        } else return null;

    }

    /**
     * converts data to be exposed via webservices
     * @param string $object
     * @return mixed
     */
    public function getForWebserviceExport($object) {
        $k = $this->getName();
        $getter = "get".ucfirst($k);
        if ($object->$getter() instanceof Object_Data_Link) {

            $keys = get_object_vars($object->$getter());
            foreach ($keys as $key => $value) {
                $method = "get" . ucfirst($key);
                if (!method_exists($object->$getter(), $method) or $key=="object") {
                    unset($keys[$key]);
                }
            }
            return $keys;
        } else return null;
    }

    /**
     * converts data to be imported via webservices
     * @param mixed $value
     * @return mixed
     */
    public function getFromWebserviceImport($value, $relatedObject = null, $idMapper = null) {
        if ($value instanceof stdclass) {
            $value = (array) $value;
        }

        if (empty($value)) {
            return null;
        } else if (is_array($value) and !empty($value['text']) and !empty($value['direct'])) {
            $link = new Object_Data_Link();
            foreach ($value as $key => $value) {
                $method = "set" . ucfirst($key);
                if (method_exists($link, $method)) {
                    $link->$method($value);
                } else {
                    throw new Exception("cannot get values from web service import - invalid data. Unknown Object_Data_Link setter [ " . $method . " ]");
                }
            }
            return $link;

        } else if (is_array($value) and !empty($value['text']) and !empty($value['internalType']) and !empty($value['internal'])) {
            $id = $value['internal'];

            if ($idMapper) {
                $id = $idMapper->getMappedId($value['internalType'], $id);
            }

            $element = Element_Service::getElementById($value['internalType'],$id);
            if(!$element){
                if ($idMapper && $idMapper->ignoreMappingFailures()) {
                    $idMapper->recordMappingFailure("object", $relatedObject->getId(),$value['internalType'], $value['internal']);
                    return null;
                } else {
                    throw new Exception("cannot get values from web service import - referencing unknown internal element with type [ ".$value['internalType']." ] and id [ ".$value['internal']." ]");
                }
            }

            $link = new Object_Data_Link();
            foreach ($value as $key => $value) {
                $method = "set" . ucfirst($key);
                if (method_exists($link, $method)) {
                    $link->$method($value);
                } else {
                    throw new Exception("cannot get values from web service import - invalid data. Unknown Object_Data_Link setter [ " . $method . " ]");
                }
            }
            return $link;

        } else {
            throw new Exception("cannot get values from web service import - invalid data");
        }

    }

    /** True if change is allowed in edit mode.
     * @return bool
     */
    public function isDiffChangeAllowed() {
        return true;
    }

    /** Generates a pretty version preview (similar to getVersionPreview) can be either html or
     * a image URL. See the ObjectMerger plugin documentation for details
     * @param $data
     * @param null $object
     * @return array|string
     */
    public function getDiffVersionPreview($data, $object = null) {
        if ($data) {
           if ($data->text) {
               return $data->text;
           } else if ($data->direct) {
               return $data->direct;
           }
        }
    }
}


text:
import struct
import sys
import os
import msvcrt
from   ctypes import *
from   ctypes.wintypes import HWND
from   array import *
from   time import *

def interpretRP1210Fields (bufferAsBytes,nRetVal,protocol):
	'''This function provides a way to separate out the bytes from a received RP1210 message.'''
	if "J1939" in protocol:
		timeStamp = int(struct.unpack('>L',(ucTxRxBuffer[0]+ucTxRxBuffer[1]+ucTxRxBuffer[2]+ucTxRxBuffer[3]))[0])
		PGN       = int(struct.unpack('<L',(ucTxRxBuffer[4]+ucTxRxBuffer[5]+ucTxRxBuffer[6]+b'\x00'))[0])
		HowSentAndPriority   =  int( struct.unpack( 'B', ucTxRxBuffer[7] )[0])
		priority = int( HowSentAndPriority & 0x07)
		HowSent  = int((HowSentAndPriority & 0x80) >> 7 )
		SourceAddress      = struct.unpack( 'B', ucTxRxBuffer[8]   )[0]
		DestinationAddress = struct.unpack( 'B', ucTxRxBuffer[9]   )[0]

		nDataBytes = nRetVal - 10
		print("J1939",end=",")
		print("%10i" %timeStamp, end="," )
		print(PGN, end="," )
		print(priority, end="," )
		print(HowSent, end="," )
		print(SourceAddress, end="," )
		print(DestinationAddress, end="" )
		for ucByte in ucTxRxBuffer[10:nRetVal] :
			print(",%02X" %ucByte, end="" )
		print()
	return

#define the name of the RP1210 DLL
dllName =   "DPA4PMA.DLL"

#define the protocol ID:
protocolID = 2

#define the device ID
deviceID = 1

#Load the Windows Device Library
RP1210DLL = windll.LoadLibrary( dllName )

# Define windows prototype functions:
# typedef short (WINAPI *fxRP1210_ClientConnect)       ( HWND, short, char *, long, long, short );
prototype                   = WINFUNCTYPE( c_short, HWND, c_short, c_char_p, c_long, c_long, c_short)
RP1210_ClientConnect        = prototype( ( "RP1210_ClientConnect", RP1210DLL ) )

# typedef short (WINAPI *fxRP1210_ClientDisconnect)    ( short                                  );
prototype                   = WINFUNCTYPE( c_short, c_short )
RP1210_ClientDisconnect     = prototype( ( "RP1210_ClientDisconnect", RP1210DLL ) )

# typedef short (WINAPI *fxRP1210_SendMessage)         ( short, char*, short, short, short      );
prototype                   = WINFUNCTYPE( c_short, c_short,  POINTER( c_char*2000 ), c_short, c_short, c_short      )
RP1210_SendMessage          = prototype( ("RP1210_SendMessage", RP1210DLL ) )

# typedef short (WINAPI *fxRP1210_ReadMessage)         ( short, char*, short, short             );
prototype                   = WINFUNCTYPE( c_short, c_short, POINTER( c_char*2000 ), c_short, c_short             )
RP1210_ReadMessage          = prototype( ("RP1210_ReadMessage", RP1210DLL ) )

# typedef short (WINAPI *fxRP1210_SendCommand)         ( short, short, char*, short             );
prototype                   = WINFUNCTYPE( c_short, c_short, c_short, POINTER( c_char*2000 ), c_short             )
RP1210_SendCommand          = prototype( ("RP1210_SendCommand", RP1210DLL ) )

# typedef short (WINAPI *fxRP1210_ReadVersion)         ( char*, char*, char*, char*             );
prototype                   = WINFUNCTYPE( c_short, c_char_p, c_char_p, c_char_p, c_char_p             )
RP1210_ReadVersion          = prototype( ("RP1210_ReadVersion", RP1210DLL ) )

# typedef short (WINAPI *fxRP1210_ReadDetailedVersion) ( short, char*, char*, char*             );
prototype                   = WINFUNCTYPE( c_short, c_short, POINTER(c_char*17), POINTER(c_char*17), POINTER(c_char*17) )
RP1210_ReadDetailedVersion  = prototype( ("RP1210_ReadDetailedVersion", RP1210DLL ) )

# typedef short (WINAPI *fxRP1210_GetHardwareStatus)   ( short, char*, short, short             );
prototype                   = WINFUNCTYPE( c_short, c_short, c_char_p, c_short, c_short             )
RP1210_GetHardwareStatus    = prototype( ("RP1210_GetHardwareStatus", RP1210DLL ) )

# typedef short (WINAPI *fxRP1210_GetErrorMsg)         ( short, char*                           );
prototype                   = WINFUNCTYPE( c_short, c_short, c_char_p                           )
RP1210_GetErrorMsg          = prototype( ("RP1210_GetErrorMsg", RP1210DLL ) )

# typedef short (WINAPI *fxRP1210_GetLastErrorMsg)     ( short, int *, char*, short             );
prototype                   = WINFUNCTYPE( c_short, c_void_p, c_char_p, c_short             )
RP1210_GetLastErrorMsg      = prototype( ("RP1210_GetLastErrorMsg", RP1210DLL ) )

clientNames = {} # build a dictionary of client Connect sessions

# Connect to Device
print( "Attempting connect to DLL [%s], DeviceID [%d]" %( dllName, deviceID ) )
szProtocolName = bytes("J1939:Channel=1;Baud=Auto",'ascii') #This protocol name comes from the .ini file in the Windows directory.
nClientID = RP1210_ClientConnect( HWND(None), c_short( deviceID ), szProtocolName, 0, 0, 0  )
clientNames[nClientID] = str(szProtocolName,'ascii')
print('The Client ID is: %i for Protocol: %s' %(nClientID, str(szProtocolName,'ascii') ))

# szProtocolName = bytes("J1708",'ascii') #This protocol name comes from the .ini file in the Windows directory.
# nClientID = RP1210_ClientConnect( HWND(None), c_short( deviceID ), szProtocolName, 0, 0, 0  )
# clientNames[nClientID] = str(szProtocolName,'ascii')
# print('The Client ID is: %i for Protocol: %s' %(nClientID, str(szProtocolName,'ascii') ))

#-----------------------------------------------------------------------------------------------------
# Call RP1210_ReadDetailedVersion to get DLL, API, FW versions.
#-----------------------------------------------------------------------------------------------------

chAPIVersionInfo    = (c_char*17)()
chDLLVersionInfo    = (c_char*17)()
chFWVersionInfo     = (c_char*17)()
nRetVal = RP1210_ReadDetailedVersion( c_short( nClientID ), byref( chAPIVersionInfo ), byref( chDLLVersionInfo ), byref( chFWVersionInfo ) )

if nRetVal == 0 :
   print('Congratulations! You have connected to a VDA! No need to check your USB connection.')
   print('DLL = %s' % str( chDLLVersionInfo, 'ascii' ) )
   print('API = %s' % str( chAPIVersionInfo, 'ascii' ) )
   print('FW  = %s' % str( chFWVersionInfo , 'ascii' ) )
else :
   print("ReadDetailedVersion fails with a return value of  %i" %nRetVal )

# Set all filters to pass.  This allows messages to be read.
RP1210_Set_All_Filters_States_to_Pass = 3
nRetVal = RP1210_SendCommand( c_short( RP1210_Set_All_Filters_States_to_Pass ), c_short( nClientID ), None, 0 )

if nRetVal == 0 :
   print("RP1210_Set_All_Filters_States_to_Pass - SUCCESS" )
else :
   print('RP1210_Set_All_Filters_States_to_Pass returns %i' %nRetVal )

#Read some messages:
ucTxRxBuffer = (c_char*2000)()
NON_BLOCKING_IO = 0
while True:

	if msvcrt.kbhit():
		break

	nRetVal = RP1210_ReadMessage( c_short( nClientID ), byref( ucTxRxBuffer ), c_short( 2000 ), c_short( NON_BLOCKING_IO ) )
	if nRetVal > 0:
		print("RAW", end=",")
		print(ucTxRxBuffer[:nRetVal])
		interpretRP1210Fields (ucTxRxBuffer, nRetVal, clientNames[nClientID])

# Disconnect from the VDA

input("Press Enter to Quit.")

nRetVal = RP1210_ClientDisconnect( c_short( nClientID ) )

if nRetVal == 0 :
   print("RP1210_ClientDisconnect - SUCCESS" )
else :
   print("RP1210_ClientDisconnect returns %i" %nRetVal )


text:
package com.example.helloworld.resources;

import com.example.helloworld.db.FortuneDAO;
import com.example.helloworld.db.model.Fortune;
import com.example.helloworld.resources.views.FortuneView;
import com.google.common.collect.Lists;
import io.dropwizard.hibernate.UnitOfWork;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Collections;
import java.util.List;

@Path("/fortunes")
@Produces(MediaType.TEXT_HTML + ";charset=UTF-8")
public class FortuneResource {

    private final FortuneDAO fortuneDAO;

    public FortuneResource(FortuneDAO fortuneDAO) {
        this.fortuneDAO = fortuneDAO;
    }

    @GET
    @UnitOfWork
    public FortuneView dbTest() {
        final List<Fortune> fortunes = Lists.newArrayListWithExpectedSize(32);

        fortunes.addAll(fortuneDAO.list());
        fortunes.add(new Fortune("Additional fortune added at request time."));

        Collections.sort(fortunes);
        return new FortuneView(fortunes);
    }
}


text:
using Lucene.Net.Documents;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using System.Collections.Generic;

namespace Lucene.Net.Index
{
    using NUnit.Framework;

    using BinaryDocValuesField = BinaryDocValuesField;
    using IBits = Lucene.Net.Util.IBits;
    using BytesRef = Lucene.Net.Util.BytesRef;
    using Directory = Lucene.Net.Store.Directory;
    using Document = Documents.Document;
    using Field = Field;
    using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
    using NumericDocValuesField = NumericDocValuesField;
    using SortedDocValuesField = SortedDocValuesField;
    using SortedSetDocValuesField = SortedSetDocValuesField;
    using TestUtil = Lucene.Net.Util.TestUtil;

    /// <summary>
    /// Tests MultiDocValues versus ordinary segment merging </summary>
    [SuppressCodecs("Lucene3x")]
    [TestFixture]
    public class TestMultiDocValues : LuceneTestCase
    {
        [Test]
        public virtual void TestNumerics()
        {
            Directory dir = NewDirectory();
            Document doc = new Document();
            Field field = new NumericDocValuesField("numbers", 0);
            doc.Add(field);

            IndexWriterConfig iwc = NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, null);
            iwc.SetMergePolicy(NewLogMergePolicy());
            RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwc);

            int numDocs = AtLeast(500);
            for (int i = 0; i < numDocs; i++)
            {
                field.SetInt64Value(Random().NextLong());
                iw.AddDocument(doc);
                if (Random().Next(17) == 0)
                {
                    iw.Commit();
                }
            }
            DirectoryReader ir = iw.Reader;
            iw.ForceMerge(1);
            DirectoryReader ir2 = iw.Reader;
            AtomicReader merged = GetOnlySegmentReader(ir2);
            iw.Dispose();

            NumericDocValues multi = MultiDocValues.GetNumericValues(ir, "numbers");
            NumericDocValues single = merged.GetNumericDocValues("numbers");
            for (int i = 0; i < numDocs; i++)
            {
                Assert.AreEqual(single.Get(i), multi.Get(i));
            }
            ir.Dispose();
            ir2.Dispose();
            dir.Dispose();
        }

        [Test]
        public virtual void TestBinary()
        {
            Directory dir = NewDirectory();
            Document doc = new Document();
            BytesRef @ref = new BytesRef();
            Field field = new BinaryDocValuesField("bytes", @ref);
            doc.Add(field);

            IndexWriterConfig iwc = NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, null);
            iwc.SetMergePolicy(NewLogMergePolicy());
            RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwc);

            int numDocs = AtLeast(500);
            for (int i = 0; i < numDocs; i++)
            {
                @ref.CopyChars(TestUtil.RandomUnicodeString(Random()));
                iw.AddDocument(doc);
                if (Random().Next(17) == 0)
                {
                    iw.Commit();
                }
            }
            DirectoryReader ir = iw.Reader;
            iw.ForceMerge(1);
            DirectoryReader ir2 = iw.Reader;
            AtomicReader merged = GetOnlySegmentReader(ir2);
            iw.Dispose();

            BinaryDocValues multi = MultiDocValues.GetBinaryValues(ir, "bytes");
            BinaryDocValues single = merged.GetBinaryDocValues("bytes");
            BytesRef actual = new BytesRef();
            BytesRef expected = new BytesRef();
            for (int i = 0; i < numDocs; i++)
            {
                single.Get(i, expected);
                multi.Get(i, actual);
                Assert.AreEqual(expected, actual);
            }
            ir.Dispose();
            ir2.Dispose();
            dir.Dispose();
        }

        [Test]
        public virtual void TestSorted()
        {
            Directory dir = NewDirectory();
            Document doc = new Document();
            BytesRef @ref = new BytesRef();
            Field field = new SortedDocValuesField("bytes", @ref);
            doc.Add(field);

            IndexWriterConfig iwc = NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, null);
            iwc.SetMergePolicy(NewLogMergePolicy());
            RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwc);

            int numDocs = AtLeast(500);
            for (int i = 0; i < numDocs; i++)
            {
                @ref.CopyChars(TestUtil.RandomUnicodeString(Random()));
                if (DefaultCodecSupportsDocsWithField() && Random().Next(7) == 0)
                {
                    iw.AddDocument(new Document());
                }
                iw.AddDocument(doc);
                if (Random().Next(17) == 0)
                {
                    iw.Commit();
                }
            }
            DirectoryReader ir = iw.Reader;
            iw.ForceMerge(1);
            DirectoryReader ir2 = iw.Reader;
            AtomicReader merged = GetOnlySegmentReader(ir2);
            iw.Dispose();

            SortedDocValues multi = MultiDocValues.GetSortedValues(ir, "bytes");
            SortedDocValues single = merged.GetSortedDocValues("bytes");
            Assert.AreEqual(single.ValueCount, multi.ValueCount);
            BytesRef actual = new BytesRef();
            BytesRef expected = new BytesRef();
            for (int i = 0; i < numDocs; i++)
            {
                // check ord
                Assert.AreEqual(single.GetOrd(i), multi.GetOrd(i));
                // check value
                single.Get(i, expected);
                multi.Get(i, actual);
                Assert.AreEqual(expected, actual);
            }
            ir.Dispose();
            ir2.Dispose();
            dir.Dispose();
        }

        // tries to make more dups than testSorted
        [Test]
        public virtual void TestSortedWithLotsOfDups()
        {
            Directory dir = NewDirectory();
            Document doc = new Document();
            BytesRef @ref = new BytesRef();
            Field field = new SortedDocValuesField("bytes", @ref);
            doc.Add(field);

            IndexWriterConfig iwc = NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, null);
            iwc.SetMergePolicy(NewLogMergePolicy());
            RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwc);

            int numDocs = AtLeast(500);
            for (int i = 0; i < numDocs; i++)
            {
                @ref.CopyChars(TestUtil.RandomSimpleString(Random(), 2));
                iw.AddDocument(doc);
                if (Random().Next(17) == 0)
                {
                    iw.Commit();
                }
            }
            DirectoryReader ir = iw.Reader;
            iw.ForceMerge(1);
            DirectoryReader ir2 = iw.Reader;
            AtomicReader merged = GetOnlySegmentReader(ir2);
            iw.Dispose();

            SortedDocValues multi = MultiDocValues.GetSortedValues(ir, "bytes");
            SortedDocValues single = merged.GetSortedDocValues("bytes");
            Assert.AreEqual(single.ValueCount, multi.ValueCount);
            BytesRef actual = new BytesRef();
            BytesRef expected = new BytesRef();
            for (int i = 0; i < numDocs; i++)
            {
                // check ord
                Assert.AreEqual(single.GetOrd(i), multi.GetOrd(i));
                // check ord value
                single.Get(i, expected);
                multi.Get(i, actual);
                Assert.AreEqual(expected, actual);
            }
            ir.Dispose();
            ir2.Dispose();
            dir.Dispose();
        }

        [Test]
        public virtual void TestSortedSet()
        {
            AssumeTrue("codec does not support SORTED_SET", DefaultCodecSupportsSortedSet());
            Directory dir = NewDirectory();

            IndexWriterConfig iwc = NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, null);
            iwc.SetMergePolicy(NewLogMergePolicy());
            RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwc);

            int numDocs = AtLeast(500);
            for (int i = 0; i < numDocs; i++)
            {
                Document doc = new Document();
                int numValues = Random().Next(5);
                for (int j = 0; j < numValues; j++)
                {
                    doc.Add(new SortedSetDocValuesField("bytes", new BytesRef(TestUtil.RandomUnicodeString(Random()))));
                }
                iw.AddDocument(doc);
                if (Random().Next(17) == 0)
                {
                    iw.Commit();
                }
            }
            DirectoryReader ir = iw.Reader;
            iw.ForceMerge(1);
            DirectoryReader ir2 = iw.Reader;
            AtomicReader merged = GetOnlySegmentReader(ir2);
            iw.Dispose();

            SortedSetDocValues multi = MultiDocValues.GetSortedSetValues(ir, "bytes");
            SortedSetDocValues single = merged.GetSortedSetDocValues("bytes");
            if (multi == null)
            {
                Assert.IsNull(single);
            }
            else
            {
                Assert.AreEqual(single.ValueCount, multi.ValueCount);
                BytesRef actual = new BytesRef();
                BytesRef expected = new BytesRef();
                // check values
                for (long i = 0; i < single.ValueCount; i++)
                {
                    single.LookupOrd(i, expected);
                    multi.LookupOrd(i, actual);
                    Assert.AreEqual(expected, actual);
                }
                // check ord list
                for (int i = 0; i < numDocs; i++)
                {
                    single.SetDocument(i);
                    List<long> expectedList = new List<long>();
                    long ord;
                    while ((ord = single.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS)
                    {
                        expectedList.Add(ord);
                    }

                    multi.SetDocument(i);
                    int upto = 0;
                    while ((ord = multi.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS)
                    {
                        Assert.AreEqual(expectedList[upto], ord);
                        upto++;
                    }
                    Assert.AreEqual(expectedList.Count, upto);
                }
            }

            ir.Dispose();
            ir2.Dispose();
            dir.Dispose();
        }

        // tries to make more dups than testSortedSet
        [Test]
        public virtual void TestSortedSetWithDups()
        {
            AssumeTrue("codec does not support SORTED_SET", DefaultCodecSupportsSortedSet());
            Directory dir = NewDirectory();

            IndexWriterConfig iwc = NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, null);
            iwc.SetMergePolicy(NewLogMergePolicy());
            RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwc);

            int numDocs = AtLeast(500);
            for (int i = 0; i < numDocs; i++)
            {
                Document doc = new Document();
                int numValues = Random().Next(5);
                for (int j = 0; j < numValues; j++)
                {
                    doc.Add(new SortedSetDocValuesField("bytes", new BytesRef(TestUtil.RandomSimpleString(Random(), 2))));
                }
                iw.AddDocument(doc);
                if (Random().Next(17) == 0)
                {
                    iw.Commit();
                }
            }
            DirectoryReader ir = iw.Reader;
            iw.ForceMerge(1);
            DirectoryReader ir2 = iw.Reader;
            AtomicReader merged = GetOnlySegmentReader(ir2);
            iw.Dispose();

            SortedSetDocValues multi = MultiDocValues.GetSortedSetValues(ir, "bytes");
            SortedSetDocValues single = merged.GetSortedSetDocValues("bytes");
            if (multi == null)
            {
                Assert.IsNull(single);
            }
            else
            {
                Assert.AreEqual(single.ValueCount, multi.ValueCount);
                BytesRef actual = new BytesRef();
                BytesRef expected = new BytesRef();
                // check values
                for (long i = 0; i < single.ValueCount; i++)
                {
                    single.LookupOrd(i, expected);
                    multi.LookupOrd(i, actual);
                    Assert.AreEqual(expected, actual);
                }
                // check ord list
                for (int i = 0; i < numDocs; i++)
                {
                    single.SetDocument(i);
                    List<long?> expectedList = new List<long?>();
                    long ord;
                    while ((ord = single.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS)
                    {
                        expectedList.Add(ord);
                    }

                    multi.SetDocument(i);
                    int upto = 0;
                    while ((ord = multi.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS)
                    {
                        Assert.AreEqual((long)expectedList[upto], ord);
                        upto++;
                    }
                    Assert.AreEqual(expectedList.Count, upto);
                }
            }

            ir.Dispose();
            ir2.Dispose();
            dir.Dispose();
        }

        [Test]
        public virtual void TestDocsWithField()
        {
            AssumeTrue("codec does not support docsWithField", DefaultCodecSupportsDocsWithField());
            Directory dir = NewDirectory();

            IndexWriterConfig iwc = NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, null);
            iwc.SetMergePolicy(NewLogMergePolicy());
            RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwc);

            int numDocs = AtLeast(500);
            for (int i = 0; i < numDocs; i++)
            {
                Document doc = new Document();
                if (Random().Next(4) >= 0)
                {
                    doc.Add(new NumericDocValuesField("numbers", Random().NextLong()));
                }
                doc.Add(new NumericDocValuesField("numbersAlways", Random().NextLong()));
                iw.AddDocument(doc);
                if (Random().Next(17) == 0)
                {
                    iw.Commit();
                }
            }
            DirectoryReader ir = iw.Reader;
            iw.ForceMerge(1);
            DirectoryReader ir2 = iw.Reader;
            AtomicReader merged = GetOnlySegmentReader(ir2);
            iw.Dispose();

            IBits multi = MultiDocValues.GetDocsWithField(ir, "numbers");
            IBits single = merged.GetDocsWithField("numbers");
            if (multi == null)
            {
                Assert.IsNull(single);
            }
            else
            {
                Assert.AreEqual(single.Length, multi.Length);
                for (int i = 0; i < numDocs; i++)
                {
                    Assert.AreEqual(single.Get(i), multi.Get(i));
                }
            }

            multi = MultiDocValues.GetDocsWithField(ir, "numbersAlways");
            single = merged.GetDocsWithField("numbersAlways");
            Assert.AreEqual(single.Length, multi.Length);
            for (int i = 0; i < numDocs; i++)
            {
                Assert.AreEqual(single.Get(i), multi.Get(i));
            }
            ir.Dispose();
            ir2.Dispose();
            dir.Dispose();
        }
    }
}


text:
@interface BRLiveCell ()

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *locationLabel;
@property (nonatomic, strong) UILabel *onLineLabel;
@property (nonatomic, strong) UILabel *lookLabel;
@property (nonatomic, strong) UIImageView *bigImageView;
@property (nonatomic, strong) UIImageView *liveImageView;

@end

@implementation BRLiveCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if ([super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = [UIColor groupTableViewBackgroundColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone; //选中cell时无色(没有变化)
        self.bgView.hidden = NO;
        self.headImageView.hidden = NO;
        self.nameLabel.hidden = NO;
        self.locationLabel.hidden = NO;
        self.onLineLabel.hidden = NO;
        self.lookLabel.hidden = NO;
        self.bigImageView.hidden = NO;
        self.liveImageView.hidden = NO;
    }
    return self;
}

// 重写setter方法给属性赋值
- (void)setModel:(BRLiveModel *)model {
    _model = model;
    [self.headImageView br_setImageWithPath:model.creator.portrait placeholder:@"default_room"];
    self.nameLabel.text = model.creator.nick;
    if ([NSString isBlankString:model.city]) {
        model.city = @"难道在火星?";
    }
    self.locationLabel.text = [NSString stringWithFormat:@"%@ >", model.city];
    self.onLineLabel.text = [@(model.onlineUsers) stringValue];
    [self.bigImageView br_setImageWithPath:model.creator.portrait placeholder:@"default_room"];
}

#pragma mark - 懒加载
- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc]init];
        _bgView.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:_bgView];
        [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.height.mas_equalTo(70);
        }];
    }
    return _bgView;
}

- (UIImageView *)headImageView {
    if (!_headImageView) {
        _headImageView = [[UIImageView alloc]init];
        _headImageView.layer.cornerRadius = 25.0f;
        _headImageView.layer.masksToBounds = YES;
        [self.contentView addSubview:_headImageView];
        [_headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(10);
            make.left.mas_equalTo(10);
            make.size.mas_equalTo(CGSizeMake(50, 50));
        }];
    }
    return _headImageView;
}

- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc]init];
        _nameLabel.textColor = [UIColor grayColor];
        _nameLabel.font = [UIFont systemFontOfSize:18.0f];
        [self.contentView addSubview:_nameLabel];
        __weak typeof(self) weakSelf = self;
        [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(15);
            make.left.mas_equalTo(weakSelf.headImageView.mas_right).with.offset(10);
            make.right.mas_equalTo(weakSelf.onLineLabel.mas_left);
            make.height.mas_equalTo(20);
        }];

    }
    return _nameLabel;
}

- (UILabel *)locationLabel {
    if (!_locationLabel) {
        _locationLabel = [[UILabel alloc]init];
        _locationLabel.textColor = [UIColor lightGrayColor];
        _locationLabel.font = [UIFont systemFontOfSize:14.0f];
        [self.contentView addSubview:_locationLabel];
        __weak typeof(self) weakSelf = self;
        [_locationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(weakSelf.nameLabel.mas_bottom).with.offset(5);
            make.left.mas_equalTo(weakSelf.nameLabel);
            make.size.mas_equalTo(weakSelf.nameLabel);
        }];
    }
    return _locationLabel;
}

- (UILabel *)onLineLabel {
    if (!_onLineLabel) {
        _onLineLabel = [[UILabel alloc]init];
        _onLineLabel.textColor = [UIColor orangeColor];
        _onLineLabel.font = [UIFont systemFontOfSize:18.0f];
        _onLineLabel.textAlignment = NSTextAlignmentRight;
        [self.contentView addSubview:_onLineLabel];
        [_onLineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(15);
            make.right.mas_equalTo(-10);
            make.size.mas_equalTo(CGSizeMake(80, 20));
        }];
    }
    return _onLineLabel;
}

- (UILabel *)lookLabel {
    if (!_lookLabel) {
        _lookLabel = [[UILabel alloc]init];
        _lookLabel.textColor = [UIColor lightGrayColor];
        _lookLabel.font = [UIFont systemFontOfSize:14.0f];
        _lookLabel.textAlignment = NSTextAlignmentRight;
        _lookLabel.text = @"在看";
        [self.contentView addSubview:_lookLabel];
        __weak typeof(self) weakSelf = self;
        [_lookLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(weakSelf.onLineLabel.mas_bottom).with.offset(5);
            make.right.mas_equalTo(-10);
            make.size.mas_equalTo(weakSelf.onLineLabel);
        }];
    }
    return _lookLabel;
}

- (UIImageView *)bigImageView {
    if (!_bigImageView) {
        _bigImageView = [[UIImageView alloc]init];
        [self.contentView addSubview:_bigImageView];
        [_bigImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(70);
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH));
        }];
    }
    return _bigImageView;
}

- (UIImageView *)liveImageView {
    if (!_liveImageView) {
        _liveImageView = [[UIImageView alloc]init];
        _liveImageView.image = [UIImage imageNamed:@"live_tag_live"];
        __weak typeof(self) weakSelf = self;
        [self.contentView addSubview:_liveImageView];
        [_liveImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-10);
            make.top.mas_equalTo(weakSelf.bigImageView).with.offset(10);
        }];
    }
    return _liveImageView;
}

@end


text:
#if defined (FSL_RTOS_MQX)

#include <assert.h>
#include "fsl_os_abstraction.h"

/*******************************************************************************
 * Code
 ******************************************************************************/

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_TaskCreate
 * Description   : This function is used to create a task and make it ready.
 * Return kStatus_OSA_Success if register successfully, otherwise return
 * kStatus_OSA_Error.
 *
 *END**************************************************************************/

osa_status_t OSA_TaskCreate(task_t          task,
                         uint8_t        *name,
                         uint16_t        stackSize,
                         task_stack_t   *stackMem,
                         uint16_t        priority,
                         task_param_t    param,
                         bool            usesFloat,
                         task_handler_t *handler)
{
    taskinit_t task_parameters = {
        .exec       = task,
        .stacksize  = stackSize,
        .stackaddr  = stackSize == 0 ? NULL : stackMem,
        .priority   = PRIORITY_OSA_TO_RTOS(priority),
        .exec_param = (void *)param,
    };

    *handler = create_task(&task_parameters);

    if (MQX_NULL_TASK_ID != *handler)
    {
        return kStatus_OSA_Success;
    }
    else
    {
        return kStatus_OSA_Error;
    }
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_TaskDestroy
 * Description   : This function destroy a task. Return kStatus_OSA_Success if
 * the task is destroied, otherwise return kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_TaskDestroy(task_handler_t handler)
{
    return (MQX_OK == _task_destroy(handler)) ? kStatus_OSA_Success : kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_TaskYield
 * Description   : When a task calls this function, it will give up CPU and put
 * itself to the tail of ready list.
 *
 *END**************************************************************************/
osa_status_t OSA_TaskYield(void)
{
    _sched_yield();
    return kStatus_OSA_Success;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_TaskGetHandler
 * Description   : This function is used to get current active task's handler.
 *
 *END**************************************************************************/
task_handler_t OSA_TaskGetHandler(void)
{
    return _task_get_id_from_td(_task_get_td(MQX_NULL_TASK_ID));
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_TaskGetPriority
 * Description   : This function returns task's priority by task handler.
 *
 *END**************************************************************************/
uint16_t OSA_TaskGetPriority(task_handler_t handler)
{
    _mqx_uint priority;
    _task_get_priority(handler, &priority);
    return PRIORITY_RTOS_TO_OSA(priority);
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_TaskSetPriority
 * Description   : This function sets task's priority by task handler.
 *
 *END**************************************************************************/
osa_status_t OSA_TaskSetPriority(task_handler_t handler, uint16_t priority)
{
#if MQX_HAS_DYNAMIC_PRIORITIES
    _mqx_uint oldPriority;

    if (MQX_OK == _task_set_priority(handler, PRIORITY_OSA_TO_RTOS(priority), &oldPriority))
    {
        return kStatus_OSA_Success;
    }
    else
    {
        return kStatus_OSA_Error;
    }
#else /* MQX_HAS_DYNAMIC_PRIORITIES */
    return kStatus_OSA_Error;
#endif /* MQX_HAS_DYNAMIC_PRIORITIES */
}

/*FUNCTION**********************************************************************
 *
 * Function Name : wait_timeout_msec_to_tick
 * Description   : This function converts timeout from millisecond to tick for
 * wait functions.
 *
 *END**************************************************************************/
static uint32_t wait_timeout_msec_to_tick(uint32_t timeout)
{
    if (OSA_WAIT_FOREVER == timeout)   /* Wait forever. */
    {
        return 0U; /* Timeout 0 means wait forever for MQX. */
    }
    else
    {
        timeout *= _time_get_ticks_per_sec();
        timeout /= 1000U;
        /*
         * If timeout is too short that changed to 0 tick, reset it to 1 tick
         * in case of infinitely wait.
         */
        if (!timeout)
        {
            timeout = 1U;
        }
        return timeout;
    }
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_SemaCreate
 * Description   : This function is used to create a semaphore. Return
 * kStatus_OSA_Success if create successfully, otherwise return kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_SemaCreate(semaphore_t *pSem, uint8_t initValue)
{
    return MQX_OK == _lwsem_create(pSem, initValue) ?
                     kStatus_OSA_Success            :
                     kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_SemaWait
 * Description   : This function checks the semaphore's counting value, if it is
 * positive, decreases it and returns kStatus_OSA_Success, otherwise, timeout
 * will be used for wait. The parameter timeout indicates how long should wait
 * in milliseconds. Pass OSA_WAIT_FOREVER to wait indefinitely, pass 0 will
 * return kStatus_OSA_Timeout immediately if semaphore is not positive.
 * This function returns kStatus_OSA_Success if the semaphore is received, returns
 * kStatus_OSA_Timeout if the semaphore is not received within the specified
 * 'timeout', returns kStatus_OSA_Error if any errors occur during waiting.
 *
 *END**************************************************************************/
osa_status_t OSA_SemaWait(semaphore_t *pSem, uint32_t timeout)
{
    _mqx_uint retVal;

    /* If timeout is 0, try to get the semaphore. */
    if (!timeout)
    {
        return _lwsem_poll(pSem) ? kStatus_OSA_Success : kStatus_OSA_Timeout;
    }
    else
    {
        /* If timeout is not 0, convert it to ticks. */
        timeout = wait_timeout_msec_to_tick(timeout);
        retVal = _lwsem_wait_ticks(pSem, timeout);

        if(MQX_OK == retVal)
        {
            return kStatus_OSA_Success;
        }
        else if (MQX_LWSEM_WAIT_TIMEOUT == retVal)
        {
            return kStatus_OSA_Timeout;
        }
        else
        {
            return kStatus_OSA_Error;
        }
    }
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_SemaPost
 * Description   : This function is used to wake up one task that wating on the
 * semaphore. If no task is waiting, increase the semaphore. The function returns
 * kStatus_OSA_Success if the semaphre is post successfully, otherwise returns
 * kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_SemaPost(semaphore_t *pSem)
{
    return (MQX_OK == _lwsem_post(pSem)) ? kStatus_OSA_Success : kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_SemaDestroy
 * Description   : This function is used to destroy a semaphore.
 * Return kStatus_OSA_Success if the semaphore is destroyed successfully, otherwise
 * return kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_SemaDestroy(semaphore_t *pSem)
{
    return (MQX_OK == _lwsem_destroy(pSem)) ? kStatus_OSA_Success : kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MutexCreate
 * Description   : This function is used to create a mutex.
 * Return kStatus_OSA_Success if create successfully, otherwise return
 * kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_MutexCreate(mutex_t *pMutex)
{
    if (NULL == pMutex)
    {
        return kStatus_OSA_Error;
    }

    pMutex->owner = 0U;
    return MQX_OK == _lwsem_create(&(pMutex->sema), 1) ?
                     kStatus_OSA_Success :
                     kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MutexLock
 * Description   : This function checks the mutex's status, if it is unlocked,
 * lock it and returns kStatus_OSA_Success, otherwise, wait for the mutex.
 * MQX does not support timeout to wait for a mutex.
 * This function returns kStatus_OSA_Success if the mutex is obtained, returns
 * kStatus_OSA_Error if any errors occur during waiting. If the mutex has been
 * locked, pass 0 as timeout will return kStatus_OSA_Timeout immediately.
 *
 *END**************************************************************************/
osa_status_t OSA_MutexLock(mutex_t *pMutex, uint32_t timeout)
{
    _mqx_uint retVal;
    osa_status_t ret = kStatus_OSA_Error;
    uint32_t tid = _task_get_id();

    if (NULL == pMutex)
    {
        return kStatus_OSA_Error;
    }

    /* Check whether the mutex has been locked by current task. */
    if (pMutex->owner == tid)
    {
        return kStatus_OSA_Error;
    }

    /* If timeout is 0, try to get the semaphore. */
    if (timeout == 0)
    {
        /* Ensure that the owner is updated together with mutex acquisition. */
        _int_disable();
        retVal = _lwsem_poll(&(pMutex->sema)) ? MQX_OK : MQX_LWSEM_WAIT_TIMEOUT;
    }
    else if (timeout == OSA_WAIT_FOREVER)
    {
        _int_disable();
        retVal = _lwsem_wait(&(pMutex->sema));
    }
    else
    {
        /* Convert timeout to ticks. */
        timeout = wait_timeout_msec_to_tick(timeout);
        _int_disable();
        /* Check if the conversion has overflown */
        if (timeout)
        {
            retVal = _lwsem_wait_ticks(&(pMutex->sema), timeout);
        }
        else
        {
            /* The conversion has overflown, timeout is 0 and should not be. Wait forever. */
            retVal = _lwsem_wait(&(pMutex->sema));
        }
    }

    if (MQX_OK == retVal)
    {
        pMutex->owner = tid;
        ret = kStatus_OSA_Success;
    }
    else if (MQX_LWSEM_WAIT_TIMEOUT == retVal)
    {
        ret = kStatus_OSA_Timeout;
    }
    _int_enable();

    return ret;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MutexUnlock
 * Description   : This function is used to unlock a mutex.
 *
 *END**************************************************************************/
osa_status_t OSA_MutexUnlock(mutex_t *pMutex)
{
    osa_status_t ret = kStatus_OSA_Error;

    if (NULL == pMutex)
    {
        return kStatus_OSA_Error;
    }

    /* If task does not own this mutex, it can not unlock it. */
    if (pMutex->owner != _task_get_id())
    {
        return kStatus_OSA_Error;
    }

    /* Ensure that the owner is updated together with mutex unlocking. */
    _int_disable();
    if (MQX_OK == _lwsem_post(&(pMutex->sema)))
    {
        pMutex->owner = 0U;
        ret = kStatus_OSA_Success;
    }
    _int_enable();

    return ret;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MutexDestroy
 * Description   : This function is used to destroy a mutex.
 * Return kStatus_OSA_Success if the lock object is destroyed successfully,
 * otherwise return kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_MutexDestroy(mutex_t *pMutex)
{
    osa_status_t ret;

    assert(pMutex != NULL);

    _int_disable();
    if (MQX_OK == _lwsem_destroy(&(pMutex->sema)))
    {
        pMutex->owner = 0U;
        ret = kStatus_OSA_Success;
    }
    else
    {
        ret = kStatus_OSA_Error;
    }
    _int_enable();

    return ret;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_EventCreate
 * Description   : This function is used to create a event object. Return
 * kStatus_OSA_Success if create successfully, otherwise return kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_EventCreate(event_t *pEvent, osa_event_clear_mode_t clearMode)
{
    _mqx_uint retVal;

    retVal = _lwevent_create(pEvent, (kEventAutoClear == clearMode) ? LWEVENT_AUTO_CLEAR : 0);

    return (retVal == MQX_OK) ? kStatus_OSA_Success : kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_EventWait
 * Description   : This function checks the event's status, if it meets the wait
 * condition, return kStatus_OSA_Success, otherwise, timeout will be used for
 * wait. The parameter timeout indicates how long should wait in milliseconds.
 * Pass OSA_WAIT_FOREVER to wait indefinitely, pass 0 will return the value
 * kStatus_OSA_Timeout immediately if wait condition is not met. The event flags
 * will be cleared if the event is auto clear mode. Flags that wakeup waiting
 * task could be obtained from the parameter setFlags.
 * This function returns kStatus_OSA_Success if wait condition is met, returns
 * kStatus_OSA_Timeout if wait condition is not met within the specified
 * 'timeout', returns kStatus_OSA_Error if any errors occur during waiting.
 *
 *END**************************************************************************/
osa_status_t OSA_EventWait(event_t       *pEvent,
                        event_flags_t  flagsToWait,
                        bool           waitAll,
                        uint32_t       timeout,
                        event_flags_t *setFlags)
{
    _mqx_uint retVal;

    *setFlags = 0;
    /*
     * TODO:
     * MQX lwevent doesn't provide API to poll event, so use a work around here.
     */
    if (!timeout)
    {
        _int_disable();
        if ((waitAll && ((pEvent->VALUE & flagsToWait) == flagsToWait)) ||
           ((!waitAll) && (pEvent->VALUE & flagsToWait)))
        {
            retVal = _lwevent_wait_ticks(pEvent, flagsToWait, waitAll, 1);
            _int_enable();
            if (MQX_OK == retVal)
            {
                *setFlags = _lwevent_get_signalled();
                return kStatus_OSA_Success;
            }
            else
            {
                return kStatus_OSA_Error;
            }
        }
        else
        {
            _int_enable();
            return kStatus_OSA_Timeout;
        }
    }
    else
    {
        timeout = wait_timeout_msec_to_tick(timeout);
        retVal = _lwevent_wait_ticks(pEvent, flagsToWait, waitAll, timeout);

        if (MQX_OK == retVal)
        {
            *setFlags = _lwevent_get_signalled();
            return kStatus_OSA_Success;
        }
        else if (LWEVENT_WAIT_TIMEOUT == retVal)
        {
            return kStatus_OSA_Timeout;
        }
        else
        {
            return kStatus_OSA_Error;
        }
    }
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_EventSet
 * Description   : Set one or more event flags of an event object.
 * Return kStatus_OSA_Success if set successfully, kStatus_OSA_Error if failed.
 *
 *END**************************************************************************/
osa_status_t OSA_EventSet(event_t *pEvent, event_flags_t flagsToSet)
{
    return (MQX_OK == _lwevent_set(pEvent, flagsToSet)) ?
                                    kStatus_OSA_Success :
                                    kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_EventClear
 * Description   : Clear one or more event flags of an event object.
 * Return kStatus_OSA_Success if clear successfully, kStatus_OSA_Error if failed.
 *
 *END**************************************************************************/
osa_status_t OSA_EventClear(event_t *pEvent, event_flags_t flagsToClear)
{
    return (MQX_OK == _lwevent_clear(pEvent, flagsToClear)) ?
                                        kStatus_OSA_Success :
                                        kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_EventGetFlags
 * Description   : Get event flags status.
 * Return current event flags.
 *
 *END**************************************************************************/
event_flags_t OSA_EventGetFlags(event_t *pEvent)
{
    assert(pEvent);

    return pEvent->VALUE;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_EventDestroy
 * Description   : This function is used to destroy a event object. Return
 * kStatus_OSA_Success if the event object is destroyed successfully, otherwise
 * return kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_EventDestroy(event_t *pEvent)
{
    return (MQX_OK == _lwevent_destroy(pEvent)) ? kStatus_OSA_Success : kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MsgQCreate
 * Description   : This function is used to create a message queue.
 * Return the handle to the message queue if create successfully, otherwise
 * return 0.
 *
 *END**************************************************************************/
msg_queue_handler_t OSA_MsgQCreate(msg_queue_t *queue,
                                        uint16_t  message_number,
                                        uint16_t  message_size)
{
    _mqx_uint retVal;

    /* Create the message queue where each element is a pointer to the message item. */
    retVal = _lwmsgq_init(queue, message_number, SIZE_IN_MMT_UNITS(message_size * 4));

    if (MQX_OK == retVal)
    {
        return (msg_queue_handler_t)queue;
    }
    else
    {
        return (msg_queue_handler_t)NULL;
    }
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MsgQPut
 * Description   : This function is used to put a message to a message queue.
 * Return kStatus_OSA_Success if the message is put successfully, otherwise
 * return kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_MsgQPut(msg_queue_handler_t handler, void* pMessage)
{
    /* Does not block if full */
    return (MQX_OK == _lwmsgq_send(handler, (_mqx_max_type_ptr)pMessage, 0)) ?
                                                         kStatus_OSA_Success :
                                                         kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MsgQGet
 * Description   : This function checks the queue's status, if it is not empty,
 * get message from it and return kStatus_OSA_Success, otherwise, timeout will
 * be used for wait. The parameter timeout indicates how long should wait in
 * milliseconds. Pass OSA_WAIT_FOREVER to wait indefinitely, pass 0 will return
 * kStatus_OSA_Timeout immediately if queue is empty.
 * This function returns kStatus_OSA_Success if message is got successfully,
 * returns kStatus_OSA_Timeout if message queue is empty within the specified
 * 'timeout', returns kStatus_OSA_Error if any errors occur during waiting.
 *
 *END**************************************************************************/
osa_status_t OSA_MsgQGet(msg_queue_handler_t handler,
                           void               *pMessage,
                           uint32_t            timeout)
{
    _mqx_uint retVal;

    if(!timeout)
    {
        retVal = _lwmsgq_receive(handler, (_mqx_max_type_ptr)pMessage, 0, 0, NULL);
    }
    else
    {
        timeout = wait_timeout_msec_to_tick(timeout);
        retVal = _lwmsgq_receive(handler, (_mqx_max_type_ptr)pMessage,
                LWMSGQ_RECEIVE_BLOCK_ON_EMPTY, timeout, NULL);
    }

    if (MQX_OK == retVal)
    {
        return kStatus_OSA_Success;
    }
    else if ((LWMSGQ_TIMEOUT == retVal) || (LWMSGQ_EMPTY == retVal))
    {
        return kStatus_OSA_Timeout;
    }
    else
    {
        return kStatus_OSA_Error;
    }
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MsgQDestroy
 * Description   : This function is used to destroy the message queue.
 * Return kStatus_OSA_Success if the message queue is destroyed successfully,
 * otherwise return kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_MsgQDestroy(msg_queue_handler_t handler)
{
    return (MQX_OK == _lwmsgq_deinit(handler)) ? kStatus_OSA_Success : kStatus_OSA_Error;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MemAlloc
 * Description   : This function is used to allocate amount of memory in bytes.
 * Return the pointer to the memory if success, otherwise return NULL;
 *
 *END**************************************************************************/
void * OSA_MemAlloc(size_t size)
{
     /* We allocate memory as a system, not as a calling task. That will prevent
      * us from failures during freeing the same memory from another task.
      */
#if MQXCFG_ALLOCATOR
    return _mem_alloc_system(size);
#else
    return NULL;
#endif //MQXCFG_ALLOCATOR
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MemAllocZero
 * Description   : This function is used to allocate amount of memory in bytes
 * and initializes it to 0.
 * Return the pointer to the memory if success, otherwise return NULL;
 *
 *END**************************************************************************/
void * OSA_MemAllocZero(size_t size)
{
#if MQXCFG_ALLOCATOR
    return _mem_alloc_system_zero(size);
#else
    return NULL;
#endif //MQXCFG_ALLOCATOR
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_MemFree
 * Description   : This function is used to free the memory previously allocated.
 *
 *END**************************************************************************/
osa_status_t OSA_MemFree(void *ptr)
{
#if MQXCFG_ALLOCATOR
    return MQX_OK == _mem_free(ptr) ? kStatus_OSA_Success : kStatus_OSA_Error;
#else
    return kStatus_OSA_Error;
#endif //MQXCFG_ALLOCATOR
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_EnterCritical
 * Description   : This function is used to ensure some code will not be preempted.
 *
 *END**************************************************************************/
void OSA_EnterCritical(osa_critical_section_mode_t mode)
{
    if (kCriticalDisableInt == mode)
    {
        _int_disable();
    }
    else
    {
        _task_stop_preemption();
    }
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_ExitCritical
 * Description   : This function is used to exit critical section.
 *
 *END**************************************************************************/
void OSA_ExitCritical(osa_critical_section_mode_t mode)
{
    if (kCriticalDisableInt == mode)
    {
        _int_enable();
    }
    else
    {
        _task_start_preemption();
    }
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_TimeDelay
 * Description   : This function is used to delay for a number of milliseconds.
 *
 *END**************************************************************************/
void OSA_TimeDelay(uint32_t delay)
{
    _time_delay(delay);
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_TimeGetMsec
 * Description   : This function gets current time in milliseconds.
 *
 *END**************************************************************************/
uint32_t OSA_TimeGetMsec(void)
{
    /*
     * NOTE: Time overflow is not checked.
     */
    bool overflow;
    MQX_TICK_STRUCT tickStruct;
    _time_get_elapsed_ticks(&tickStruct);
    return(PSP_TICKS_TO_MILLISECONDS(&tickStruct, &overflow));
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_InstallIntHandler
 * Description   : This function is used to install interrupt handler.
 *
 *END**************************************************************************/
osa_status_t OSA_InstallIntHandler (int32_t IRQNumber,
                                                        void (*handler)(void))
{
    // For MISRA 2004 11.1.
#if defined ( __IAR_SYSTEMS_ICC__ )
_Pragma ("diag_suppress = Pm138")
#endif
    if (!_int_install_isr(IRQNumber, (INT_ISR_FPTR)handler, NULL))
#if defined ( __IAR_SYSTEMS_ICC__ )
_Pragma ("diag_default = PM138")
#endif
    {
        return kStatus_OSA_Error;
    }
    else
    {
        return kStatus_OSA_Success;
    }
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_Init
 * Description   : This function is used to setup the basic services, it should
 * be called first in function main. Return kStatus_OSA_Success if services
 * are initialized successfully, otherwise return kStatus_OSA_Error.
 *
 *END**************************************************************************/
osa_status_t OSA_Init(void)
{
    #if MQX_CUSTOM_MAIN
        extern MQX_INITIALIZATION_STRUCT MQX_init_struct;
        return MQX_OK == mqx_init(&MQX_init_struct) ? kStatus_OSA_Success : kStatus_OSA_Error;
    #else /* MQX_CUSTOM_MAIN */
        return kStatus_OSA_Success;
    #endif /* MQX_CUSTOM_MAIN */
}

/*FUNCTION**********************************************************************
 *
 * Function Name : OSA_Start
 * Description   : This function is used to start RTOS scheduler.
 *
 *END**************************************************************************/
osa_status_t OSA_Start(void)
{
    #if MQX_CUSTOM_MAIN
        return MQX_OK == mqx_start() ? kStatus_OSA_Success : kStatus_OSA_Error;
    #else /* MQX_CUSTOM_MAIN */
        return kStatus_OSA_Success;
    #endif /* MQX_CUSTOM_MAIN */
}

#endif
/*******************************************************************************
 * EOF
 ******************************************************************************/


text:
from typing import *

import json

from edb.pgsql import ast as pgast

from .exceptions import PSqlUnsupportedError
from .parser import pg_parse
from .ast_builder import build_queries

def parse(sql_query: str) -> List[pgast.Query]:
    ast_json = pg_parse(bytes(sql_query, encoding="UTF8"))

    try:
        return build_queries(json.loads(ast_json), sql_query)
    except IndexError:
        raise PSqlUnsupportedError()


text:
<?php

$_test_dir = realpath(dirname(__FILE__).'/..');

require_once(dirname(__FILE__).'/../../../../config/ProjectConfiguration.class.php');
$configuration = new ProjectConfiguration();
include($configuration->getSymfonyLibDir().'/vendor/lime/lime.php');

$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'test', true);
$context = sfContext::createInstance($configuration);


text:
RandomData
==========

A quick project to create data for a friend's EMR system.

Modify `template.json` or specify your own template in settings.py to create data in any form you wish.


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

package com.google.gerrit.extensions.api.changes;

import com.google.gerrit.extensions.restapi.NotImplementedException;
import com.google.gerrit.extensions.restapi.RestApiException;
import java.util.Map;

public interface ReviewerApi {

  Map<String, Short> votes() throws RestApiException;

  void deleteVote(String label) throws RestApiException;

  void deleteVote(DeleteVoteInput input) throws RestApiException;

  void remove() throws RestApiException;

  void remove(DeleteReviewerInput input) throws RestApiException;

  /**
   * A default implementation which allows source compatibility when adding new methods to the
   * interface.
   */
  class NotImplemented implements ReviewerApi {
    @Override
    public Map<String, Short> votes() throws RestApiException {
      throw new NotImplementedException();
    }

    @Override
    public void deleteVote(String label) throws RestApiException {
      throw new NotImplementedException();
    }

    @Override
    public void deleteVote(DeleteVoteInput input) throws RestApiException {
      throw new NotImplementedException();
    }

    @Override
    public void remove() throws RestApiException {
      throw new NotImplementedException();
    }

    @Override
    public void remove(DeleteReviewerInput input) throws RestApiException {
      throw new NotImplementedException();
    }
  }
}