text:
package fr.neamar.kiss.toggles;

import android.bluetooth.BluetoothAdapter;
import android.content.ContentResolver;
import android.content.Context;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import fr.neamar.kiss.KissApplication;
import fr.neamar.kiss.pojo.TogglesPojo;

public class TogglesHandler {
    private final ConnectivityManager connectivityManager;
    private final WifiManager wifiManager;
    private final BluetoothAdapter bluetoothAdapter;
    private final AudioManager audioManager;
    private final ContentResolver contentResolver;

    /**
     * Initialize managers
     *
     * @param context android context
     */
    public TogglesHandler(Context context) {
        this.connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        this.wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        this.audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE));
        this.contentResolver = context.getContentResolver();
    }

    /**
     * Return the state for the specified pojo
     *
     * @param pojo item to look for
     * @return item state
     */
    public Boolean getState(TogglesPojo pojo) {
        try {
            switch (pojo.settingName) {
                case "wifi":
                    return getWifiState();
                case "data":
                    return getDataState();
                case "bluetooth":
                    return getBluetoothState();
                case "silent":
                    return getSilentState();
                case "torch":
                    return getTorchState();
                case "sync":
                    return getSyncState();
                case "autorotate":
                    return getAutorotationState();
                default:
                    Log.e("wtf", "Unsupported toggle for reading: " + pojo.settingName);
                    return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.w("log", "Unsupported toggle for device: " + pojo.settingName);
            return null;
        }
    }

    public void setState(TogglesPojo pojo, Boolean state) {
        try {
            switch (pojo.settingName) {
                case "wifi":
                    setWifiState(state);
                    break;
                case "data":
                    setDataState(state);
                    break;
                case "bluetooth":
                    setBluetoothState(state);
                    break;
                case "silent":
                    setSilentState(state);
                    break;
                case "torch":
                    setTorchState(state);
                    break;
                case "sync":
                    setSyncState(state);
                case "autorotate":
                    setAutorotationState(state);
                default:
                    Log.e("wtf", "Unsupported toggle for update: " + pojo.settingName);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.w("log", "Unsupported toggle for device: " + pojo.settingName);
        }
    }

    private Boolean getWifiState() {
        return wifiManager.isWifiEnabled();
    }

    private void setWifiState(Boolean state) {
        wifiManager.setWifiEnabled(state);
    }

    private Boolean getDataState() {
        Method dataMtd;
        try {
            dataMtd = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");
            dataMtd.setAccessible(true);
            return (Boolean) dataMtd.invoke(connectivityManager);
        } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void setDataState(Boolean state) {
        Method dataMtd;
        try {
            dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled",
                    boolean.class);
            dataMtd.setAccessible(true);
            dataMtd.invoke(connectivityManager, state);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    private Boolean getBluetoothState() {
        return bluetoothAdapter.isEnabled();
    }

    private void setBluetoothState(Boolean state) {
        if (state)
            bluetoothAdapter.enable();
        else
            bluetoothAdapter.disable();
    }

    private Boolean getTorchState() {
        return KissApplication.getCameraHandler().isTorchAvailable() && KissApplication.getCameraHandler().getTorchState();
    }

    private void setTorchState(Boolean state) {
        if(KissApplication.getCameraHandler().isTorchAvailable()) {
            KissApplication.getCameraHandler().setTorchState(state);
        }
    }

    private Boolean getSilentState() {
        int state = audioManager.getRingerMode();
        return state == AudioManager.RINGER_MODE_SILENT || state == AudioManager.RINGER_MODE_VIBRATE;
    }

    private void setSilentState(Boolean state) {
        if (!state) {
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            audioManager.setStreamVolume(AudioManager.STREAM_RING,
                    audioManager.getStreamVolume(AudioManager.STREAM_RING),
                    AudioManager.FLAG_PLAY_SOUND);
        } else {
            audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
            audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, AudioManager.FLAG_VIBRATE);
        }
    }

    private Boolean getSyncState() {
        return ContentResolver.getMasterSyncAutomatically();
    }

    private void setSyncState(Boolean state) {
        ContentResolver.setMasterSyncAutomatically(state);
    }

    private Boolean getAutorotationState() {
        return android.provider.Settings.System.getInt(this.contentResolver,Settings.System.ACCELEROMETER_ROTATION, 0) == 1;
    }

    private void setAutorotationState(Boolean state) {
        android.provider.Settings.System.putInt(this.contentResolver,Settings.System.ACCELEROMETER_ROTATION, (state) ? 1 : 0 );
    }
}


text:
#include "ui/UIText.h"
#include "2d/CCLabel.h"
#include "platform/CCFileUtils.h"

NS_CC_BEGIN

namespace ui {

static const int LABEL_RENDERER_Z = (-1);

IMPLEMENT_CLASS_GUI_INFO(Text)

Text::Text():
_touchScaleChangeEnabled(false),
_normalScaleValueX(1.0f),
_normalScaleValueY(1.0f),
_fontName("Thonburi"),
_fontSize(10.f),
_onSelectedScaleOffset(0.5),
_labelRenderer(nullptr),
_labelRendererAdaptDirty(true),
_type(Type::SYSTEM)
{
}

Text::~Text()
{

}

Text* Text::create()
{
    Text* widget = new (std::nothrow) Text();
    if (widget && widget->init())
    {
        widget->autorelease();
        return widget;
    }
    CC_SAFE_DELETE(widget);
    return nullptr;
}

bool Text::init()
{
    if (Widget::init())
    {
        return true;
    }
    return false;
}

Text* Text::create(const std::string &textContent, const std::string &fontName, float fontSize)
{
    Text *text = new (std::nothrow) Text;
    if (text && text->init(textContent, fontName, fontSize))
    {
        text->autorelease();
        return text;
    }
    CC_SAFE_DELETE(text);
    return nullptr;
}

bool Text::init(const std::string &textContent, const std::string &fontName, float fontSize)
{
    bool ret = true;
    do
    {
        if (!Widget::init())
        {
            ret = false;
            break;
        }
        this->setFontName(fontName);
        this->setFontSize(fontSize);
        this->setString(textContent);
    } while (0);
    return ret;
}

void Text::initRenderer()
{
    _labelRenderer = Label::create();
    addProtectedChild(_labelRenderer, LABEL_RENDERER_Z, -1);
}

void Text::setString(const std::string &text)
{
    if (text == _labelRenderer->getString())
    {
        return;
    }
    _labelRenderer->setString(text);
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

const std::string& Text::getString() const
{
    return _labelRenderer->getString();
}

ssize_t Text::getStringLength()const
{
    return _labelRenderer->getStringLength();
}

void Text::setFontSize(float size)
{
    if (_type == Type::SYSTEM)
    {
        _labelRenderer->setSystemFontSize(size);
    }
    else
    {
        TTFConfig config = _labelRenderer->getTTFConfig();
        config.fontSize = size;
        _labelRenderer->setTTFConfig(config);
    }
    _fontSize = size;
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

float Text::getFontSize()const
{
    return _fontSize;
}

void Text::setFontName(const std::string& name)
{
    if(FileUtils::getInstance()->isFileExist(name))
    {
        TTFConfig config = _labelRenderer->getTTFConfig();
        config.fontFilePath = name;
        config.fontSize = _fontSize;
        _labelRenderer->setTTFConfig(config);
        _type = Type::TTF;
    }
    else
    {
        _labelRenderer->setSystemFontName(name);
        if (_type == Type::TTF)
        {
            _labelRenderer->requestSystemFontRefresh();
        }
        _type = Type::SYSTEM;
    }
    _fontName = name;
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

const std::string& Text::getFontName()const
{
    return _fontName;
}

Text::Type Text::getType() const
{
    return _type;
}

void Text::setTextAreaSize(const Size &size)
{
    _labelRenderer->setDimensions(size.width,size.height);
    if (!_ignoreSize)
    {
        _customSize=size;
    }
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

const Size& Text::getTextAreaSize()const
{
    return _labelRenderer->getDimensions();
}

void Text::setTextHorizontalAlignment(TextHAlignment alignment)
{
    _labelRenderer->setHorizontalAlignment(alignment);
}

TextHAlignment Text::getTextHorizontalAlignment()const
{
    return _labelRenderer->getHorizontalAlignment();
}

void Text::setTextVerticalAlignment(TextVAlignment alignment)
{
    _labelRenderer->setVerticalAlignment(alignment);
}

TextVAlignment Text::getTextVerticalAlignment()const
{
    return _labelRenderer->getVerticalAlignment();
}

void Text::setTextColor(const Color4B color)
{
    _labelRenderer->setTextColor(color);
}

const Color4B& Text::getTextColor() const
{
    return _labelRenderer->getTextColor();
}

void Text::setTouchScaleChangeEnabled(bool enable)
{
    _touchScaleChangeEnabled = enable;
}

bool Text::isTouchScaleChangeEnabled()const
{
    return _touchScaleChangeEnabled;
}

void Text::onPressStateChangedToNormal()
{
    if (!_touchScaleChangeEnabled)
    {
        return;
    }
    _labelRenderer->setScaleX(_normalScaleValueX);
    _labelRenderer->setScaleY(_normalScaleValueY);
}

void Text::onPressStateChangedToPressed()
{
    if (!_touchScaleChangeEnabled)
    {
        return;
    }
    _labelRenderer->setScaleX(_normalScaleValueX + _onSelectedScaleOffset);
    _labelRenderer->setScaleY(_normalScaleValueY + _onSelectedScaleOffset);
}

void Text::onPressStateChangedToDisabled()
{

}

void Text::onSizeChanged()
{
    Widget::onSizeChanged();
    _labelRendererAdaptDirty = true;
}

void Text::adaptRenderers()
{
    if (_labelRendererAdaptDirty)
    {
        labelScaleChangedWithSize();
        _labelRendererAdaptDirty = false;
    }
}

Size Text::getVirtualRendererSize() const
{
    return _labelRenderer->getContentSize();
}

Size Text::getAutoRenderSize()
{
    Size virtualSize = _labelRenderer->getContentSize();
    if (!_ignoreSize)
    {
        _labelRenderer->setDimensions(0, 0);
        virtualSize = _labelRenderer->getContentSize();
        _labelRenderer->setDimensions(_contentSize.width, _contentSize.height);
    }

    return virtualSize;
}

Node* Text::getVirtualRenderer()
{
    return _labelRenderer;
}

void Text::labelScaleChangedWithSize()
{
    if (_ignoreSize)
    {
        _labelRenderer->setScale(1.0f);
        _normalScaleValueX = _normalScaleValueY = 1.0f;
    }
    else
    {
        _labelRenderer->setDimensions(_contentSize.width,_contentSize.height);
        Size textureSize = _labelRenderer->getContentSize();
        if (textureSize.width <= 0.0f || textureSize.height <= 0.0f)
        {
            _labelRenderer->setScale(1.0f);
            return;
        }
        float scaleX = _contentSize.width / textureSize.width;
        float scaleY = _contentSize.height / textureSize.height;
        _labelRenderer->setScaleX(scaleX);
        _labelRenderer->setScaleY(scaleY);
        _normalScaleValueX = scaleX;
        _normalScaleValueY = scaleY;
    }
    _labelRenderer->setPosition(_contentSize.width / 2.0f, _contentSize.height / 2.0f);
}

std::string Text::getDescription() const
{
    return "Label";
}

void Text::enableShadow(const Color4B& shadowColor,const Size &offset, int blurRadius)
{
    _labelRenderer->enableShadow(shadowColor, offset, blurRadius);
}

void Text::enableOutline(const Color4B& outlineColor,int outlineSize)
{
    _labelRenderer->enableOutline(outlineColor, outlineSize);
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

void Text::enableGlow(const Color4B& glowColor)
{
    if (_type == Type::TTF)
        _labelRenderer->enableGlow(glowColor);
}

void Text::disableEffect()
{
    _labelRenderer->disableEffect();
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

void Text::disableEffect(LabelEffect effect)
{
    _labelRenderer->disableEffect(effect);
    //only outline effect will affect the content size of label
    if(LabelEffect::OUTLINE == effect)
    {
        updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
        _labelRendererAdaptDirty = true;
    }
}

bool Text::isShadowEnabled() const
{
    return _labelRenderer->isShadowEnabled();
}
Size Text::getShadowOffset() const
{
    return _labelRenderer->getShadowOffset();
}
float Text::getShadowBlurRadius() const
{
    return _labelRenderer->getShadowBlurRadius();
}
Color4B Text::getShadowColor() const
{
    Color4F effect = _labelRenderer->getShadowColor();
    return Color4B(effect.r * 255, effect.g * 255, effect.b * 255, effect.a * 255);
}

int Text::getOutlineSize() const
{
    return _labelRenderer->getOutlineSize();
}
LabelEffect Text::getLabelEffectType() const
{
    return _labelRenderer->getLabelEffectType();
}
Color4B Text::getEffectColor() const
{
    Color4F effect = _labelRenderer->getEffectColor();
    return Color4B(effect.r * 255, effect.g * 255, effect.b * 255, effect.a * 255);
}

Widget* Text::createCloneInstance()
{
    return Text::create();
}

void Text::copySpecialProperties(Widget *widget)
{
    Text* label = dynamic_cast<Text*>(widget);
    if (label)
    {
        setFontName(label->_fontName);
        setFontSize(label->getFontSize());
        setTextColor(label->getTextColor());
        setString(label->getString());
        setTouchScaleChangeEnabled(label->_touchScaleChangeEnabled);
        setTextHorizontalAlignment(label->_labelRenderer->getHorizontalAlignment());
        setTextVerticalAlignment(label->_labelRenderer->getVerticalAlignment());
        setTextAreaSize(label->_labelRenderer->getDimensions());
        setContentSize(label->getContentSize());

        LabelEffect effectType = label->getLabelEffectType();
        if (effectType == LabelEffect::GLOW)
        {
            enableGlow(label->getEffectColor());
        }
        else if (effectType == LabelEffect::OUTLINE)
        {
            enableOutline(label->getEffectColor(),label->getOutlineSize());
        }
        if (label->isShadowEnabled())
        {
            enableShadow(label->getShadowColor(),label->getShadowOffset(),label->getShadowBlurRadius());
        }
    }
}

}

NS_CC_END

redpajama_set_name: RedPajamaGithub


text:
import { html, css, LitElement } from "lit";
import { customElement, property } from "lit/decorators.js";

@customElement("pekkis-duckling-suckler")
export class PekkisDucklingSuckler extends LitElement {
  static styles = css`
    div {
      background-color: black;
      color: white;
      padding: 1em;
      border-radius: 10px;
    }

    p:first-child {
      margin-top: 0;
    }

    p:last-child {
      margin-bottom: 0;
    }
  `;

  @property()
  name = "Somebody";

  render() {
    return html`

        I am pretty sure that somewhere, someone, is
        suckling on a juicy duckling. But I do assure you that it is
        not me, ${this.name}.

This black box is a native web component, by the way.

`;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    "pekkis-duckling-suckler": PekkisDucklingSuckler;
  }

  namespace JSX {
    interface IntrinsicElements {
      "pekkis-duckling-suckler": { name?: string };
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/employeeadmim.iml" filepath="$PROJECT_DIR$/employeeadmim.iml" />
    </modules>
  </component>
</project>


text:
-- MySQL dump 10.16  Distrib 10.1.26-MariaDB, for debian-linux-gnu (x86_64)
--
-- Host: localhost    Database: discord
-- ------------------------------------------------------
-- Server version	10.1.26-MariaDB-0+deb9u1

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `chessroom`
--

DROP TABLE IF EXISTS `chessroom`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `chessroom` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `player1` varchar(255) DEFAULT NULL,
  `player2` varchar(255) DEFAULT NULL,
  `chessboard` varchar(255) DEFAULT NULL,
  `now` int(11) DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `chesslog`
--

DROP TABLE IF EXISTS `chesslog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `chesslog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `color` int(1) DEFAULT NULL,
  `x` int(2) DEFAULT NULL,
  `y` int(2) DEFAULT NULL,
  `chessroomid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `room` (`chessroomid`),
  CONSTRAINT `room` FOREIGN KEY (`chessroomid`) REFERENCES `chessroom` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `gift`
--

DROP TABLE IF EXISTS `gift`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `gift` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `price` int(11) NOT NULL,
  `charm` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `gift_log`
--

DROP TABLE IF EXISTS `gift_log`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `gift_log` (
  `senderid` varchar(255) DEFAULT NULL,
  `receiverid` varchar(255) DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `giftid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `user`
--

DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
  `userid` varchar(255) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `money` int(11) DEFAULT '100',
  `charmPoint` int(11) DEFAULT '0',
  `richPoint` int(11) DEFAULT '0',
  KEY `userid` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `user_osu_id`
--

DROP TABLE IF EXISTS `user_osu_id`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_osu_id` (
  `userid` varchar(255) NOT NULL,
  `osuid` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2018-03-13 22:38:41


text:
#ifndef _CK_SEQUENCE_H
#define _CK_SEQUENCE_H

#include <ck_cc.h>
#include <ck_pr.h>
#include <stdbool.h>

struct ck_sequence {
	unsigned int sequence;
};
typedef struct ck_sequence ck_sequence_t;

#define CK_SEQUENCE_INITIALIZER { .sequence = 0 }

CK_CC_INLINE static void
ck_sequence_init(struct ck_sequence *sq)
{

	ck_pr_store_uint(&sq->sequence, 0);
	return;
}

CK_CC_INLINE static unsigned int
ck_sequence_read_begin(struct ck_sequence *sq)
{
	unsigned int version;

	for (;;) {
		version = ck_pr_load_uint(&sq->sequence);

		/*
		 * If a sequence is even then associated data may be in a
		 * consistent state.
		 */
		if ((version & 1) == 0)
			break;

		/*
		 * If a sequence is odd then a thread is in the middle of an
		 * update. Retry the read to avoid operating on inconsistent
		 * data.
		 */
		ck_pr_stall();
	}

	ck_pr_fence_load();
	return version;
}

CK_CC_INLINE static bool
ck_sequence_read_retry(struct ck_sequence *sq, uint32_t version)
{

	/*
	 * If the sequence number was updated then a read should be
	 * re-attempted.
	 */
	ck_pr_fence_load();
	return ck_pr_load_uint(&sq->sequence) != version;
}

/*
 * This must be called after a successful mutex acquisition.
 */
CK_CC_INLINE static void
ck_sequence_write_begin(struct ck_sequence *sq)
{

	/*
	 * Increment the sequence to an odd number to indicate
	 * the beginning of a write update.
	 */
	ck_pr_inc_uint(&sq->sequence);
	ck_pr_fence_store();
	return;
}

/*
 * This must be called before mutex ownership is relinquished.
 */
CK_CC_INLINE static void
ck_sequence_write_end(struct ck_sequence *sq)
{

	/*
	 * Increment the sequence to an even number to indicate
	 * completion of a write update.
	 */
	ck_pr_fence_store();
	ck_pr_inc_uint(&sq->sequence);
	return;
}

#endif /* _CK_SEQUENCE_H */


text:
param([Switch]$Rebuild)

[string]$temp = '.\nugettmp'
[string]$builder = "$env:windir\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe"

[string]$sln = 'MsgPack.Xamarin.sln'

[string]$nuspec = 'MsgPack.nuspec'

$buildOptions = @()
if( $Rebuild )
{
    $buildOptions += '/t:Rebuild'
}

$buildOptions += '/p:Configuration=Release'
# build
&$builder $sln $buildOptions


text:
CFLAGS += -O2 -I..

ifneq ($(KERNELRELEASE),)
# call from kernel build system

obj-m	:= shortprint.o

else

KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD       := $(shell pwd)

default:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules

endif

clean:
	rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions

depend .depend dep:
	$(CC) $(CFLAGS) -M *.c > .depend

ifeq (.depend,$(wildcard .depend))
include .depend
endif


text:
from rspecs.parser_base import ParserBase
from rspecs.commons_se import SELink
from rspecs.commons_tn import Node, Interface

import core
logger = core.log.getLogger("utility-rspec")

class SERMv3RequestParser(ParserBase):
    def __init__(self, from_file=None, from_string=None):
        super(SERMv3RequestParser, self).__init__(from_file, from_string)
        self.__sv = self.rspec.nsmap.get('sharedvlan')
        self.__felix = self.rspec.nsmap.get('felix')
        self.__proto = self.rspec.nsmap.get('protogeni')

    def check_se_node_resource(self, node):
        # according to the proposed URNs structure, a SE-node MUST have
        # "serm" as resource-name (client_id) and authority
        # (component_manager_id) fields
        # At least we verify the autority field here!
        if node.attrib.get("component_manager_id", None) is not None and \
            node.attrib.get("client_id", None) is not None:
            if "serm" in node.attrib.get("component_manager_id", "") or \
                "serm" in node.attrib.get("client_id", ""):
                return True
        return False

    def check_se_link_resource(self, link, c_manager):
        # according to the proposed URNs structure, a TN-link MUST have
        # "serm" as resource-name (client_id) and authority
        # (component_manager_name) fields
        # At least we verify the autority field here!
        if not c_manager.attrib.get("name"):
            return False
        if "serm" in c_manager.attrib.get("name"):
            return True
        return False

    def update_protogeni_cm_uuid(self, tag, obj):
        cmuuid = tag.attrib.get("{%s}component_manager_uuid" % (self.__proto))
        if cmuuid is not None:
            obj.add_component_manager_uuid(cmuuid)

    def get_nodes(self, rspec):
        nodes = []
        for n in rspec.findall(".//{%s}node" % (self.none)):
            if not self.check_se_node_resource(n):
                logger.info("Skipping this node, not a SE-res: %s", (n,))
                continue

            node = Node(n.attrib.get("client_id"),
                        n.attrib.get("component_manager_id"),
                        n.attrib.get("exclusive"))

            self.update_protogeni_cm_uuid(n, node)

            for i in n.iterfind("{%s}interface" % (self.none)):
                interface = Interface(i.attrib.get("client_id"))
                for sv in i.iterfind("{%s}link_shared_vlan" % (self.__sv)):
                    interface.add_vlan(sv.attrib.get("vlantag"),
                                       sv.attrib.get("name"))
                node.add_interface(interface.serialize())

            nodes.append(node.serialize())
        return nodes

    def nodes(self):
        return self.get_nodes(self.rspec)

    def get_links(self, rspec):
        links_ = []
        for l in rspec.findall(".//{%s}link" % (self.none)):
            manager_ = l.find("{%s}component_manager" % (self.none))
            if manager_ is None:
                self.raise_exception("Component-Mgr tag not found in link!")

            if not self.check_se_link_resource(l, manager_):
                logger.info("Skipping this link, not a SE-res: %s", (l,))
                continue

            type_ = l.find("{%s}link_type" % (self.none))
            if type_ is None:
                self.raise_exception("Link-Type tag not found in link!")

            l_ = SELink(l.attrib.get("client_id"), type_.attrib.get("name"),
                        manager_.attrib.get("name"))

            self.update_protogeni_cm_uuid(l, l_)

            # FIXME: VLAN seems not properly added to interface
            [l_.add_interface_ref(i.attrib.get("client_id"),
            i.attrib.get("{%s}vlan" % (self.__felix)))
             for i in l.iterfind("{%s}interface_ref" % (self.none))]

            [l_.add_property(p.attrib.get("source_id"),
                             p.attrib.get("dest_id"),
                             p.attrib.get("capacity"))
             for p in l.iterfind("{%s}property" % (self.none))]

            links_.append(l_.serialize())

        return links_

    def links(self):
        return self.get_links(self.rspec)


text:
#include "ConsoleLogger.h"
#include "Shell.h"

STATIC CONST CHAR16                     mCrLfString[3] = { CHAR_CARRIAGE_RETURN, CHAR_LINEFEED, CHAR_NULL };

/**
  Install our intermediate ConOut into the system table to
  keep a log of all the info that is displayed to the user.

  @param[in] ScreensToSave  Sets how many screen-worths of data to save.
  @param[out] ConsoleInfo   The object to pass into later functions.

  @retval EFI_SUCCESS       The operation was successful.
  @return other             The operation failed.

  @sa ConsoleLoggerResetBuffers
  @sa InstallProtocolInterface
**/
EFI_STATUS
EFIAPI
ConsoleLoggerInstall(
  IN CONST UINTN ScreensToSave,
  OUT CONSOLE_LOGGER_PRIVATE_DATA **ConsoleInfo
  )
{
  EFI_STATUS Status;
  ASSERT(ConsoleInfo != NULL);

  (*ConsoleInfo) = AllocateZeroPool(sizeof(CONSOLE_LOGGER_PRIVATE_DATA));
  if ((*ConsoleInfo) == NULL) {
    return (EFI_OUT_OF_RESOURCES);
  }

  (*ConsoleInfo)->Signature                   = CONSOLE_LOGGER_PRIVATE_DATA_SIGNATURE;
  (*ConsoleInfo)->OldConOut                   = gST->ConOut;
  (*ConsoleInfo)->OldConHandle                = gST->ConsoleOutHandle;
  (*ConsoleInfo)->Buffer                      = NULL;
  (*ConsoleInfo)->BufferSize                  = 0;
  (*ConsoleInfo)->OriginalStartRow            = 0;
  (*ConsoleInfo)->CurrentStartRow             = 0;
  (*ConsoleInfo)->RowsPerScreen               = 0;
  (*ConsoleInfo)->ColsPerScreen               = 0;
  (*ConsoleInfo)->Attributes                  = NULL;
  (*ConsoleInfo)->AttribSize                  = 0;
  (*ConsoleInfo)->ScreenCount                 = ScreensToSave;
  (*ConsoleInfo)->HistoryMode.MaxMode         = 1;
  (*ConsoleInfo)->HistoryMode.Mode            = 0;
  (*ConsoleInfo)->HistoryMode.Attribute       = 0;
  (*ConsoleInfo)->HistoryMode.CursorColumn    = 0;
  (*ConsoleInfo)->HistoryMode.CursorRow       = 0;
  (*ConsoleInfo)->HistoryMode.CursorVisible   = FALSE;
  (*ConsoleInfo)->OurConOut.Reset             = ConsoleLoggerReset;
  (*ConsoleInfo)->OurConOut.OutputString      = ConsoleLoggerOutputString;
  (*ConsoleInfo)->OurConOut.TestString        = ConsoleLoggerTestString;
  (*ConsoleInfo)->OurConOut.QueryMode         = ConsoleLoggerQueryMode;
  (*ConsoleInfo)->OurConOut.SetMode           = ConsoleLoggerSetMode;
  (*ConsoleInfo)->OurConOut.SetAttribute      = ConsoleLoggerSetAttribute;
  (*ConsoleInfo)->OurConOut.ClearScreen       = ConsoleLoggerClearScreen;
  (*ConsoleInfo)->OurConOut.SetCursorPosition = ConsoleLoggerSetCursorPosition;
  (*ConsoleInfo)->OurConOut.EnableCursor      = ConsoleLoggerEnableCursor;
  (*ConsoleInfo)->OurConOut.Mode              = gST->ConOut->Mode;
  (*ConsoleInfo)->Enabled                     = TRUE;

  Status = ConsoleLoggerResetBuffers(*ConsoleInfo);
  if (EFI_ERROR(Status)) {
    SHELL_FREE_NON_NULL((*ConsoleInfo));
    *ConsoleInfo = NULL;
    return (Status);
  }

  Status = gBS->InstallProtocolInterface(&gImageHandle, &gEfiSimpleTextOutProtocolGuid, EFI_NATIVE_INTERFACE, (VOID*)&((*ConsoleInfo)->OurConOut));
  if (EFI_ERROR(Status)) {
    SHELL_FREE_NON_NULL((*ConsoleInfo)->Buffer);
    SHELL_FREE_NON_NULL((*ConsoleInfo)->Attributes);
    SHELL_FREE_NON_NULL((*ConsoleInfo));
    *ConsoleInfo = NULL;
    return (Status);
  }

  gST->ConsoleOutHandle = gImageHandle;
  gST->ConOut           = &(*ConsoleInfo)->OurConOut;

  return (Status);
}

/**
  Return the system to the state it was before InstallConsoleLogger
  was installed.

  @param[in] ConsoleInfo  The object from the install function.

  @retval EFI_SUCCESS     The operation was successful
  @return other           The operation failed.  This was from UninstallProtocolInterface.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerUninstall(
  IN CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo
  )
{
  ASSERT(ConsoleInfo != NULL);
  ASSERT(ConsoleInfo->OldConOut != NULL);

  if (ConsoleInfo->Buffer != NULL) {
    FreePool(ConsoleInfo->Buffer);
    DEBUG_CODE(ConsoleInfo->Buffer     = NULL;);
    DEBUG_CODE(ConsoleInfo->BufferSize = 0;);
  }
  if (ConsoleInfo->Attributes != NULL) {
    FreePool(ConsoleInfo->Attributes);
    DEBUG_CODE(ConsoleInfo->Attributes = NULL;);
    DEBUG_CODE(ConsoleInfo->AttribSize = 0;);
  }

  gST->ConsoleOutHandle = ConsoleInfo->OldConHandle;
  gST->ConOut = ConsoleInfo->OldConOut;

  return (gBS->UninstallProtocolInterface(gImageHandle, &gEfiSimpleTextOutProtocolGuid, (VOID*)&ConsoleInfo->OurConOut));
}

/**
  Displays previously logged output back to the screen.

  This will scroll the screen forwards and backwards through the log of previous
  output.  If Rows is 0 then the size of 1/2 the screen will be scrolled.  If Rows
  is (UINTN)(-1) then the size of the screen will be scrolled.

  @param[in] Forward      If TRUE then the log will be displayed forwards (scroll to newer).
                          If FALSE then the log will be displayed backwards (scroll to older).
  @param[in] Rows         Determines how many rows the log should scroll.
  @param[in] ConsoleInfo  The pointer to the instance of the console logger information.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerDisplayHistory(
  IN CONST BOOLEAN  Forward,
  IN CONST UINTN    Rows,
  IN CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo
  )
{
  UINTN   RowChange;

  ASSERT(ConsoleInfo != NULL);

  //
  // Calculate the row number change
  //
  switch (Rows) {
  case ((UINTN)(-1)):
    RowChange = ConsoleInfo->RowsPerScreen;
    break;
  case (0):
    RowChange = ConsoleInfo->RowsPerScreen / 2;
    break;
  default:
    RowChange = Rows;
    break;
  }

  //
  // Do the math for direction
  //
  if (Forward) {
    if ((ConsoleInfo->OriginalStartRow - ConsoleInfo->CurrentStartRow) < RowChange) {
      RowChange = ConsoleInfo->OriginalStartRow - ConsoleInfo->CurrentStartRow;
    }
  } else {
    if (ConsoleInfo->CurrentStartRow < RowChange) {
      RowChange = ConsoleInfo->CurrentStartRow;
    }
  }

  //
  // If we are already at one end or the other
  //
  if (RowChange == 0) {
    return (EFI_SUCCESS);
  }

  //
  // Clear the screen
  //
  ConsoleInfo->OldConOut->ClearScreen(ConsoleInfo->OldConOut);

  //
  // Set the new start row
  //
  if (Forward) {
    ConsoleInfo->CurrentStartRow += RowChange;
  } else {
    ConsoleInfo->CurrentStartRow -= RowChange;
  }

  //
  // Change the screen
  //
  return (UpdateDisplayFromHistory(ConsoleInfo));
}

/**
  Function to return to normal output whent he scrolling is complete.
  @param[in] ConsoleInfo  The pointer to the instance of the console logger information.

  @retval EFI_SUCCESS   The operation was successful.
  @return other         The operation failed.  See UpdateDisplayFromHistory.

  @sa UpdateDisplayFromHistory
**/
EFI_STATUS
EFIAPI
ConsoleLoggerStopHistory(
  IN CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo
  )
{
  ASSERT(ConsoleInfo != NULL);
  if (ConsoleInfo->CurrentStartRow == ConsoleInfo->OriginalStartRow) {
    return (EFI_SUCCESS);
  }
  ConsoleInfo->CurrentStartRow = ConsoleInfo->OriginalStartRow;
  return (UpdateDisplayFromHistory(ConsoleInfo));
}

/**
  Updates the hidden ConOut to be displaying the correct stuff.
  @param[in] ConsoleInfo  The pointer to the instance of the console logger information.

  @retval EFI_SUCCESS     The operation was successful.
  @return other           The operation failed.
**/
EFI_STATUS
EFIAPI
UpdateDisplayFromHistory(
  IN CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo
  )
{
  EFI_STATUS      Status;
  EFI_STATUS      RetVal;
  CHAR16          *Screen;
  INT32           *Attributes;
  UINTN           CurrentRow;
  CHAR16          TempCharHolder;
  UINTN           Column;
  INT32           CurrentAttrib;
  UINTN           CurrentColumn;
  CHAR16          *StringSegment;
  CHAR16          *StringSegmentEnd;
  CHAR16          StringSegmentEndChar;
  INT32           OrigAttribute;

  ASSERT(ConsoleInfo != NULL);
  TempCharHolder = CHAR_NULL;
  RetVal = EFI_SUCCESS;
  OrigAttribute = ConsoleInfo->OldConOut->Mode->Attribute;

  //
  // Disable cursor visibility and move it to the top left corner
  //
  ConsoleInfo->OldConOut->EnableCursor       (ConsoleInfo->OldConOut, FALSE);
  ConsoleInfo->OldConOut->SetCursorPosition  (ConsoleInfo->OldConOut, 0, 0);

  Screen = &ConsoleInfo->Buffer[(ConsoleInfo->ColsPerScreen + 2) * ConsoleInfo->CurrentStartRow];
  Attributes = &ConsoleInfo->Attributes[ConsoleInfo->ColsPerScreen * ConsoleInfo->CurrentStartRow];
  for ( CurrentRow = 0
      ; CurrentRow < ConsoleInfo->RowsPerScreen
      ; CurrentRow++
      , Screen += (ConsoleInfo->ColsPerScreen + 2)
      , Attributes += ConsoleInfo->ColsPerScreen
     ){
    //
    // dont use the last char - prevents screen scroll
    //
    if (CurrentRow == (ConsoleInfo->RowsPerScreen-1)){
      TempCharHolder = Screen[ConsoleInfo->ColsPerScreen - 1];
      Screen[ConsoleInfo->ColsPerScreen - 1] = CHAR_NULL;
    }

    for ( Column = 0
        ; Column < ConsoleInfo->ColsPerScreen
        ; Column++
       ){
      if (Screen[Column] != CHAR_NULL) {
        CurrentAttrib = Attributes[Column];
        CurrentColumn = Column;
        StringSegment = &Screen[Column];

        //
        // Find the first char with a different arrribute and make that temporarily NULL
        // so we can do fewer printout statements.  (later) restore that one and we will
        // start at that collumn on the next loop.
        //
        StringSegmentEndChar = CHAR_NULL;
        for ( StringSegmentEnd = StringSegment
            ; StringSegmentEnd != CHAR_NULL
            ; StringSegmentEnd++
            , Column++
           ){
          if (Attributes[Column] != CurrentAttrib) {
            StringSegmentEndChar = *StringSegmentEnd;
            *StringSegmentEnd    = CHAR_NULL;
            break;
          }
        } // StringSegmentEnd loop

        //
        // Now write out as much as had the same Attributes
        //

        ConsoleInfo->OldConOut->SetAttribute(ConsoleInfo->OldConOut, CurrentAttrib);
        ConsoleInfo->OldConOut->SetCursorPosition(ConsoleInfo->OldConOut, CurrentColumn, CurrentRow);
        Status = ConsoleInfo->OldConOut->OutputString(ConsoleInfo->OldConOut, StringSegment);

        if (EFI_ERROR(Status)) {
          ASSERT(FALSE);
          RetVal = Status;
        }

        //
        // If we found a change in attribute put the character back and decrement the column
        // so when it increments it will point at that character and we will start printing
        // a segment with that new attribute
        //
        if (StringSegmentEndChar != CHAR_NULL) {
          *StringSegmentEnd = StringSegmentEndChar;
          StringSegmentEndChar = CHAR_NULL;
          Column--;
        }
      }
    } // column for loop

    //
    // If we removed the last char and this was the last row put it back
    //
    if (TempCharHolder != CHAR_NULL) {
      Screen[ConsoleInfo->ColsPerScreen - 1] = TempCharHolder;
      TempCharHolder = CHAR_NULL;
    }
  } // row for loop

  //
  // If we are setting the screen back to original turn on the cursor and make it visible
  // and set the attributes back to what they were
  //
  if (ConsoleInfo->CurrentStartRow == ConsoleInfo->OriginalStartRow) {
    ConsoleInfo->OldConOut->SetAttribute (
                                ConsoleInfo->OldConOut,
                                ConsoleInfo->HistoryMode.Attribute
                               );
    ConsoleInfo->OldConOut->SetCursorPosition (
                                ConsoleInfo->OldConOut,
                                ConsoleInfo->HistoryMode.CursorColumn,
                                ConsoleInfo->HistoryMode.CursorRow - ConsoleInfo->OriginalStartRow
                               );

    Status = ConsoleInfo->OldConOut->EnableCursor (
                                ConsoleInfo->OldConOut,
                                ConsoleInfo->HistoryMode.CursorVisible
                               );
    if (EFI_ERROR (Status)) {
      RetVal = Status;
    }
  } else {
    ConsoleInfo->OldConOut->SetAttribute (
                                ConsoleInfo->OldConOut,
                                OrigAttribute
                               );
  }

  return (RetVal);
}

/**
  Reset the text output device hardware and optionaly run diagnostics

  @param  This                pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL
  @param ExtendedVerification Indicates that a more extensive test may be performed

  @retval EFI_SUCCESS         The text output device was reset.
  @retval EFI_DEVICE_ERROR    The text output device is not functioning correctly and
                              could not be reset.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerReset (
  IN  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
  IN  BOOLEAN                         ExtendedVerification
  )
{
  EFI_STATUS                  Status;
  CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo;
  ConsoleInfo = CONSOLE_LOGGER_PRIVATE_DATA_FROM_THIS(This);

  //
  // Forward the request to the original ConOut
  //
  Status = ConsoleInfo->OldConOut->Reset (ConsoleInfo->OldConOut, ExtendedVerification);

  //
  // Check that the buffers are still correct for logging
  //
  if (!EFI_ERROR (Status)) {
    ConsoleLoggerResetBuffers(ConsoleInfo);
  }

  return Status;
}

/**
  Appends a string to the history buffer.  If the buffer is full then the oldest
  information in the buffer will be dropped.  Information is added in a line by
  line manner such that an empty line takes up just as much space as a full line.

  @param[in] String       String pointer to add.
  @param[in] ConsoleInfo  The pointer to the instance of the console logger information.
**/
EFI_STATUS
EFIAPI
AppendStringToHistory(
  IN CONST CHAR16 *String,
  IN CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo
  )
{
  CONST CHAR16  *Walker;
  UINTN         CopySize;
  UINTN         PrintIndex;
  UINTN         Index;

  ASSERT(ConsoleInfo != NULL);

  for ( Walker = String
      ; Walker != NULL && *Walker != CHAR_NULL
      ; Walker++
     ){
    switch (*Walker) {
    case (CHAR_BACKSPACE):
      if (ConsoleInfo->HistoryMode.CursorColumn > 0) {
        ConsoleInfo->HistoryMode.CursorColumn--;
      }
      break;
    case (CHAR_LINEFEED):
      if (ConsoleInfo->HistoryMode.CursorRow >= (INT32)((ConsoleInfo->RowsPerScreen * ConsoleInfo->ScreenCount)-1)) {
        //
        // Should never be bigger
        //
        ASSERT(ConsoleInfo->HistoryMode.CursorRow == (INT32)((ConsoleInfo->RowsPerScreen * ConsoleInfo->ScreenCount)-1));

        //
        // scroll history attributes 'up' 1 row and set the last row to default attribute
        //
        CopySize = ConsoleInfo->ColsPerScreen
                 * ((ConsoleInfo->RowsPerScreen * ConsoleInfo->ScreenCount) - 1)
                 * sizeof(ConsoleInfo->Attributes[0]);
        ASSERT(CopySize < ConsoleInfo->AttribSize);
        CopyMem(
          ConsoleInfo->Attributes,
          ConsoleInfo->Attributes + ConsoleInfo->ColsPerScreen,
          CopySize
         );

        for ( Index = 0
            ; Index < ConsoleInfo->ColsPerScreen
            ; Index++
           ){
          *(ConsoleInfo->Attributes + (CopySize/sizeof(ConsoleInfo->Attributes)) + Index) = ConsoleInfo->HistoryMode.Attribute;
        }

        //
        // scroll history buffer 'up' 1 row and set the last row to spaces (L' ')
        //
        CopySize = (ConsoleInfo->ColsPerScreen + 2)
                 * ((ConsoleInfo->RowsPerScreen * ConsoleInfo->ScreenCount) - 1)
                 * sizeof(ConsoleInfo->Buffer[0]);
        ASSERT(CopySize < ConsoleInfo->BufferSize);
        CopyMem(
          ConsoleInfo->Buffer,
          ConsoleInfo->Buffer + (ConsoleInfo->ColsPerScreen + 2),
          CopySize
         );

        //
        // Set that last row of chars to spaces
        //
        SetMem16(((UINT8*)ConsoleInfo->Buffer)+CopySize, ConsoleInfo->ColsPerScreen*sizeof(CHAR16), L' ');
      } else {
        //
        // we are not on the last row
        //

        //
        // We should not be scrolling history
        //
        ASSERT (ConsoleInfo->OriginalStartRow == ConsoleInfo->CurrentStartRow);
        //
        // are we at the end of a row?
        //
        if (ConsoleInfo->HistoryMode.CursorRow == (INT32) (ConsoleInfo->OriginalStartRow + ConsoleInfo->RowsPerScreen - 1)) {
          ConsoleInfo->OriginalStartRow++;
          ConsoleInfo->CurrentStartRow++;
        }
        ConsoleInfo->HistoryMode.CursorRow++;
      }
      break;
    case (CHAR_CARRIAGE_RETURN):
      //
      // Move the cursor to the beginning of the current row.
      //
      ConsoleInfo->HistoryMode.CursorColumn = 0;
      break;
    default:
      //
      // Acrtually print characters into the history buffer
      //

      PrintIndex = ConsoleInfo->HistoryMode.CursorRow * ConsoleInfo->ColsPerScreen + ConsoleInfo->HistoryMode.CursorColumn;

      for ( // no initializer needed
          ; ConsoleInfo->HistoryMode.CursorColumn < (INT32) ConsoleInfo->ColsPerScreen
          ; ConsoleInfo->HistoryMode.CursorColumn++
          , PrintIndex++
          , Walker++
         ){
        if (*Walker == CHAR_NULL
          ||*Walker == CHAR_BACKSPACE
          ||*Walker == CHAR_LINEFEED
          ||*Walker == CHAR_CARRIAGE_RETURN
         ){
            Walker--;
            break;
        }
        //
        // The buffer is 2*CursorRow more since it has that many \r\n characters at the end of each row.
        //

        ASSERT(PrintIndex + ConsoleInfo->HistoryMode.CursorRow < ConsoleInfo->BufferSize);
        ConsoleInfo->Buffer[PrintIndex + (2*ConsoleInfo->HistoryMode.CursorRow)] = *Walker;
        ASSERT(PrintIndex < ConsoleInfo->AttribSize);
        ConsoleInfo->Attributes[PrintIndex] = ConsoleInfo->HistoryMode.Attribute;
      } // for loop

      //
      // Add the carriage return and line feed at the end of the lines
      //
      if (ConsoleInfo->HistoryMode.CursorColumn >= (INT32)ConsoleInfo->ColsPerScreen) {
        AppendStringToHistory(L"\r\n", ConsoleInfo);
        Walker--;
      }

      break;
    } // switch for character
  } // for loop

  return (EFI_SUCCESS);
}

/**
  Worker function to handle printing the output to the screen
  and the history buffer

  @param[in] String               The string to output
  @param[in] ConsoleInfo          The pointer to the instance of the console logger information.

  @retval EFI_SUCCESS             The string was printed
  @retval EFI_DEVICE_ERROR        The device reported an error while attempting to output
                                  the text.
  @retval EFI_UNSUPPORTED         The output device's mode is not currently in a
                                  defined text mode.
  @retval EFI_WARN_UNKNOWN_GLYPH  This warning code indicates that some of the
                                  characters in the Unicode string could not be
                                  rendered and were skipped.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerOutputStringSplit(
  IN CONST CHAR16   *String,
  IN CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo
  )
{
  EFI_STATUS    Status;

  //
  // Forward the request to the original ConOut
  //
  Status = ConsoleInfo->OldConOut->OutputString (ConsoleInfo->OldConOut, (CHAR16*)String);

  if (EFI_ERROR(Status)) {
    return (Status);
  }

  return (AppendStringToHistory(String, ConsoleInfo));
}

/**
  Function to handle page break mode.

  This function will prompt for continue or break.

  @retval EFI_SUCCESS   Continue was choosen
  @return other         Break was choosen
**/
EFI_STATUS
EFIAPI
ConsoleLoggerDoPageBreak(
  VOID
  )
{
  SHELL_PROMPT_RESPONSE *Resp;
  EFI_STATUS            Status;

  Resp = NULL;
  ASSERT(ShellInfoObject.PageBreakEnabled);
  ShellInfoObject.PageBreakEnabled = FALSE;
  Status = ShellPromptForResponseHii(ShellPromptResponseTypeQuitContinue, STRING_TOKEN(STR_SHELL_QUIT_CONT), ShellInfoObject.HiiHandle, (VOID**)&Resp);
  ShellInfoObject.PageBreakEnabled = TRUE;
  ASSERT(Resp != NULL);
  if (Resp == NULL) {
    return (EFI_NOT_FOUND);
  }
  if (EFI_ERROR(Status)) {
    if (Resp != NULL) {
      FreePool(Resp);
    }
    return (Status);
  }
  if (*Resp == ShellPromptResponseContinue) {
    FreePool(Resp);
    ShellInfoObject.ConsoleInfo->RowCounter                   = 0;
//    ShellInfoObject.ConsoleInfo->OurConOut.Mode->CursorRow    = 0;
//    ShellInfoObject.ConsoleInfo->OurConOut.Mode->CursorColumn = 0;

    return (EFI_SUCCESS);
  } else if (*Resp == ShellPromptResponseQuit) {
    FreePool(Resp);
    ShellInfoObject.ConsoleInfo->Enabled = FALSE;
    return (EFI_DEVICE_ERROR);
  } else {
    ASSERT(FALSE);
  }
  return (EFI_SUCCESS);
}
/**
  Worker function to handle printing the output with page breaks.

  @param[in] String               The string to output
  @param[in] ConsoleInfo          The pointer to the instance of the console logger information.

  @retval EFI_SUCCESS             The string was printed
  @retval EFI_DEVICE_ERROR        The device reported an error while attempting to output
                                  the text.
  @retval EFI_UNSUPPORTED         The output device's mode is not currently in a
                                  defined text mode.
  @retval EFI_WARN_UNKNOWN_GLYPH  This warning code indicates that some of the
                                  characters in the Unicode string could not be
                                  rendered and were skipped.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerPrintWithPageBreak(
  IN CONST CHAR16   *String,
  IN CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo
  )
{
  CONST CHAR16  *Walker;
  CONST CHAR16  *LineStart;
  CHAR16        *StringCopy;
  CHAR16        TempChar;

  StringCopy = NULL;
  StringCopy = StrnCatGrow(&StringCopy, NULL, String, 0);
  if (StringCopy == NULL) {
    return (EFI_OUT_OF_RESOURCES);
  }

  for ( Walker = StringCopy
      , LineStart = StringCopy
      ; Walker != NULL && *Walker != CHAR_NULL
      ; Walker++
     ){
    switch (*Walker) {
    case (CHAR_BACKSPACE):
      if (ConsoleInfo->OurConOut.Mode->CursorColumn > 0) {
        ConsoleInfo->OurConOut.Mode->CursorColumn--;
      }
      break;
    case (CHAR_LINEFEED):
      //
      // add a temp NULL terminator
      //
      TempChar = *(Walker + 1);
      *((CHAR16*)(Walker+1)) = CHAR_NULL;

      //
      // output the string
      //
      ConsoleLoggerOutputStringSplit (LineStart, ConsoleInfo);

      //
      // restore the temp NULL terminator to it's original character
      //
      *((CHAR16*)(Walker+1)) = TempChar;

      //
      // Update LineStart Variable
      //
      LineStart = Walker + 1;

      //
      // increment row count
      //
      ShellInfoObject.ConsoleInfo->RowCounter++;
      ConsoleInfo->OurConOut.Mode->CursorRow++;

      break;
    case (CHAR_CARRIAGE_RETURN):
      //
      // Move the cursor to the beginning of the current row.
      //
      ConsoleInfo->OurConOut.Mode->CursorColumn = 0;
      break;
    default:
      //
      // increment column count
      //
      ConsoleInfo->OurConOut.Mode->CursorColumn++;
      //
      // check if that is the last column
      //
      if ((INTN)ConsoleInfo->ColsPerScreen == ConsoleInfo->OurConOut.Mode->CursorColumn + 1) {
        //
        // output a line similar to the linefeed character.
        //

        //
        // add a temp NULL terminator
        //
        TempChar = *(Walker + 1);
        *((CHAR16*)(Walker+1)) = CHAR_NULL;

        //
        // output the string
        //
        ConsoleLoggerOutputStringSplit (LineStart, ConsoleInfo);

        //
        // restore the temp NULL terminator to it's original character
        //
        *((CHAR16*)(Walker+1)) = TempChar;

        //
        // Update LineStart Variable
        //
        LineStart = Walker + 1;

        //
        // increment row count and zero the column
        //
        ShellInfoObject.ConsoleInfo->RowCounter++;
        ConsoleInfo->OurConOut.Mode->CursorRow++;
        ConsoleInfo->OurConOut.Mode->CursorColumn = 0;
      } // last column on line
      break;
    } // switch for character

    //
    // check if that was the last printable row.  If yes handle PageBreak mode
    //
    if ((ConsoleInfo->RowsPerScreen) -1 == ShellInfoObject.ConsoleInfo->RowCounter) {
      if (EFI_ERROR(ConsoleLoggerDoPageBreak())) {
        //
        // We got an error which means 'break' and halt the printing
        //
        SHELL_FREE_NON_NULL(StringCopy);
        return (EFI_DEVICE_ERROR);
      }
    }
  } // for loop

  if (LineStart != NULL && *LineStart != CHAR_NULL) {
    ConsoleLoggerOutputStringSplit (LineStart, ConsoleInfo);
  }

  SHELL_FREE_NON_NULL(StringCopy);
  return (EFI_SUCCESS);
}

/**
  Write a Unicode string to the output device.

  @param[in] This                 Protocol instance pointer.
  @param[in] WString              The NULL-terminated Unicode string to be displayed on the output
                                  device(s). All output devices must also support the Unicode
                                  drawing defined in this file.
  @retval EFI_SUCCESS             The string was output to the device.
  @retval EFI_DEVICE_ERROR        The device reported an error while attempting to output
                                  the text.
  @retval EFI_UNSUPPORTED         The output device's mode is not currently in a
                                  defined text mode.
  @retval EFI_WARN_UNKNOWN_GLYPH  This warning code indicates that some of the
                                  characters in the Unicode string could not be
                                  rendered and were skipped.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerOutputString (
  IN  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
  IN  CHAR16                          *WString
  )
{
  EFI_INPUT_KEY               Key;
  UINTN                       EventIndex;
  CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo;
  ConsoleInfo = CONSOLE_LOGGER_PRIVATE_DATA_FROM_THIS(This);
  if (ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleOut) {
    return (EFI_UNSUPPORTED);
  }
  ASSERT(ShellInfoObject.ConsoleInfo == ConsoleInfo);
  if (ShellInfoObject.HaltOutput) {
    //
    // just get some key
    //
    gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &EventIndex);
    gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
    ShellInfoObject.HaltOutput = FALSE;
  }
  if (!ShellInfoObject.ConsoleInfo->Enabled) {
    return (EFI_DEVICE_ERROR);
  } else if (ShellInfoObject.PageBreakEnabled) {
    return (ConsoleLoggerPrintWithPageBreak(WString, ConsoleInfo));
  } else {
    return (ConsoleLoggerOutputStringSplit(WString, ConsoleInfo));
  }
}

/**
  Verifies that all characters in a Unicode string can be output to the
  target device.

  @param[in] This     Protocol instance pointer.
  @param[in] WString  The NULL-terminated Unicode string to be examined for the output
                      device(s).

  @retval EFI_SUCCESS           The device(s) are capable of rendering the output string.
  @retval EFI_UNSUPPORTED       Some of the characters in the Unicode string cannot be
                                rendered by one or more of the output devices mapped
                                by the EFI handle.

**/
EFI_STATUS
EFIAPI
ConsoleLoggerTestString (
  IN  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL  *This,
  IN  CHAR16                        *WString
  )
{
  CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo;
  ConsoleInfo = CONSOLE_LOGGER_PRIVATE_DATA_FROM_THIS(This);
  //
  // Forward the request to the original ConOut
  //
  return (ConsoleInfo->OldConOut->TestString (ConsoleInfo->OldConOut, WString));
}

/**
  Returns information for an available text mode that the output device(s)
  supports.

  @param[in] This               Protocol instance pointer.
  @param[in] ModeNumber         The mode number to return information on.
  @param[out] Columns           Upon return, the number of columns in the selected geometry
  @param[out] Rows              Upon return, the number of rows in the selected geometry

  @retval EFI_SUCCESS           The requested mode information was returned.
  @retval EFI_DEVICE_ERROR      The device had an error and could not
                                complete the request.
  @retval EFI_UNSUPPORTED       The mode number was not valid.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerQueryMode (
  IN  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL  *This,
  IN  UINTN                         ModeNumber,
  OUT UINTN                         *Columns,
  OUT UINTN                         *Rows
  )
{
  CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo;
  ConsoleInfo = CONSOLE_LOGGER_PRIVATE_DATA_FROM_THIS(This);
  //
  // Forward the request to the original ConOut
  //
  return (ConsoleInfo->OldConOut->QueryMode (
    ConsoleInfo->OldConOut,
    ModeNumber,
    Columns,
    Rows
   ));
}

/**
  Sets the output device(s) to a specified mode.

  @param[in] This               Protocol instance pointer.
  @param[in] ModeNumber         The mode number to set.

  @retval EFI_SUCCESS           The requested text mode was set.
  @retval EFI_DEVICE_ERROR      The device had an error and
                                could not complete the request.
  @retval EFI_UNSUPPORTED       The mode number was not valid.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerSetMode (
  IN  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL   *This,
  IN  UINTN                             ModeNumber
  )
{
  EFI_STATUS                  Status;

  CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo;
  ConsoleInfo = CONSOLE_LOGGER_PRIVATE_DATA_FROM_THIS(This);

  //
  // Forward the request to the original ConOut
  //
  Status = ConsoleInfo->OldConOut->SetMode (ConsoleInfo->OldConOut, ModeNumber);

  //
  // Check that the buffers are still correct for logging
  //
  if (!EFI_ERROR (Status)) {
    ConsoleInfo->OurConOut.Mode = gST->ConOut->Mode;
    ConsoleLoggerResetBuffers(ConsoleInfo);
  }

  return Status;
}

/**
  Sets the background and foreground colors for the OutputString () and
  ClearScreen () functions.

  @param[in] This               Protocol instance pointer.
  @param[in] Attribute          The attribute to set. Bits 0..3 are the foreground color, and
                                bits 4..6 are the background color. All other bits are undefined
                                and must be zero. The valid Attributes are defined in this file.

  @retval EFI_SUCCESS           The attribute was set.
  @retval EFI_DEVICE_ERROR      The device had an error and
                                could not complete the request.
  @retval EFI_UNSUPPORTED       The attribute requested is not defined.

**/
EFI_STATUS
EFIAPI
ConsoleLoggerSetAttribute (
  IN  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
  IN  UINTN                           Attribute
  )
{
  EFI_STATUS                  Status;

  CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo;
  ConsoleInfo = CONSOLE_LOGGER_PRIVATE_DATA_FROM_THIS(This);

  //
  // Forward the request to the original ConOut
  //
  Status = ConsoleInfo->OldConOut->SetAttribute (ConsoleInfo->OldConOut, Attribute);

  //
  // Record console output history
  //
  if (!EFI_ERROR (Status)) {
    ConsoleInfo->HistoryMode.Attribute = (INT32) Attribute;
  }

  return Status;
}

/**
  Clears the output device(s) display to the currently selected background
  color.

  @param[in] This               Protocol instance pointer.

  @retval EFI_SUCCESS           The operation completed successfully.
  @retval EFI_DEVICE_ERROR      The device had an error and
                                could not complete the request.
  @retval EFI_UNSUPPORTED       The output device is not in a valid text mode.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerClearScreen (
  IN  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL  *This
  )
{
  EFI_STATUS        Status;
  CHAR16            *Screen;
  INT32             *Attributes;
  UINTN             Row;
  UINTN             Column;
  CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo;

  if (ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleOut) {
    return (EFI_UNSUPPORTED);
  }

  ConsoleInfo = CONSOLE_LOGGER_PRIVATE_DATA_FROM_THIS(This);

  //
  // Forward the request to the original ConOut
  //
  Status = ConsoleInfo->OldConOut->ClearScreen (ConsoleInfo->OldConOut);

  //
  // Record console output history
  //
  if (!EFI_ERROR (Status)) {
    Screen = &ConsoleInfo->Buffer[(ConsoleInfo->ColsPerScreen + 1) * ConsoleInfo->CurrentStartRow];
    Attributes = &ConsoleInfo->Attributes[ConsoleInfo->ColsPerScreen * ConsoleInfo->CurrentStartRow];
    for ( Row = ConsoleInfo->OriginalStartRow
        ; Row < (ConsoleInfo->RowsPerScreen * ConsoleInfo->ScreenCount)
        ; Row++
       ){
      for ( Column = 0
          ; Column < ConsoleInfo->ColsPerScreen
          ; Column++
          , Screen++
          , Attributes++
         ){
        *Screen = L' ';
        *Attributes = ConsoleInfo->OldConOut->Mode->Attribute;
      }
      //
      // Skip the NULL on each column end in text buffer only
      //
      Screen++;
    }
    ConsoleInfo->HistoryMode.CursorColumn = 0;
    ConsoleInfo->HistoryMode.CursorRow    = 0;
  }

  return Status;
}

/**
  Sets the current coordinates of the cursor position

  @param[in] This               Protocol instance pointer.
  @param[in] Column             Column to put the cursor in.  Must be between zero and Column returned from QueryMode
  @param[in] Row                Row to put the cursor in.  Must be between zero and Row returned from QueryMode

  @retval EFI_SUCCESS           The operation completed successfully.
  @retval EFI_DEVICE_ERROR      The device had an error and
                                could not complete the request.
  @retval EFI_UNSUPPORTED       The output device is not in a valid text mode, or the
                                cursor position is invalid for the current mode.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerSetCursorPosition (
  IN  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL  *This,
  IN  UINTN                         Column,
  IN  UINTN                         Row
  )
{
  EFI_STATUS                  Status;
  CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo;

  if (ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleOut) {
    return (EFI_UNSUPPORTED);
  }

  ConsoleInfo = CONSOLE_LOGGER_PRIVATE_DATA_FROM_THIS(This);
  //
  // Forward the request to the original ConOut
  //
  Status = ConsoleInfo->OldConOut->SetCursorPosition (
    ConsoleInfo->OldConOut,
    Column,
    Row
   );

  //
  // Record console output history
  //
  if (!EFI_ERROR (Status)) {
    ConsoleInfo->HistoryMode.CursorColumn = (INT32)Column;
    ConsoleInfo->HistoryMode.CursorRow    = (INT32)(ConsoleInfo->OriginalStartRow + Row);
  }

  return Status;
}

/**
  Makes the cursor visible or invisible

  @param[in] This       Protocol instance pointer.
  @param[in] Visible    If TRUE, the cursor is set to be visible. If FALSE, the cursor is
                        set to be invisible.

  @retval EFI_SUCCESS           The operation completed successfully.
  @retval EFI_DEVICE_ERROR      The device had an error and could not complete the
                                request, or the device does not support changing
                                the cursor mode.
  @retval EFI_UNSUPPORTED       The output device is not in a valid text mode.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerEnableCursor (
  IN  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL  *This,
  IN  BOOLEAN                       Visible
  )
{
  EFI_STATUS                  Status;

  CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo;
  ConsoleInfo = CONSOLE_LOGGER_PRIVATE_DATA_FROM_THIS(This);
  //
  // Forward the request to the original ConOut
  //
  Status = ConsoleInfo->OldConOut->EnableCursor (ConsoleInfo->OldConOut, Visible);

  //
  // Record console output history
  //
  if (!EFI_ERROR (Status)) {
    ConsoleInfo->HistoryMode.CursorVisible = Visible;
  }

  return Status;
}

/**
  Function to update and verify that the current buffers are correct.

  @param[in] ConsoleInfo  The pointer to the instance of the console logger information.

  This will be used when a mode has changed or a reset ocurred to verify all
  history buffers.
**/
EFI_STATUS
EFIAPI
ConsoleLoggerResetBuffers(
  IN CONSOLE_LOGGER_PRIVATE_DATA *ConsoleInfo
  )
{
  EFI_STATUS Status;

  if (ConsoleInfo->Buffer != NULL) {
    FreePool(ConsoleInfo->Buffer);
    ConsoleInfo->Buffer     = NULL;
    ConsoleInfo->BufferSize = 0;
  }
  if (ConsoleInfo->Attributes != NULL) {
    FreePool(ConsoleInfo->Attributes);
    ConsoleInfo->Attributes = NULL;
    ConsoleInfo->AttribSize = 0;
  }

  Status = gST->ConOut->QueryMode (gST->ConOut, gST->ConOut->Mode->Mode, &ConsoleInfo->ColsPerScreen, &ConsoleInfo->RowsPerScreen);
  if (EFI_ERROR(Status)){
    return (Status);
  }

  ConsoleInfo->BufferSize = (ConsoleInfo->ColsPerScreen + 2) * ConsoleInfo->RowsPerScreen * ConsoleInfo->ScreenCount * sizeof(ConsoleInfo->Buffer[0]);
  ConsoleInfo->AttribSize = ConsoleInfo->ColsPerScreen * ConsoleInfo->RowsPerScreen * ConsoleInfo->ScreenCount * sizeof(ConsoleInfo->Attributes[0]);

  ConsoleInfo->Buffer = (CHAR16*)AllocateZeroPool(ConsoleInfo->BufferSize);

  if (ConsoleInfo->Buffer == NULL) {
    return (EFI_OUT_OF_RESOURCES);
  }

  ConsoleInfo->Attributes = (INT32*)AllocateZeroPool(ConsoleInfo->AttribSize);
  if (ConsoleInfo->Attributes == NULL) {
    FreePool(ConsoleInfo->Buffer);
    ConsoleInfo->Buffer     = NULL;
    return (EFI_OUT_OF_RESOURCES);
  }

  CopyMem (&ConsoleInfo->HistoryMode, ConsoleInfo->OldConOut->Mode, sizeof (EFI_SIMPLE_TEXT_OUTPUT_MODE));

  return (EFI_SUCCESS);
}


text:
/**
 * Implementation of the domain management.
 */
package org.onosproject.net.domain.impl;


text:
/**
 * Seed controller for fill your db of fake data
 */

import HTTPStatus from 'http-status';

import User from '../models/user.model';
import Post from '../models/post.model';
import { userSeed, deleteUserSeed } from '../seeds/user.seed';

export async function seedUsers(req, res, next) {
  try {
    await userSeed(req.params.count);

    return res
      .status(HTTPStatus.OK)
      .send(`User seed success! Created ${req.params.count || 10} users!`);
  } catch (e) {
    e.status = HTTPStatus.BAD_REQUEST;
    return next(e);
  }
}

export async function clearSeedUsers(req, res, next) {
  try {
    await deleteUserSeed();

    return res.status(HTTPStatus.OK).send('User collection empty');
  } catch (e) {
    e.status = HTTPStatus.BAD_REQUEST;
    return next(e);
  }
}

/**
 * Take all your model and clear it
 *
 * @param {any} req
 * @param {any} res
 * @param {any} next
 * @returns {String} All collections clear
 */
export async function clearAll(req, res, next) {
  try {
    await Promise.all([User.remove(), Post.remove()]);

    return res.status(HTTPStatus.OK).send('All collections clear');
  } catch (e) {
    e.status = HTTPStatus.BAD_REQUEST;
    return next(e);
  }
}


text:
require 'test/unit'

require 'yaml'
require 'base64'

require 'rufus/sqs'

class SqsTest < Test::Unit::TestCase

  #def setup
  #end

  #def teardown
  #end

  def test_usage

    qs = Rufus::SQS::QueueService.new

    qs.create_queue "mytestqueue"

    msg = "hello SQS world !"

    msg_id = qs.put_message "mytestqueue", msg

    sleep 1

    msgs = qs.get_messages "mytestqueue"

    assert_equal 1, msgs.size
    assert_equal msg, msgs[0].message_body

    qs.delete_queue "mytestqueue"
  end

  def test_0

    hash = {
      :red => :color,
      :count => "twelve",
      "fish" => "sakana",
      :llen => 4,
      :list => [ 0, 1, 2, 3, 4, :fizz ]
    }

    qs = Rufus::SQS::QueueService.new

    qs.create_queue(:yamltest)

    puts "created queue 'yamltest'"

    msg = YAML.dump(hash)
    msg = Base64.encode64(msg)

    puts "message size is #{msg.size.to_f / 1024.0} K"

    msg_id = qs.put_message(:yamltest, msg)

    puts "sent hash as message, msg_id is #{msg_id}"

    sleep 1

    msg = qs.get_message(:yamltest, msg_id)

    puts "got message back"

    msg = Base64.decode64(msg.message_body)
    msg = YAML.load(msg)

    pp msg

    assert_equal msg, hash

    count = qs.flush_queue(:yamltest)

    puts "flushed #{count} messages from queue 'yamltest'"

    qs.delete_queue(:yamltest)
  end
end


text:
package net.ncguy.argent.physics;

import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.Bullet;
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject;
import com.badlogic.gdx.physics.bullet.collision.btCollisionShape;
import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody;
import net.ncguy.argent.render.WorldRenderer;

/**
 * Created by Guy on 20/06/2016.
 */
public class PhysicsCore {

    public PhysicsCore() {
        Bullet.init();
    }

    public <T> void buildComplexCollisionMesh(WorldRenderer<T> renderer, T obj) {
        ModelInstance inst = renderer.getRenderable(obj);
        if(inst == null) return;

        btCollisionShape shape = Bullet.obtainStaticNodeShape(inst.model.nodes);
        if(shape != null)
            renderer.buildBulletCollision(obj, shape);
    }

    public <T> void buildComplexCollisionMeshes(WorldRenderer<T> renderer) {
        renderer.objects().forEach(o -> buildComplexCollisionMesh(renderer, o));
    }

    public btCollisionObject buildComplexCollisionMesh(ModelInstance inst) {
        btCollisionShape shape = Bullet.obtainStaticNodeShape(inst.model.nodes);
        if(shape != null) {
            btRigidBody.btRigidBodyConstructionInfo info = new btRigidBody.btRigidBodyConstructionInfo(0, null, shape, Vector3.Zero);
            btRigidBody body = new btRigidBody(info);
            info.dispose();
            return body;
        }
        return null;
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ServletResponse (Java Card API, Connected Edition)
</TITLE>

<META NAME="date" CONTENT="2009-12-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

javax.servlet

Interface ServletResponse

All Known Subinterfaces:
HttpServletResponse

All Known Implementing Classes:
HttpServletResponseWrapper, ServletResponseWrapper

@TransactionType(value=NOT_SUPPORTED)
public interface ServletResponse

Defines an object to assist a servlet in sending a response to the client.
 The servlet container creates a ServletResponse object and
 passes it as an argument to the servlet's service method.

 To send binary data in a MIME body response, use the
 ServletOutputStream returned by getOutputStream(). To send
 character data, use the PrintWriter object returned by
 getWriter(). To mix binary and text data, for example, to create a
 multipart response, use a ServletOutputStream and manage the
 character sections manually.

 The charset for the MIME body response can be specified explicitly using the
 setCharacterEncoding(java.lang.String) and setContentType(java.lang.String) methods, or
 implicitly using the setLocale(java.util.Locale) method. Explicit specifications take
 precedence over implicit specifications. If no charset is specified,
 ISO-8859-1 will be used. The setCharacterEncoding,
 setContentType, or setLocale method must be
 called before getWriter and before committing the response for
 the character encoding to be used.

 See the Internet RFCs such as
 RFC 2045 for more information on MIME. Protocols such as SMTP and HTTP
 define profiles of MIME, and those standards are still evolving.

Since:

Servlet 2.x, Java Card 3.0

See Also:
ServletOutputStream

Method Summary

 void
flushBuffer()

          Forces any content in the buffer to be written to the client.

 int
getBufferSize()

          Returns the actual buffer size used for the response.

 String
getCharacterEncoding()

          Returns the name of the character encoding (MIME charset) used for the
 body sent in this response.

 String
getContentType()

          Returns the content type used for the MIME body sent in this response.

 Locale
getLocale()

          Returns the locale specified for this response using the
 setLocale(java.util.Locale) method.

 ServletOutputStream
getOutputStream()

          Returns a ServletOutputStream suitable for writing binary data in
 the response.

 PrintWriter
getWriter()

          Returns a PrintWriter object that can send character text
 to the client.

 boolean
isCommitted()

          Returns a boolean indicating if the response has been committed.

 void
reset()

          Clears any data that exists in the buffer as well as the status code and
 headers.

 void
resetBuffer()

          Clears the content of the underlying buffer in the response without
 clearing headers or status code.

 void
setBufferSize(int size)

          Sets the preferred buffer size for the body of the response.

 void
setCharacterEncoding(String charset)

          Sets the character encoding (MIME charset) of the response being sent to
 the client, for example, to UTF-8.

 void
setContentLength(int len)

          Sets the length of the content body in the response In HTTP servlets,
 this method sets the HTTP Content-Length header.

 void
setContentType(String type)

          Sets the content type of the response being sent to the client, if the
 response has not been committed yet.

 void
setLocale(Locale loc)

          Sets the locale of the response, if the response has not been committed
 yet.

Method Detail

getCharacterEncoding

String getCharacterEncoding()

Returns the name of the character encoding (MIME charset) used for the
 body sent in this response. The character encoding may have been
 specified explicitly using the setCharacterEncoding(java.lang.String) or
 setContentType(java.lang.String) methods, or implicitly using the
 setLocale(java.util.Locale) method. Explicit specifications take precedence over
 implicit specifications. Calls made to these methods after
 getWriter has been called or after the response has been
 committed have no effect on the character encoding. If no character
 encoding has been specified, ISO-8859-1 is returned.

 See RFC 2047 (http://www.ietf.org/rfc/rfc2047.txt) for more information
 about character encoding and MIME.

Returns:
a String specifying the name of the character
         encoding, for example, UTF-8

getContentType

String getContentType()

Returns the content type used for the MIME body sent in this response.
 The content type proper must have been specified using
 setContentType(java.lang.String) before the response is committed. If no content
 type has been specified, this method returns null. If a content type has
 been specified and a character encoding has been explicitly or implicitly
 specified as described in getCharacterEncoding(), the charset
 parameter is included in the string returned. If no character encoding
 has been specified, the charset parameter is omitted.

Returns:
a String specifying the content type, for example,
         text/html; charset=UTF-8, or null
Since:

Servlet 2.4

getOutputStream

ServletOutputStream getOutputStream()
                                    throws IOException

Returns a ServletOutputStream suitable for writing binary data in
 the response. The servlet container does not encode the binary data.

 Calling flush() on the ServletOutputStream commits the response.

 Either this method or getWriter() may be called to write the body,
 not both.

Returns:
a ServletOutputStream for writing binary data

Throws:

IllegalStateException - if the getWriter method has been called on
                this response

IOException - if an input or output exception occurred
See Also:
getWriter()

getWriter

PrintWriter getWriter()
                      throws IOException

Returns a PrintWriter object that can send character text
 to the client. The PrintWriter uses the character encoding
 returned by getCharacterEncoding(). If the response's character
 encoding has not been specified as described in
 getCharacterEncoding (i.e., the method just returns the
 default value ISO-8859-1), getWriter
 updates it to ISO-8859-1.

 Calling flush() on the PrintWriter commits the response.

 Either this method or getOutputStream() may be called to write the
 body, not both.

Returns:
a PrintWriter object that can return character
         data to the client

Throws:

UnsupportedEncodingException - if the character encoding returned by
                getCharacterEncoding cannot be used

IllegalStateException - if the getOutputStream method has already
                been called for this response object

IOException - if an input or output exception occurred
See Also:
getOutputStream(),
setCharacterEncoding(java.lang.String)

setCharacterEncoding

void setCharacterEncoding(String charset)

Sets the character encoding (MIME charset) of the response being sent to
 the client, for example, to UTF-8. If the character encoding has already
 been set by setContentType(java.lang.String) or setLocale(java.util.Locale), this method
 overrides it. Calling setContentType(java.lang.String) with the
 String of text/html and calling this method
 with the String of UTF-8 is equivalent with
 calling setContentType with the String of
 text/html; charset=UTF-8.

 This method can be called repeatedly to change the character encoding.
 This method has no effect if it is called after getWriter
 has been called or after the response has been committed.

 Containers must communicate the character encoding used for the servlet
 response's writer to the client if the protocol provides a way for doing
 so. In the case of HTTP, the character encoding is communicated as part
 of the Content-Type header for text media types. Note that
 the character encoding cannot be communicated via HTTP headers if the
 servlet does not specify a content type; however, it is still used to
 encode text written via the servlet response's writer.

Parameters:
charset - a String specifying only the character set defined by IANA
            Character Sets
            (http://www.iana.org/assignments/character-sets)
Since:

Servlet 2.4

See Also:
#setLocale

setContentLength

void setContentLength(int len)

Sets the length of the content body in the response In HTTP servlets,
 this method sets the HTTP Content-Length header.

Parameters:
len - an integer specifying the length of the content being returned
            to the client; sets the Content-Length header

setContentType

void setContentType(String type)

Sets the content type of the response being sent to the client, if the
 response has not been committed yet. The given content type may include a
 character encoding specification, for example,
 text/html;charset=UTF-8. The response's character
 encoding is only set from the given content type if this method is called
 before getWriter is called.

 This method may be called repeatedly to change content type and character
 encoding. This method has no effect if called after the response has been
 committed. It does not set the response's character encoding if it is
 called after getWriter has been called or after the
 response has been committed.

 Containers must communicate the content type and the character encoding
 used for the servlet response's writer to the client if the protocol
 provides a way for doing so. In the case of HTTP, the
 Content-Type header is used.

Parameters:
type - a String specifying the MIME type of the
            content
See Also:
setLocale(java.util.Locale),
setCharacterEncoding(java.lang.String),
getOutputStream(),
getWriter()

setBufferSize

void setBufferSize(int size)

Sets the preferred buffer size for the body of the response. The servlet
 container will use a buffer at least as large as the size requested. The
 actual buffer size used can be found using getBufferSize.

 A larger buffer allows more content to be written before anything is
 actually sent, thus providing the servlet with more time to set
 appropriate status codes and headers. A smaller buffer decreases server
 memory load and allows the client to start receiving data more quickly.

 This method must be called before any response body content is written;
 if content has been written or the response object has been committed,
 this method throws an IllegalStateException.

Parameters:
size - the preferred buffer size

Throws:

IllegalStateException - if this method is called after content has been written

IllegalArgumentException - if size is greater than 0 and the container
                does not support response buffering.
Since:

Java Card 3.0

See Also:
getBufferSize(),
flushBuffer(),
isCommitted(),
reset()

getBufferSize

int getBufferSize()

Returns the actual buffer size used for the response. If no buffering is
 used, this method returns 0.

Returns:
the actual buffer size used
See Also:
setBufferSize(int),
flushBuffer(),
isCommitted(),
reset()

flushBuffer

void flushBuffer()
                 throws IOException

Forces any content in the buffer to be written to the client. A call to
 this method automatically commits the response, meaning the status code
 and headers will be written.

Throws:

IOException
See Also:
setBufferSize(int),
getBufferSize(),
isCommitted(),
reset()

resetBuffer

void resetBuffer()

Clears the content of the underlying buffer in the response without
 clearing headers or status code. If the response has been committed, this
 method throws an IllegalStateException.

Since:

Servlet 2.3

See Also:
setBufferSize(int),
getBufferSize(),
isCommitted(),
reset()

isCommitted

boolean isCommitted()

Returns a boolean indicating if the response has been committed. A
 committed response has already had its status code and headers written.

Returns:
a boolean indicating if the response has been committed
See Also:
setBufferSize(int),
getBufferSize(),
flushBuffer(),
reset()

reset

void reset()

Clears any data that exists in the buffer as well as the status code and
 headers. If the response has been committed, this method throws an
 IllegalStateException.

Throws:

IllegalStateException - if the response has already been committed
See Also:
setBufferSize(int),
getBufferSize(),
flushBuffer(),
isCommitted()

setLocale

void setLocale(Locale loc)

Sets the locale of the response, if the response has not been committed
 yet. It also sets the response's character encoding appropriately for the
 locale, if the character encoding has not been explicitly set using
 setContentType(java.lang.String) or setCharacterEncoding(java.lang.String),
 getWriter hasn't been called yet, and the response hasn't
 been committed yet. If the deployment descriptor contains a
 locale-encoding-mapping-list element, and that element
 provides a mapping for the given locale, that mapping is used. Otherwise,
 the mapping from locale to character encoding is container dependent.

 This method may be called repeatedly to change locale and character
 encoding. The method has no effect if called after the response has been
 committed. It does not set the response's character encoding if it is
 called after setContentType(java.lang.String) has been called with a charset
 specification, after setCharacterEncoding(java.lang.String) has been called, after
 getWriter has been called, or after the response has been
 committed.

 Containers must communicate the locale and the character encoding used
 for the servlet response's writer to the client if the protocol provides
 a way for doing so. In the case of HTTP, the locale is communicated via
 the Content-Language header, the character encoding as
 part of the Content-Type header for text media types. Note
 that the character encoding cannot be communicated via HTTP headers if
 the servlet does not specify a content type; however, it is still used to
 encode text written via the servlet response's writer.

Parameters:
loc - the locale of the response
See Also:
getLocale(),
setContentType(java.lang.String),
setCharacterEncoding(java.lang.String)

getLocale

Locale getLocale()

Returns the locale specified for this response using the
 setLocale(java.util.Locale) method. Calls made to setLocale after
 the response is committed have no effect. If no locale has been
 specified, the container's default locale is returned.

See Also:
setLocale(java.util.Locale)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (c) 2009 Sun Microsystems, Inc. All rights reserved.


text:
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper'))
require 'mail'
require 'jpmobile/mail'

describe "Jpmobile::Mail#receive" do
  include Jpmobile::Util

  before(:each) do
    @to = "info@jpmobile-rails.org"
    Jpmobile::Email.japanese_mail_address_regexp = Regexp.new(/\.jp[^a-zA-Z\.\-]/)
  end

  describe "PC mail" do
    before(:each) do
      @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "email-fixtures/pc-mail-single.eml")).read)
    end

    it "subject should be parsed correctly" do
      @mail.subject.should == "タイトルの長いメールの場合の対処を実装するためのテストケースとしてのメールに含まれている件名であるサブジェクト部分"
    end

    it "body should be parsed correctly" do
      @mail.body.to_s.should == "本文です"
    end

    context "to_s" do
      it "should have subject which is same as original" do
        ascii_8bit(@mail.to_s).should match("GyRCJT8lJCVIJWskTkQ5JCQlYSE8JWskTj5s")
      end

      it "should have body which is same as original" do
        ascii_8bit(@mail.to_s).should match(Regexp.compile(Regexp.escape(ascii_8bit(utf8_to_jis("本文です")))))
      end
    end

    context "modify and to_s" do
      it "should encode subject correctly" do
        @mail.subject = "大江戸"
        ascii_8bit(@mail.to_s).should match("GyRCQmc5PjhNGyhC")
      end

      it "should encode body correctly" do
        @mail.body = "会議が開催"
        ascii_8bit(@mail.to_s).should match(Regexp.compile(Regexp.escape(ascii_8bit(utf8_to_jis("会議が開催")))))
      end
    end
  end

  describe "multipart" do
    describe "PC mail" do
      before(:each) do
        @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "email-fixtures/pc-mail-multi.eml")).read)
      end

      it "subject should be parsed correctly" do
        @mail.subject.should == "タイトルの長いメールの場合の対処を実装するためのテストケースとしてのメールに含まれている件名であるサブジェクト部分"
      end

      it "body should be parsed correctly" do
        @mail.body.parts.size.should == 2
        @mail.body.parts.first.body.to_s.should == "本文です"
      end

      it "should encode correctly" do
        ascii_8bit(@mail.to_s).should match(/GyRCJT8lJCVIJWskTkQ5JCQlYSE8JWskTj5s/)
      end
    end

    describe "Docomo" do
      before(:each) do
        @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "../../test/rails/overrides/spec/fixtures/mobile_mailer/docomo-gmail-sjis.eml")).read)
      end

      it "subject should be parsed correctly" do
        @mail.subject.should == "テスト"
      end

      it "body should be parsed correctly" do
        @mail.body.parts.size.should == 1
        @mail.body.parts.first.parts.size == 2
        @mail.body.parts.first.parts.first.body.should match("テストです")
        @mail.body.parts.first.parts.last.body.raw_source.should match("テストです")
      end

      it "should encode correctly" do
        @mail.to_s.should match(Regexp.escape("g2WDWINn+ZE"))
      end
    end

    describe "Au" do
      before(:each) do
        @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "../../test/rails/overrides/spec/fixtures/mobile_mailer/au-decomail.eml")).read)
      end

      it "subject should be parsed correctly" do
        @mail.subject.should == "テスト"
      end

      it "body should be parsed correctly" do
        @mail.body.parts.size.should == 1
        @mail.body.parts.first.parts.size == 1
        @mail.body.parts.first.parts.first.body.to_s.should match("テストです")
        @mail.body.parts.first.parts.last.body.raw_source.should match("テストです")
      end

      it "should encode correctly" do
        ascii_8bit(@mail.to_s).should match(Regexp.escape("GyRCJUYlOSVIdk8bKEI="))
      end
    end

    describe "Softbank" do
      context "Shift_JIS" do
        before(:each) do
          @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "../../test/rails/overrides/spec/fixtures/mobile_mailer/softbank-gmail-sjis.eml")).read)
        end

        it "subject should be parsed correctly" do
          @mail.subject.should == "テスト"
        end

        it "body should be parsed correctly" do
          @mail.body.parts.size.should == 2
          @mail.body.parts.first.body.to_s.should == "テストです"
        end

        it "should encode correctly" do
          @mail.to_s.should match(Regexp.escape("g2WDWINn98H3w/fB"))
        end
      end

      context "UTF-8" do
        before(:each) do
          @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "../../test/rails/overrides/spec/fixtures/mobile_mailer/softbank-gmail-utf8.eml")).read)
        end

        it "subject should be parsed correctly" do
          @mail.subject.should == "テストです"
        end

        it "body should be parsed correctly" do
          @mail.body.parts.size.should == 2
          @mail.body.parts.first.body.raw_source.should == "テストです"
        end

        it "should encode correctly to Shift_JIS" do
          @mail.to_s.should match(Regexp.escape("g2WDWINngsWCt/fB"))
        end
      end
    end
  end

  describe "Docomo" do
    before(:each) do
      @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "email-fixtures/docomo-emoji.eml")).read)
    end

    it "subject should be parsed correctly" do
      @mail.subject.should == "題名"
    end

    it "body should be parsed correctly" do
      @mail.body.to_s.should == "本文\nFor docomo"
    end

    context "to_s" do
      it "should have subject which is same as original" do
        @mail.to_s.should match(Regexp.escape("keiWvPjX"))
      end

      it "should have body which is same as original" do
        @mail.to_s.should match(sjis_regexp(utf8_to_sjis("本文")))
      end
    end

    context "modify and to_s" do
      it "should encode subject correctly" do
        @mail.subject = "大江戸"
        @mail.to_s.should match(Regexp.escape("keWNXYzL+J8="))
      end

      it "should encode body correctly" do
        @mail.body = "会議が開催"
        @mail.to_s.should match(sjis_regexp(sjis("\x89\xEF\x8Bc\x82\xAA\x8AJ\x8D\xC3\xF8\xA7")))
      end
    end
  end

  describe "Au" do
    before(:each) do
      @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "email-fixtures/au-emoji.eml")).read)
    end

    it "subject should be parsed correctly" do
      @mail.subject.should == "題名"
    end

    it "body should be parsed correctly" do
      @mail.body.to_s.should == "本文\nFor au"
    end

    context "to_s" do
      it "should have subject which is same as original" do
        ascii_8bit(@mail.to_s).should match(Regexp.escape("GyRCQmpMPnZeGyhC"))
      end

      it "should have body which is same as original" do
        ascii_8bit(@mail.to_s).should match(Regexp.compile(Regexp.escape(ascii_8bit("\e\x24\x42\x4B\x5C\x4A\x38\x76\x7D\e\x28\x42"))))
      end
    end

    context "modify and to_s" do
      it "should encode subject correctly" do
        @mail.subject = "大江戸"
        ascii_8bit(@mail.to_s).should match(/\?GyRCQmc5PjhNdUEbKEI=/)
      end

      it "should encode body correctly" do
        @mail.body = "会議が開催"
        ascii_8bit(@mail.to_s).should match(Regexp.compile(Regexp.escape(ascii_8bit("\x1b\x24\x42\x32\x71\x35\x44\x24\x2C\x33\x2B\x3A\x45\x75\x48\x1b\x28\x42"))))
      end
    end
  end

  describe "Softbank" do
    before(:each) do
      @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "email-fixtures/softbank-emoji.eml")).read)
    end

    it "subject should be parsed correctly" do
      @mail.subject.should == "題名"
    end

    it "body should be parsed correctly" do
      @mail.body.to_s.should == "本文\nFor softbank"
    end

    context "to_s" do
      it "should have subject which is same as original" do
        @mail.to_s.should match(sjis_regexp("keiWvPl8"))
      end

      it "should have body which is same as original" do
        @mail.to_s.should match(sjis_regexp(utf8_to_sjis("本文")))
      end
    end

    context "modify and to_s" do
      it "should encode subject correctly" do
        @mail.subject = "大江戸"
        @mail.to_s.should match(Regexp.escape("keWNXYzL+Ys="))
      end

      it "should encode body correctly" do
        @mail.body = "会議が開催"
        @mail.to_s.should match(sjis_regexp(utf8_to_sjis("会議が開催") + sjis("\xf7\xdf")))
      end
    end
  end

  describe "Softbank blank-mail" do
    before(:each) do
      @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "email-fixtures/softbank-blank.eml")).read)
    end

    it "subject should be parsed correctly" do
      @mail.subject.should be_blank
    end

    it "body should be parsed correctly" do
      @mail.body.to_s.should be_blank
    end
  end

  describe "JIS mail" do
    context "Docomo" do
      before(:each) do
        @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "email-fixtures/docomo-jis.eml")).read)
      end

      it "subject should be parsed correctly" do
        @mail.subject.should == "テスト"
      end

      it "body should be parsed correctly" do
        @mail.body.to_s.should == "テスト本文"
      end
    end
  end

  describe "non-Japanese mail" do
    context "us-ascii" do
      before(:each) do
        @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "../../test/rails/overrides/spec/fixtures/mobile_mailer/non-jp.eml")).read)
      end

      it "mobile should be nil" do
        @mail.mobile.should be_nil
        @mail.parts.first.charset.should == 'us-ascii'
      end
    end

    context "no From header" do
      before(:each) do
        @mail = Mail.new(open(File.join(File.expand_path(File.dirname(__FILE__)), "../../test/rails/overrides/spec/fixtures/mobile_mailer/no-from.eml")).read)
      end

      it "mobile should be nil" do
        @mail.mobile.should be_nil
        @mail.parts.first.charset.should == 'iso-8859-1'
      end
    end
  end
end


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

package com.google.api.ads.adwords.jaxws;

import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.google.api.ads.adwords.lib.client.AdWordsServiceDescriptor;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.conf.AdWordsApiConfiguration;
import com.google.api.ads.common.lib.soap.jaxws.JaxWsHandler;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.verification.VerificationMode;

import javax.xml.ws.BindingProvider;

/**
 * Tests for {@link AdWordsJaxWsExpressHeaderHandler}.
 *
 * @author Josh Radcliff (jradcliff@google.com)
 */
@RunWith(JUnit4.class)
public class AdWordsJaxWsExpressHeaderHandlerTest {

  private AdWordsJaxWsExpressHeaderHandler expressHandler;

  @Mock
  private AdWordsApiConfiguration apiConfiguration;
  @Mock
  private JaxWsHandler jaxHandler;
  @Mock
  private AdWordsSession adWordsSession;
  @Mock
  private AdWordsServiceDescriptor adWordsServiceDescriptor;
  @Mock
  private BindingProvider bindingProvider;

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    expressHandler = new AdWordsJaxWsExpressHeaderHandler(jaxHandler, apiConfiguration);
  }

  /**
   * Tests setHeaders when business ID is not null on the session.
   */
  @Test
  public void testSetHeaders_withBusinessId() throws Exception {
    testSetHeaders(123456789L, times(1), null, never());
  }

  /**
   * Tests setHeaders when business ID and plus page ID are both null on the session.
   */
  @Test
  public void testSetHeaders_withoutBusinessId_withoutPlusPageId() throws Exception {
    testSetHeaders(null, never(), null, never());
  }

  /**
   * Tests setHeaders when plus page ID is not null on the session.
   */
  @Test
  public void testSetHeaders_withPlusPageId() throws Exception {
    testSetHeaders(null, never(), "ABCDE", times(1));
  }

  /**
   * Tests setHeaders when business ID and plus page ID are both not null on the session.
   */
  @Test
  public void testSetHeaders_withBusinessId_withPlusPageId_fails() throws Exception {
    thrown.expect(IllegalArgumentException.class);
    testSetHeaders(123456789L, never(), "ABCDE", never());
  }

  /**
   * Tests setHeaders using the provided businessId and plusPageId. Will verify that setHeaderChild
   * was (or was not) invoked for each header according to its corresponding verification mode.
   */
  private void testSetHeaders(Long businessId,
      VerificationMode setBusinessIdHeaderChildVerificationMode, String plusPageId,
      VerificationMode setPageIdHeaderChildVerificationMode)
      throws Exception {
    when(adWordsSession.getExpressBusinessId()).thenReturn(businessId);
    when(adWordsSession.getExpressPlusPageId()).thenReturn(plusPageId);

    String version = "v201406";
    String namespacePrefix = "http://www.example.com";

    when(adWordsServiceDescriptor.getVersion()).thenReturn(version);
    when(apiConfiguration.getNamespacePrefix()).thenReturn(namespacePrefix);

    String expectedNamespace = "http://www.example.com/express/v201406";

    expressHandler.setHeaders(bindingProvider, adWordsSession, adWordsServiceDescriptor);

    verify(jaxHandler, setBusinessIdHeaderChildVerificationMode).setHeaderChildString(
        bindingProvider, AdWordsJaxWsHeaderHandler.REQUEST_HEADER_LOCAL_PART, expectedNamespace,
        AdWordsJaxWsExpressHeaderHandler.EXPRESS_BUSINESS_ID_LOCAL_PART,
        businessId == null ? null : businessId.toString());
    verify(jaxHandler, setPageIdHeaderChildVerificationMode).setHeaderChildString(bindingProvider,
        AdWordsJaxWsHeaderHandler.REQUEST_HEADER_LOCAL_PART, expectedNamespace,
        AdWordsJaxWsExpressHeaderHandler.PLUS_PAGE_ID_LOCAL_PART,
        plusPageId == null ? null : plusPageId);
  }

}