text:
const debug = require('ghost-ignition').debug('admin:controller'),
    path = require('path'),
    config = require('../../config'),
    updateCheck = require('../../update-check'),
    common = require('../../lib/common');

// Route: index
// Path: /ghost/
// Method: GET
module.exports = function adminController(req, res) {
    debug('index called');

    // run in background, don't block the admin rendering
    updateCheck()
        .catch(function onError(err) {
            common.logging.error(err);
        });

    let defaultTemplate = config.get('env') === 'production' ? 'default-prod.html' : 'default.html',
        templatePath = path.resolve(config.get('paths').adminViews, defaultTemplate);

    res.sendFile(templatePath);
};


text:
The repository for all of my blog content. This was created using Jekyll Now. Further information can be found and forked from here:

https://github.com/barryclark/jekyll-now

## About Me

I am in my final semester as a computer science major at Southern Illinois University Edwardsville. After discovering my calling in cyber security, I seek to share my personal projects, forward news in the industry, and create articles to help others new to the field get a head start. My main focus centers around wireless security (Wi-Fi & Bluetooth), web application exploitation, and systems security engineering.

### Blog Inception

As someone who struggles to think on a blank page, or discover a sense of direction on a topic I'm interested in, it is important to me to provide ideas and direction for those with similar interests and struggles as me. Additionally, to teach is an excellent way to learn. By creating posts, I will learn new topics in the field, be able to share them, and increase my technical writing abilities.

### Goals

Learn new competences around my focuses
Share knowledge from simple tasks to more laborious tasks
Increase technical writing abilities
Contribute to the security community
Archive for reflection
Contact me

admin@ryandinho.me

redpajama_set_name: RedPajamaGithub


text:
package org.isisaddons.security.dom.feature;

import java.util.List;

import org.isisaddons.security.service.ApplicationSecurityService;

import org.apache.isis.applib.AbstractFactoryAndRepository;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.query.QueryDefault;
import org.apache.isis.core.metamodel.services.devutils.MetaModelRow;

@DomainService
public class ApplicationFeatures extends AbstractFactoryAndRepository {

    @Programmatic
    public List<ApplicationFeature> allFeatures() {
        return allMatches(new QueryDefault<ApplicationFeature>(ApplicationFeature.class, "allByName"));
    }

    @Programmatic
    public List<ApplicationFeature> findByPackageName(String packageName) {
        return allMatches(new QueryDefault<ApplicationFeature>(ApplicationFeature.class, "findByPackageName", "packageName", packageName));
    }

    @Programmatic
    public ApplicationFeature findFeatureByName(String name) {
        return firstMatch(new QueryDefault<ApplicationFeature>(ApplicationFeature.class, "findByName", "name", name));
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Programmatic
    public List<String> findPackageName(String searchString) {
        String escapedString = searchString == null ? null : java.util.regex.Pattern.quote(searchString.replace("*", ".*"));
        return allMatches(new QueryDefault(ApplicationFeature.class, "findPackageName", "matcher", escapedString));
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Programmatic
    public List<String> allPackageNames() {
        return allMatches(new QueryDefault(ApplicationFeature.class, "allPackageNames"));
    }

    @Programmatic
    public ApplicationFeature addFeature(ApplicationSecurityService applicationSecurityService, MetaModelRow row) {
        final String name = row.getPackageName().concat(".").concat(row.getClassName()).concat(".").concat(row.getMemberName());

        final ApplicationFeature feature = findFeatureByName(name);
        if (feature != null) {
            return feature;
        }
        ApplicationFeature newFeature = newTransientInstance(ApplicationFeature.class);
        newFeature.setName(name);
        newFeature.setClassName(row.getClassName());
        newFeature.setPackageName(row.getPackageName());
        newFeature.setClassType(row.getClassType());
        newFeature.setMemberName(row.getMemberName());
        newFeature.setMemberType(row.getType());
        persist(newFeature);
        return newFeature;
    }

}


text:
namespace Google.Cloud.Logging.V2.Snippets
{
    // [START logging_v2_generated_ConfigServiceV2_GetExclusion_async_flattened]
    using Google.Cloud.Logging.V2;
    using System.Threading.Tasks;

    public sealed partial class GeneratedConfigServiceV2ClientSnippets
    {
        /// <summary>Snippet for GetExclusionAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetExclusionAsync()
        {
            // Create client
            ConfigServiceV2Client configServiceV2Client = await ConfigServiceV2Client.CreateAsync();
            // Initialize request argument(s)
            string name = "projects/[PROJECT]/exclusions/[EXCLUSION]";
            // Make the request
            LogExclusion response = await configServiceV2Client.GetExclusionAsync(name);
        }
    }
    // [END logging_v2_generated_ConfigServiceV2_GetExclusion_async_flattened]
}


text:
layout: null
permalink: /atom.xml
---
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <title>{{ site.data.main.name }}</title>
 <link href="{{ site.data.main.link }}/atom.xml" rel="self"/>
 <link href="{{ site.data.main.link }}"/>
 <updated>{{ site.time | date_to_xmlschema }}</updated>
 <id>{{ site.data.main.link }}</id>
 <author>
   <name>{{ site.data.main.name }}</name>
 </author>

 {% for post in site.posts %}
 <entry>
   <title>{{ post.title }}</title>
   <link href="{{ site.link }}{{ post.url }}"/>
   <updated>{{ post.date | date_to_xmlschema }}</updated>
   <id>{{ site.link }}{{ post.id }}</id>
   <content type="html">{{ post.content | xml_escape }}</content>
 </entry>
 {% endfor %}

</feed>


text:
- Adaptation to Dart 2.0

## 0.0.8

- Minor bug fixes

## 0.0.7

- Minor bug fixes
- Minor improvements in the scheduling and interleaving of the threads

## 0.0.6

- Bug fixes

## 0.0.5

- Bug fixes
- Solved the problem with sleeping microtasks

## 0.0.4

- Fixed bug with exception injection. Has the effect on interruption of the passive threads

## 0.0.3

- Added public getter `Thread.state`

## 0.0.2

- Added an example `example_producer_consumer_problem.dart`. Also known as the `bounded-buffer problem`

## 0.0.1

- Initial release


text:
/**
 * @module TweenJS
 */

// namespace:
this.createjs = this.createjs||{};

(function() {
	"use strict";

	/**
	 * A sample TweenJS plugin. This plugin does not actually affect tweens in any way, it's merely intended to document
	 * how to build TweenJS plugins. Please look at the code for inline comments.
	 *
	 * A TweenJS plugin is simply an object that exposes one property (priority), and three methods (init, step, and tween).
	 * Generally a plugin will also expose an install method as well, though this is not strictly necessary.
	 * @class SamplePlugin
	 * @constructor
	 **/
	function SamplePlugin() {
		throw("SamplePlugin cannot be instantiated.")
	};

// static interface:
	/**
	 * Used by TweenJS to determine when to call this plugin. Plugins with higher priority have their methods called
	 * before plugins with lower priority. The priority value can be any positive or negative number.
	 * @property priority
	 * @static
	 **/
	SamplePlugin.priority = 0;

	/**
	 * Installs this plugin for use with TweenJS, and registers for a list of properties that this plugin will operate
	 * with. Call this once after TweenJS is loaded to enable this plugin.
	 * @method install
	 * @static
	 **/
	SamplePlugin.install = function() {
		// this registers this plugin to work with the "test" property.
		createjs.Tween.installPlugin(SamplePlugin, ["test"]);
	};

	/**
	 * Called by TweenJS when a new tween property initializes that this plugin is registered for. Generally, the call
	 * to Plugin.init will be immediately followed by a call to Plugin.step.
	 * @method init
	 * @param {Tween} tween The related tween instance.
	 * @param {String} prop The name of the property that is being initialized.
	 * @param {any} value The current value of the property on the tween's target.
	 * @return {any} The starting tween value for the property. In most cases, you would simply
	 * return the value parameter, but some plugins may need to modify the starting value.
	 * @static
	 **/
	SamplePlugin.init = function(tween, prop, value) {
		console.log("init", prop, value);

		// return the unmodified property value:
		return value;
	};

	/**
	 * Called by TweenJS when a new step is added to a tween that includes a property the plugin is registered for (ie.
	 * a new "to" action is added to a tween).
	 * @method init
	 * @param {Tween} tween The related tween instance.
	 * @param {String} prop The name of the property being tweened.
	 * @param {any} startValue The value of the property at the beginning of the step. This will
	 * be the same as the init value if this is the first step, or the same as the
	 * endValue of the previous step if not.
	 * @param {Object} injectProps A generic object to which the plugin can append other properties which should be updated on this step.
	 * @param {any} endValue The value of the property at the end of the step.
	 * @static
	 **/
	SamplePlugin.step = function(tween, prop, startValue, endValue, injectProps) {
		console.log("to: ", prop, startValue, endValue);
	};

	/**
	 * Called when a tween property advances that this plugin is registered for.
	 * @method tween
	 * @param {Tween} tween The related tween instance.
	 * @param {String} prop The name of the property being tweened.
	 * @param {any} value The current tweened value of the property, as calculated by TweenJS.
	 * @param {Object} startValues A hash of all of the property values at the start of the current
	 * step. You could access the start value of the current property using
	 * startValues[prop].
	 * @param {Object} endValues A hash of all of the property values at the end of the current
	 * step.
	 * @param {Number} ratio A value indicating the eased progress through the current step. This
	 * number is generally between 0 and 1, though some eases will generate values outside
	 * this range.
	 * @param {Boolean} wait Indicates whether the current step is a "wait" step.
	 * @param {Boolean} end Indicates that the tween has reached the end.
	 * @return {any} Return the value that should be assigned to the target property. For example
	 * returning Math.round(value) would assign the default calculated value
	 * as an integer. Returning Tween.IGNORE will prevent Tween from assigning a value to
	 * the target property.
	 * @static
	 **/
	SamplePlugin.tween = function(tween, prop, value, startValues, endValues, ratio, wait, end) {
		// ratio is the eased ratio
		console.log("tween", prop, value, ratio, wait, end);

		// return the unmodified calculated tween value (use the default tweening behaviour):
		return value;
	};

	createjs.SamplePlugin = SamplePlugin;

}());


text:
@interface PodsDummy_Pods_MakeItHybrid_Tests_FBSnapshotTestCase : NSObject
@end
@implementation PodsDummy_Pods_MakeItHybrid_Tests_FBSnapshotTestCase
@end


text:
$:.unshift File.expand_path("..", __FILE__) unless $:.include? File.expand_path("..", __FILE__)

require 'rake'
require 'thor'
require 'httparty'
require 'redis'
require 'json'

require 'whirl/version'
require 'whirl/redis'
require 'whirl/job/base'

module Whirl
  def self.jobs
    jobs = Whirl::Job.constants.
      map { |d| Whirl::Job.const_get(d) }.
      select { |d| d.respond_to? :perform }

    jobs -= [Whirl::Job::Base]
  end

  def self.run
    trap("SIGINT") do
      Whirl::Job::Base.newline
      Whirl::Job::Base.say "Whirled.", :green
      Whirl::Job::Base.newline
      exit 0
    end

    begin
      jobs.each do |j|
        fork do
          j.perform
        end
      end

      sleep whirl_interval.to_i
    end while loop?
  end

  def self.loop?
    true
  end

  def self.whirl_interval
    ENV['WHIRL_LOOP_INTERVAL'] || 10
  end
end


text:
#ifndef IVW_PYTHONEXECUTIONOUTPUTOBSERVABLE_H
#define IVW_PYTHONEXECUTIONOUTPUTOBSERVABLE_H

#include <modules/python3/python3moduledefine.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/util/observer.h>

namespace inviwo {

enum IVW_MODULE_PYTHON3_API PythonExecutionOutputStream { sysstdout, sysstderr };

class IVW_MODULE_PYTHON3_API PythonExecutionOutputObeserver : public Observer {
public:
    virtual void onPyhonExecutionOutput(const std::string &msg,
                                        const PythonExecutionOutputStream &outputType) = 0;
};

class IVW_MODULE_PYTHON3_API PythonExecutionOutputObservable
    : public Observable<PythonExecutionOutputObeserver> {
public:
    void pythonExecutionOutputEvent(const std::string &msg,
                                    const PythonExecutionOutputStream &outputType);
};

}  // namespace

#endif  // IVW_PYTHONEXECUTIONOUTPUTOBSERVABLE_H


text:
from __future__ import print_function, division, absolute_import, unicode_literals

import logging
import re

from glyphsLib.util import cast_to_number_or_bool, reverse_cast_to_number_or_bool

logger = logging.getLogger(__name__)

def parse_glyphs_filter(filter_str, is_pre=False):
    """Parses glyphs custom filter string into a dict object that
       ufo2ft can consume.

        Reference:
            ufo2ft: https://github.com/googlei18n/ufo2ft
            Glyphs 2.3 Handbook July 2016, p184

        Args:
            filter_str - a string of glyphs app filter

        Return:
            A dictionary contains the structured filter.
            Return None if parse failed.
    """
    elements = filter_str.split(";")

    if elements[0] == "":
        logger.error(
            "Failed to parse glyphs filter, expecting a filter name: \
             %s",
            filter_str,
        )
        return None

    result = {"name": elements[0]}
    for idx, elem in enumerate(elements[1:]):
        if not elem:
            # skip empty arguments
            continue
        if ":" in elem:
            # Key value pair
            key, value = elem.split(":", 1)
            if key.lower() in ["include", "exclude"]:
                if idx != len(elements[1:]) - 1:
                    logger.error(
                        "{} can only present as the last argument in the filter. "
                        "{} is ignored.".format(key, elem)
                    )
                    continue
                result[key.lower()] = re.split("[ ,]+", value)
            else:
                if "kwargs" not in result:
                    result["kwargs"] = {}
                result["kwargs"][key] = cast_to_number_or_bool(value)
        else:
            if "args" not in result:
                result["args"] = []
            result["args"].append(cast_to_number_or_bool(elem))
    if is_pre:
        result["pre"] = True
    return result

def write_glyphs_filter(result):
    elements = [result["name"]]
    if "args" in result:
        for arg in result["args"]:
            elements.append(reverse_cast_to_number_or_bool(arg))
    if "kwargs" in result:
        for key, arg in result["kwargs"].items():
            if key.lower() not in ("include", "exclude"):
                elements.append(key + ":" + reverse_cast_to_number_or_bool(arg))
        for key, arg in result["kwargs"].items():
            if key.lower() in ("include", "exclude"):
                elements.append(key + ":" + reverse_cast_to_number_or_bool(arg))
    for key, arg in result.items():
        if key.lower() in ("include", "exclude"):
            elements.append(key + ":" + ",".join(arg))
    return ";".join(elements)


text:
package ru.yandexmusiccasher;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}


text:
package org.apache.hc.core5.http;

/**
 * Represents an element of an HTTP {@link Header header} value consisting of
 * a name / value pair and a number of optional name / value parameters.
 *
 * @since 4.0
 */
public interface HeaderElement {

    /**
     * Returns header element name.
     *
     * @return header element name
     */
    String getName();

    /**
     * Returns header element value.
     *
     * @return header element value
     */
    String getValue();

    /**
     * Returns an array of name / value pairs.
     *
     * @return array of name / value pairs
     */
    NameValuePair[] getParameters();

    /**
     * Returns the first parameter with the given name.
     *
     * @param name parameter name
     *
     * @return name / value pair
     */
    NameValuePair getParameterByName(String name);

    /**
     * Returns the total count of parameters.
     *
     * @return parameter count
     */
    int getParameterCount();

    /**
     * Returns parameter with the given index.
     *
     * @param index index
     * @return name / value pair
     */
    NameValuePair getParameter(int index);

}


text:
from osc_lib.command import command
from osc_lib import utils

object_path = "/classifications"
resource = 'classification'

class CreateIPV4Classification(command.ShowOne):
    """Create an IPV4 Classification."""

    def get_parser(self, prog_name):
        parser = super(CreateIPV4Classification, self).get_parser(prog_name)
        parser.add_argument(
            'name', metavar='NAME',
            help=('Name of the IPV4 Classification.'))
        parser.add_argument(
            '--description',
            help=('Description for the IPV4 Classification.'))
        parser.add_argument(
            '--negated',
            help=('Whether the complement of the IPV4 '
                  'Classification should be matched.'))
        parser.add_argument(
            '--shared',
            help=('Whether the IPV4 Classification should be '
                  'shared with other projects.'))
        parser.add_argument(
            '--dscp',
            help=('DSCP Classification value. Type of Service.'))
        parser.add_argument(
            '--dscp-mask',
            help=('DSCP Mask value. Type of Service.'))
        parser.add_argument(
            '--ecn',
            help=('Allows notification of network congestion.'))
        parser.add_argument(
            '--length-min',
            help=('Minimum length of the IP Packet, including '
                  'IP header and IP payload.'))
        parser.add_argument(
            '--length-max',
            help=('Maximum length of the IP Packet, including '
                  'IP header and IP payload.'))
        parser.add_argument(
            '--flags',
            help=('Whether the packet can be fragmented.'))
        parser.add_argument(
            '--flags-mask',
            help=('Whether the packet can be fragmented.'))
        parser.add_argument(
            '--ttl-min',
            help=('Minimum number of hops which the packet may '
                  'be routed over.'))
        parser.add_argument(
            '--ttl-max',
            help=('Maximum number of hops which the packet may '
                  'be routed over.'))
        parser.add_argument(
            '--protocol',
            help=('Type of transport the packet belongs to.'))
        parser.add_argument(
            '--src-addr',
            help=('Source Address of the IPV4 Classification.'))
        parser.add_argument(
            '--dst-addr',
            help=('Destination Address of the IPV4 Classification.'))
        parser.add_argument(
            '--options',
            help=('Options values for the IPV4 Classification.'))
        parser.add_argument(
            '--options-mask',
            help=('Options values for the IPV4 Classification.'))

        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.neutronclient
        attrs = _get_attrs(self.app.client_manager,
                           parsed_args, is_create=True)
        obj = client.create_ext(object_path, {resource: attrs})
        columns = _get_columns(obj[resource])
        data = utils.get_dict_properties(obj[resource], columns)
        return columns, data

class DeleteIPV4Classification(command.Command):
    """Delete a given IPV4 Classification."""

    def get_parser(self, prog_name):
        parser = super(DeleteIPV4Classification, self).get_parser(prog_name)
        parser.add_argument(
            'ipv4_classification',
            metavar="IPV4_CLASSIFICATION",
            help=('ID of the IPV4 Classification to delete.'))
        return parser

    def take_action(self, parsed_args):
        id = parsed_args.ipv4_classification
        client = self.app.client_manager.neutronclient
        client.delete_ext(object_path + '/%s', id)

class ListIPV4Classification(command.Lister):
    """List the IPV4 Classification that belong to a given tenant."""

    def take_action(self, parsed_args):
        data = self.app.client_manager.neutronclient.list(
            collection='classifications', path=object_path,
            retrieve_all=True, c_type='ipv4')
        headers = ('C_Type', 'ID', 'Name', 'Description', 'Negated', 'Shared')
        columns = ('c_type', 'id', 'name', 'description', 'negated', 'shared')

        return (headers, (utils.get_dict_properties(
            s, columns) for s in data['classifications']))

class ShowIPV4Classification(command.ShowOne):
    """Show information of a given IPV4 Classification"""

    def get_parser(self, prog_name):
        parser = super(ShowIPV4Classification, self).get_parser(prog_name)
        parser.add_argument(
            'ipv4_classification',
            metavar="IPV4_CLASSIFICATION",
            help=('ID of the IPV4 Classification to display.'))

        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.neutronclient
        cl = client.show_ext(object_path + '/%s',
                             parsed_args.ipv4_classification, c_type='ipv4')
        columns = _get_columns(cl[resource])
        data = utils.get_dict_properties(cl[resource], columns)
        return columns, data

class UpdateIPV4Classification(command.ShowOne):
    """Update name and description of a given IPV4Classification."""

    def get_parser(self, prog_name):
        parser = super(UpdateIPV4Classification, self).get_parser(prog_name)
        parser.add_argument(
            '--name', default='',
            metavar='NAME',
            help=('Name of the IPV4 Classification.'))
        parser.add_argument(
            '--description', default='',
            help=('Description of the IPV4 Classification.'))
        parser.add_argument(
            'ipv4_classification',
            metavar="IPV4_CLASSIFICATION",
            help=('ID of the IPV4 Classification to update.'))

        return parser

    def take_action(self, parsed_args):
        id = parsed_args.ipv4_classification
        client = self.app.client_manager.neutronclient
        attrs = _get_attrs(self.app.client_manager,
                           parsed_args, is_create=False)
        cl = client.update_ext(object_path + '/%s', id, {resource: attrs})
        columns = _get_columns(cl[resource])
        data = utils.get_dict_properties(cl[resource], columns)
        return columns, data

def _get_attrs(client_manager, parsed_args, is_create=False):
    attrs = {}
    definition = {}

    if parsed_args.name is not None:
        attrs['name'] = str(parsed_args.name)
    if parsed_args.description is not None:
        attrs['description'] = str(parsed_args.description)
    if is_create:
        attrs['c_type'] = 'ipv4'
        if parsed_args.negated is not None:
            attrs['negated'] = str(parsed_args.negated)
        if parsed_args.shared is not None:
            attrs['shared'] = str(parsed_args.shared)
        if parsed_args.dscp is not None:
            definition['dscp'] = parsed_args.dscp
        if parsed_args.dscp_mask is not None:
            definition['dscp_mask'] = parsed_args.dscp_mask
        if parsed_args.ecn is not None:
            definition['ecn'] = parsed_args.ecn
        if parsed_args.length_min is not None:
            definition['length_min'] = parsed_args.length_min
        if parsed_args.length_max is not None:
            definition['length_max'] = parsed_args.length_max
        if parsed_args.ttl_min is not None:
            definition['ttl_min'] = parsed_args.ttl_min
        if parsed_args.flags is not None:
            definition['flags'] = parsed_args.flags
        if parsed_args.flags_mask is not None:
            definition['flags_mask'] = parsed_args.flags_mask
        if parsed_args.protocol is not None:
            definition['protocol'] = parsed_args.protocol
        if parsed_args.src_addr is not None:
            definition['src_addr'] = parsed_args.src_addr
        if parsed_args.dst_addr is not None:
            definition['dst_addr'] = parsed_args.dst_addr
        if parsed_args.options is not None:
            definition['options'] = parsed_args.options
        if parsed_args.options_mask is not None:
            definition['options_mask'] = parsed_args.options_mask
        attrs['definition'] = definition

    return attrs

def _get_columns(resource):
    columns = list(resource.keys())
    if 'tenant_id' in columns:
        columns.remove('tenant_id')
    if 'project_id' not in columns:
        columns.append('project_id')
    return tuple(sorted(columns))


text:
order: 3
title:
  zh-CN: 日期时间选择
  en-US: Choose Time
---

## zh-CN

增加选择时间功能,当 `showTime` 为一个对象时,其属性会传递给内建的 `TimePicker`。

## en-US

This property provide an additional time selection. When `showTime` is an Object, its properties will be passed on to built-in `TimePicker`.

```tsx
import { DatePicker, Space } from 'antd';
import type { DatePickerProps, RangePickerProps } from 'antd/es/date-picker';
import React from 'react';

const { RangePicker } = DatePicker;

const onChange = (
  value: DatePickerProps['value'] | RangePickerProps['value'],
  dateString: [string, string] | string,
) => {
  console.log('Selected Time: ', value);
  console.log('Formatted Selected Time: ', dateString);
};

const onOk = (value: DatePickerProps['value'] | RangePickerProps['value']) => {
  console.log('onOk: ', value);
};

const App: React.FC = () => (
  <Space direction="vertical" size={12}>
    <DatePicker showTime onChange={onChange} onOk={onOk} />
    <RangePicker
      showTime={{ format: 'HH:mm' }}
      format="YYYY-MM-DD HH:mm"
      onChange={onChange}
      onOk={onOk}
    />
  </Space>
);

export default App;
```


text:
<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\EntityRole */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= Html::hiddenInput('referrer', Yii::$app->request->referrer) ?>

    <?= Html::hiddenInput('entity', Yii::$app->request->get('id')) ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Сохранить' : 'Сохранить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
package magic.yuyong.model;

import java.util.ArrayList;
import java.util.List;

import magic.yuyong.util.Debug;
import magic.yuyong.util.JsonUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Parcel;

public class User implements android.os.Parcelable {
	private static final String ID = "id";
	private static final String SCREEN_NAME = "screen_name";
	private static final String PROFILE_IMAGE_URL = "profile_image_url";
	private static final String AVATAR_LARGE = "avatar_large";
	private static final String GENDER = "gender";
	private static final String LOCATION = "location";
	private static final String DESCRIPTION = "description";
	private static final String FOLLOWERS_COUNT = "followers_count";
	private static final String FRIENDS_COUNT = "friends_count";
	private static final String STATUSES_COUNT = "statuses_count";
	private static final String FAVOURITES_COUNT = "favourites_count";
	private static final String FOLLOWING = "following";
	private static final String FOLLOW_ME = "follow_me";

	private Long id;
	private String screen_name;
	private String profile_image_url;
	private String avatar_large;
	private String gender;
	private String location;
	private String description;
	private int followers_count;
	private int friends_count;
	private int statuses_count;
	private int favourites_count;
	private boolean following;
	private boolean follow_me;

	private boolean isChoose;

	public User() {
		super();
		this.id = 0L;
		this.screen_name = "";
		this.profile_image_url = "";
		this.avatar_large = "";
		this.gender = "";
		this.location = "";
		this.description = "";
		this.followers_count = 0;
		this.friends_count = 0;
		this.statuses_count = 0;
		this.favourites_count = 0;
		this.following = false;
		this.follow_me = false;
		this.isChoose = false;
	}

	public Long getId() {
		return id;
	}

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

	public String getScreen_name() {
		return screen_name;
	}

	public void setScreen_name(String screen_name) {
		this.screen_name = screen_name;
	}

	public String getProfile_image_url() {
//		return profile_image_url;
		return avatar_large;
	}

	public void setProfile_image_url(String profile_image_url) {
		this.profile_image_url = profile_image_url;
	}

	public String getImageView_large() {
		return avatar_large;
	}

	public void setImageView_large(String avatar_large) {
		this.avatar_large = avatar_large;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public String getDescription() {
		return description;
	}

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

	public int getFollowers_count() {
		return followers_count;
	}

	public void setFollowers_count(int followers_count) {
		this.followers_count = followers_count;
	}

	public int getFriends_count() {
		return friends_count;
	}

	public void setFriends_count(int friends_count) {
		this.friends_count = friends_count;
	}

	public int getStatuses_count() {
		return statuses_count;
	}

	public void setStatuses_count(int statuses_count) {
		this.statuses_count = statuses_count;
	}

	public int getFavourites_count() {
		return favourites_count;
	}

	public void setFavourites_count(int favourites_count) {
		this.favourites_count = favourites_count;
	}

	public boolean isFollowing() {
		return following;
	}

	public void setFollowing(boolean following) {
		this.following = following;
	}

	public boolean isFollow_me() {
		return follow_me;
	}

	public void setFollow_me(boolean follow_me) {
		this.follow_me = follow_me;
	}

	public boolean isChoose() {
		return isChoose;
	}

	public void setChoose(boolean isChoose) {
		this.isChoose = isChoose;
	}

	public static User parse(JSONObject jsonObj) {
		User user = new User();
		user.setId(JsonUtil.getLong(jsonObj, ID));
		user.setScreen_name(JsonUtil.getString(jsonObj, SCREEN_NAME));
		user.setProfile_image_url(JsonUtil
				.getString(jsonObj, PROFILE_IMAGE_URL));
		user.setImageView_large(JsonUtil
				.getString(jsonObj, AVATAR_LARGE));
		user.setGender(JsonUtil.getString(jsonObj, GENDER));
		user.setLocation(JsonUtil.getString(jsonObj, LOCATION));
		user.setDescription(JsonUtil.getString(jsonObj, DESCRIPTION));
		user.setFriends_count(JsonUtil.getInt(jsonObj, FRIENDS_COUNT));
		user.setStatuses_count(JsonUtil.getInt(jsonObj, STATUSES_COUNT));
		user.setFollowers_count(JsonUtil.getInt(jsonObj, FOLLOWERS_COUNT));
		user.setFavourites_count(JsonUtil.getInt(jsonObj, FAVOURITES_COUNT));
		user.setFollowing(JsonUtil.getBoolean(jsonObj, FOLLOWING));
		user.setFollow_me(JsonUtil.getBoolean(jsonObj, FOLLOW_ME));

		return user;
	}

	public static List<User> parseUsers(String json) {
		try {
			List<User> list = new ArrayList<User>();
			JSONObject jsonObj = new JSONObject(json);
			JSONArray jsonArray = JsonUtil.getJSONArray(jsonObj, "users");
			if (jsonArray != null && jsonArray.length() != 0) {
				for (int i = 0; i < jsonArray.length(); i++) {
					jsonObj = ((JSONObject) jsonArray.opt(i));
					User user = parse(jsonObj);
					if (user != null)
						list.add(user);
				}
			}
			return list;
		} catch (Exception e) {
			Debug.e("Exception : " + e.getMessage());
		}
		return null;
	}

	public static final android.os.Parcelable.Creator<User> CREATOR = new android.os.Parcelable.Creator<User>() {

		@Override
		public User createFromParcel(Parcel source) {
			User user = new User();
			user.id = source.readLong();
			user.screen_name = source.readString();
			user.profile_image_url = source.readString();
			user.avatar_large = source.readString();
			user.gender = source.readString();
			user.location = source.readString();
			user.description = source.readString();
			user.friends_count = source.readInt();
			user.statuses_count = source.readInt();
			user.followers_count = source.readInt();
			user.favourites_count = source.readInt();
			user.following = Boolean.valueOf(source.readString());
			user.follow_me = Boolean.valueOf(source.readString());
			return user;
		}

		@Override
		public User[] newArray(int size) {
			return new User[size];
		}

	};

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeLong(id);
		dest.writeString(screen_name);
		dest.writeString(profile_image_url);
		dest.writeString(avatar_large);
		dest.writeString(gender);
		dest.writeString(location);
		dest.writeString(description);
		dest.writeInt(friends_count);
		dest.writeInt(statuses_count);
		dest.writeInt(followers_count);
		dest.writeInt(favourites_count);
		dest.writeString(String.valueOf(following));
		dest.writeString(String.valueOf(follow_me));
	}
}


text:
<?php
namespace Clutch\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Question\Question;
use Clutch\Command\BaseCommand;
use ZipArchive;
use Symfony\Component\Finder\Finder;
use Symfony\Component\DomCrawler\Crawler;
use Wa72\HtmlPageDom\HtmlPageCrawler;

class CreateCommand extends Command {
  protected function configure(){
    $this
      ->setName('generate')
      ->setDescription('This will generate your components folder')
      ->setDefinition(array(
        new InputOption('sitemap-url',
        '-url', InputOption::VALUE_REQUIRED, 'Name of the zip file.'),
        new InputOption('theme-name', 't', InputOption::VALUE_REQUIRED, 'Theme Name'),
        new InputOption('theme-description', 'd', InputOption::VALUE_REQUIRED, 'Theme description'),
      ));
  }

   protected function execute(InputInterface $input, OutputInterface $output) {
    $zipFile = $input->getOption('sitemap-url');
    if(!$zipFile){
      $helper = $this->getHelper('question');
      $question = new Question('<info>Please enter your sitemap URL:</info> <comment>http://YOURSITE.webflow.io/sitemap.xml]</comment> ');
      $zipFile = $helper->ask($input, $output, $question);
    }
    $withZip = $zipFile. ".zip";
    // Theme Name
    $theme = $input->getOption('theme-name');
    if(!$theme){
      $helper = $this->getHelper('question');
      $question = new Question('<info>Please enter theme name:</info> <comment>[webflow]</comment> ', 'webflow');
      $theme = $helper->ask($input, $output, $question);
    }

    $themeDesc = 'These is a webflow theme';

    $tempPath = getcwd().'/temp';

    $sitemap = file_get_contents(trim($zipFile));
    $crawler = new Crawler($sitemap);
    $nodeValues = $crawler->filter('url')->each(function (Crawler $node, $i) {
      return $node->text();
    });

    foreach($nodeValues as $site) {
      $url = file_get_contents(trim($site));
      $page = new HtmlPageCrawler($url);
      $images = $page
        ->filterXpath('//img')
        ->extract(array('src'));
          foreach ($images as $image) {
              $path = basename($image);
              $imageName = ltrim(stristr($path, '_'), '_');
              $insert = file_put_contents('images', $imageName);
              if (!$insert) {
                  throw new \Exception('Failed to write image');
              }
          }
        // echo $page->filter('div')->addClass('w-section')->setAttribute('data-block', 'that_block');
    }
    $style = $page->filterXpath('//style')->text(). "\r\n";
    // $script = $page->filter('script')->attr('src'). "\r\n";
    $script = $page->filter('script')->extract(array('src'));
      foreach ($script as $src) {
          echo $src;
      }

    $extract_webflow_dir = "$tempPath/$zipFile/";

    $htmlfiles = array();

    $finder = new Finder();
    $finder->files()->name('*.html')->in($extract_webflow_dir);
    foreach ($finder as $file) {
      $htmlfiles[] = $file->getRealpath();
    }
    $theme_machine_name = strtolower(str_replace(" ","_",$theme));
    $root = getcwd();
    $themeDir = "$root/themes/$theme_machine_name/";
    if(!file_exists($themeDir)) {
      mkdir($themeDir, 0777);
    }
    $clutchCLI = new ClutchCli();
    $folders_to_copy = array('blocks','nodes', 'menus', 'forms', 'css', 'js', 'fonts', 'images');
    $clutchCLI->traverseFiles($extract_webflow_dir, $themeDir, $theme_machine_name, $htmlfiles);
    $clutchCLI->copyWebflowFilesToTheme($extract_webflow_dir, $themeDir, $theme_machine_name, $folders_to_copy, $output);
    $theme_vars = array('{{themeName}}'=> $theme,'{{themeMachine}}'=> $theme_machine_name,'{{themeDescription}}'=> $themeDesc);
    $clutchCLI->generateThemeTemplates($themeDir, $theme_vars);
    $clutchCLI->deleteDirectory($tempPath);
    $output->writeln('<comment>'. "\r\n" .'Your theme '.$theme.' is now created.</comment>');
  }
}


text:
package connect.ui.activity.login.presenter;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import connect.ui.activity.R;
import connect.ui.activity.login.bean.UserBean;
import connect.ui.activity.login.contract.ScanLoginContract;
import connect.ui.activity.set.presenter.BackUpPresenter;
import connect.utils.ConfigUtil;
import connect.utils.ProgressUtil;
import connect.utils.ProtoBufUtil;
import connect.utils.ToastEUtil;
import connect.utils.ToastUtil;
import connect.utils.UriUtil;
import connect.utils.cryption.DecryptionUtil;
import connect.utils.cryption.SupportKeyUril;
import connect.utils.okhttp.OkHttpUtil;
import connect.utils.okhttp.ResultCall;
import protos.Connect;

/**
 * Created by Administrator on 2017/4/13 0013.
 */

public class ScanLoginPresenter implements ScanLoginContract.Presenter{

    public final int PARSE_BARCODE_SUC = 601;
    private final ScanLoginContract.View mView;

    public ScanLoginPresenter(ScanLoginContract.View mView) {
        this.mView = mView;
    }

    @Override
    public void start() {

    }

    @Override
    public Handler getHandle() {
        return mLocalHandler;
    }

    public Handler mLocalHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ProgressUtil.getInstance().dismissProgress();
            switch (msg.what){
                case PARSE_BARCODE_SUC:
                    checkString((String) msg.obj);
                    break;
            }
        }
    };

    @Override
    public void checkString(String value) {
        if(SupportKeyUril.checkPrikey(value)){
            requestExisted(value);
            return;
        }

        try {
            String enStr = value.replace(BackUpPresenter.scanHead,"");
            if(TextUtils.isEmpty(enStr)){
                ToastUtil.getInstance().showToast(R.string.Login_scan_string_error);
            }else{
                byte[] byteArrayDe = Base64.decode(enStr, Base64.DEFAULT);
                Connect.ExoprtPrivkeyQrcode privkeyQrcode = Connect.ExoprtPrivkeyQrcode.parseFrom(byteArrayDe);
                switch (privkeyQrcode.getVersion()) {
                    case 1:
                    case 2:
                        UserBean userBean = new UserBean();
                        userBean.setName(privkeyQrcode.getUsername());
                        userBean.setTalkKey(privkeyQrcode.getEncriptionPri());
                        userBean.setPassHint(privkeyQrcode.getPasswordHint());
                        userBean.setPhone(privkeyQrcode.getPhone());
                        userBean.setAvatar(ConfigUtil.getInstance().serverAddress() + "/avatar/v1/"
                                + privkeyQrcode.getAvatar() + ".jpg");
                        userBean.setConnectId(privkeyQrcode.getConnectId());
                        mView.goinCodeLogin(userBean, "");
                        break;
                    default:
                        ToastEUtil.makeText(mView.getActivity(), R.string.Login_Invalid_version_number, ToastEUtil.TOAST_STATUS_FAILE).show();
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastEUtil.makeText(mView.getActivity(),R.string.Login_scan_string_error,ToastEUtil.TOAST_STATUS_FAILE).show();
        }
    }

    private void requestExisted(final String priKey){
        OkHttpUtil.getInstance().postEncry(UriUtil.CONNECT_V1_PRIVATE_EXISTED,
                ByteString.copyFrom(SupportKeyUril.createrBinaryRandom()),
                SupportKeyUril.EcdhExts.EMPTY,
                priKey,
                SupportKeyUril.getPubKeyFromPriKey(priKey),
                new ResultCall<Connect.HttpResponse>() {
                    @Override
                    public void onResponse(Connect.HttpResponse response) {
                        try {
                            Connect.IMResponse imResponse = Connect.IMResponse.parseFrom(response.getBody().toByteArray());
                            Connect.StructData structData = DecryptionUtil.decodeAESGCMStructData(SupportKeyUril.EcdhExts.EMPTY,priKey,imResponse.getCipherData());
                            if(structData == null){
                                ToastEUtil.makeText(mView.getActivity(),R.string.Network_equest_failed_please_try_again_later,ToastEUtil.TOAST_STATUS_FAILE).show();
                                return;
                            }
                            Connect.UserExistedToken existedToken = Connect.UserExistedToken.parseFrom(structData.getPlainData());
                            if(ProtoBufUtil.getInstance().checkProtoBuf(existedToken)){
                                Connect.UserInfo userInfo = existedToken.getUserInfo();
                                if(ProtoBufUtil.getInstance().checkProtoBuf(userInfo)){
                                    UserBean userBean = new UserBean();
                                    userBean.setAddress(userInfo.getAddress());
                                    userBean.setName(userInfo.getUsername());
                                    userBean.setAvatar(userInfo.getAvatar());
                                    userBean.setPriKey(priKey);
                                    userBean.setPubKey(userInfo.getPubKey());
                                    userBean.setConnectId(userInfo.getConnectId());
                                    mView.goinCodeLogin(userBean,existedToken.getToken());
                                }
                            }
                        } catch (InvalidProtocolBufferException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Connect.HttpResponse response) {
                        if(response.getCode() == 2404){
                            mView.goinRegister(priKey);
                        }
                    }
                });
    }

}


text:
layout: post
title: ASP.NET MVC 2 Validation
excerpt:
author: daxaar
categories:
  - NET

tags:

draft: false
---
Just watched a great video over on Channel 9 about the new validation features.  Having implemented a framework in our development team that was aiming for full declarative validation I found this really interesting.

Anyone on the fence about switching to ASP.NET MVC should take a look:

MSDN Channel 9 - Validation in MVC 2


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Effects</title>

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

effects

$pulsate

$opacity

$shiftOpacity

$highlight

$textColor

$morphColor

   <input type="button" onclick="$toggle('testtoggle'); return false" name="Button" value="$toggle" />  <input type="button" onclick="$blinddown('testtoggle'); return false" name="Button2" value="$blinddown" />
   <input type="button" onclick="$blindup('testtoggle'); return false" name="Button" value="$blindup" />

  Lorem Ipsum is simply dummy text of the
  printing and typesetting industry. Lorem Ipsum has been the industry's standard
  dummy text ever since the 1500s, when an unknown printer took a galley of type
  and scrambled it to make a type specimen book. It has survived not only five
  centuries, but also the leap into electronic typesetting, remaining essentially
  unchanged. It was popularised in the 1960s with the release of Letraset sheets
  containing Lorem Ipsum passages, and more recently with desktop publishing
  software like Aldus PageMaker including versions of Lorem Ipsum.

<script language="javascript" type="text/javascript" src="simple.js"></script>


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m151012_203728_about extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('about', [
            'id' => $this->primaryKey(),
            'conteudo' => $this->text()->notNull(),
            'status' => "ENUM('ativo', 'inativo') NOT NULL DEFAULT 'ativo'",
            'created_at' => $this->integer()->notNull(),
            'updated_at' => $this->integer()->notNull(),
        ], $tableOptions);
    }

    public function down()
    {
        $this->dropTable('about');
    }
}


text:
<?php

namespace BibliSymfony\BaseBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function loginAction()
    {
        return $this->render('BaseBundle:Default:login.html.twig');
    }

    public function bienvenueAction()
    {
        $film =  $this->getDoctrine()->getManager()
                ->getRepository("FilmBundle:Film")
                ->findAll();

        return $this->render('BaseBundle:Default:accueil.html.twig', array('film'=>$film));
    }

    public function gestionUtilisateursAction()
    {
        $listeUti =  $this->getDoctrine()->getManager()
                ->getRepository("BaseBundle:Utilisateur")
                ->findAll();

        return $this->render('BaseBundle:Default:gestionUtilisateurs.html.twig', array('listeUti' => $listeUti));
    }

    public function gestionLocationsAction($id)
    {
        $location =  $this->getDoctrine()->getManager()
                ->getRepository("FilmBundle:Location")
                ->findByIdUtilisateur($id, array('dateLocation' => 'DESC'));

        $utilisateur = $this->getDoctrine()->getManager()
                ->getRepository("BaseBundle:Utilisateur")
                ->findOneById($id)->getLogin();
        //$logger = $this->get('logger');
        //$logger->error('GTH : '.print_r($utili));
        //$utilisateur = $utili->getLogin();

        return $this->render('BaseBundle:Default:gestionLocations.html.twig',array('location'=>$location, 'utilisateur'=>$utilisateur));

    }

    /*public function gestionUtilisateursAction()
    {
        return $this->render('BaseBundle:Default:index.html.twig', array('name' => $name));
    }*/
}


text:
import re
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.spatial.distance import cosine

__author__ = 'alse'

def tfidf(train_examples, test_examples):
    vectorizer = TfidfVectorizer()
    data = [" ".join(train_examples), " ".join(test_examples)]
    value = vectorizer.fit(data).toarray()
    return cosine(value[0], value[1])

def soft_tfidf(train_examples, test_examples):
    pass

def get_abbr_patterns(abbr):
    if len(abbr) > 5:
        return []

    abbr = re.sub(r'\p{P}', "", abbr)
    patterns = [r"\b"] * 4
    for char in abbr[:-1]:
        patterns[0] += (char + "[a-z]+\p{Z}+")
        patterns[1] += (char + "[a-z]*")
        patterns[2] += (char + "[a-z]*?\p{Z}")
    patterns[0] += (abbr[-1] + "[a-z]+\b")
    patterns[1] += (abbr[-1] + "[a-z]*\b")
    patterns[2] += (abbr[-1] + "[a-z]*\b")
    patterns[3] += (abbr + "[a-z]+\b")

    for idx, pattern in enumerate(patterns):
        patterns[idx] = re.compile(pattern, re.IGNORECASE)

    return patterns

def abbr_test(train_examples, test_examples):
    # if testExamples is a string, perform metadata abbr test (label thing). Else do the normal one
    train_example_set = set(train_examples)

    countMatches = 0

    if isinstance(test_examples, str):
        patterns = get_abbr_patterns(test_examples)
        for pattern in patterns:
            for train_example in train_example_set:
                if pattern.match(train_example):
                    countMatches += 1
        return countMatches * 2.0 / len(train_example_set)
    else:
        test_example_set = set(test_examples)

        if len(test_example_set) > 200:
            return 0.0

        for test_example in test_example_set:
            patterns = get_abbr_patterns(test_example)
            for pattern in patterns:
                for train_example in train_example_set:
                    if pattern.match(train_example):
                        countMatches += 1
        return countMatches * 2.0 / (len(train_example_set) + len(train_example_set))


text:
package io.netty.buffer;

import org.junit.Test;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static io.netty.buffer.Unpooled.*;
import static io.netty.util.ReferenceCountUtil.*;
import static io.netty.util.internal.EmptyArrays.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

/**
 * An abstract test class for composite channel buffers
 */
public abstract class AbstractCompositeByteBufTest extends AbstractByteBufTest {

    private final ByteOrder order;

    protected AbstractCompositeByteBufTest(ByteOrder order) {
        if (order == null) {
            throw new NullPointerException("order");
        }
        this.order = order;
    }

    private List<ByteBuf> buffers;
    private ByteBuf buffer;

    @Override
    protected ByteBuf newBuffer(int length) {
        buffers = new ArrayList<ByteBuf>();
        for (int i = 0; i < length + 45; i += 45) {
            buffers.add(EMPTY_BUFFER);
            buffers.add(wrappedBuffer(new byte[1]));
            buffers.add(EMPTY_BUFFER);
            buffers.add(wrappedBuffer(new byte[2]));
            buffers.add(EMPTY_BUFFER);
            buffers.add(wrappedBuffer(new byte[3]));
            buffers.add(EMPTY_BUFFER);
            buffers.add(wrappedBuffer(new byte[4]));
            buffers.add(EMPTY_BUFFER);
            buffers.add(wrappedBuffer(new byte[5]));
            buffers.add(EMPTY_BUFFER);
            buffers.add(wrappedBuffer(new byte[6]));
            buffers.add(EMPTY_BUFFER);
            buffers.add(wrappedBuffer(new byte[7]));
            buffers.add(EMPTY_BUFFER);
            buffers.add(wrappedBuffer(new byte[8]));
            buffers.add(EMPTY_BUFFER);
            buffers.add(wrappedBuffer(new byte[9]));
            buffers.add(EMPTY_BUFFER);
        }

        buffer = Unpooled.wrappedBuffer(
                Integer.MAX_VALUE, buffers.toArray(new ByteBuf[buffers.size()])).order(order);

        // Truncate to the requested capacity.
        buffer.capacity(length);

        assertEquals(length, buffer.capacity());
        assertEquals(length, buffer.readableBytes());
        assertFalse(buffer.isWritable());
        buffer.writerIndex(0);
        return buffer;
    }

    @Override
    protected ByteBuf[] components() {
        return buffers.toArray(new ByteBuf[buffers.size()]);
    }

    // Composite buffer does not waste bandwidth on discardReadBytes, but
    // the test will fail in strict mode.
    @Override
    protected boolean discardReadBytesDoesNotMoveWritableBytes() {
        return false;
    }

    /**
     * Tests the "getBufferFor" method
     */
    @Test
    public void testComponentAtOffset() {
        CompositeByteBuf buf = releaseLater((CompositeByteBuf) wrappedBuffer(new byte[]{1, 2, 3, 4, 5},
                new byte[]{4, 5, 6, 7, 8, 9, 26}));

        //Ensure that a random place will be fine
        assertEquals(5, buf.componentAtOffset(2).capacity());

        //Loop through each byte

        byte index = 0;

        while (index < buf.capacity()) {
            ByteBuf _buf = buf.componentAtOffset(index++);
            assertNotNull(_buf);
            assertTrue(_buf.capacity() > 0);
            assertNotNull(_buf.getByte(0));
            assertNotNull(_buf.getByte(_buf.readableBytes() - 1));
        }
    }

    @Test
    public void testDiscardReadBytes3() {
        ByteBuf a, b;
        a = wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).order(order);
        b = releaseLater(wrappedBuffer(
                wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, 5).order(order),
                wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 5, 5).order(order)));
        a.skipBytes(6);
        a.markReaderIndex();
        b.skipBytes(6);
        b.markReaderIndex();
        assertEquals(a.readerIndex(), b.readerIndex());
        a.readerIndex(a.readerIndex() - 1);
        b.readerIndex(b.readerIndex() - 1);
        assertEquals(a.readerIndex(), b.readerIndex());
        a.writerIndex(a.writerIndex() - 1);
        a.markWriterIndex();
        b.writerIndex(b.writerIndex() - 1);
        b.markWriterIndex();
        assertEquals(a.writerIndex(), b.writerIndex());
        a.writerIndex(a.writerIndex() + 1);
        b.writerIndex(b.writerIndex() + 1);
        assertEquals(a.writerIndex(), b.writerIndex());
        assertTrue(ByteBufUtil.equals(a, b));
        // now discard
        a.discardReadBytes();
        b.discardReadBytes();
        assertEquals(a.readerIndex(), b.readerIndex());
        assertEquals(a.writerIndex(), b.writerIndex());
        assertTrue(ByteBufUtil.equals(a, b));
        a.resetReaderIndex();
        b.resetReaderIndex();
        assertEquals(a.readerIndex(), b.readerIndex());
        a.resetWriterIndex();
        b.resetWriterIndex();
        assertEquals(a.writerIndex(), b.writerIndex());
        assertTrue(ByteBufUtil.equals(a, b));
    }

    @Test
    public void testAutoConsolidation() {
        CompositeByteBuf buf = releaseLater(compositeBuffer(2));

        buf.addComponent(wrappedBuffer(new byte[] { 1 }));
        assertEquals(1, buf.numComponents());

        buf.addComponent(wrappedBuffer(new byte[] { 2, 3 }));
        assertEquals(2, buf.numComponents());

        buf.addComponent(wrappedBuffer(new byte[] { 4, 5, 6 }));

        assertEquals(1, buf.numComponents());
        assertTrue(buf.hasArray());
        assertNotNull(buf.array());
        assertEquals(0, buf.arrayOffset());
    }

    @Test
    public void testCompositeToSingleBuffer() {
        CompositeByteBuf buf = releaseLater(compositeBuffer(3));

        buf.addComponent(wrappedBuffer(new byte[] {1, 2, 3}));
        assertEquals(1, buf.numComponents());

        buf.addComponent(wrappedBuffer(new byte[] {4}));
        assertEquals(2, buf.numComponents());

        buf.addComponent(wrappedBuffer(new byte[] {5, 6}));
        assertEquals(3, buf.numComponents());

        // NOTE: hard-coding 6 here, since it seems like addComponent doesn't bump the writer index.
        // I'm unsure as to whether or not this is correct behavior
        ByteBuffer nioBuffer = buf.nioBuffer(0, 6);
        byte[] bytes = nioBuffer.array();
        assertEquals(6, bytes.length);
        assertArrayEquals(new byte[] {1, 2, 3, 4, 5, 6}, bytes);
    }

    @Test
    public void testFullConsolidation() {
        CompositeByteBuf buf = releaseLater(compositeBuffer(Integer.MAX_VALUE));
        buf.addComponent(wrappedBuffer(new byte[] { 1 }));
        buf.addComponent(wrappedBuffer(new byte[] { 2, 3 }));
        buf.addComponent(wrappedBuffer(new byte[] { 4, 5, 6 }));
        buf.consolidate();

        assertEquals(1, buf.numComponents());
        assertTrue(buf.hasArray());
        assertNotNull(buf.array());
        assertEquals(0, buf.arrayOffset());
    }

    @Test
    public void testRangedConsolidation() {
        CompositeByteBuf buf = releaseLater(compositeBuffer(Integer.MAX_VALUE));
        buf.addComponent(wrappedBuffer(new byte[] { 1 }));
        buf.addComponent(wrappedBuffer(new byte[] { 2, 3 }));
        buf.addComponent(wrappedBuffer(new byte[] { 4, 5, 6 }));
        buf.addComponent(wrappedBuffer(new byte[] { 7, 8, 9, 10 }));
        buf.consolidate(1, 2);

        assertEquals(3, buf.numComponents());
        assertEquals(wrappedBuffer(new byte[] { 1 }), buf.component(0));
        assertEquals(wrappedBuffer(new byte[] { 2, 3, 4, 5, 6 }), buf.component(1));
        assertEquals(wrappedBuffer(new byte[] { 7, 8, 9, 10 }), buf.component(2));
    }

    @Test
    public void testCompositeWrappedBuffer() {
        ByteBuf header = releaseLater(buffer(12)).order(order);
        ByteBuf payload = releaseLater(buffer(512)).order(order);

        header.writeBytes(new byte[12]);
        payload.writeBytes(new byte[512]);

        ByteBuf buffer = releaseLater(wrappedBuffer(header, payload));

        assertEquals(12, header.readableBytes());
        assertEquals(512, payload.readableBytes());

        assertEquals(12 + 512, buffer.readableBytes());
        assertEquals(2, buffer.nioBufferCount());
    }

    @Test
    public void testSeveralBuffersEquals() {
        ByteBuf a, b;
        // XXX Same tests with several buffers in wrappedCheckedBuffer
        // Different length.
        a = releaseLater(wrappedBuffer(new byte[] { 1 }).order(order));
        b = releaseLater(wrappedBuffer(
                wrappedBuffer(new byte[] { 1 }).order(order),
                wrappedBuffer(new byte[] { 2 }).order(order)));
        assertFalse(ByteBufUtil.equals(a, b));

        // Same content, same firstIndex, short length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3 }).order(order));
        b = releaseLater(wrappedBuffer(
                wrappedBuffer(new byte[]{1}).order(order),
                wrappedBuffer(new byte[]{2}).order(order),
                wrappedBuffer(new byte[]{3}).order(order)));
        assertTrue(ByteBufUtil.equals(a, b));

        // Same content, different firstIndex, short length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3 }).order(order));
        b = releaseLater(wrappedBuffer(
                wrappedBuffer(new byte[] { 0, 1, 2, 3, 4 }, 1, 2).order(order),
                wrappedBuffer(new byte[] { 0, 1, 2, 3, 4 }, 3, 1).order(order)));
        assertTrue(ByteBufUtil.equals(a, b));

        // Different content, same firstIndex, short length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3 }).order(order));
        b = releaseLater(wrappedBuffer(
                wrappedBuffer(new byte[] { 1, 2 }).order(order),
                wrappedBuffer(new byte[] { 4 }).order(order)));
        assertFalse(ByteBufUtil.equals(a, b));

        // Different content, different firstIndex, short length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3 }).order(order));
        b = releaseLater(wrappedBuffer(
                wrappedBuffer(new byte[] { 0, 1, 2, 4, 5 }, 1, 2).order(order),
                wrappedBuffer(new byte[] { 0, 1, 2, 4, 5 }, 3, 1).order(order)));
        assertFalse(ByteBufUtil.equals(a, b));

        // Same content, same firstIndex, long length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).order(order));
        b = releaseLater(wrappedBuffer(
                wrappedBuffer(new byte[] { 1, 2, 3 }).order(order),
                wrappedBuffer(new byte[] { 4, 5, 6 }).order(order),
                wrappedBuffer(new byte[] { 7, 8, 9, 10 }).order(order)));
        assertTrue(ByteBufUtil.equals(a, b));

        // Same content, different firstIndex, long length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).order(order));
        b = releaseLater(wrappedBuffer(
                wrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, 1, 5).order(order),
                wrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, 6, 5).order(order)));
        assertTrue(ByteBufUtil.equals(a, b));

        // Different content, same firstIndex, long length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).order(order));
        b = releaseLater(wrappedBuffer(
                wrappedBuffer(new byte[] { 1, 2, 3, 4, 6 }).order(order),
                wrappedBuffer(new byte[] { 7, 8, 5, 9, 10 }).order(order)));
        assertFalse(ByteBufUtil.equals(a, b));

        // Different content, different firstIndex, long length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).order(order));
        b = releaseLater(wrappedBuffer(
                wrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 6, 7, 8, 5, 9, 10, 11 }, 1, 5).order(order),
                wrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 6, 7, 8, 5, 9, 10, 11 }, 6, 5).order(order)));
        assertFalse(ByteBufUtil.equals(a, b));
    }

    @Test
    public void testWrappedBuffer() {

        assertEquals(16, wrappedBuffer(wrappedBuffer(ByteBuffer.allocateDirect(16))).capacity());

        assertEquals(
                wrappedBuffer(wrappedBuffer(new byte[] { 1, 2, 3 }).order(order)),
                wrappedBuffer(wrappedBuffer(new byte[][] { new byte[] { 1, 2, 3 } }).order(order)));

        assertEquals(
                wrappedBuffer(wrappedBuffer(new byte[] { 1, 2, 3 }).order(order)),
                releaseLater(wrappedBuffer(wrappedBuffer(
                        new byte[] { 1 },
                        new byte[] { 2 },
                        new byte[] { 3 }).order(order))));

        assertEquals(
                wrappedBuffer(wrappedBuffer(new byte[] { 1, 2, 3 }).order(order)),
                wrappedBuffer(new ByteBuf[] {
                        wrappedBuffer(new byte[] { 1, 2, 3 }).order(order)
                }));

        assertEquals(
                wrappedBuffer(wrappedBuffer(new byte[] { 1, 2, 3 }).order(order)),
                releaseLater(wrappedBuffer(
                        wrappedBuffer(new byte[] { 1 }).order(order),
                        wrappedBuffer(new byte[] { 2 }).order(order),
                        wrappedBuffer(new byte[] { 3 }).order(order))));

        assertEquals(
                wrappedBuffer(wrappedBuffer(new byte[] { 1, 2, 3 }).order(order)),
                wrappedBuffer(wrappedBuffer(new ByteBuffer[] {
                        ByteBuffer.wrap(new byte[] { 1, 2, 3 })
                })));

        assertEquals(
                wrappedBuffer(wrappedBuffer(new byte[] { 1, 2, 3 }).order(order)),
                releaseLater(wrappedBuffer(wrappedBuffer(
                        ByteBuffer.wrap(new byte[] { 1 }),
                        ByteBuffer.wrap(new byte[] { 2 }),
                        ByteBuffer.wrap(new byte[] { 3 })))));
    }

    @Test
    public void testWrittenBuffersEquals() {
        //XXX Same tests than testEquals with written AggregateChannelBuffers
        ByteBuf a, b;
        // Different length.
        a = releaseLater(wrappedBuffer(new byte[] { 1  })).order(order);
        b = releaseLater(wrappedBuffer(wrappedBuffer(new byte[] { 1 }, new byte[1])).order(order));
        // to enable writeBytes
        b.writerIndex(b.writerIndex() - 1);
        b.writeBytes(releaseLater(wrappedBuffer(new byte[] { 2 })).order(order));
        assertFalse(ByteBufUtil.equals(a, b));

        // Same content, same firstIndex, short length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3 })).order(order);
        b = releaseLater(wrappedBuffer(releaseLater(wrappedBuffer(new byte[] { 1 }, new byte[2]))).order(order));
        // to enable writeBytes
        b.writerIndex(b.writerIndex() - 2);
        b.writeBytes(releaseLater(wrappedBuffer(new byte[] { 2 })).order(order));
        b.writeBytes(releaseLater(wrappedBuffer(new byte[] { 3 })).order(order));
        assertTrue(ByteBufUtil.equals(a, b));

        // Same content, different firstIndex, short length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3 })).order(order);
        b = releaseLater(wrappedBuffer(releaseLater(wrappedBuffer(new byte[] { 0, 1, 2, 3, 4 }, 1, 3))).order(order));
        // to enable writeBytes
        b.writerIndex(b.writerIndex() - 1);
        b.writeBytes(releaseLater(wrappedBuffer(new byte[] { 0, 1, 2, 3, 4 }, 3, 1)).order(order));
        assertTrue(ByteBufUtil.equals(a, b));

        // Different content, same firstIndex, short length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3 })).order(order);
        b = releaseLater(wrappedBuffer(releaseLater(wrappedBuffer(new byte[] { 1, 2 }, new byte[1])).order(order)));
        // to enable writeBytes
        b.writerIndex(b.writerIndex() - 1);
        b.writeBytes(releaseLater(wrappedBuffer(new byte[] { 4 })).order(order));
        assertFalse(ByteBufUtil.equals(a, b));

        // Different content, different firstIndex, short length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3 })).order(order);
        b = releaseLater(wrappedBuffer(releaseLater(wrappedBuffer(new byte[] { 0, 1, 2, 4, 5 }, 1, 3))).order(order));
        // to enable writeBytes
        b.writerIndex(b.writerIndex() - 1);
        b.writeBytes(releaseLater(wrappedBuffer(new byte[] { 0, 1, 2, 4, 5 }, 3, 1)).order(order));
        assertFalse(ByteBufUtil.equals(a, b));

        // Same content, same firstIndex, long length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })).order(order);
        b = releaseLater(wrappedBuffer(releaseLater(wrappedBuffer(new byte[] { 1, 2, 3 }, new byte[7]))).order(order));
        // to enable writeBytes
        b.writerIndex(b.writerIndex() - 7);
        b.writeBytes(releaseLater(wrappedBuffer(new byte[] { 4, 5, 6 })).order(order));
        b.writeBytes(releaseLater(wrappedBuffer(new byte[] { 7, 8, 9, 10 })).order(order));
        assertTrue(ByteBufUtil.equals(a, b));

        // Same content, different firstIndex, long length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })).order(order);
        b = releaseLater(wrappedBuffer(releaseLater(
                wrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, 1, 10))).order(order));
        // to enable writeBytes
        b.writerIndex(b.writerIndex() - 5);
        b.writeBytes(releaseLater(
                wrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, 6, 5)).order(order));
        assertTrue(ByteBufUtil.equals(a, b));

        // Different content, same firstIndex, long length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })).order(order);
        b = releaseLater(wrappedBuffer(wrappedBuffer(new byte[] { 1, 2, 3, 4, 6 }, new byte[5])).order(order));
        // to enable writeBytes
        b.writerIndex(b.writerIndex() - 5);
        b.writeBytes(releaseLater(wrappedBuffer(new byte[] { 7, 8, 5, 9, 10 })).order(order));
        assertFalse(ByteBufUtil.equals(a, b));

        // Different content, different firstIndex, long length.
        a = releaseLater(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })).order(order);
        b = releaseLater(wrappedBuffer(releaseLater(
                wrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 6, 7, 8, 5, 9, 10, 11 }, 1, 10))).order(order));
        // to enable writeBytes
        b.writerIndex(b.writerIndex() - 5);
        b.writeBytes(releaseLater(
                wrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 6, 7, 8, 5, 9, 10, 11 }, 6, 5)).order(order));
        assertFalse(ByteBufUtil.equals(a, b));
    }

    @Test
    public void testEmptyBuffer() {
        ByteBuf b = releaseLater(wrappedBuffer(new byte[]{1, 2}, new byte[]{3, 4}));
        b.readBytes(new byte[4]);
        b.readBytes(EMPTY_BYTES);
    }

    // Test for https://github.com/netty/netty/issues/1060
    @Test
    public void testReadWithEmptyCompositeBuffer() {
        ByteBuf buf = releaseLater(compositeBuffer());
        int n = 65;
        for (int i = 0; i < n; i ++) {
            buf.writeByte(1);
            assertEquals(1, buf.readByte());
        }
    }

    @Test
    public void testComponentMustBeSlice() {
        CompositeByteBuf buf = releaseLater(compositeBuffer());
        buf.addComponent(buffer(4).setIndex(1, 3));
        assertThat(buf.component(0), is(instanceOf(SlicedByteBuf.class)));
        assertThat(buf.component(0).capacity(), is(2));
        assertThat(buf.component(0).maxCapacity(), is(2));
    }

    @Test
    public void testReferenceCounts1() {
        ByteBuf c1 = buffer().writeByte(1);
        ByteBuf c2 = buffer().writeByte(2).retain();
        ByteBuf c3 = buffer().writeByte(3).retain(2);

        CompositeByteBuf buf = releaseLater(compositeBuffer());
        assertThat(buf.refCnt(), is(1));
        buf.addComponents(c1, c2, c3);

        assertThat(buf.refCnt(), is(1));

        // Ensure that c[123]'s refCount did not change.
        assertThat(c1.refCnt(), is(1));
        assertThat(c2.refCnt(), is(2));
        assertThat(c3.refCnt(), is(3));

        assertThat(buf.component(0).refCnt(), is(1));
        assertThat(buf.component(1).refCnt(), is(2));
        assertThat(buf.component(2).refCnt(), is(3));

        c3.release(2);
        c2.release();
    }

    @Test
    public void testReferenceCounts2() {
        ByteBuf c1 = buffer().writeByte(1);
        ByteBuf c2 = buffer().writeByte(2).retain();
        ByteBuf c3 = buffer().writeByte(3).retain(2);

        CompositeByteBuf bufA = compositeBuffer();
        bufA.addComponents(c1, c2, c3).writerIndex(3);

        CompositeByteBuf bufB = compositeBuffer();
        bufB.addComponents(bufA);

        // Ensure that bufA.refCnt() did not change.
        assertThat(bufA.refCnt(), is(1));

        // Ensure that c[123]'s refCnt did not change.
        assertThat(c1.refCnt(), is(1));
        assertThat(c2.refCnt(), is(2));
        assertThat(c3.refCnt(), is(3));

        // This should decrease bufA.refCnt().
        bufB.release();
        assertThat(bufB.refCnt(), is(0));

        // Ensure bufA.refCnt() changed.
        assertThat(bufA.refCnt(), is(0));

        // Ensure that c[123]'s refCnt also changed due to the deallocation of bufA.
        assertThat(c1.refCnt(), is(0));
        assertThat(c2.refCnt(), is(1));
        assertThat(c3.refCnt(), is(2));

        c3.release(2);
        c2.release();
    }

    @Test
    public void testReferenceCounts3() {
        ByteBuf c1 = buffer().writeByte(1);
        ByteBuf c2 = buffer().writeByte(2).retain();
        ByteBuf c3 = buffer().writeByte(3).retain(2);

        CompositeByteBuf buf = releaseLater(compositeBuffer());
        assertThat(buf.refCnt(), is(1));

        List<ByteBuf> components = new ArrayList<ByteBuf>();
        Collections.addAll(components, c1, c2, c3);
        buf.addComponents(components);

        // Ensure that c[123]'s refCount did not change.
        assertThat(c1.refCnt(), is(1));
        assertThat(c2.refCnt(), is(2));
        assertThat(c3.refCnt(), is(3));

        assertThat(buf.component(0).refCnt(), is(1));
        assertThat(buf.component(1).refCnt(), is(2));
        assertThat(buf.component(2).refCnt(), is(3));

        c3.release(2);
        c2.release();
    }

    @Test
    public void testNestedLayout() {
        CompositeByteBuf buf = releaseLater(compositeBuffer());
        buf.addComponent(
                compositeBuffer()
                        .addComponent(wrappedBuffer(new byte[]{1, 2}))
                        .addComponent(wrappedBuffer(new byte[]{3, 4})).slice(1, 2));

        ByteBuffer[] nioBuffers = buf.nioBuffers(0, 2);
        assertThat(nioBuffers.length, is(2));
        assertThat(nioBuffers[0].remaining(), is(1));
        assertThat(nioBuffers[0].get(), is((byte) 2));
        assertThat(nioBuffers[1].remaining(), is(1));
        assertThat(nioBuffers[1].get(), is((byte) 3));
    }

    @Test
    public void testRemoveLastComponent() {
        CompositeByteBuf buf = releaseLater(compositeBuffer());
        buf.addComponent(wrappedBuffer(new byte[]{1, 2}));
        assertEquals(1, buf.numComponents());
        buf.removeComponent(0);
        assertEquals(0, buf.numComponents());
    }

    @Test
    public void testCopyEmpty() {
        CompositeByteBuf buf = releaseLater(compositeBuffer());
        assertEquals(0, buf.numComponents());
        assertEquals(0, releaseLater(buf.copy()).readableBytes());
    }

    @Test
    public void testDuplicateEmpty() {
        CompositeByteBuf buf = releaseLater(compositeBuffer());
        assertEquals(0, buf.numComponents());
        assertEquals(0, releaseLater(buf.duplicate()).readableBytes());
    }

    @Test
    public void testRemoveLastComponentWithOthersLeft() {
        CompositeByteBuf buf = releaseLater(compositeBuffer());
        buf.addComponent(wrappedBuffer(new byte[]{1, 2}));
        buf.addComponent(wrappedBuffer(new byte[]{1, 2}));
        assertEquals(2, buf.numComponents());
        buf.removeComponent(1);
        assertEquals(1, buf.numComponents());
    }

    @Test
    public void testGatheringWritesHeap() throws Exception {
        testGatheringWrites(buffer().order(order), buffer().order(order));
    }

    @Test
    public void testGatheringWritesDirect() throws Exception {
        testGatheringWrites(directBuffer().order(order), directBuffer().order(order));
    }

    @Test
    public void testGatheringWritesMixes() throws Exception {
        testGatheringWrites(buffer().order(order), directBuffer().order(order));
    }

    @Test
    public void testGatheringWritesHeapPooled() throws Exception {
        testGatheringWrites(PooledByteBufAllocator.DEFAULT.heapBuffer().order(order),
                PooledByteBufAllocator.DEFAULT.heapBuffer().order(order));
    }

    @Test
    public void testGatheringWritesDirectPooled() throws Exception {
        testGatheringWrites(PooledByteBufAllocator.DEFAULT.directBuffer().order(order),
                PooledByteBufAllocator.DEFAULT.directBuffer().order(order));
    }

    @Test
    public void testGatheringWritesMixesPooled() throws Exception {
        testGatheringWrites(PooledByteBufAllocator.DEFAULT.heapBuffer().order(order),
                PooledByteBufAllocator.DEFAULT.directBuffer().order(order));
    }

    private static void testGatheringWrites(ByteBuf buf1, ByteBuf buf2) throws Exception {
        CompositeByteBuf buf = releaseLater(compositeBuffer());
        buf.addComponent(buf1.writeBytes(new byte[]{1, 2}));
        buf.addComponent(buf2.writeBytes(new byte[]{1, 2}));
        buf.writerIndex(3);
        buf.readerIndex(1);

        TestGatheringByteChannel channel = new TestGatheringByteChannel();

        buf.readBytes(channel, 2);

        byte[] data = new byte[2];
        buf.getBytes(1, data);
        assertArrayEquals(data, channel.writtenBytes());
    }

    @Test
    public void testGatheringWritesPartialHeap() throws Exception {
        testGatheringWritesPartial(buffer().order(order), buffer().order(order), false);
    }

    @Test
    public void testGatheringWritesPartialDirect() throws Exception {
        testGatheringWritesPartial(directBuffer().order(order), directBuffer().order(order), false);
    }

    @Test
    public void testGatheringWritesPartialMixes() throws Exception {
        testGatheringWritesPartial(buffer().order(order), directBuffer().order(order), false);
    }

    @Test
    public void testGatheringWritesPartialHeapSlice() throws Exception {
        testGatheringWritesPartial(buffer().order(order), buffer().order(order), true);
    }

    @Test
    public void testGatheringWritesPartialDirectSlice() throws Exception {
        testGatheringWritesPartial(directBuffer().order(order), directBuffer().order(order), true);
    }

    @Test
    public void testGatheringWritesPartialMixesSlice() throws Exception {
        testGatheringWritesPartial(buffer().order(order), directBuffer().order(order), true);
    }

    @Test
    public void testGatheringWritesPartialHeapPooled() throws Exception {
        testGatheringWritesPartial(PooledByteBufAllocator.DEFAULT.heapBuffer().order(order),
                PooledByteBufAllocator.DEFAULT.heapBuffer().order(order), false);
    }

    @Test
    public void testGatheringWritesPartialDirectPooled() throws Exception {
        testGatheringWritesPartial(PooledByteBufAllocator.DEFAULT.directBuffer().order(order),
                PooledByteBufAllocator.DEFAULT.directBuffer().order(order), false);
    }

    @Test
    public void testGatheringWritesPartialMixesPooled() throws Exception {
        testGatheringWritesPartial(PooledByteBufAllocator.DEFAULT.heapBuffer().order(order),
                PooledByteBufAllocator.DEFAULT.directBuffer().order(order), false);
    }

    @Test
    public void testGatheringWritesPartialHeapPooledSliced() throws Exception {
        testGatheringWritesPartial(PooledByteBufAllocator.DEFAULT.heapBuffer().order(order),
                PooledByteBufAllocator.DEFAULT.heapBuffer().order(order), true);
    }

    @Test
    public void testGatheringWritesPartialDirectPooledSliced() throws Exception {
        testGatheringWritesPartial(PooledByteBufAllocator.DEFAULT.directBuffer().order(order),
                PooledByteBufAllocator.DEFAULT.directBuffer().order(order), true);
    }

    @Test
    public void testGatheringWritesPartialMixesPooledSliced() throws Exception {
        testGatheringWritesPartial(PooledByteBufAllocator.DEFAULT.heapBuffer().order(order),
                PooledByteBufAllocator.DEFAULT.directBuffer().order(order), true);
    }

    private static void testGatheringWritesPartial(ByteBuf buf1, ByteBuf buf2, boolean slice) throws Exception {
        CompositeByteBuf buf = releaseLater(compositeBuffer());
        buf1.writeBytes(new byte[]{1, 2, 3, 4});
        buf2.writeBytes(new byte[]{1, 2, 3, 4});
        if (slice) {
            buf1 = buf1.readerIndex(1).slice();
            buf2 = buf2.writerIndex(3).slice();
            buf.addComponent(buf1);
            buf.addComponent(buf2);
            buf.writerIndex(6);
        } else {
            buf.addComponent(buf1);
            buf.addComponent(buf2);
            buf.writerIndex(7);
            buf.readerIndex(1);
        }

        TestGatheringByteChannel channel = new TestGatheringByteChannel(1);

        while (buf.isReadable()) {
            buf.readBytes(channel, buf.readableBytes());
        }

        byte[] data = new byte[6];

        if (slice) {
            buf.getBytes(0, data);
        } else {
            buf.getBytes(1, data);
        }
        assertArrayEquals(data, channel.writtenBytes());
    }

    @Test
    public void testGatheringWritesSingleHeap() throws Exception {
        testGatheringWritesSingleBuf(buffer().order(order));
    }

    @Test
    public void testGatheringWritesSingleDirect() throws Exception {
        testGatheringWritesSingleBuf(directBuffer().order(order));
    }

    private static void testGatheringWritesSingleBuf(ByteBuf buf1) throws Exception {
        CompositeByteBuf buf = releaseLater(compositeBuffer());
        buf.addComponent(buf1.writeBytes(new byte[]{1, 2, 3, 4}));
        buf.writerIndex(3);
        buf.readerIndex(1);

        TestGatheringByteChannel channel = new TestGatheringByteChannel();
        buf.readBytes(channel, 2);

        byte[] data = new byte[2];
        buf.getBytes(1, data);
        assertArrayEquals(data, channel.writtenBytes());
    }

    @Override
    @Test
    public void testInternalNioBuffer() {
        // ignore
    }

    @Test
    public void testisDirectMultipleBufs() {
        CompositeByteBuf buf = releaseLater(compositeBuffer());
        assertFalse(buf.isDirect());

        buf.addComponent(directBuffer().writeByte(1));

        assertTrue(buf.isDirect());
        buf.addComponent(directBuffer().writeByte(1));
        assertTrue(buf.isDirect());

        buf.addComponent(buffer().writeByte(1));
        assertFalse(buf.isDirect());
    }

    // See https://github.com/netty/netty/issues/1976
    @Test
    public void testDiscardSomeReadBytes() {
        CompositeByteBuf cbuf = releaseLater(compositeBuffer());
        int len = 8 * 4;
        for (int i = 0; i < len; i += 4) {
            ByteBuf buf = Unpooled.buffer().writeInt(i);
            cbuf.capacity(cbuf.writerIndex()).addComponent(buf).writerIndex(i + 4);
        }
        cbuf.writeByte(1);

        byte[] me = new byte[len];
        cbuf.readBytes(me);
        cbuf.readByte();

        cbuf.discardSomeReadBytes();
    }
}


text:
package cmd

import (
	"errors"
	"fmt"
	"os"
	"path"
	"regexp"

	"github.com/VirusTotal/vt-cli/utils"
	vt "github.com/VirusTotal/vt-go"
	"github.com/cavaliercoder/grab"
	"github.com/fatih/color"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var monitorPartnerItemsCmdExample = `  vt monitorpartner list
  vt monitorpartner list --filter "engine:<EngineName>" --include sha256,first_detection_date`

// NewMonitorPartnerHashesListCmd returns a list or monitor_partner according to a filter.
func NewMonitorPartnerHashesListCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:     "list",
		Short:   "List available monitor partner hashes",
		Example: monitorItemsCmdExample,
		RunE: func(cmd *cobra.Command, args []string) error {
			p, err := NewPrinter(cmd)
			if err != nil {
				return err
			}
			return p.PrintCollection(vt.URL("monitor_partner/hashes"))
		},
	}

	addIncludeExcludeFlags(cmd.Flags())
	addFilterFlag(cmd.Flags())
	addLimitFlag(cmd.Flags())
	addCursorFlag(cmd.Flags())

	return cmd
}

// Monitor Partner downloader, it implements the Doer interface. Retrieves the item
// path to know the destination filename and downloads and save each individual
// file using fileDownloader.DownloadFile
type monitorPartnerDownloader struct {
	fileDownloader
}

func (d *monitorPartnerDownloader) Do(file interface{}, ds *utils.DoerState) string {
	var hash string
	if f, isObject := file.(*vt.Object); isObject {
		hash = f.ID()
	} else {
		hash = file.(string)
	}

	ds.Progress = fmt.Sprintf("%s %4.1f%%", hash, 0.0)

	// Get download URL
	var downloadURL string
	_, err := d.client.GetData(vt.URL("monitor_partner/files/%s/download_url", hash), &downloadURL)

	if err == nil {
		dstPath := path.Join(viper.GetString("output"), hash)
		err = d.DownloadFile(downloadURL, dstPath, func(resp *grab.Response) {
			progress := 100 * resp.Progress()
			if progress < 100 {
				ds.Progress = fmt.Sprintf("%s %4.1f%% %6.1f KBi/s",
					hash, progress, resp.BytesPerSecond()/1024)
			}
		})
	}

	msg := color.GreenString("ok")
	if err != nil {
		if apiErr, ok := err.(vt.Error); ok && apiErr.Code == "NotFoundError" {
			msg = color.RedString("not found")
		} else {
			msg = color.RedString(err.Error())
		}
	}

	return fmt.Sprintf("%s [%s]", hash, msg)
}

var monitorPartnerHashDownloadCmdHelp = `Download files from your partner account.

This command download files from your monitor partner account using their sha256.`

var monitorPartnerHashDownloadCmdExample = `  vt monitorpartner download <sha256-1> <sha256-2> ...
  cat list_of_monitor_ids | vt monitorpartner download -`

// NewMonitorPartnerHashDownloadCmd returns a command for downloading files from your
// monitor account.
func NewMonitorPartnerHashDownloadCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:     "download [sha256]...",
		Short:   "Download files from your monitor partner account",
		Long:    monitorPartnerHashDownloadCmdHelp,
		Example: monitorPartnerHashDownloadCmdExample,
		RunE: func(cmd *cobra.Command, args []string) error {
			var argReader utils.StringReader
			if len(args) == 0 {
				return errors.New("No hash provided")
			} else if len(args) == 1 && args[0] == "-" {
				argReader = utils.NewStringIOReader(os.Stdin)
			} else {
				argReader = utils.NewStringArrayReader(args)
			}
			client, err := NewAPIClient()
			if err != nil {
				return err
			}
			re, _ := regexp.Compile("[[:xdigit:]]{64}")
			monitorHashes := utils.NewFilteredStringReader(argReader, re)

			c := utils.NewCoordinator(viper.GetInt("threads"))
			c.DoWithStringsFromReader(
				&monitorPartnerDownloader{fileDownloader: newFileDownloader(client)},
				monitorHashes)
			return err
		},
	}

	addThreadsFlag(cmd.Flags())
	addOutputFlag(cmd.Flags())
	return cmd
}

var monitorPartnerCmdHelp = `Manage your VirusTotal Monitor Partner account.

This command allows you to list and retrieve files detected by your engine.

Reference:
  https://developers.virustotal.com/v3.0/reference#monitor-partner`

// NewMonitorPartnerCmd returns a new instance of the 'monitor_hash' command.
func NewMonitorPartnerCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "monitorpartner",
		Short: "Manage your monitor partner account",
		Long:  monitorPartnerCmdHelp,
		Args:  cobra.MinimumNArgs(1),
	}

	addThreadsFlag(cmd.Flags())
	addIncludeExcludeFlags(cmd.Flags())

	cmd.AddCommand(NewMonitorPartnerHashesListCmd())
	cmd.AddCommand(NewMonitorPartnerHashDownloadCmd())

	addRelationshipCmds(cmd, "monitor_partner/hashes", "monitor_hash", "[sha256]")

	return cmd
}


text:
require 'spec_helper'

# rubocop:disable Metrics/BlockLength
describe 'Datanauts::FormHelper#form_for' do
  before do
    @user = User.new(first_name: 'Jo', last_name: 'Blogs')
  end

  include Datanauts::FormHelper
  def request
    r = double('request')
    allow(r).to receive(:script_name) { '/admin' }
    r
  end

  it 'has a version number' do
    expect(Datanauts::FormHelper::VERSION).not_to be nil
  end

  it 'doesnt raise an error' do
    expect { form_for(@user) { '
abc def
' } }.not_to raise_error
  end

  context 'with no arguments' do
    it 'returns the right thing' do
      f = form_for(@user) { '
abc def
' }

      expect(f.no_white_space).to match <<-FORM.no_white_space.strip
        <form method="post" action="/admin/users/1" class="form was-validated">
          <input type="hidden" name="_method" value="put" />

abc def

        </form>
      FORM
    end
  end

  context 'with action' do
    it 'returns the right thing' do
      f = form_for(@user, action: '/foo') { '
abc def
' }
      expect(f.no_white_space).to match <<-FORM.no_white_space.strip
        <form method="post" action="/foo" class="form was-validated">
          <input type="hidden" name="_method" value="put" />

abc def

        </form>
      FORM
    end
  end

  context 'with method override' do
    it 'returns the right thing' do
      f = form_for(@user, method: 'POST') { '
abc def
' }

      expect(f.no_white_space).to match <<-FORM.no_white_space.strip
        <form method="POST" action="/admin/users/1" class="form was-validated">

abc def

        </form>
      FORM
    end
  end
end
# rubocop:enable Metrics/BlockLength


text:
#include "config.h"

#if ENABLE(DEVICE_ORIENTATION)

#include "JSDeviceMotionEvent.h"

#include "DeviceMotionData.h"
#include "DeviceMotionEvent.h"
#include <runtime/JSCJSValueInlines.h>
#include <runtime/ObjectConstructor.h>
#include <runtime/StructureInlines.h>

using namespace JSC;

namespace WebCore {

static PassRefPtr<DeviceMotionData::Acceleration> readAccelerationArgument(JSValue value, ExecState* exec)
{
    if (value.isUndefinedOrNull())
        return 0;

    // Given the above test, this will always yield an object.
    JSObject* object = value.toObject(exec);

    JSValue xValue = object->get(exec, Identifier(exec, "x"));
    if (exec->hadException())
        return 0;
    bool canProvideX = !xValue.isUndefinedOrNull();
    double x = xValue.toNumber(exec);
    if (exec->hadException())
        return 0;

    JSValue yValue = object->get(exec, Identifier(exec, "y"));
    if (exec->hadException())
        return 0;
    bool canProvideY = !yValue.isUndefinedOrNull();
    double y = yValue.toNumber(exec);
    if (exec->hadException())
        return 0;

    JSValue zValue = object->get(exec, Identifier(exec, "z"));
    if (exec->hadException())
        return 0;
    bool canProvideZ = !zValue.isUndefinedOrNull();
    double z = zValue.toNumber(exec);
    if (exec->hadException())
        return 0;

    if (!canProvideX && !canProvideY && !canProvideZ)
        return 0;

    return DeviceMotionData::Acceleration::create(canProvideX, x, canProvideY, y, canProvideZ, z);
}

static PassRefPtr<DeviceMotionData::RotationRate> readRotationRateArgument(JSValue value, ExecState* exec)
{
    if (value.isUndefinedOrNull())
        return 0;

    // Given the above test, this will always yield an object.
    JSObject* object = value.toObject(exec);

    JSValue alphaValue = object->get(exec, Identifier(exec, "alpha"));
    if (exec->hadException())
        return 0;
    bool canProvideAlpha = !alphaValue.isUndefinedOrNull();
    double alpha = alphaValue.toNumber(exec);
    if (exec->hadException())
        return 0;

    JSValue betaValue = object->get(exec, Identifier(exec, "beta"));
    if (exec->hadException())
        return 0;
    bool canProvideBeta = !betaValue.isUndefinedOrNull();
    double beta = betaValue.toNumber(exec);
    if (exec->hadException())
        return 0;

    JSValue gammaValue = object->get(exec, Identifier(exec, "gamma"));
    if (exec->hadException())
        return 0;
    bool canProvideGamma = !gammaValue.isUndefinedOrNull();
    double gamma = gammaValue.toNumber(exec);
    if (exec->hadException())
        return 0;

    if (!canProvideAlpha && !canProvideBeta && !canProvideGamma)
        return 0;

    return DeviceMotionData::RotationRate::create(canProvideAlpha, alpha, canProvideBeta, beta, canProvideGamma, gamma);
}

static JSObject* createAccelerationObject(const DeviceMotionData::Acceleration* acceleration, ExecState* exec)
{
    JSObject* object = constructEmptyObject(exec);
    object->putDirect(exec->vm(), Identifier(exec, "x"), acceleration->canProvideX() ? jsNumber(acceleration->x()) : jsNull());
    object->putDirect(exec->vm(), Identifier(exec, "y"), acceleration->canProvideY() ? jsNumber(acceleration->y()) : jsNull());
    object->putDirect(exec->vm(), Identifier(exec, "z"), acceleration->canProvideZ() ? jsNumber(acceleration->z()) : jsNull());
    return object;
}

static JSObject* createRotationRateObject(const DeviceMotionData::RotationRate* rotationRate, ExecState* exec)
{
    JSObject* object = constructEmptyObject(exec);
    object->putDirect(exec->vm(), Identifier(exec, "alpha"), rotationRate->canProvideAlpha() ? jsNumber(rotationRate->alpha()) : jsNull());
    object->putDirect(exec->vm(), Identifier(exec, "beta"),  rotationRate->canProvideBeta()  ? jsNumber(rotationRate->beta())  : jsNull());
    object->putDirect(exec->vm(), Identifier(exec, "gamma"), rotationRate->canProvideGamma() ? jsNumber(rotationRate->gamma()) : jsNull());
    return object;
}

JSValue JSDeviceMotionEvent::acceleration(ExecState* exec) const
{
    DeviceMotionEvent& imp = impl();
    if (!imp.deviceMotionData()->acceleration())
        return jsNull();
    return createAccelerationObject(imp.deviceMotionData()->acceleration(), exec);
}

JSValue JSDeviceMotionEvent::accelerationIncludingGravity(ExecState* exec) const
{
    DeviceMotionEvent& imp = impl();
    if (!imp.deviceMotionData()->accelerationIncludingGravity())
        return jsNull();
    return createAccelerationObject(imp.deviceMotionData()->accelerationIncludingGravity(), exec);
}

JSValue JSDeviceMotionEvent::rotationRate(ExecState* exec) const
{
    DeviceMotionEvent& imp = impl();
    if (!imp.deviceMotionData()->rotationRate())
        return jsNull();
    return createRotationRateObject(imp.deviceMotionData()->rotationRate(), exec);
}

JSValue JSDeviceMotionEvent::interval(ExecState*) const
{
    DeviceMotionEvent& imp = impl();
    if (!imp.deviceMotionData()->canProvideInterval())
        return jsNull();
    return jsNumber(imp.deviceMotionData()->interval());
}

JSValue JSDeviceMotionEvent::initDeviceMotionEvent(ExecState* exec)
{
    const String type = exec->argument(0).toString(exec)->value(exec);
    bool bubbles = exec->argument(1).toBoolean(exec);
    bool cancelable = exec->argument(2).toBoolean(exec);

    // If any of the parameters are null or undefined, mark them as not provided.
    // Otherwise, use the standard JavaScript conversion.
    RefPtr<DeviceMotionData::Acceleration> acceleration = readAccelerationArgument(exec->argument(3), exec);
    if (exec->hadException())
        return jsUndefined();

    RefPtr<DeviceMotionData::Acceleration> accelerationIncludingGravity = readAccelerationArgument(exec->argument(4), exec);
    if (exec->hadException())
        return jsUndefined();

    RefPtr<DeviceMotionData::RotationRate> rotationRate = readRotationRateArgument(exec->argument(5), exec);
    if (exec->hadException())
        return jsUndefined();

    bool intervalProvided = !exec->argument(6).isUndefinedOrNull();
    double interval = exec->argument(6).toNumber(exec);
    RefPtr<DeviceMotionData> deviceMotionData = DeviceMotionData::create(acceleration, accelerationIncludingGravity, rotationRate, intervalProvided, interval);
    impl().initDeviceMotionEvent(type, bubbles, cancelable, deviceMotionData.get());
    return jsUndefined();
}

} // namespace WebCore

#endif // ENABLE(DEVICE_ORIENTATION)