text:
package com.ibm.websphere.samples.daytrader.web.prims;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ibm.websphere.samples.daytrader.util.Log;

/**
 *
 * PingHTTPSession3 tests the servers ability to manage and persist large
 * HTTPSession data objects. The servlet creates the large custom java object
 * {@link PingSession3Object}. This large session object is retrieved and stored
 * to the session on each user request. The default settings result in approx
 * 2024 bits being retrieved and stored upon each request.
 *
 */
@WebServlet(name = "PingSession3", urlPatterns = { "/servlet/PingSession3" })
public class PingSession3 extends HttpServlet {
    private static final long serialVersionUID = -6129599971684210414L;
    private static int NUM_OBJECTS = 2;
    private static String initTime = null;
    private static int hitCount = 0;

    /**
     * forwards post requests to the doGet method Creation date: (11/6/2000
     * 10:52:39 AM)
     *
     * @param res
     *            javax.servlet.http.HttpServletRequest
     * @param res2
     *            javax.servlet.http.HttpServletResponse
     */
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }

    /**
     * this is the main method of the servlet that will service all get
     * requests.
     *
     * @param request
     *            HttpServletRequest
     * @param responce
     *            HttpServletResponce
     **/
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        // Using a StringBuffer to output all at once.
        StringBuffer outputBuffer = new StringBuffer();
        HttpSession session = null;
        PingSession3Object[] sessionData;
        response.setContentType("text/html");

        // this is a general try/catch block. The catch block at the end of this
        // will forward the responce
        // to an error page if there is an exception
        try {

            try {
                session = request.getSession(true);
            } catch (Exception e) {
                Log.error(e, "PingSession3.doGet(...): error getting session");
                // rethrow the exception for handling in one place.
                throw e;

            }
            // Each PingSession3Object in the PingSession3Object array is 1K in
            // size
            // NUM_OBJECTS sets the size of the array to allocate and thus set
            // the size in KBytes of the session object
            // NUM_OBJECTS can be initialized by the servlet
            // Here we check for the request parameter to change the size and
            // invalidate the session if it exists
            // NOTE: Current user sessions will remain the same (i.e. when
            // NUM_OBJECTS is changed, all user thread must be restarted
            // for the change to fully take effect

            String num_objects;
            if ((num_objects = request.getParameter("num_objects")) != null) {
                // validate input
                try {
                    int x = Integer.parseInt(num_objects);
                    if (x > 0) {
                        NUM_OBJECTS = x;
                    }
                } catch (Exception e) {
                    Log.error(e, "PingSession3.doGet(...): input should be an integer, input=" + num_objects);
                } // revert to current value on exception

                outputBuffer.append(" Session object size set to " + NUM_OBJECTS + "K bytes ");
                if (session != null) {
                    session.invalidate();
                }
                out.print(outputBuffer.toString());
                out.close();
                return;
            }

            // Get the session data value
            sessionData = (PingSession3Object[]) session.getAttribute("sessiontest.sessionData");
            if (sessionData == null) {
                sessionData = new PingSession3Object[NUM_OBJECTS];
                for (int i = 0; i < NUM_OBJECTS; i++) {
                    sessionData[i] = new PingSession3Object();
                }
            }

            session.setAttribute("sessiontest.sessionData", sessionData);

            // Each PingSession3Object is about 1024 bits, there are 8 bits in a
            // byte.
            int num_bytes = (NUM_OBJECTS * 1024) / 8;
            response.setHeader("SessionTrackingTest-largeSessionData", num_bytes + "bytes");

            outputBuffer
                    .append("<title>Session Large Data Test</title>

HTTP Session Test 3: Large Data
Init time: ")
                    .append(initTime).append("

");
            hitCount++;
            outputBuffer.append("Hit Count: ").append(hitCount)
                    .append("
Session object updated. Session Object size = " + num_bytes + " bytes ");
            // output the Buffer to the printWriter.
            out.println(outputBuffer.toString());

        } catch (Exception e) {
            // log the excecption
            Log.error(e, "PingSession3.doGet(..l.): error.");
            // set the server responce to 500 and forward to the web app defined
            // error page
            response.sendError(500, "PingSession3.doGet(...): error. " + e.toString());
        }
    }

    /**
     * returns a string of information about the servlet
     *
     * @return info String: contains info about the servlet
     **/
    @Override
    public String getServletInfo() {
        return "HTTP Session Object: Tests management of a large custom session class";
    }

    /**
     * called when the class is loaded to initialize the servlet
     *
     * @param config
     *            ServletConfig:
     **/
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        hitCount = 0;
        initTime = new java.util.Date().toString();

    }
}


text:
require 'spec_helper'

describe Gitlab::GitRefValidator do
  it { expect(described_class.validate('feature/new')).to be_truthy }
  it { expect(described_class.validate('implement_@all')).to be_truthy }
  it { expect(described_class.validate('my_new_feature')).to be_truthy }
  it { expect(described_class.validate('my-branch')).to be_truthy }
  it { expect(described_class.validate('#1')).to be_truthy }
  it { expect(described_class.validate('feature/refs/heads/foo')).to be_truthy }
  it { expect(described_class.validate('feature/~new/')).to be_falsey }
  it { expect(described_class.validate('feature/^new/')).to be_falsey }
  it { expect(described_class.validate('feature/:new/')).to be_falsey }
  it { expect(described_class.validate('feature/?new/')).to be_falsey }
  it { expect(described_class.validate('feature/*new/')).to be_falsey }
  it { expect(described_class.validate('feature/[new/')).to be_falsey }
  it { expect(described_class.validate('feature/new/')).to be_falsey }
  it { expect(described_class.validate('feature/new.')).to be_falsey }
  it { expect(described_class.validate('feature\@{')).to be_falsey }
  it { expect(described_class.validate('feature\new')).to be_falsey }
  it { expect(described_class.validate('feature//new')).to be_falsey }
  it { expect(described_class.validate('feature new')).to be_falsey }
  it { expect(described_class.validate('refs/heads/')).to be_falsey }
  it { expect(described_class.validate('refs/remotes/')).to be_falsey }
  it { expect(described_class.validate('refs/heads/feature')).to be_falsey }
  it { expect(described_class.validate('refs/remotes/origin')).to be_falsey }
  it { expect(described_class.validate('-')).to be_falsey }
  it { expect(described_class.validate('-branch')).to be_falsey }
  it { expect(described_class.validate('.tag')).to be_falsey }
  it { expect(described_class.validate('my branch')).to be_falsey }
end

redpajama_set_name: RedPajamaGithub


text:
<title>
products
</title>
<?php
    require_once('auth.php');
?>
 <link href="css/bootstrap.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="css/DT_bootstrap.css">

  <link rel="stylesheet" href="css/font-awesome.min.css">

    <link href="css/bootstrap-responsive.css" rel="stylesheet">

<link href="../style.css" media="screen" rel="stylesheet" type="text/css" />

<link href="src/facebox.css" media="screen" rel="stylesheet" type="text/css" />

<?php
function createRandomPassword() {
    $chars = "003232303232023232023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;
    while ($i <= 7) {

        $num = rand() % 33;

        $tmp = substr($chars, $num, 1);

        $pass = $pass . $tmp;

        $i++;

    }
    return $pass;
}
$finalcode='INV-'.createRandomPassword();
?>

<?php include('navfixed.php');?>

             products

<button class="btn btn-success btn-large" style="float: left;"> Back</button>

<input type="text" name="filter" style="padding:15px;" id="filter" placeholder="Search product..." autocomplete="off" />

             brand name
             generic name
             batch no
             expiry date
             quantity
             action

            <?php
                include('../connect.php');
                $start=0;
                $limit=10;
                if(isset($_GET['id']))
{
    $id=$_GET['id'];
    $start=($id-1)*$limit;
}
else{
    $id=1;
}
                $result = $db->prepare("SELECT* FROM products RIGHT OUTER JOIN batch ON batch.product_id=products.product_id ORDER BY product_code DESC, expirydate  ASC");
                $result->execute();
                for($i=0; $row = $result->fetch(); $i++){
            ?>

            <?php echo $row['product_code']; ?>
            <?php echo $row['gen_name']; ?>
            <?php echo $row['batch_no']; ?>
            <?php echo $row['expirydate']; ?>
            <?php echo $row['quantity']; ?>

            <?php
$position=$_SESSION['SESS_LAST_NAME'];
if($position=='admin') {
?>
<a  title="Click To Edit batch" rel="facebox" href="editbatch.php?id=<?php echo $row['id']; ?>"><button class="btn btn-warning btn-mini"> Edit </button>

            <?php
                }
            ?>
            <?php
$position=$_SESSION['SESS_LAST_NAME'];
if($position=='pharmacist') {
?>

            <?php } }

            ?>

<?php

            include('../connect.php');
                $result = $db->prepare("SELECT* FROM products RIGHT OUTER JOIN batch ON batch.product_id=products.product_id");
                $result->execute();
                $rowcount123 = $result->rowcount();

//calculate total page number for the given table in the database
$total=ceil($rowcount123/$limit); ?>

<?php if($id>1)
{
    //Go to previous page to show previous 10 items. If its in page 1 then it is inactive
    echo "<button class='btn btn-primary'>PREVIOUS</button>";
}
if($id!=$total)
{
    ////Go to previous page to show next 10 items.
    echo "<button class='btn btn-primary'>NEXT</button>";
}
?>

<?php
//show all the page link with page number. When click on these numbers go to particular page.
        for($i=1;$i<=$total;$i++)
        {
            if($i==$id) { echo "<button class='active'>".$i."</button>"; }

            else { echo "<button class='btn btn-primary'>".$i."</button>"; }
        }
?>

<?php include('footer.php');?>


text:
import pyb, ustruct

text = "Hello World!\n"
data = ustruct.pack("<%ds" % len(text), text)
# Use "ustruct" to build data packets to send.
# "<" puts the data in the struct in little endian order.
# "%ds" puts a string in the data stream. E.g. "13s" for "Hello World!\n" (13 chars).
# See https://docs.python.org/3/library/struct.html

# READ ME!!!
#
# Please understand that when your OpenMV Cam is not the I2C master it may miss responding to
# sending data as a I2C slave no matter if you call "i2c.send()" in an interupt callback or in the
# main loop below. When this happens the Arduino will get a NAK and have to try reading from the
# OpenMV Cam again. Note that both the Arduino and OpenMV Cam I2C drivers are not good at getting
# unstuck after encountering any I2C errors. On the OpenMV Cam and Arduino you can recover by
# de-initing and then re-initing the I2C peripherals.

# The hardware I2C bus for your OpenMV Cam is always I2C bus 2.
bus = pyb.I2C(2, pyb.I2C.SLAVE, addr=0x12)
bus.deinit() # Fully reset I2C device...
bus = pyb.I2C(2, pyb.I2C.SLAVE, addr=0x12)
print("Waiting for Arduino...")

# Note that for sync up to work correctly the OpenMV Cam must be running this script before the
# Arduino starts to poll the OpenMV Cam for data. Otherwise the I2C byte framing gets messed up,
# and etc. So, keep the Arduino in reset until the OpenMV Cam is "Waiting for Arduino...".

while(True):
    try:
        bus.send(ustruct.pack("<h", len(data)), timeout=10000) # Send the len first (16-bits).
        try:
            bus.send(data, timeout=10000) # Send the data second.
            print("Sent Data!") # Only reached on no error.
        except OSError as err:
            pass # Don't care about errors - so pass.
            # Note that there are 3 possible errors. A timeout error, a general purpose error, or
            # a busy error. The error codes are 116, 5, 16 respectively for "err.arg[0]".
    except OSError as err:
        pass # Don't care about errors - so pass.
        # Note that there are 3 possible errors. A timeout error, a general purpose error, or
        # a busy error. The error codes are 116, 5, 16 respectively for "err.arg[0]".

###################################################################################################
# Arduino Code
###################################################################################################
#
# #include <Wire.h>
# #define BAUD_RATE 19200
# #define CHAR_BUF 128
#
# void setup() {
#   Serial.begin(BAUD_RATE);
#   Wire.begin();
#   delay(1000); // Give the OpenMV Cam time to bootup.
# }
#
# void loop() {
#   int32_t temp = 0;
#   char buff[CHAR_BUF] = {0};
#
#   Wire.requestFrom(0x12, 2);
#   if(Wire.available() == 2) { // got length?
#
#     temp = Wire.read() | (Wire.read() << 8);
#     delay(1); // Give some setup time...
#
#     Wire.requestFrom(0x12, temp);
#     if(Wire.available() == temp) { // got full message?
#
#       temp = 0;
#       while(Wire.available()) buff[temp++] = Wire.read();
#
#     } else {
#       while(Wire.available()) Wire.read(); // Toss garbage bytes.
#     }
#   } else {
#     while(Wire.available()) Wire.read(); // Toss garbage bytes.
#   }
#
#   Serial.print(buff);
#   delay(1); // Don't loop to quickly.
# }


text:
package com.patrick.disruptoromssettlement.service.impl;

import com.client.bean.order.CmdType;
import com.client.bean.order.OrderCmd;
import com.client.bean.order.OrderDirection;
import com.client.bean.order.OrderType;
import com.patrick.disruptoromssettlement.bean.res.OrderInfo;
import com.patrick.disruptoromssettlement.bean.res.PosiInfo;
import com.patrick.disruptoromssettlement.bean.res.TradeInfo;
import com.patrick.disruptoromssettlement.config.AppConfig;
import com.patrick.disruptoromssettlement.config.GatewayConn;
import com.patrick.disruptoromssettlement.service.IOrderService;
import com.patrick.disruptoromssettlement.util.DbUtil;
import com.patrick.disruptoromssettlement.util.IDConverter;
import io.vertx.core.buffer.Buffer;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.patrick.disruptoromssettlement.bean.MatchDataConsumer.ORDER_DATA_CACHE_ADDR;

@Log4j2
@Component
public class OrderServiceImpl implements IOrderService {
    @Override
    public Long getBalance(long uid) {
        return DbUtil.getBalance(uid);
    }

    @Override
    public List<PosiInfo> getPostList(long uid) {
        return DbUtil.getPosiList(uid);
    }

    @Override
    public List<OrderInfo> getOrderList(long uid) {
        return DbUtil.getOrderList(uid);
    }

    @Override
    public List<TradeInfo> getTradeList(long uid) {
        return DbUtil.getTradeList(uid);
    }

    @Autowired
    private AppConfig config;

    @Autowired
    private GatewayConn gatewayConn;

    @Override
    public boolean sendOrder(long uid, short type, long timestamp, int code,
                             byte direction, long price, long volume, byte ordertype) {
        final OrderCmd orderCmd = OrderCmd.builder()
                .type(CmdType.of(type))
                .timestamp(timestamp)
                .mid(config.getId())
                .uid(uid)
                .code(code)
                .direction(OrderDirection.of(direction))
                .price(price)
                .volume(volume)
                .orderType(OrderType.of(ordertype))
                .build();

        //1.入库
        int oid = DbUtil.saveOrder(orderCmd);
        if(oid < 0){
            return false;
        }else {
            //TODO 发送网关
            //1.调整资金持仓数据
            if (orderCmd.direction == OrderDirection.BUY) {
                DbUtil.minusBalance(orderCmd.uid, orderCmd.volume * orderCmd.volume);
            } else if(orderCmd.direction == OrderDirection.SELL) {
                DbUtil.minusPosi(orderCmd.uid, orderCmd.code, orderCmd.volume, orderCmd.price);
            } else {
                log.error("wrong direction[{}], ordercmd:{}", orderCmd.direction, orderCmd);
            }
            //2.生成全局ID  组装ID long[int(柜台ID),int(委托ID,数据库中的主键)]
            orderCmd.oid = IDConverter.combineInt2Long(config.getId(), oid);

            //存入缓存
            byte[] serialize = null;
            try {
                serialize = config.getBodyCodec().serialize(orderCmd);
            } catch (Exception e) {
                log.error(e);
            }
            if (serialize == null) {
                return false;
            }
            config.getVertx().eventBus().send(ORDER_DATA_CACHE_ADDR, Buffer.buffer(serialize));

            //3。打包委托,发送数据(OrderCmd -> CommonMsg -> TCP数据流)
            //4. 发送数据
            gatewayConn.sendOrder(orderCmd);

            log.info(orderCmd);

            return true;
        }
    }

    @Override
    public boolean cancelOrder(int uid, int counteroid, int code) {

        final OrderCmd orderCmd = OrderCmd.builder()
                .uid(uid)
                .code(code)
                .type(CmdType.CANCEL_ORDER)
                .oid(IDConverter.combineInt2Long(config.getId(), counteroid))
                .build();

        log.info("recv cancel order :{}", orderCmd);
        gatewayConn.sendOrder(orderCmd);
        return true;
    }
}


text:
package com.liuguangqiang.idaily.adapter.ItemProvider;

import androidx.databinding.DataBindingUtil;

import com.chad.library.adapter.base.provider.BaseItemProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.liuguangqiang.idaily.R;
import com.liuguangqiang.idaily.databinding.ItemStoryBinding;
import com.liuguangqiang.idaily.entity.Story;
import com.liuguangqiang.idaily.adapter.StoriesAdapter;

import org.jetbrains.annotations.NotNull;

import timber.log.Timber;

/**
 * Created by Eric at 2021/8/2
 */
public class StoryItemProvider<T> extends BaseItemProvider<Story> {

    @Override
    public int getItemViewType() {
        return StoriesAdapter.ITEM_STORY;
    }

    @Override
    public int getLayoutId() {
        return R.layout.item_story;
    }

    @Override
    public void onViewHolderCreated(BaseViewHolder viewHolder, int viewType) {
        DataBindingUtil.bind(viewHolder.itemView);
    }

    @Override
    public void convert(@NotNull BaseViewHolder helper, @NotNull Story data) {
        Timber.d("StoryItemProvider convert");
        ItemStoryBinding binding = DataBindingUtil.getBinding(helper.itemView);
        if (binding != null) {
            Timber.d("StoryItemProvider binding");
            binding.setStory(data);
            binding.executePendingBindings();
        }
    }

}


text:
BSLS_IDENT_RCSID(bbldc_basicdaycountutil_cpp,"$Id$ $CSID$")

#include <bbldc_basicactual360.h>
#include <bbldc_basicactual365fixed.h>
#include <bbldc_basicisdaactualactual.h>
#include <bbldc_basicisma30360.h>
#include <bbldc_basicnl365.h>
#include <bbldc_basicpsa30360eom.h>
#include <bbldc_basicsia30360eom.h>
#include <bbldc_basicsia30360neom.h>
#include <bbldc_terminatedisda30360eom.h>

#include <bdlt_date.h>

#include <bsls_assert.h>

namespace BloombergLP {
namespace bbldc {

                         // ------------------------
                         // struct BasicDayCountUtil
                         // ------------------------

// CLASS METHODS
int BasicDayCountUtil::daysDiff(const bdlt::Date&        beginDate,
                                const bdlt::Date&        endDate,
                                DayCountConvention::Enum convention)
{
    int numDays;

    switch (convention) {
      case DayCountConvention::e_ACTUAL_360: {
        numDays = bbldc::BasicActual360::daysDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_ACTUAL_365_FIXED: {
        numDays = bbldc::BasicActual365Fixed::daysDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_ISDA_30_360_EOM: {
        numDays = bbldc::TerminatedIsda30360Eom::daysDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_ISDA_ACTUAL_ACTUAL: {
        numDays = bbldc::BasicIsdaActualActual::daysDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_ISMA_30_360: {
        numDays = bbldc::BasicIsma30360::daysDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_NL_365: {
        numDays = bbldc::BasicNl365::daysDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_PSA_30_360_EOM: {
        numDays = bbldc::BasicPsa30360Eom::daysDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_SIA_30_360_EOM: {
        numDays = bbldc::BasicSia30360Eom::daysDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_SIA_30_360_NEOM: {
        numDays = bbldc::BasicSia30360Neom::daysDiff(beginDate, endDate);
      } break;
      default: {
        BSLS_ASSERT_OPT(0 && "Unrecognized convention");
        numDays = 0;
      } break;
    }

    return numDays;
}

bool BasicDayCountUtil::isSupported(DayCountConvention::Enum convention)
{
    bool rv = true;

    switch (convention) {
      case DayCountConvention::e_ACTUAL_360:
      case DayCountConvention::e_ACTUAL_365_FIXED:
      case DayCountConvention::e_ISDA_30_360_EOM:
      case DayCountConvention::e_ISDA_ACTUAL_ACTUAL:
      case DayCountConvention::e_ISMA_30_360:
      case DayCountConvention::e_NL_365:
      case DayCountConvention::e_PSA_30_360_EOM:
      case DayCountConvention::e_SIA_30_360_EOM:
      case DayCountConvention::e_SIA_30_360_NEOM: {
      } break;
      default: {
        rv = false;
      } break;
    }

    return rv;
}

double BasicDayCountUtil::yearsDiff(const bdlt::Date&        beginDate,
                                    const bdlt::Date&        endDate,
                                    DayCountConvention::Enum convention)
{
    double numYears;

    switch (convention) {
      case DayCountConvention::e_ACTUAL_360: {
        numYears = bbldc::BasicActual360::yearsDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_ACTUAL_365_FIXED: {
        numYears = bbldc::BasicActual365Fixed::yearsDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_ISDA_30_360_EOM: {
        numYears = bbldc::TerminatedIsda30360Eom::yearsDiff(beginDate,
                                                            endDate);
      } break;
      case DayCountConvention::e_ISDA_ACTUAL_ACTUAL: {
        numYears = bbldc::BasicIsdaActualActual::yearsDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_ISMA_30_360: {
        numYears = bbldc::BasicIsma30360::yearsDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_NL_365: {
        numYears = bbldc::BasicNl365::yearsDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_PSA_30_360_EOM: {
        numYears = bbldc::BasicPsa30360Eom::yearsDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_SIA_30_360_EOM: {
        numYears = bbldc::BasicSia30360Eom::yearsDiff(beginDate, endDate);
      } break;
      case DayCountConvention::e_SIA_30_360_NEOM: {
        numYears = bbldc::BasicSia30360Neom::yearsDiff(beginDate, endDate);
      } break;
      default: {
        BSLS_ASSERT_OPT(0 && "Unrecognized convention");
        numYears = 0.0;
      } break;
    }

    return numYears;
}

}  // close package namespace
}  // close enterprise namespace

// ----------------------------------------------------------------------------
// Copyright 2016 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------


text:
<?php

namespace Acme\Task\Infrastructure\Persistence\Doctrine;

use Acme\Task\Query\Repository\TaskViewModelRepositoryInterface;
use Acme\Task\Query\ViewModel\TaskViewModel;
use Acme\Task\Query\ViewModel\TaskViewModelCollection;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\SchemaException;
use Doctrine\DBAL\Schema\Schema;

class TaskViewModelDoctrineDbalRepository implements TaskViewModelRepositoryInterface
{
    protected $connection;
    protected $tableName;

    /**
     * Constructor
     *
     * @param Connection $connection
     * @param string     $tableName
     */
    public function __construct(Connection $connection, $tableName = 'tasks_views')
    {
        $this->connection = $connection;
        $this->tableName = $tableName;
    }

    /**
     * {@inheritDoc}
     */
    public function save(TaskViewModel $taskViewModel)
    {
        $data = $taskViewModel->toArray();

        $this->connection->insert($this->tableName, $data);
    }

    /**
     * {@inheritDoc}
     */
    public function getByTaskId($id)
    {
        return $this->em->getRepository($this->class)->find($id);
    }

    /**
     * {@inheritDoc}
     */
    public function getList($offset, $limit)
    {
        $rows = $this->connection->fetchAll(sprintf(
            'SELECT * FROM %s LIMIT %d, %d', $this->tableName, $offset, $limit));

        if (!$rows) {
            return null;
        }

        $collection = new TaskViewModelCollection(array(), $offset, $limit, count($rows));
        foreach($rows as $row) {
            $collection->add(new TaskViewModel(array(
                'id' => $row['id'],
                'content' => $row['content'],
            )));
        }

        return $collection;
    }

    /**
     * Creates task view model table in the database
     */
    public function createTable()
    {
        $schema = new Schema();
        $table = $schema->createTable($this->tableName);
        $table->addColumn('id', 'string', array('length' => 64, 'nullable' => false, 'unique' => true));
        $table->addColumn('content', 'string', array('length' => 255, 'nullable' => false));
        $table->setPrimaryKey(array('id'));

        foreach ($schema->toSql($this->connection->getDatabasePlatform()) as $sql) {
            $this->connection->exec($sql);
        }
    }
}


text:
require "rails_helper"

RSpec.describe Message, type: :model do
  subject { build(:message) }

  it { is_expected.to respond_to(:name) }
  it { is_expected.to respond_to(:email) }
  it { is_expected.to respond_to(:content) }

  it { is_expected.to be_valid }

  it { is_expected.to validate_presence_of(:name) }
  it { is_expected.to validate_presence_of(:email) }
  it { is_expected.to validate_presence_of(:content) }
end


text:
//-----------------------------------------------------------------------------
// <copyright file="WheelMudSqlServerProvider.cs" company="WheelMUD Development Team">
//   Copyright (c) WheelMUD Development Team. See LICENSE.txt. This file is
//   subject to the Microsoft Public License. All other rights reserved.
// </copyright>
// <summary>
//   Created by: Fastalanasa
//   Date      : April 30, 2012
//   Purpose   : ORMLite Microsoft SQL Server provider for WheelMUD
// </summary>
//-----------------------------------------------------------------------------

namespace WheelMUD.Data.SqlServer
{
    using System.ComponentModel.Composition;
    using System.Data;
    using ServiceStack.OrmLite;
    using ServiceStack.OrmLite.SqlServer;

    /// <summary>ORMLite Microsoft SQL Server provider for WheelMUD.</summary>
    [Export(typeof(IWheelMudDbProvider))]
    public class WheelMudSqlServerProvider : IWheelMudDbProvider
    {
        public WheelMudSqlServerProvider()
        {
        }

        public WheelMudSqlServerProvider(string connectionString)
        {
            this.ConnectionString = connectionString;
        }

        public string ConnectionString { get; set; }

        public string DatabaseName
        {
            get { return "Microsoft SQL Server"; }
        }

        public string ProviderNamespace
        {
            get { return "system.data.sqlclient"; }
        }

        public IDbConnection CreateDatabaseSession()
        {
            var connectionFactory = new OrmLiteConnectionFactory(this.ConnectionString, false, SqlServerOrmLiteDialectProvider.Instance);
            IDbConnection connection = connectionFactory.OpenDbConnection();
            return connection;
        }
    }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name showcaseApp.controller:CreationCtrl
 * @description
 * # CreationCtrl
 * Controller of the showcaseApp
 */
angular.module('showcaseApp')
  .controller('CreationCtrl', ['common', function (common) {
      common.setSection('creation');
  }]);


text:
<!DOCTYPE html>

<title> Constructing Your First PC - 13</title>
<meta name="author" content="660899" >
<meta name="date" content="2016-01-12T11:27:52-0700" >

Glossary

Clock Speed
The clock speed of a CPU refers to the number of instructions that is can process in a second. Typically clock speed is read in frequency as megahertz or gigahertz. For example in the chart the Intel core i7-4930K has a clock speed of 3.4 gigahertz. With a 3.4 gigahertz clock speed that CPU can process three billion four hundred million instructions per second. [23]

Overclocking
Overclocking is the process of forcing a computer or hardware component to operate faster than the manufacturer-specified clock frequency. [23]

Hyper Threaded
Hyper threading uses processor resources more efficiently, enabling multiple threads to run on each core. [23]

Multi-core processor
 A multicore processor is a single computing component with two or more independent processors (cores).  [23]

Thermal Output
 Thermal output also known as TDP is the maximum power that is required to run the cooling system. The higher the thermal output, the hotter the processor gets. [23]

Processor Numbers
When looking at a processor there are usually the brand name, such as Intel, as well as accompanied by system configuration, and system-level benchmarks. The higher the number means the newer the processor along with more features. [24]

Cache
 A processor comes with built in memory known as cache. The cache has three levels: L1, L2, and L3. [23]

Memory Capacity (VRAM)
 This is a major component of video card specifications that are often listed as a requirement for software and applications like video games. Memory capacity directly impacts the video resolution and the quality of texture images that can be rendered on screen at a time. [25]

Memory Bandwidth
 This impacts the speed at which your GPU can access the assets in the Video RAM. A higher bandwidth is important to performance, since any machine is only as fast as its slowest component, and having slow memory bandwidth would cause a performance bottleneck. [25]

Length
 This is simply the physical length of the video card. This is an important specification to pay attention to as some computer cases will not be able to accommodate larger cards, and you should pay attention to what your size limitations might be. [25]

Direct X
 DirectX is a collection of Application Programming Interfaces (APIs) that allows programs to talk to the multimedia in your computer. The version of direct X is largely limited to the operating system that you're currently running, so make sure you simply have the version that is required by the game you're looking for. [25]

RAM
 RAM is one type of memory in computer which can be accessed randomly. RAM is most common type of memory that is found in computer.  RAM stores data in computer for immediate use. [8] [9]

Operating System
 Operating system is the system software that manage hardware and software.  Every generation computer needs operating system to run other computer programs and application. Operating system controls computer's operations. Runs programs (applications), recognize inputs such as keyboard and mouse, also send out the outputs such as monitor screen, printer, sounds. [13]

 index page
 previous
</foster>


text:
package org.cfr.matcha.direct.spring;

import java.lang.annotation.Annotation;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.cfr.matcha.direct.spi.BaseDirectContext;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;

class ActionAnnotationBeanPostProcessor implements MergedBeanDefinitionPostProcessor, BeanFactoryAware {

    /**
     *
     */
    private BeanFactory beanFactory;

    /**
     *
     */
    // TODO [devacfr] create interface
    private final BaseDirectContext directContext;

    /**
     *
     */
    private final Set<Class<? extends Annotation>> annotations = new LinkedHashSet<Class<? extends Annotation>>();

    /**
     * {@inheritDoc}
     */
    @Override
    public void setBeanFactory(final BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void postProcessMergedBeanDefinition(final RootBeanDefinition beanDefinition, final Class<?> beanType,
                                                final String beanName) {
    }

    /**
     *
     */
    public ActionAnnotationBeanPostProcessor(@Nonnull final BaseDirectContext directContext) {
        this.directContext = directContext;
    }

    @Override
    public Object postProcessBeforeInitialization(final Object bean, final String beanName) {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(@Nullable final Object bean, @Nullable final String beanName) {
        if (isSupported(bean)) {
            directContext.registerAction(bean);
        }
        return bean;
    }

    private boolean isSupported(final Object bean) {
        return BaseDirectContext.isAction(bean);
    }

}


text:
package serve

import (
	"encoding/base64"
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
	"time"
)

type requestCtx struct {
	RemoteAddr string
	Req        *http.Request
	Rw         http.ResponseWriter

	Host string //eg www.baidu.com
	Port int    //eg 80

	User     *User
	Docid    int
	IsRePlay bool

	SessionId     int64
	HasBroadcast  bool
	FormPost      *url.Values
	ClientSession *clientSession

	OriginUrl string
	logData   map[interface{}]interface{}
	Msg       string

	ser           *ProxyServe
	startTime     time.Time
	timeDurations map[string]time.Duration
	hasPrint      bool
}

func NewRequestCtx(ser *ProxyServe, rw http.ResponseWriter, req *http.Request) *requestCtx {
	ctx := &requestCtx{}
	ctx.Req = req
	ctx.ser = ser
	ctx.Rw = rw
	ctx.SessionId = ser.reqNum

	ctx.logData = make(map[interface{}]interface{})
	ctx.timeDurations = make(map[string]time.Duration)

	ctx.FormPost = &url.Values{}
	ctx.init()
	ctx.startTime = time.Now()
	return ctx
}

func (ctx *requestCtx) init() {
	if ctx.Req == nil {
		return
	}
	fixRequest(ctx.Req)
	req := ctx.Req
	ctx.Host, ctx.Port, _ = getHostPortFromReq(req)

	ctx.User = getAuthorInfo(req)
	ctx.FormPost = getPostData(req)

	ctx.OriginUrl = req.URL.String()
	ctx.IsRePlay = len(req.Header.Get(REPLAY_FLAG)) > 0
	ctx.SetLog("url", req.URL.String())

	ctx.RemoteAddr = req.RemoteAddr

	if _replay_addr := req.Header.Get(REPLAY_REMOTEADDR); _replay_addr != "" {
		ctx.RemoteAddr = _replay_addr
	}
	if _replay_user := req.Header.Get(REPLAY_USER_NAME); _replay_user != "" {
		ctx.User = &User{Name: _replay_user, SkipCheckPsw: true}
	}
	ctx.Docid = ctx.getNewDocid()
	ctx.ser.regirestReq(ctx)
}

func fixRequest(req *http.Request) {
	if req.Method != "CONNECT" && !req.URL.IsAbs() {
		urlOrigin := req.URL.String()
		urlStr := "http://" + req.Host + req.URL.Path
		if req.URL.RawQuery != "" {
			urlStr += "?" + req.URL.RawQuery
		}
		var err error
		req.URL, err = url.Parse(urlStr)
		if err != nil {
			log.Println("fix url failed,originUrl:", urlOrigin, "err:", err)
			return
		}
	}
}

func (ctx *requestCtx) IsLocalRequest() bool {
	isLocalReq := ctx.Port == ctx.ser.conf.Port
	if isLocalReq {
		isLocalReq = IsLocalIp(ctx.Host)
	}
	return isLocalReq
}

func (ctx *requestCtx) GetIp() string {
	host_info := strings.Split(ctx.RemoteAddr, ":")
	return host_info[0]
}

func (ctx *requestCtx) PrintLog() {
	reqId := 0
	if ctx.ClientSession != nil {
		reqId = ctx.ClientSession.RequestNum
	}
	log.Println(
		"session_id:", ctx.SessionId,
		"remote:", ctx.RemoteAddr,
		"reqId:", reqId,
		"docid:", ctx.Docid,
		"uname:", ctx.User.Name,
		"broadcast:", ctx.HasBroadcast,
		"startTime:", ctx.startTime.Unix(),
		"timeUsed:", fmt.Sprintf("%.3fs", time.Now().Sub(ctx.startTime).Seconds()),
		"data:", ctx.logData,
		"times:", ctx.timeDurations,
	)
}

func (ctx *requestCtx) RoundTrip() {
	defer func() {
		ctx.hasPrint = true
		ctx.SetLog("logType", "defer")
		ctx.PrintLog()
	}()

	time.AfterFunc(10*time.Second, func() {
		if !ctx.hasPrint {
			ctx.SetLog("logType", "timeout10")
			ctx.PrintLog()
		}
	})

	removeHeader(ctx.Req)
	rewrite_code := ctx.ser.reqRewrite(ctx)

	ctx.HasBroadcast = ctx.ser.Broadcast_Req(ctx)

	ctx.SetLog("js_rewrite_code", rewrite_code)

	time.AfterFunc(1*time.Second, ctx.saveRequestData)

	if rewrite_code != 200 && rewrite_code != 304 {
		ctx.badGateway(fmt.Errorf("rewrite failed"))
		return
	}
	ctx.ser.proxy.RoundTrip(ctx)
}
func (ctx *requestCtx) badGateway(err error) {
	ctx.SetLog("errMsg", fmt.Sprintf("%s", err))
	ctx.Rw.WriteHeader(http.StatusBadGateway)
	ctx.Rw.Write([]byte("pproxy error"))
}

func (ctx *requestCtx) DestAddr() string {
	return fmt.Sprintf("%s:%d", ctx.Host, ctx.Port)
}

func (ctx *requestCtx) saveRequestData() {
	if ctx.ser.conf.ResponseSave == ResponseSave_All ||
		(ctx.ser.conf.ResponseSave == ResponseSave_HasBroad && ctx.HasBroadcast) {
		logdata := KvType{}
		logdata["host"] = ctx.Req.Host
		logdata["schema"] = ctx.Req.URL.Scheme
		logdata["header"] = map[string][]string(ctx.Req.Header)
		logdata["url"] = ctx.Req.URL.String()
		logdata["url_origin"] = ctx.OriginUrl
		logdata["path"] = ctx.Req.URL.Path
		logdata["cookies"] = ctx.Req.Cookies()
		logdata["now"] = time.Now().Unix()
		logdata["user"] = ctx.User.Name
		logdata["client_ip"] = ctx.RemoteAddr
		logdata["method"] = ctx.Req.Method
		logdata["form_get"] = ctx.Req.URL.Query()
		logdata["replay"] = ctx.IsRePlay
		logdata["msg"] = ctx.Msg

		logdata["now"] = ctx.startTime.Unix()

		dumpBody := false
		req_dump, err_dump := httputil.DumpRequest(ctx.Req, dumpBody)
		if err_dump != nil {
			ctx.SetLog("dumpMsg", "dump request failed")
			req_dump = []byte("dump failed")
		}
		logdata["dump"] = base64.StdEncoding.EncodeToString(req_dump)

		logdata["form_post"] = ctx.FormPost

		err := ctx.ser.mydb.RequestTable.Set(ctx.Docid, logdata)
		if err != nil {
			log.Println("save req failed:", err)
		}
	}
}

func (ctx *requestCtx) saveResponse(res *http.Response) {
	if ctx.Docid < 1 || res == nil {
		return
	}
	data := KvType{}
	data["now"] = time.Now().Unix()
	data["header"] = map[string][]string(res.Header)
	data["status"] = res.StatusCode
	data["content_length"] = res.ContentLength
	data["msg"] = ctx.Msg

	res_dump, dump_err := httputil.DumpResponse(res, false)
	if dump_err != nil {
		log.Println("dump res err", dump_err)
		res_dump = []byte("dump res failed")
	}
	data["dump"] = base64.StdEncoding.EncodeToString(res_dump)
	//   data["cookies"]=res.Cookies()

	body := []byte("pproxy skip")
	if res.Body != nil && res.ContentLength <= ctx.ser.MaxResSaveLength {
		buf := forgetRead(&res.Body)
		if res.Header.Get(Content_Encoding) == "gzip" {
			body = []byte(gzipDocode(buf))
		} else {
			body = buf.Bytes()
		}
		l := int64(len(body))
		if l > ctx.ser.MaxResSaveLength {
			body = []byte(fmt.Sprintf("pproxy skip,body too large,[len=%d]", l))
		}
	}
	data["body"] = base64.StdEncoding.EncodeToString(body)

	err := ctx.ser.mydb.ResponseTable.Set(ctx.Docid, data)

	log.Println("save_res", ctx.SessionId, "docid=", ctx.Docid, "body_len=", len(data["body"].(string)), err)
}

func (ctx *requestCtx) SetLog(k, v interface{}) {
	ctx.logData[k] = v
}
func (ctx *requestCtx) SetTimePoint(key string) {
	ctx.timeDurations[key] = time.Now().Sub(ctx.startTime)
}

func (ctx *requestCtx) getNewDocid() int {
	id_str := fmt.Sprintf("%s%d", time.Now().Format("200601021504"), ctx.ser.reqNum)
	id, err := parseDocId(id_str)
	if err == nil {
		return id
	}
	log.Println("GetNewDocid failed", id_str, err)
	return int(time.Now().UnixNano() + ctx.ser.reqNum)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="BuildJarProjectSettings">
    <option name="BUILD_JARS_ON_MAKE" value="false" />
  </component>
  <component name="DependencyValidationManager">
    <option name="SKIP_IMPORT_STATEMENTS" value="false" />
  </component>
  <component name="IvyIDEA.ProjectSettings">
    <option name="propertiesSettings">
      <PropertiesSettings />
    </option>
  </component>
  <component name="JavadocGenerationManager">
    <option name="OUTPUT_DIRECTORY" />
    <option name="OPTION_SCOPE" value="protected" />
    <option name="OPTION_HIERARCHY" value="true" />
    <option name="OPTION_NAVIGATOR" value="true" />
    <option name="OPTION_INDEX" value="true" />
    <option name="OPTION_SEPARATE_INDEX" value="true" />
    <option name="OPTION_DOCUMENT_TAG_USE" value="false" />
    <option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" />
    <option name="OPTION_DOCUMENT_TAG_VERSION" value="false" />
    <option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="true" />
    <option name="OPTION_DEPRECATED_LIST" value="true" />
    <option name="OTHER_OPTIONS" value="" />
    <option name="HEAP_SIZE" />
    <option name="LOCALE" />
    <option name="OPEN_IN_BROWSER" value="true" />
  </component>
  <component name="ProjectDetails">
    <option name="projectName" value="coffeescript" />
  </component>
  <component name="ProjectKey">
    <option name="state" value="project://default" />
  </component>
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" assert-keyword="true" jdk-15="true" project-jdk-name="IDEA IC-93.94" project-jdk-type="IDEA JDK">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
  <component name="SvnConfiguration">
    <option name="USER" value="" />
    <option name="PASSWORD" value="" />
    <option name="LAST_MERGED_REVISION" />
    <option name="UPDATE_RUN_STATUS" value="false" />
    <option name="MERGE_DRY_RUN" value="false" />
    <option name="MERGE_DIFF_USE_ANCESTRY" value="true" />
    <option name="UPDATE_LOCK_ON_DEMAND" value="false" />
    <option name="IGNORE_SPACES_IN_MERGE" value="false" />
    <option name="SHOW_MERGE_SOURCES_IN_ANNOTATE" value="true" />
    <myIsUseDefaultProxy>false</myIsUseDefaultProxy>
  </component>
  <component name="XPathView.XPathProjectComponent">
    <history />
    <find-history />
  </component>
</project>


text:
package gnu.trove.impl.unmodifiable;

//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////

////////////////////////////////////////////////////////////
// THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY!  //
// Access to these methods should be through TCollections //
////////////////////////////////////////////////////////////

import gnu.trove.iterator.*;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.list.*;
import gnu.trove.function.*;
import gnu.trove.map.*;
import gnu.trove.*;

import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.Map;
import java.util.RandomAccess;
import java.util.Random;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class TUnmodifiableShortDoubleMap implements TShortDoubleMap, Serializable {
	private static final long serialVersionUID = -1034234728574286014L;

	private final TShortDoubleMap m;

	public TUnmodifiableShortDoubleMap( TShortDoubleMap m ) {
		if ( m == null )
			throw new NullPointerException();
		this.m = m;
	}

	public int size()                       { return m.size(); }
	public boolean isEmpty()                { return m.isEmpty(); }
	public boolean containsKey( short key )   { return m.containsKey( key ); }
	public boolean containsValue( double val ) { return m.containsValue( val ); }
	public double get( short key)                { return m.get( key ); }

	public double put( short key, double value ) { throw new UnsupportedOperationException(); }
	public double remove( short key ) { throw new UnsupportedOperationException(); }
	public void putAll( TShortDoubleMap m ) { throw new UnsupportedOperationException(); }
	public void putAll( Map<? extends Short, ? extends Double> map ) { throw new UnsupportedOperationException(); }
	public void clear() { throw new UnsupportedOperationException(); }

	private transient TShortSet keySet = null;
	private transient TDoubleCollection values = null;

	public TShortSet keySet() {
		if ( keySet == null )
			keySet = TCollections.unmodifiableSet( m.keySet() );
		return keySet;
	}
	public short[] keys() { return m.keys(); }
	public short[] keys( short[] array ) { return m.keys( array ); }

	public TDoubleCollection valueCollection() {
		if ( values == null )
			values = TCollections.unmodifiableCollection( m.valueCollection() );
		return values;
	}
	public double[] values() { return m.values(); }
	public double[] values( double[] array ) { return m.values( array ); }

	public boolean equals(Object o) { return o == this || m.equals(o); }
	public int hashCode()           { return m.hashCode(); }
	public String toString()        { return m.toString(); }
	public short getNoEntryKey()      { return m.getNoEntryKey(); }
	public double getNoEntryValue()    { return m.getNoEntryValue(); }

	public boolean forEachKey( TShortProcedure procedure ) {
		return m.forEachKey( procedure );
	}
	public boolean forEachValue( TDoubleProcedure procedure ) {
		return m.forEachValue( procedure );
	}
	public boolean forEachEntry( TShortDoubleProcedure procedure ) {
		return m.forEachEntry( procedure );
	}

	public TShortDoubleIterator iterator() {
		return new TShortDoubleIterator() {
			TShortDoubleIterator iter = m.iterator();

			public short key() { return iter.key(); }
			public double value() { return iter.value(); }
			public void advance() { iter.advance(); }
			public boolean hasNext() { return iter.hasNext(); }
			public double setValue( double val ) { throw new UnsupportedOperationException(); }
			public void remove() { throw new UnsupportedOperationException(); }
		};
	}

	public double putIfAbsent( short key, double value ) { throw new UnsupportedOperationException(); }
	public void transformValues( TDoubleFunction function ) { throw new UnsupportedOperationException(); }
	public boolean retainEntries( TShortDoubleProcedure procedure ) { throw new UnsupportedOperationException(); }
	public boolean increment( short key ) { throw new UnsupportedOperationException(); }
	public boolean adjustValue( short key, double amount ) { throw new UnsupportedOperationException(); }
	public double adjustOrPutValue( short key, double adjust_amount, double put_amount ) { throw new UnsupportedOperationException(); }
}


text:
using namespace BloombergLP;
using namespace BloombergLP::bsltf;

//=============================================================================
//                             TEST PLAN
//-----------------------------------------------------------------------------
//                              Overview
//                              --------
// The component under test is a single unconstrained (value-semantic)
// attribute class, except it doesn't provide equality comparison operators.
// The Primary Manipulators and Basic Accessors are therefore, respectively,
// the attribute setters and getters, each of which follows our standard
// unconstrained attribute-type naming conventions: 'setAttributeName' and
// 'attributeName'.
//
// Primary Manipulators:
//: o 'setData'
//
// Basic Accessors:
//: o 'data'
//
// This particular attribute class also provides a value constructor capable of
// creating an object in any state relevant for thorough testing, obviating the
// primitive generator function, 'gg', normally used for this purpose.  We will
// therefore follow our standard 10-case approach to testing value-semantic
// types except that we will test the value constructor in case 3 (in lieu of
// the generator function), with the default constructor and primary
// manipulators tested fully in case 2.
//
// Global Concerns:
//: o No memory is every allocated from this component.
//-----------------------------------------------------------------------------
// CREATORS
// [ 2] NonEqualComparableTestType();
// [ 3] NonEqualComparableTestType(int data);
// [ 7] NonEqualComparableTestType(const NonEqualComparableTestType&);
// [ 2] ~NonEqualComparableTestType();
//
// MANIPULATORS
// [ 9] NonEqualComparableTestType& operator=(rhs);
// [ 2] void setData(int value);
//
// ACCESSORS
// [ 4] int data() const;
//
//-----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [11] USAGE EXAMPLE
// [ 6] TEST APPARATUS
// [ *] CONCERN: No memory is ever allocated.
// [ 6] CONCERN: 'operator==' is not defined
// [ 6] CONCERN: 'operator!=' is not defined

// ============================================================================
//                     STANDARD BSL ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------

namespace {

int testStatus = 0;

void aSsErT(bool condition, const char *message, int line)
{
    if (condition) {
        printf("Error " __FILE__ "(%d): %s    (failed)\n", line, message);

        if (0 <= testStatus && testStatus <= 100) {
            ++testStatus;
        }
    }
}

}  // close unnamed namespace

// ============================================================================
//               STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------

#define ASSERT       BSLS_BSLTESTUTIL_ASSERT
#define ASSERTV      BSLS_BSLTESTUTIL_ASSERTV

#define LOOP_ASSERT  BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT

#define Q            BSLS_BSLTESTUTIL_Q   // Quote identifier literally.
#define P            BSLS_BSLTESTUTIL_P   // Print identifier and value.
#define P_           BSLS_BSLTESTUTIL_P_  // P(X) without '\n'.
#define T_           BSLS_BSLTESTUTIL_T_  // Print a tab (w/o newline).
#define L_           BSLS_BSLTESTUTIL_L_  // current Line number

// ============================================================================
//                  NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------

#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR)      BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR)      BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR)  BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR)  BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)

// ============================================================================
//                     GLOBAL TYPEDEFS FOR TESTING
// ----------------------------------------------------------------------------

typedef bsltf::NonEqualComparableTestType Obj;

// ============================================================================
//                     GLOBAL CONSTANTS USED FOR TESTING
// ----------------------------------------------------------------------------

struct DefaultValueRow {
    int d_line;  // source line number
    int d_data;
};

static
const DefaultValueRow DEFAULT_VALUES[] =
{
    //LINE     DATA
    //----     ----

    // default (must be first)
    { L_,         0 },

    // 'data'
    { L_,   INT_MIN },
    { L_,        -1 },
    { L_,         1 },
    { L_,   INT_MAX },
};

const int DEFAULT_NUM_VALUES = sizeof DEFAULT_VALUES / sizeof *DEFAULT_VALUES;

// ============================================================================
//                               TEST APPARATUS
// ----------------------------------------------------------------------------
// JSL: REMOVE THIS after it is moved to the test allocator.
// JSL: change the name to 'TestAllocatorMonitor'.

namespace {

bool isEqual(const bsltf::NonEqualComparableTestType& lhs,
             const bsltf::NonEqualComparableTestType& rhs)
{
    return lhs.data() == rhs.data();
}

bool isNotEqual(const bsltf::NonEqualComparableTestType& lhs,
                const bsltf::NonEqualComparableTestType& rhs)
{
    return lhs.data() != rhs.data();
}

namespace check {

typedef char no[7];
template<class T> no& operator == (const T&, const T&);
template<class T> no& operator != (const T&, const T&);

template <class T>
struct op_equal_exist
{
    enum { value = (sizeof(*(T*)(0) == *(T*)(0)) != sizeof(no)) };
};

template <class T>
struct op_not_equal_exist
{
    enum { value = (sizeof(*(T*)(0) != *(T*)(0)) != sizeof(no)) };
};

}  // close namespace check

namespace u {

unsigned numBitsChanged(const void *segmentA,
                        const void *segmentB,
                        size_t      size)
    // Compare the specified memory segments 'segmentA' and 'segmentB', both of
    // the specified 'size' bytes, and return the number of bits that differ
    // between them.
{
    const unsigned char *a = static_cast<const unsigned char *>(segmentA);
    const unsigned char *b = static_cast<const unsigned char *>(segmentB);

    unsigned ret = 0;
    for (const unsigned char *end = a + size; a < end; ++a, ++b) {
        for (unsigned diff = *a ^ *b; diff; diff >>= 1) {
            ret += diff & 1;
        }
    }

    return ret;
}

                                // =====
                                // Thing
                                // =====

struct Thing {
    char d_byte;

    // CLASS METHOD
    static
    bool isDtorExecuted();
        // Return 'true' if the destructor of a 'Thing' is observed to execute
        // on object destruction, and 'false' otherwise.
        //
        // On some compilers in optimized mode, destructors that change only
        // the footprint of the object are optimized away and are not executed.

    // CREATORS
    Thing() : d_byte(0) {}
    ~Thing() { d_byte = 127; }
};

                                // -----
                                // Thing
                                // -----

// CLASS METHOD
bool Thing::isDtorExecuted()
{
    bsls::ObjectBuffer<Thing> buffer;
    new (buffer.address()) Thing();
    buffer.address()->~Thing();

    return 0 != *reinterpret_cast<char *>(buffer.address());
}

}  // close namespace u
}  // close unnamed namespace

//=============================================================================
//                                 MAIN PROGRAM
//-----------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    int                 test = argc > 1 ? atoi(argv[1]) : 0;
    bool             verbose = argc > 2;
    bool         veryVerbose = argc > 3;
    bool     veryVeryVerbose = argc > 4;
    bool veryVeryVeryVerbose = argc > 5;

    (void)veryVeryVerbose;      // suppress warning
    (void)veryVeryVeryVerbose;  // suppress warning

    printf("TEST " __FILE__ " CASE %d\n", test);

    switch (test) { case 0:  // Zero is always the leading case.
      case 11: {
          if (verbose) printf("\nUSAGE EXAMPLE"
                              "\n=============\n");
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: Demonstrating The Type Can't Be Equal Compared
///- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Suppose we wanted to show 'NonEqualComparableTestType' can't be equal
// compared.
//
// First, we create two 'NonEqualComparableTestType' objects, 'X' and 'Y':
//..
          NonEqualComparableTestType X(1);
          NonEqualComparableTestType Y(2);
//..
// Now, we show that equal comparing 'X' and 'Y' will not compile:
//..
          // assert(X != Y); // This will not compile
//..
      } break;
      case 10: {
        // --------------------------------------------------------------------
        // BSLX STREAMING
        //   N/A
        // --------------------------------------------------------------------
      } break;
      case 9: {
        // --------------------------------------------------------------------
        // COPY-ASSIGNMENT OPERATOR
        //   Ensure that we can assign the value of any object of the class to
        //   any object of the class, such that the two objects subsequently
        //   have the same value.
        //
        // Concerns:
        //: 1 The assignment operator can change the value of any modifiable
        //:   target object to that of any source object.
        //:
        //: 2 The signature and return type are standard.
        //:
        //: 3 The reference returned is to the target object (i.e., '*this').
        //:
        //: 4 The value of the source object is not modified.
        //:
        //: 5 Assigning an object to itself behaves as expected (alias-safety).
        //
        // Plan:
        //: 1 Use the address of 'operator=' to initialize a member-function
        //:   pointer having the appropriate signature and return type for the
        //:   copy-assignment operator defined in this component.  (C-2)
        //:
        //: 2 Using the table-driven technique, specify a set of distinct
        //:   object values (one per row) in terms of their attributes.
        //:
        //: 3 For each row 'R1' in the table of P-2:  (C-1, 3..4)
        //:
        //:   1 Create two 'const' 'Obj', 'Z' and 'ZZ', having the value of
        //:     'R1'.
        //:
        //:   2 For each row 'R2 in the tree of P-2:  (C-1, 3..4)
        //:
        //:     1 Create a modifiable 'Obj', 'mX', having the value of 'R2'.
        //:
        //:     2 Assign 'mX' from 'Z'.  (C-1)
        //:
        //:     3 Verify that the address of the return value is the same as
        //:       that of 'mX'.  (C-3)
        //:
        //:     4 Use the equality-comparison operator to verify that:
        //:
        //:       1 The target object, 'mX', now has the same value as that of
        //:         'Z'.  (C-1)
        //:
        //:       2 'Z' still has the same value as that of 'ZZ'.  (C-4)
        //:
        //: 4 For each node 'N1' in tree of P-2:  (C-3, 5)
        //:
        //:   1 Create a modifiable 'Obj', 'mX', pointing to 'N1'.
        //:
        //:   1 Create a 'const' 'Obj', 'ZZ', pointing to 'N1'.
        //:
        //:   2 Let 'Z' be a reference providing only 'const' access to 'mX'.
        //:
        //:   3 Assign 'mX' from 'Z'.
        //:
        //:   4 Verify that the address of the return value is the same as
        //:       that of 'mX'.  (C-3)
        //:
        //:   5 Use the equal-comparison operator to verify that 'mX' has the
        //:     same value as 'ZZ'.  (C-5)
        //
        // Testing:
        //   NonEqualComparableTestType& operator=(rhs);
        // --------------------------------------------------------------------

        if (verbose) printf("\nCOPY-ASSIGNMENT OPERATOR"
                            "\n========================\n");

        if (verbose)
            printf("\nAssign the address of the operator to a variable.\n");
        {
            typedef Obj& (Obj::*operatorPtr)(const Obj&);

            // Verify that the signature and return type are standard.

            operatorPtr operatorAssignment = &Obj::operator=;

            (void) operatorAssignment;  // quash potential compiler warning
        }

        const int NUM_VALUES                        = DEFAULT_NUM_VALUES;
        const DefaultValueRow (&VALUES)[NUM_VALUES] = DEFAULT_VALUES;

        for (int ti = 0; ti < NUM_VALUES; ++ti) {
            const int LINE1 = VALUES[ti].d_line;
            const int DATA1 = VALUES[ti].d_data;

            if (veryVerbose) { T_ P_(LINE1) P(DATA1) }

            const Obj Z(DATA1);
            const Obj ZZ(DATA1);

            for (int tj = 0; tj < NUM_VALUES; ++tj) {
                const int LINE2 = VALUES[tj].d_line;
                const int DATA2 = VALUES[tj].d_data;

                if (veryVerbose) { T_ T_ P_(LINE2) P(DATA2) }

                Obj mX(DATA2);

                Obj *mR = &(mX = Z);
                ASSERTV(ti, tj, mR, &mX, mR == &mX);

                ASSERTV(ti, tj, Z.data(), mX.data(), isEqual(Z, mX));
                ASSERTV(ti, tj, Z.data(), ZZ.data(), isEqual(Z, ZZ));
            }
        }

        for (int ti = 0; ti < NUM_VALUES; ++ti) {
            const int LINE = VALUES[ti].d_line;
            const int DATA = VALUES[ti].d_data;

            if (veryVerbose) { T_ P_(LINE) P(DATA) }

            Obj mX(DATA);
            const Obj ZZ(DATA);

            const Obj& Z = mX;
            Obj *mR = &(mX = Z);
            ASSERTV(ti, mR, &mX, mR == &mX);

            ASSERTV(ti, Z.data(), mX.data(), isEqual(Z, mX));
            ASSERTV(ti, Z.data(), ZZ.data(), isEqual(Z, ZZ));
        }

      } break;
      case 8: {
        // --------------------------------------------------------------------
        // SWAP MEMBER AND FREE FUNCTIONS
        //   N/A
        // --------------------------------------------------------------------
      } break;
      case 7: {
        // --------------------------------------------------------------------
        // COPY CONSTRUCTOR
        //   Ensure that we can create a distinct object of the class from any
        //   other one, such that the two objects have the same value.
        //
        // Concerns:
        //: 1 The copy constructor creates an object having the same value as
        //:   that of the supplied original object.
        //:
        //: 2 The original object is passed as a reference providing
        //:   non-modifiable access to that object.
        //:
        //: 3 The value of the original object is unchanged.
        //
        // Plan:
        //: 1 Using the table-driven technique, specify a set of distinct
        //:   object values (one per row) in terms of their attributes.
        //:
        //: 2 For each row 'R1' in the table of P-1:  (C-1..3)
        //:
        //:   1 Create two 'const' 'Obj', 'Z' and 'ZZ', having the value of
        //:     'R1'.
        //:
        //:   2 Use the copy constructor to create an object 'X', supplying it
        //:     the 'const' object 'Z'.  (C-2)
        //:
        //:   3 Verify that the newly constructed object 'X', has the same
        //:     value as that of 'Z'.  (C-1)
        //:
        //:   4 Verify that 'Z' still has the same value as that of 'ZZ'.
        //:     (C-3)
        //
        // Testing:
        //   NonEqualComparableTestType(const NonEqualComparableTestType&);
        // --------------------------------------------------------------------

        if (verbose) printf("\nCOPY CONSTRUCTORS"
                            "\n=================\n");

        const int NUM_VALUES                        = DEFAULT_NUM_VALUES;
        const DefaultValueRow (&VALUES)[NUM_VALUES] = DEFAULT_VALUES;

        for (int ti = 0; ti < NUM_VALUES; ++ti) {
            const int LINE = VALUES[ti].d_line;
            const int DATA = VALUES[ti].d_data;

            if (veryVerbose) { T_ P_(LINE) P(DATA) }

            const Obj Z(DATA);
            const Obj ZZ(DATA);

            const Obj X(Z);

            ASSERTV(Z.data(), X.data(), isEqual(Z, X));
            ASSERTV(Z.data(), ZZ.data(), isEqual(Z, ZZ));
        }

      } break;
      case 6: {
        // --------------------------------------------------------------------
        // EQUALITY-COMPARISON OPERATORS
        //   Ensure that the test apparatus functions 'isEqual' and
        //   'isNotEqual', for use in later test cases, behaves according to
        //   'operator==' and 'operator!=' in value-semantic types.  Also
        //   ensure that 'operator==' and 'operator!=' are not defined by this
        //   component.
        //
        // Concerns:
        //: 1 Two objects, 'X' and 'Y', compare equal if and only if they point
        //:   to the same node in the same tree.
        //:
        //: 2 'true  == isEqual(X, X)'  (i.e., identity)
        //:
        //: 3 'false == isNotEqual(X, X)'  (i.e., identity)
        //:
        //: 4 'isEqual(X, Y)' if and only if 'isEqual(Y, X)' (i.e.,
        //:   commutativity)
        //:
        //: 5 'isNotEqual(X, Y)' if and only if 'isNotEqual(Y, X)' (i.e.,
        //:   commutativity)
        //:
        //: 6 'isNotEqual(X, Y)' if and only if '!isEqual(X, Y)'
        //:
        //: 7 Comparison is symmetric with respect to user-defined conversion
        //:   (i.e., both comparison operators are free functions).
        //:
        //: 8 Non-modifiable objects can be compared (i.e., objects or
        //:   references providing only non-modifiable access).
        //:
        //:10 The 'isEqual' function's signature and return type are standard.
        //:
        //:11 The 'isNotEqual' function's signature and return type are
        //:   standard.
        //:
        //:12 'operator==' and 'operator!=' are not defined by this component.
        //
        // Plan:
        //: 1 Use the respective addresses of 'isEqual' and 'isNotEqual' to
        //:   initialize function pointers having the appropriate signatures
        //:   and return types for the two homogeneous, free equality-
        //:   comparison operators defined in this component.
        //:   (C-7..10)
        //:
        //: 2 Use a meta function to verify that 'operator==' and 'operator!='
        //:   are not defined by this component.
        //:
        //: 2 Using the table-driven technique, specify a set of distinct
        //:   object values (one per row) in terms of their attributes.
        //:
        //: 3 For each row 'R1' in the table of P-2:  (C-1..6)
        //:
        //:   1 Create a single object, and use it to verify the reflexive
        //:     (anti-reflexive) property of equality (inequality) in the
        //:     presence of aliasing.  (C-2..3)
        //:
        //:   2 For each row 'R2' in the table of P-3:  (C-1, 4..6)
        //:
        //:     1 Record, in 'EXP', whether or not distinct objects created
        //:       from 'R1' and 'R2', respectively, are expected to have the
        //:       same value.
        //:
        //:     2 Create an object 'X' having the value of 'R1'.  Create
        //:       another object 'Y' having the value of 'R2'.
        //:
        //:     3 Verify the commutativity property and the expected return
        //:       value for both '==' and '!='.  (C-1, 4..6)
        //
        // Testing:
        //   TEST APPARATUS
        //   CONCERN: 'operator==' is not defined
        //   CONCERN: 'operator!=' is not defined
        // --------------------------------------------------------------------

        if (verbose) printf("\nEQUALITY-COMPARISON OPERATORS"
                            "\n=============================\n");

        BSLMF_ASSERT((0 == check::op_equal_exist<Obj>::value));
        BSLMF_ASSERT((0 == check::op_not_equal_exist<Obj>::value));

        if (verbose)
            printf("\nAssign the address of each operator to a variable.\n");
        {
            typedef bool (*operatorPtr)(const Obj&, const Obj&);

            // Verify that the signatures and return types are standard.

            operatorPtr operatorEq = isEqual;
            operatorPtr operatorNe = isNotEqual;

            (void) operatorEq;  // quash potential compiler warnings
            (void) operatorNe;
        }

        const int NUM_VALUES                        = DEFAULT_NUM_VALUES;
        const DefaultValueRow (&VALUES)[NUM_VALUES] = DEFAULT_VALUES;

        for (int ti = 0; ti < NUM_VALUES; ++ti) {
            const int LINE1 = VALUES[ti].d_line;
            const int DATA1 = VALUES[ti].d_data;

            if (veryVerbose) { T_ P_(LINE1) P(DATA1) }

            Obj mX(DATA1); const Obj& X = mX;

            // Ensure an object compares correctly with itself (alias test).
            ASSERTV(X.data(),   isEqual(X, X));
            ASSERTV(X.data(),  !isNotEqual(X, X));

            for (int tj = 0; tj < NUM_VALUES; ++tj) {
                const int LINE2 = VALUES[tj].d_line;
                const int DATA2 = VALUES[tj].d_data;

                bool EXP = ti == tj;

                if (veryVerbose) { T_ T_ P_(LINE2) P_(DATA2) P(EXP) }

                Obj mY(DATA2); const Obj& Y = mY;

                // Verify value, commutativity
                ASSERTV(X.data(), Y.data(),  EXP == isEqual(X, Y));
                ASSERTV(X.data(), Y.data(),  EXP == isEqual(Y, X));

                ASSERTV(X.data(), Y.data(), !EXP == isNotEqual(X, Y));
                ASSERTV(X.data(), Y.data(), !EXP == isNotEqual(Y, X));
            }
        }

      } break;
      case 5: {
        // --------------------------------------------------------------------
        // PRINT AND OUTPUT OPERATOR
        //   N/A
        // --------------------------------------------------------------------
      } break;
      case 4: {
        // --------------------------------------------------------------------
        // BASIC ACCESSORS
        //   Ensure each basic accessor properly interprets object state.
        //
        // Concerns:
        //: 1 Each accessor returns the value of the corresponding attribute
        //:    of the object.
        //:
        //: 2 Each accessor method is declared 'const'.
        //
        // Plan:
        //: 1 Use the default constructor, create an object having default
        //:   attribute values.  Verify that the accessor for the 'data'
        //:   attribute invoked on a reference providing non-modifiable access
        //:   to the object return the expected value.  (C-1)
        //:
        //: 2 Set the 'data' attribute of the object to another value.  Verify
        //:   that the accessor for the 'data' attribute invoked on a reference
        //:   providing non-modifiable access to the object return the expected
        //:   value.  (C-1, 2)
        //
        // Testing:
        //   int data() const;
        // --------------------------------------------------------------------

        if (verbose)
            printf("\nBASIC ACCESSORS"
                   "\n===============\n");

        Obj mX; const Obj& X = mX;
        ASSERTV(X.data(), 0 == X.data());

        mX.setData(1);
        ASSERTV(X.data(), 1 == X.data());

      } break;
      case 3: {
        // --------------------------------------------------------------------
        // VALUE CTOR
        //   Ensure that we can put an object into any initial state relevant
        //   for thorough testing.
        //
        // Concerns:
        //: 1 The value constructor can create an object having any value that
        //:   does not violate the documented constraints.
        //
        // Plan:
        //: 1 Using the table-driven technique, specify a set of distinct
        //:   object values (one per row) in terms of their attributes.
        //:
        //: 2 For each row 'R1' in the table of P-1:  (C-1)
        //:
        //:   1 Use the value constructor to create an object 'X', having the
        //:     value of 'R1'.
        //:
        //:   2 Use the (as yet unproven) salient attribute accessors to verify
        //:     the attributes of the object have their expected value.  (C-1)
        //
        // Testing:
        //   NonEqualComparableTestType(int data);
        // --------------------------------------------------------------------

        if (verbose) printf("\nVALUE CTOR"
                            "\n==========\n");

        const int NUM_VALUES                        = DEFAULT_NUM_VALUES;
        const DefaultValueRow (&VALUES)[NUM_VALUES] = DEFAULT_VALUES;

        for (int ti = 0; ti < NUM_VALUES; ++ti) {
            const int LINE = VALUES[ti].d_line;
            const int DATA = VALUES[ti].d_data;

            if (veryVerbose) { T_ P_(LINE) P(DATA) }

            Obj mX(DATA); const Obj& X = mX;
            ASSERTV(DATA == X.data());
        }

      } break;
      case 2: {
        // --------------------------------------------------------------------
        // DEFAULT CTOR & PRIMARY MANIPULATORS
        //   Ensure that we can use the default constructor to create an object
        //   (having the default constructed value).  Also ensure that we can
        //   use the primary manipulators to put that object into any state
        //   relevant for thorough testing.
        //
        // Concerns:
        //: 1 An object created with the default constructor has the
        //:   contractually specified default value.
        //:
        //: 2 Each attribute can be set to represent any value that does not
        //:   violate that attribute's documented constraints.
        //
        // Plan:
        //: 1 Create three attribute values for the 'data' attribute 'D', 'A',
        //:   and 'B'.  'D' should be the default value.  'A' and 'B' should be
        //:   the boundary values.
        //:
        //: 2 Default-construct an object and use the individual (as yet
        //:   unproven) salient attribute accessors to verify the
        //:   default-constructed value.  (C-1)
        //:
        //: 3 Set and object's 'data' attribute to 'A' and 'B'.  Verify the
        //:   state of object using the (as yet unproven) salient attribute
        //:   accessors.  (C-2)
        //
        // Testing:
        //   NonEqualComparableTestType();
        //   ~NonEqualComparableTestType();
        //   void setData(int value);
        // --------------------------------------------------------------------

        if (verbose) printf("\nDEFAULT CTOR & PRIMARY MANIPULATORS"
                            "\n===================================\n");

        const int D = 0;
        const int A = INT_MIN;
        const int B = INT_MAX;
        const int C = 3;

        bsls::ObjectBuffer<Obj> xBuffer, yBuffer;

        new (xBuffer.address()) Obj();
        new (yBuffer.address()) Obj();

        Obj& mX = xBuffer.object();    const Obj& X = mX;
        Obj& mY = yBuffer.object();    const Obj& Y = mY;

        ASSERTV(X.data(), D == X.data());

        mX.setData(A);
        ASSERTV(X.data(), A == X.data());

        mX.setData(B);
        ASSERTV(X.data(), B == X.data());

        mX.setData(C);
        ASSERTV(X.data(), C == X.data());

        mY.setData(C);
        ASSERTV(Y.data(), C == Y.data());

        ASSERT(X.data() == Y.data());

        bool isDtorExecuted = u::Thing::isDtorExecuted();
        if (verbose) P(isDtorExecuted);

        unsigned changed = u::numBitsChanged(xBuffer.address(),
                                             yBuffer.address(),
                                             sizeof(xBuffer));
        ASSERT(0 == changed);

        mX.~Obj();

        changed = u::numBitsChanged(xBuffer.address(),
                                    yBuffer.address(),
                                    sizeof(xBuffer));
        ASSERT(changed >= (sizeof(xBuffer) * 8) / 4 || !isDtorExecuted);

        mY.~Obj();
        ASSERT(0 == u::numBitsChanged(xBuffer.address(),
                                      yBuffer.address(),
                                      sizeof(xBuffer)));
      } break;
      case 1: {
        // --------------------------------------------------------------------
        // BREATHING TEST
        //   This case exercises (but does not fully test) basic functionality.
        //
        // Concerns:
        //: 1 The class is sufficiently functional to enable comprehensive
        //:   testing in subsequent test cases.
        //
        // Plan:
        //: 1 Perform and ad-hoc test of the primary modifiers and accessors.
        //
        // Testing:
        //   BREATHING TEST
        // --------------------------------------------------------------------

        if (verbose) printf("\nBREATHING TEST"
                            "\n==============\n");

        Obj X;
        ASSERT(X.data() == 0);

        X.setData(1);
        ASSERT(X.data() == 1);

        Obj Y(2);
        ASSERT(Y.data() == 2);

        Obj Z(Y);
        ASSERT(Z.data() == Y.data());
        ASSERT(X.data() != Y.data());

        X = Z;
        ASSERT(Z.data() == Y.data());
        ASSERT(X.data() == Y.data());

      } break;
      default: {
        fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
        testStatus = -1;
      }
    }

    if (testStatus > 0) {
        fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
    }
    return testStatus;
}

// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------


text:
package io.teknek.nibiru.coordinator;

import org.apache.log4j.Logger;

import io.teknek.nibiru.TraceTo;
import io.teknek.nibiru.transport.HttpJsonTransport;
import io.teknek.nibiru.transport.Message;

public class Tracer {

  private static Logger LOGGER = Logger.getLogger(HttpJsonTransport.class);

  public static final String TRACE_PROP = "trace";

  public boolean shouldTrace(Message message){
    if (message.getPayload() == null){
      return false;
    }
    return message.getPayload().containsKey(TRACE_PROP);
  }

  public void trace(Message message, String s, Object ... stuff){
    TraceTo t = (TraceTo) message.getPayload().get(TRACE_PROP);
    if (t == TraceTo.LOGGER){
      LOGGER.info(System.currentTimeMillis() + " " + String.format(s, stuff) );
    }
  }
}


text:
<?xml version="1.0"?>
<ruleset name="Custom Standard">

  <rule ref="Generic">
    <exclude name="Generic.Functions.OpeningFunctionBraceKernighanRitchie.BraceOnNewLine"/>
    <exclude name="Generic.PHP.LowerCaseConstant.Found"/>
    <exclude name="Generic.Formatting.MultipleStatementAlignment.NotSameWarning"/>
   </rule>

  <rule ref="Generic.Files.LineLength">
    <properties>
     <property name="lineLimit" value="120"/>
     <property name="absoluteLineLimit" value="150"/>
    </properties>
  </rule>

</ruleset>


text:
package com.netflix.spinnaker.halyard.config.model.v1.artifacts.gitrepo;

import com.netflix.spinnaker.halyard.config.model.v1.node.ArtifactProvider;
import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
public class GitRepoArtifactProvider extends ArtifactProvider<GitRepoArtifactAccount> {
  @Override
  public ProviderType providerType() {
    return ProviderType.GITREPO;
  }
}


text:
angular.module('main_ctrl', [])
.controller('mainController', function($rootScope, $location, Auth) {
	var vm = this;

	vm.loggedIn = Auth.isLoggedIn();

	$rootScope.$on('$routeChangeStart', function(){
		vm.loggedIn = Auth.isLoggedIn();
	});

	Auth.getUser()
		.success(function(data){
			vm.user = data;
		});

	vm.doLogin = function() {
		Auth.login(vm.loginData.username, vm.loginData.password)
			.success(function(data){
				Auth.getUser()
					.then(function(data){
						vm.user = data.data;
					});
				$location.path('/users');
			});
	};

	vm.doLogout = function(){
		Auth.logout();
		$location.path('/');
	};
});


text:
from django.db import models
from django.conf import *
from django.utils import timezone
from model_utils.managers import InheritanceManager
from django.utils.translation import ugettext_lazy as _

# Create your models here.

class Broadcast(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='%(app_label)s_%(class)s_related')
    date = models.DateField(_('broadcast date'),default=timezone.now)
    time = models.TimeField(_('time'),default=timezone.now)
    send_to_all = models.BooleanField(_('send to all'),default=False)
    bc_from = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,default=None, null=True,on_delete=models.CASCADE, related_name='bcfrom')
    bc_time = models.TimeField(_('rebc time'),default=timezone.now)
    bc_date = models.DateField(_('rebc date'),default=timezone.now)

    objects = InheritanceManager()

    def liked(self):
        num = Like.objects.filter(broadcast_message=self).values_list('liker')

        result = []
        for liker in num:
            print(liker)
            user = liker[0]
            result.append(user)

        return result

    def get_absolute_url(self):
        return '/broadcast/%d/view/' % self.pk

class TextBroadcast(Broadcast):
    message = models.TextField()

class ImageBroadcast(Broadcast):
    image = models.ImageField()
    description = models.TextField()

class RideBroadcast(Broadcast):
    source = models.CharField(_('source'),max_length=256)
    dest = models.CharField(_('destination'),max_length=256)
    date_needed = models.DateField(_('date needed'),default=timezone.now)

class DirectionBroadcast(Broadcast):
    location = models.TextField(_('current Location'))
    destination = models.TextField(_('destination'))
    additional_info = models.TextField(_('additional information'))

class Comment(models.Model):

    commenter = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='commenter')
    broadcast_message = models.ForeignKey(Broadcast,on_delete=models.CASCADE,related_name='broadcast_comment')
    comment = models.TextField(_('comment'),blank=False)
    date = models.DateField(_('date'),default=timezone.now)
    time = models.TimeField(_('time'),default=timezone.now)

class Like(models.Model):
    liker = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='liker')
    broadcast_message = models.ForeignKey(Broadcast, on_delete=models.CASCADE,related_name='broadcast_like')
    date = models.DateField(_('date'), default=timezone.now)
    time = models.TimeField(_('time'), default=timezone.now)


text:
from __future__ import print_function
import curses
import os
from time import sleep, strftime, time

USER = os.environ['USER']

def print_time(stdscr, y=2, x=1):
  stdscr.addstr(y, x, strftime('%Y-%m-%d %H:%m:%S'))

def print_right_time(stdscr, y=3):
  time_length = 19
  x = stdscr.getmaxyx()[1] - time_length
  print_time(stdscr, y, x)

def main(stdscr):
  curses.curs_set(0)  ## sets cursor to be invisible
  stdscr.addstr(1,1, 'qstat for user ')
  stdscr.addstr(USER, curses.A_BOLD)
  print_right_time(stdscr, y=1)
  stdscr.refresh()

  stdscr.nodelay(1)  # set nodelay(1) to make getch non-blocking
  start = time()
  wait = time()
  while True:
    print_right_time(stdscr, y=1)
    stdscr.refresh()
    c = stdscr.getch()  ## without nodelay(1), code stops here and waits for input
                        ## getch returns ascii code, so to compare with a character, use `ord`-function.
    if c == ord('q') or c == ord('Q'):
      break
    if time() >= start + 60: ## limits total running time to 60 seconds
      print_qstat(stdscr)
    sleep(1)

## normally, you could do the below
#stdscr = curses.initscr()
#curses.noecho()  ## disables echoing of keys to the screen
#curses.cbreak()  ## react to keys instantly (i.e. do not wait for Enter)
#stdscr.keypad(1) ## enable use of special keys (Page Up, Home, etc.)
# main(stdscr)
## When exiting:
#curses.nocbreak(); stdscr.keypad(0); curses.echo()
#curses.endwin()
## but instead, we use the wrapper function
## -- the function `main` receivies the "main window" as an argument.

curses.wrapper(main)


text:
import os
import uuid
import random
import aiofiles
from pathlib import Path
from functools import wraps

class Filesystem:
    def path_wrapper(func):
        """
            Wrap method calls in the make_path call

            Has the benefit of making method calls platform agnostic
        """
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            # Change the args to a mutable data structure
            # This feels wrong!
            arg_list = list(args)
            arg_list[0] = self.make_path(arg_list[0])

            return func(self, *tuple(arg_list), **kwargs)
        return wrapper

    @path_wrapper
    async def read_binary_file(self, filepath: str) -> bytes:
        """ Asynchronously read a binary file """
        async with aiofiles.open(filepath, mode="rb") as f:
            return await f.read()

    @path_wrapper
    async def write_binary_file(self, filepath: str, file: bytes) -> None:
        """ Asynchronously write a binary file """
        dir_path = Path(filepath).parent

        if not dir_path.exists():
            dir_path.mkdir()

        async with aiofiles.open(filepath, mode="wb") as fp:
            await fp.write(file)

    @path_wrapper
    def remove_file(self, filepath):
        """ Remove a file """
        return os.remove(filepath)

    @path_wrapper
    def get_directory_listing(self, path: str) -> list:
        return os.listdir(path)

    @path_wrapper
    def get_random_file_path(self, path: str) -> str:
        files = self.get_directory_listing(path)
        random_file = Path(random.choice(files))
        return str(Path(path) / random_file)

    def make_path(self, path: str) -> str:
        """
            Convert a path to a platform dependant path

            E.g. converts /a/b/c to \\a\\b\\c if you're on Windows
        """
        return str(Path(path))

    async def generate_filename(self, extension=None) -> str:
        filename = uuid.uuid4().hex
        if extension is not None:
            filename += extension
        return filename


text:
@interface OrgApacheLuceneAnalysisCharfilterNormalizeCharMap ()

- (instancetype)initWithOrgApacheLuceneUtilFstFST:(OrgApacheLuceneUtilFstFST *)map;

@end

__attribute__((unused)) static void OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_initWithOrgApacheLuceneUtilFstFST_(OrgApacheLuceneAnalysisCharfilterNormalizeCharMap *self, OrgApacheLuceneUtilFstFST *map);

__attribute__((unused)) static OrgApacheLuceneAnalysisCharfilterNormalizeCharMap *new_OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_initWithOrgApacheLuceneUtilFstFST_(OrgApacheLuceneUtilFstFST *map) NS_RETURNS_RETAINED;

__attribute__((unused)) static OrgApacheLuceneAnalysisCharfilterNormalizeCharMap *create_OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_initWithOrgApacheLuceneUtilFstFST_(OrgApacheLuceneUtilFstFST *map);

@interface OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder () {
 @public
  id<JavaUtilMap> pendingPairs_;
}

@end

J2OBJC_FIELD_SETTER(OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder, pendingPairs_, id<JavaUtilMap>)

@implementation OrgApacheLuceneAnalysisCharfilterNormalizeCharMap

- (instancetype)initWithOrgApacheLuceneUtilFstFST:(OrgApacheLuceneUtilFstFST *)map {
  OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_initWithOrgApacheLuceneUtilFstFST_(self, map);
  return self;
}

- (void)dealloc {
  RELEASE_(map_);
  RELEASE_(cachedRootArcs_);
  [super dealloc];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x2, -1, 0, -1, 1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(initWithOrgApacheLuceneUtilFstFST:);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "map_", "LOrgApacheLuceneUtilFstFST;", .constantValue.asLong = 0, 0x10, -1, -1, 2, -1 },
    { "cachedRootArcs_", "LJavaUtilMap;", .constantValue.asLong = 0, 0x10, -1, -1, 3, -1 },
  };
  static const void *ptrTable[] = { "LOrgApacheLuceneUtilFstFST;", "(Lorg/apache/lucene/util/fst/FST<Lorg/apache/lucene/util/CharsRef;>;)V", "Lorg/apache/lucene/util/fst/FST<Lorg/apache/lucene/util/CharsRef;>;", "Ljava/util/Map<Ljava/lang/Character;Lorg/apache/lucene/util/fst/FST$Arc<Lorg/apache/lucene/util/CharsRef;>;>;", "LOrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder;" };
  static const J2ObjcClassInfo _OrgApacheLuceneAnalysisCharfilterNormalizeCharMap = { "NormalizeCharMap", "org.apache.lucene.analysis.charfilter", ptrTable, methods, fields, 7, 0x1, 1, 2, -1, 4, -1, -1, -1 };
  return &_OrgApacheLuceneAnalysisCharfilterNormalizeCharMap;
}

@end

void OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_initWithOrgApacheLuceneUtilFstFST_(OrgApacheLuceneAnalysisCharfilterNormalizeCharMap *self, OrgApacheLuceneUtilFstFST *map) {
  NSObject_init(self);
  JreStrongAssignAndConsume(&self->cachedRootArcs_, new_JavaUtilHashMap_init());
  JreStrongAssign(&self->map_, map);
  if (map != nil) {
    @try {
      OrgApacheLuceneUtilFstFST_Arc *scratchArc = create_OrgApacheLuceneUtilFstFST_Arc_init();
      OrgApacheLuceneUtilFstFST_BytesReader *fstReader = [map getBytesReader];
      [map getFirstArcWithOrgApacheLuceneUtilFstFST_Arc:scratchArc];
      if (OrgApacheLuceneUtilFstFST_targetHasArcsWithOrgApacheLuceneUtilFstFST_Arc_(scratchArc)) {
        [map readFirstRealTargetArcWithLong:scratchArc->target_ withOrgApacheLuceneUtilFstFST_Arc:scratchArc withOrgApacheLuceneUtilFstFST_BytesReader:fstReader];
        while (true) {
          JreAssert(scratchArc->label_ != OrgApacheLuceneUtilFstFST_END_LABEL, @"org/apache/lucene/analysis/charfilter/NormalizeCharMap.java:58 condition failed: assert scratchArc.label != FST.END_LABEL;");
          [self->cachedRootArcs_ putWithId:JavaLangCharacter_valueOfWithChar_((jchar) scratchArc->label_) withId:[create_OrgApacheLuceneUtilFstFST_Arc_init() copyFromWithOrgApacheLuceneUtilFstFST_Arc:scratchArc]];
          if ([scratchArc isLast]) {
            break;
          }
          [map readNextRealArcWithOrgApacheLuceneUtilFstFST_Arc:scratchArc withOrgApacheLuceneUtilFstFST_BytesReader:fstReader];
        }
      }
    }
    @catch (JavaIoIOException *ioe) {
      @throw create_JavaLangRuntimeException_initWithJavaLangThrowable_(ioe);
    }
  }
}

OrgApacheLuceneAnalysisCharfilterNormalizeCharMap *new_OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_initWithOrgApacheLuceneUtilFstFST_(OrgApacheLuceneUtilFstFST *map) {
  J2OBJC_NEW_IMPL(OrgApacheLuceneAnalysisCharfilterNormalizeCharMap, initWithOrgApacheLuceneUtilFstFST_, map)
}

OrgApacheLuceneAnalysisCharfilterNormalizeCharMap *create_OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_initWithOrgApacheLuceneUtilFstFST_(OrgApacheLuceneUtilFstFST *map) {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneAnalysisCharfilterNormalizeCharMap, initWithOrgApacheLuceneUtilFstFST_, map)
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneAnalysisCharfilterNormalizeCharMap)

@implementation OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder

J2OBJC_IGNORE_DESIGNATED_BEGIN
- (instancetype)init {
  OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder_init(self);
  return self;
}
J2OBJC_IGNORE_DESIGNATED_END

- (void)addWithNSString:(NSString *)match
           withNSString:(NSString *)replacement {
  if ([((NSString *) nil_chk(match)) java_length] == 0) {
    @throw create_JavaLangIllegalArgumentException_initWithNSString_(@"cannot match the empty string");
  }
  if ([((id<JavaUtilMap>) nil_chk(pendingPairs_)) containsKeyWithId:match]) {
    @throw create_JavaLangIllegalArgumentException_initWithNSString_(JreStrcat("$$$", @"match \"", match, @"\" was already added"));
  }
  [pendingPairs_ putWithId:match withId:replacement];
}

- (OrgApacheLuceneAnalysisCharfilterNormalizeCharMap *)build {
  OrgApacheLuceneUtilFstFST *map;
  @try {
    OrgApacheLuceneUtilFstOutputs *outputs = OrgApacheLuceneUtilFstCharSequenceOutputs_getSingleton();
    OrgApacheLuceneUtilFstBuilder *builder = create_OrgApacheLuceneUtilFstBuilder_initWithOrgApacheLuceneUtilFstFST_INPUT_TYPE_withOrgApacheLuceneUtilFstOutputs_(JreLoadEnum(OrgApacheLuceneUtilFstFST_INPUT_TYPE, BYTE2), outputs);
    OrgApacheLuceneUtilIntsRefBuilder *scratch = create_OrgApacheLuceneUtilIntsRefBuilder_init();
    for (id<JavaUtilMap_Entry> __strong ent in nil_chk([((id<JavaUtilMap>) nil_chk(pendingPairs_)) entrySet])) {
      [builder addWithOrgApacheLuceneUtilIntsRef:OrgApacheLuceneUtilFstUtil_toUTF16WithJavaLangCharSequence_withOrgApacheLuceneUtilIntsRefBuilder_([((id<JavaUtilMap_Entry>) nil_chk(ent)) getKey], scratch) withId:create_OrgApacheLuceneUtilCharsRef_initWithNSString_([ent getValue])];
    }
    map = [builder finish];
    [pendingPairs_ clear];
  }
  @catch (JavaIoIOException *ioe) {
    @throw create_JavaLangRuntimeException_initWithJavaLangThrowable_(ioe);
  }
  return create_OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_initWithOrgApacheLuceneUtilFstFST_(map);
}

- (void)dealloc {
  RELEASE_(pendingPairs_);
  [super dealloc];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x1, -1, -1, -1, -1, -1, -1 },
    { NULL, "V", 0x1, 0, 1, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneAnalysisCharfilterNormalizeCharMap;", 0x1, -1, -1, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(init);
  methods[1].selector = @selector(addWithNSString:withNSString:);
  methods[2].selector = @selector(build);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "pendingPairs_", "LJavaUtilMap;", .constantValue.asLong = 0, 0x12, -1, -1, 2, -1 },
  };
  static const void *ptrTable[] = { "add", "LNSString;LNSString;", "Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;", "LOrgApacheLuceneAnalysisCharfilterNormalizeCharMap;" };
  static const J2ObjcClassInfo _OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder = { "Builder", "org.apache.lucene.analysis.charfilter", ptrTable, methods, fields, 7, 0x9, 3, 1, 3, -1, -1, -1, -1 };
  return &_OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder;
}

@end

void OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder_init(OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder *self) {
  NSObject_init(self);
  JreStrongAssignAndConsume(&self->pendingPairs_, new_JavaUtilTreeMap_init());
}

OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder *new_OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder_init() {
  J2OBJC_NEW_IMPL(OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder, init)
}

OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder *create_OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder_init() {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder, init)
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneAnalysisCharfilterNormalizeCharMap_Builder)


text:
namespace v8 {
namespace internal {

#define __ ACCESS_MASM(masm)

void PropertyICCompiler::GenerateRuntimeSetProperty(
    MacroAssembler* masm, LanguageMode language_mode) {
  ASM_LOCATION("PropertyICCompiler::GenerateRuntimeSetProperty");

  __ Push(StoreDescriptor::ReceiverRegister(), StoreDescriptor::NameRegister(),
          StoreDescriptor::ValueRegister());

  __ Mov(x10, Smi::FromInt(language_mode));
  __ Push(x10);

  // Do tail-call to runtime routine.
  __ TailCallRuntime(Runtime::kSetProperty);
}

#undef __
}  // namespace internal
}  // namespace v8

#endif  // V8_TARGET_ARCH_ARM64


text:
<?php

use Iamdual\Browser\Client;
use PHPUnit\Framework\TestCase;

final class MethodsTest extends TestCase
{
    /**
     * @covers \Iamdual\Browser\Client
     */
    public function testPutMethodNative(): void
    {
        $result = Client::create(null, Client::PROVIDER_NATIVE)
            ->json(["hello" => "world", "user_id" => "3048763"])
            ->put("https://httpbin.org/put");

        $this->assertEquals("world", $result->json->json->hello);
        $this->assertEquals("3048763", $result->json->json->user_id);
    }

    /**
     * @covers \Iamdual\Browser\Client
     */
    public function testPutMethodCurl(): void
    {
        $result = Client::create(null, Client::PROVIDER_CURL)
            ->json(["hello" => "world", "user_id" => "3048763"])
            ->put("https://httpbin.org/put");

        $this->assertEquals("world", $result->json->json->hello);
        $this->assertEquals("3048763", $result->json->json->user_id);
    }
}