text:
#include "WidgetReader.h"
#include "cocostudio/CocoLoader.h"
#include "ui/UIButton.h"
#include "cocostudio/CSParseBinary.pb.h"
#include "tinyxml2/tinyxml2.h"
#include "../ActionTimeline/CCActionTimeline.h"

USING_NS_CC;
using namespace ui;

namespace cocostudio
{

    const char* P_IgnoreSize = "ignoreSize";
    const char* P_SizeType = "sizeType";
    const char* P_PositionType = "positionType";
    const char* P_SizePercentX = "sizePercentX";
    const char* P_SizePercentY = "sizePercentY";
    const char* P_PositionPercentX = "positionPercentX";
    const char* P_PositionPercentY = "positionPercentY";
    const char* P_AdaptScreen = "adaptScreen";
    const char* P_Width = "width";
    const char* P_Height = "height";
    const char* P_Tag = "tag";
    const char* P_ActionTag = "actiontag";
    const char* P_TouchAble = "touchAble";
    const char* P_Name = "name";
    const char* P_X = "x";
    const char* P_Y = "y";
    const char* P_ScaleX = "scaleX";
    const char* P_ScaleY = "scaleY";
    const char* P_Rotation = "rotation";
    const char* P_Visbile = "visible";
    const char* P_ZOrder = "ZOrder";
    const char* P_LayoutParameter = "layoutParameter";
    const char* P_Type = "type";
    const char* P_Gravity = "gravity";
    const char* P_RelativeName = "relativeName";
    const char* P_RelativeToName = "relativeToName";
    const char* P_Align = "align";
    const char* P_MarginLeft = "marginLeft";
    const char* P_MarginRight = "marginRight";
    const char* P_MarginTop = "marginTop";
    const char* P_MarginDown = "marginDown";

    const char* P_Opacity = "opacity";
    const char* P_ColorR = "colorR";
    const char* P_ColorG = "colorG";
    const char* P_ColorB = "colorB";
    const char* P_FlipX = "flipX";
    const char* P_FlipY = "flipY";
    const char* P_AnchorPointX = "anchorPointX";
    const char* P_AnchorPointY = "anchorPointY";

    const char* P_ResourceType = "resourceType";
    const char* P_Path = "path";

    static WidgetReader* instanceWidgetReader = nullptr;

    IMPLEMENT_CLASS_WIDGET_READER_INFO(WidgetReader)

    WidgetReader::WidgetReader()
    :_sizePercentX(0.0f),
    _sizePercentY(0.0f),
    _isAdaptScreen(false),
    _width(0.0f),
    _height(0.0f),
    _positionPercentX(0.0f),
    _positionPercentY(0.0f),
    _opacity(255)
    {
        valueToInt = [=](const std::string& str) -> int{
            return atoi(str.c_str());
        };

        valueToBool = [=](const std::string& str) -> bool{
            int intValue = valueToInt(str);
            if (1 == intValue) {
                return true;
            }else{
                return false;
            }
        };

        valueToFloat = [=](const std::string& str) -> float{
            return utils::atof(str.c_str());
        };
    }

    WidgetReader::~WidgetReader()

    {

    }

    WidgetReader* WidgetReader::getInstance()
    {
        if (!instanceWidgetReader)
        {
            instanceWidgetReader = new (std::nothrow) WidgetReader();
        }
        return instanceWidgetReader;
    }

    void WidgetReader::purge()
    {
        CC_SAFE_DELETE(instanceWidgetReader);
    }

    void WidgetReader::setPropsFromJsonDictionary(Widget *widget, const rapidjson::Value &options)
    {

        bool ignoreSizeExsit = DICTOOL->checkObjectExist_json(options, P_IgnoreSize);
        if (ignoreSizeExsit) {
            widget->ignoreContentAdaptWithSize(DICTOOL->getBooleanValue_json(options, P_IgnoreSize));
        }

        widget->setSizeType((Widget::SizeType)DICTOOL->getIntValue_json(options, P_SizeType));
        widget->setPositionType((Widget::PositionType)DICTOOL->getIntValue_json(options, P_PositionType));

        widget->setSizePercent(Vec2(DICTOOL->getFloatValue_json(options, P_SizePercentX), DICTOOL->getFloatValue_json(options, P_SizePercentY)));
        widget->setPositionPercent(Vec2(DICTOOL->getFloatValue_json(options, P_PositionPercentX), DICTOOL->getFloatValue_json(options, P_PositionPercentY)));

        /* adapt screen */
        float w = 0, h = 0;
        bool adaptScrenn = DICTOOL->getBooleanValue_json(options, P_AdaptScreen);
        if (adaptScrenn)
        {
            Size screenSize = CCDirector::getInstance()->getWinSize();
            w = screenSize.width;
            h = screenSize.height;
        }
        else
        {
            w = DICTOOL->getFloatValue_json(options, P_Width);
            h = DICTOOL->getFloatValue_json(options, P_Height);
        }
        widget->setContentSize(Size(w, h));

        widget->setTag(DICTOOL->getIntValue_json(options, P_Tag));
        widget->setActionTag(DICTOOL->getIntValue_json(options, P_ActionTag));
        widget->setTouchEnabled(DICTOOL->getBooleanValue_json(options, P_TouchAble));
        const char* name = DICTOOL->getStringValue_json(options, P_Name);
        const char* widgetName = name?name:"default";
        widget->setName(widgetName);

        float x = DICTOOL->getFloatValue_json(options, P_X);
        float y = DICTOOL->getFloatValue_json(options, P_Y);
        widget->setPosition(Vec2(x,y));

        widget->setScaleX(DICTOOL->getFloatValue_json(options, P_ScaleX,1.0));

        widget->setScaleY(DICTOOL->getFloatValue_json(options, P_ScaleY,1.0));

        widget->setRotation(DICTOOL->getFloatValue_json(options, P_Rotation,0));

        bool vb = DICTOOL->checkObjectExist_json(options, P_Visbile);
        if (vb)
        {
            widget->setVisible(DICTOOL->getBooleanValue_json(options, P_Visbile));
        }
        int z = DICTOOL->getIntValue_json(options, P_ZOrder);
        widget->setLocalZOrder(z);

        bool layout = DICTOOL->checkObjectExist_json(options, P_LayoutParameter);
        if (layout)
        {
            const rapidjson::Value& layoutParameterDic = DICTOOL->getSubDictionary_json(options, P_LayoutParameter);
            int paramType = DICTOOL->getIntValue_json(layoutParameterDic, P_Type);
            LayoutParameter* parameter = nullptr;
            switch (paramType)
            {
                case 0:
                    break;
                case 1:
                {
                    parameter = LinearLayoutParameter::create();
                    int gravity = DICTOOL->getIntValue_json(layoutParameterDic, P_Gravity);
                    ((LinearLayoutParameter*)parameter)->setGravity((cocos2d::ui::LinearLayoutParameter::LinearGravity)gravity);
                    break;
                }
                case 2:
                {
                    parameter = RelativeLayoutParameter::create();
                    RelativeLayoutParameter* rParameter = (RelativeLayoutParameter*)parameter;
                    const char* relativeName = DICTOOL->getStringValue_json(layoutParameterDic, P_RelativeName);
                    rParameter->setRelativeName(relativeName);
                    const char* relativeToName = DICTOOL->getStringValue_json(layoutParameterDic, P_RelativeToName);
                    rParameter->setRelativeToWidgetName(relativeToName);
                    int align = DICTOOL->getIntValue_json(layoutParameterDic, P_Align);
                    rParameter->setAlign((cocos2d::ui::RelativeLayoutParameter::RelativeAlign)align);
                    break;
                }
                default:
                    break;
            }
            if (parameter)
            {
                float mgl = DICTOOL->getFloatValue_json(layoutParameterDic, P_MarginLeft);
                float mgt = DICTOOL->getFloatValue_json(layoutParameterDic, P_MarginTop);
                float mgr = DICTOOL->getFloatValue_json(layoutParameterDic, P_MarginRight);
                float mgb = DICTOOL->getFloatValue_json(layoutParameterDic, P_MarginDown);
                parameter->setMargin(Margin(mgl, mgt, mgr, mgb));
                widget->setLayoutParameter(parameter);
            }
        }
    }

    void WidgetReader::setColorPropsFromJsonDictionary(Widget *widget, const rapidjson::Value &options)
    {
        bool op = DICTOOL->checkObjectExist_json(options, P_Opacity);
        if (op)
        {
            widget->setOpacity(DICTOOL->getIntValue_json(options, P_Opacity));
        }
        bool cr = DICTOOL->checkObjectExist_json(options, P_ColorR);
        bool cg = DICTOOL->checkObjectExist_json(options, P_ColorG);
        bool cb = DICTOOL->checkObjectExist_json(options, P_ColorB);
        int colorR = cr ? DICTOOL->getIntValue_json(options, P_ColorR) : 255;
        int colorG = cg ? DICTOOL->getIntValue_json(options, P_ColorG) : 255;
        int colorB = cb ? DICTOOL->getIntValue_json(options, P_ColorB) : 255;
        widget->setColor(Color3B(colorR, colorG, colorB));

        this->setAnchorPointForWidget(widget, options);

        bool flipX = DICTOOL->getBooleanValue_json(options, P_FlipX);
        bool flipY = DICTOOL->getBooleanValue_json(options, P_FlipY);
        widget->setFlippedX(flipX);
        widget->setFlippedY(flipY);
    }

    void WidgetReader::beginSetBasicProperties(cocos2d::ui::Widget *widget)
    {
        _position = widget->getPosition();
        //set default color
        _color = Color3B(255,255,255);
        widget->setColor(_color);
        _opacity = widget->getOpacity();
        _originalAnchorPoint = widget->getAnchorPoint();
    }

    void WidgetReader::endSetBasicProperties(Widget *widget)
    {
        Size screenSize = Director::getInstance()->getWinSize();

        widget->setPositionPercent(Vec2(_positionPercentX, _positionPercentY));
        widget->setSizePercent(Vec2(_sizePercentX, _sizePercentY));
        if (_isAdaptScreen) {
            _width = screenSize.width;
            _height = screenSize.height;
        }
        widget->setColor(_color);
        widget->setOpacity(_opacity);
        //the setSize method will be conflict with scale9Width & scale9Height
        if (!widget->isIgnoreContentAdaptWithSize()) {
            widget->setContentSize(Size(_width, _height));
        }
        widget->setPosition(_position);
        widget->setAnchorPoint(_originalAnchorPoint);
    }

    std::string WidgetReader::getResourcePath(const rapidjson::Value &dict,
                                              const std::string &key,
                                              cocos2d::ui::Widget::TextureResType texType)
    {
        std::string jsonPath = GUIReader::getInstance()->getFilePath();
        const char* imageFileName = DICTOOL->getStringValue_json(dict, key.c_str());
        std::string imageFileName_tp;
        if (nullptr != imageFileName)
        {
            if (texType == ui::Widget::TextureResType::LOCAL) {
                imageFileName_tp = jsonPath + imageFileName;
            }
            else if(texType == ui::Widget::TextureResType::PLIST){
                imageFileName_tp = imageFileName;
            }
            else{
                CCASSERT(0, "invalid TextureResType!!!");
            }
        }
        return imageFileName_tp;
    }

    std::string WidgetReader::getResourcePath(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, cocos2d::ui::Widget::TextureResType texType)
    {
        stExpCocoNode *backGroundChildren = cocoNode->GetChildArray(cocoLoader);
        std::string backgroundValue = backGroundChildren[0].GetValue(cocoLoader);

        if (backgroundValue.size() < 3) {
            return "";
        }

        std::string binaryPath = GUIReader::getInstance()->getFilePath();

        std::string imageFileName_tp;
        if (!backgroundValue.empty())
        {
            if (texType == ui::Widget::TextureResType::LOCAL) {
                imageFileName_tp = binaryPath + backgroundValue;
            }
            else if(texType == ui::Widget::TextureResType::PLIST){
                imageFileName_tp = backgroundValue;
            }
            else{
                CCASSERT(0, "invalid TextureResType!!!");
            }
        }
        return imageFileName_tp;
    }

    void WidgetReader::setAnchorPointForWidget(cocos2d::ui::Widget *widget, const rapidjson::Value &options)
    {
        bool isAnchorPointXExists = DICTOOL->checkObjectExist_json(options, P_AnchorPointX);
        float anchorPointXInFile;
        if (isAnchorPointXExists) {
            anchorPointXInFile = DICTOOL->getFloatValue_json(options, P_AnchorPointX);
        }else{
            anchorPointXInFile = widget->getAnchorPoint().x;
        }

        bool isAnchorPointYExists = DICTOOL->checkObjectExist_json(options, P_AnchorPointY);
        float anchorPointYInFile;
        if (isAnchorPointYExists) {
            anchorPointYInFile = DICTOOL->getFloatValue_json(options, P_AnchorPointY);
        }
        else{
            anchorPointYInFile = widget->getAnchorPoint().y;
        }

        if (isAnchorPointXExists || isAnchorPointYExists) {
            widget->setAnchorPoint(Vec2(anchorPointXInFile, anchorPointYInFile));
        }
    }

    void WidgetReader::setPropsFromBinary(cocos2d::ui::Widget *widget, cocostudio::CocoLoader *cocoLoader, cocostudio::stExpCocoNode *cocoNode)
    {
        stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);

        this->beginSetBasicProperties(widget);

        for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
            std::string key = stChildArray[i].GetName(cocoLoader);
            std::string value = stChildArray[i].GetValue(cocoLoader);

            CC_BASIC_PROPERTY_BINARY_READER
        }

        this->endSetBasicProperties(widget);
    }

    void WidgetReader::setPropsFromProtocolBuffers(ui::Widget *widget, const protocolbuffers::NodeTree &nodeTree)
    {

        const protocolbuffers::WidgetOptions& options = nodeTree.widgetoptions();

        widget->setCascadeColorEnabled(true);
        widget->setCascadeOpacityEnabled(true);
        widget->setAnchorPoint(Vec2::ZERO);

        widget->setUnifySizeEnabled(true);

        bool ignoreSizeExsit = options.has_ignoresize();
        if (ignoreSizeExsit)
        {
            widget->ignoreContentAdaptWithSize(options.ignoresize());
        }

        widget->setSizeType((Widget::SizeType)options.sizetype());
        widget->setPositionType((Widget::PositionType)options.positiontype());

        widget->setSizePercent(Vec2(options.sizepercentx(), options.sizepercenty()));
        widget->setPositionPercent(Vec2(options.positionpercentx(), options.positionpercenty()));

        float w = options.width();
        float h = options.height();
        widget->setContentSize(Size(w, h));

        widget->setTag(options.tag());
        widget->setActionTag(options.actiontag());
        widget->setTouchEnabled(options.touchable());
        const char* name = options.name().c_str();
        const char* widgetName = name ? name : "default";
        widget->setName(widgetName);

        float x = options.x();
        float y = options.y();
        widget->setPosition(Vec2(x, y));

		if(options.has_alpha())
		{
			widget->setOpacity(options.alpha());
		}

        widget->setScaleX(options.has_scalex() ? options.scalex() : 1.0);

        widget->setScaleY(options.has_scaley() ? options.scaley() : 1.0);

		widget->setRotationSkewX(options.has_rotationskewx() ? options.rotationskewx() : 0.0);

		widget->setRotationSkewY(options.has_rotationskewy() ? options.rotationskewy() : 0.0);

        bool vb = options.has_visible();
        if (vb)
        {
            widget->setVisible(options.visible());
        }

        int z = options.zorder();
        widget->setLocalZOrder(z);

        bool layout = options.has_layoutparameter();
        if (layout)
        {

            const protocolbuffers::LayoutParameter& layoutParameterDic = options.layoutparameter();;
            int paramType = layoutParameterDic.type();

            LayoutParameter* parameter = nullptr;
            switch (paramType)
            {
                case 0:
                    break;
                case 1:
                {
                    parameter = LinearLayoutParameter::create();
                    int gravity = layoutParameterDic.gravity();
                    ((LinearLayoutParameter*)parameter)->setGravity((cocos2d::ui::LinearLayoutParameter::LinearGravity)gravity);
                    break;
                }
                case 2:
                {
                    parameter = RelativeLayoutParameter::create();
                    RelativeLayoutParameter* rParameter = (RelativeLayoutParameter*)parameter;
                    const char* relativeName = layoutParameterDic.relativename().c_str();
                    rParameter->setRelativeName(relativeName);
                    const char* relativeToName = layoutParameterDic.relativetoname().c_str();
                    rParameter->setRelativeToWidgetName(relativeToName);
                    int align = layoutParameterDic.align();
                    rParameter->setAlign((cocos2d::ui::RelativeLayoutParameter::RelativeAlign)align);
                    break;
                }
                default:
                    break;
            }
            if (parameter)
            {
                float mgl = layoutParameterDic.marginleft();
                float mgt = layoutParameterDic.margintop();
                float mgr = layoutParameterDic.marginright();
                float mgb = layoutParameterDic.margindown();
                parameter->setMargin(Margin(mgl, mgt, mgr, mgb));
                widget->setLayoutParameter(parameter);
            }
        }

    }

    void WidgetReader::setColorPropsFromProtocolBuffers(cocos2d::ui::Widget *widget, const protocolbuffers::NodeTree &nodeTree)
    {
        const protocolbuffers::WidgetOptions& options = nodeTree.widgetoptions();

        bool isColorRExists = options.has_colorr();
        bool isColorGExists = options.has_colorg();
        bool isColorBExists = options.has_colorb();

        int colorR = options.colorr();
        int colorG = options.colorg();
        int colorB = options.colorb();

        if (isColorRExists && isColorGExists && isColorBExists)
        {
            widget->setColor(Color3B(colorR, colorG, colorB));
        }

        setAnchorPointForWidget(widget, nodeTree);

        bool flipX = options.flipx();
        bool flipY = options.flipy();
        if (flipX)
        {
            widget->setFlippedX(flipX);
        }
        if (flipY)
        {
            widget->setFlippedY(flipY);
        }
    }

    void WidgetReader::setPropsFromXML(cocos2d::ui::Widget *widget, const tinyxml2::XMLElement *objectData)
    {
        widget->setTouchEnabled(false);

        widget->setCascadeColorEnabled(true);
        widget->setCascadeOpacityEnabled(true);

        widget->setUnifySizeEnabled(true);

        widget->setScale(0.0f, 0.0f);

        // attributes
        const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute();
        while (attribute)
        {
            std::string name = attribute->Name();
            std::string value = attribute->Value();

            if (name == "Name")
            {
                const char* widgetName = value.c_str() ? value.c_str() :"default";
                widget->setName(widgetName);
            }
            else if (name == "ActionTag")
            {
                int actionTag = atoi(value.c_str());
                widget->setUserObject(timeline::ActionTimelineData::create(actionTag));
            }
            else if (name == "RotationSkewX")
            {
                widget->setRotationSkewX(atof(value.c_str()));
            }
            else if (name == "RotationSkewY")
            {
                widget->setRotationSkewY(atof(value.c_str()));
            }
            else if (name == "ZOrder")
            {
                widget->setLocalZOrder(atoi(value.c_str()));
            }
            else if (name == "VisibleForFrame")
            {
                widget->setVisible((value == "True") ? true : false);
            }
            else if (name == "Alpha")
            {
                widget->setOpacity(atoi(value.c_str()));
            }
            else if (name == "Tag")
            {
                widget->setTag(atoi(value.c_str()));
            }
            else if (name == "FlipX")
            {
                widget->setFlippedX((value == "True") ? true : false);
            }
            else if (name == "FlipY")
            {
                widget->setFlippedY((value == "True") ? true : false);
            }
            else if (name == "TouchEnable")
            {
                widget->setTouchEnabled((value == "True") ? true : false);
            }
            else if (name == "ControlSizeType")
            {
                widget->ignoreContentAdaptWithSize((value == "Auto") ? true : false);
            }

            attribute = attribute->Next();
        }

        const tinyxml2::XMLElement* child = objectData->FirstChildElement();
        while (child)
        {
            std::string name = child->Name();
            if (name == "Children")
            {
                break;
            }
            else if (name == "Position")
            {
                attribute = child->FirstAttribute();

                while (attribute)
                {
                    name = attribute->Name();
                    std::string value = attribute->Value();

                    if (name == "X")
                    {
                        widget->setPositionX(atof(value.c_str()));
                    }
                    else if (name == "Y")
                    {
                        widget->setPositionY(atof(value.c_str()));
                    }

                    attribute = attribute->Next();
                }
            }
            else if (name == "Scale")
            {
                attribute = child->FirstAttribute();

                while (attribute)
                {
                    name = attribute->Name();
                    std::string value = attribute->Value();

                    if (name == "ScaleX")
                    {
                        widget->setScaleX(atof(value.c_str()));
                    }
                    else if (name == "ScaleY")
                    {
                        widget->setScaleY(atof(value.c_str()));
                    }

                    attribute = attribute->Next();
                }
            }
            else if (name == "AnchorPoint")
            {
                attribute = child->FirstAttribute();
                float anchor_x = 0.0f, anchor_y = 0.0f;

                while (attribute)
                {
                    name = attribute->Name();
                    std::string value = attribute->Value();

                    if (name == "ScaleX")
                    {
                        anchor_x = atof(value.c_str());
                    }
                    else if (name == "ScaleY")
                    {
                        anchor_y = atof(value.c_str());
                    }

                    attribute = attribute->Next();
                }

                widget->setAnchorPoint(Vec2(anchor_x, anchor_y));
            }
            else if (name == "CColor")
            {
                attribute = child->FirstAttribute();
                int red = 255, green = 255, blue = 255;

                while (attribute)
                {
                    name = attribute->Name();
                    std::string value = attribute->Value();

                    if (name == "A")
                    {
                        widget->setOpacity(atoi(value.c_str()));
                    }
                    else if (name == "R")
                    {
                        red = atoi(value.c_str());
                    }
                    else if (name == "G")
                    {
                        green = atoi(value.c_str());
                    }
                    else if (name == "B")
                    {
                        blue = atoi(value.c_str());
                    }

                    attribute = attribute->Next();
                }

                widget->setColor(Color3B(red, green, blue));
            }
            else if (name == "Size")
            {
                attribute = child->FirstAttribute();
                float width = 0.0f, height = 0.0f;

                while (attribute)
                {
                    name = attribute->Name();
                    std::string value = attribute->Value();

                    if (name == "X")
                    {
                        width = atof(value.c_str());
                    }
                    else if (name == "Y")
                    {
                        height = atof(value.c_str());
                    }

                    attribute = attribute->Next();
                }

                widget->setContentSize(Size(width, height));
            }

            child = child->NextSiblingElement();
        }

    }

    void WidgetReader::setAnchorPointForWidget(cocos2d::ui::Widget *widget, const protocolbuffers::NodeTree &nodeTree)
    {
        const protocolbuffers::WidgetOptions& options = nodeTree.widgetoptions();

        bool isAnchorPointXExists = options.has_anchorpointx();
        float anchorPointXInFile;
        if (isAnchorPointXExists)
        {
            anchorPointXInFile = options.anchorpointx();
        }
        else
        {
            anchorPointXInFile = widget->getAnchorPoint().x;
        }

        bool isAnchorPointYExists = options.has_anchorpointy();
        float anchorPointYInFile;
        if (isAnchorPointYExists)
        {
            anchorPointYInFile = options.anchorpointy();
        }
        else
        {
            anchorPointYInFile = widget->getAnchorPoint().y;
        }

        if (isAnchorPointXExists || isAnchorPointYExists)
        {
            widget->setAnchorPoint(Vec2(anchorPointXInFile, anchorPointYInFile));
        }
    }

    std::string WidgetReader::getResourcePath(const std::string &path, cocos2d::ui::Widget::TextureResType texType)
    {
        std::string filePath = GUIReader::getInstance()->getFilePath();
        const char* imageFileName = path.c_str();
        std::string imageFileName_tp;
        if (nullptr != imageFileName && 0 != strcmp("", imageFileName))
        {
            if (texType == ui::Widget::TextureResType::LOCAL) {
                imageFileName_tp = filePath + imageFileName;
            }
            else if(texType == ui::Widget::TextureResType::PLIST){
                imageFileName_tp = imageFileName;
            }
            else{
                CCASSERT(0, "invalid TextureResType!!!");
            }
        }
        return imageFileName_tp;
    }

}


text:
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace System.IO.Tests
{
    public class FileStream_ReadAsync : FileSystemTest
    {
        [Fact]
        public void NullBufferThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                AssertExtensions.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(null, 0, 1)));
            }
        }

        [Fact]
        public void NegativeOffsetThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, 1)));

                // buffer is checked first
                AssertExtensions.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, 1)));
            }
        }

        [Fact]
        public void NegativeCountThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, -1)));

                // offset is checked before count
                AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, -1)));

                // buffer is checked first
                AssertExtensions.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, -1)));
            }
        }

        [Fact]
        public void BufferOutOfBoundsThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                // offset out of bounds
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 1, 1)));

                // offset out of bounds for 0 count ReadAsync
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 2, 0)));

                // offset out of bounds even for 0 length buffer
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[0], 1, 0)));

                // combination offset and count out of bounds
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[2], 1, 2)));

                // edges
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[0], int.MaxValue, 0)));
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[0], int.MaxValue, int.MaxValue)));
            }
        }

        [Fact]
        public void ReadAsyncDisposedThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                fs.Dispose();
                Assert.Throws<ObjectDisposedException>(() =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, 1)));
                // even for noop ReadAsync
                Assert.Throws<ObjectDisposedException>(() =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, 0)));

                // out of bounds checking happens first
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[2], 1, 2)));

                // count is checked prior
                AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, -1)));

                // offset is checked prior
                AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, -1)));

                // buffer is checked first
                AssertExtensions.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, -1)));
            }
        }

        [Fact]
        public void WriteOnlyThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
            {
                Assert.Throws<NotSupportedException>(() =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, 1)));

                fs.Dispose();
                // Disposed checking happens first
                Assert.Throws<ObjectDisposedException>(() =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, 1)));

                // out of bounds checking happens first
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[2], 1, 2)));

                // count is checked prior
                AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, -1)));

                // offset is checked prior
                AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, -1)));

                // buffer is checked first
                AssertExtensions.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, -1)));
            }
        }

        [Fact]
        public void CancelledTokenFastPath()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.Cancel();
            CancellationToken cancelledToken = cts.Token;

            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                FSAssert.IsCancelled(fs.ReadAsync(new byte[1], 0, 1, cancelledToken), cancelledToken);
            }

            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
            {
                // before write only check
                FSAssert.IsCancelled(fs.ReadAsync(new byte[1], 0, 1, cancelledToken), cancelledToken);

                fs.Dispose();
                // before disposed check
                FSAssert.IsCancelled(fs.ReadAsync(new byte[1], 0, 1, cancelledToken), cancelledToken);

                // out of bounds checking happens first
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[2], 1, 2, cancelledToken)));

                // count is checked prior
                AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, -1, cancelledToken)));

                // offset is checked prior
                AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, -1, cancelledToken)));

                // buffer is checked first
                AssertExtensions.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, -1, cancelledToken)));
            }
        }

        [Fact]
        public async Task NoopReadAsyncsSucceed()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                // note that these do not succeed synchronously even though they do nothing.

                Assert.Equal(0, await fs.ReadAsync(new byte[0], 0, 0));
                Assert.Equal(0, await fs.ReadAsync(new byte[1], 0, 0));
                // even though offset is out of bounds of buffer, this is still allowed
                // for the last element
                Assert.Equal(0, await fs.ReadAsync(new byte[1], 1, 0));
                Assert.Equal(0, await fs.ReadAsync(new byte[2], 1, 0));
            }
        }

        [Fact]
        public async Task EmptyFileReadAsyncSucceedSynchronously()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                byte[] buffer = new byte[TestBuffer.Length];

                // use a recognizable pattern
                TestBuffer.CopyTo(buffer, 0);

                // note that these do not succeed synchronously even though they do nothing.
                Assert.Equal(0, await fs.ReadAsync(buffer, 0, 1));
                Assert.Equal(TestBuffer, buffer);

                Assert.Equal(0, await fs.ReadAsync(buffer, 0, buffer.Length));
                Assert.Equal(TestBuffer, buffer);

                Assert.Equal(0, await fs.ReadAsync(buffer, buffer.Length - 1, 1));
                Assert.Equal(TestBuffer, buffer);

                Assert.Equal(0, await fs.ReadAsync(buffer, buffer.Length / 2, buffer.Length - buffer.Length / 2));
                Assert.Equal(TestBuffer, buffer);
            }
        }

        [Fact]
        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "In netcoreapp we modified ReadAsync/WriteAsync to complete synchronously here, but that change was not backported to netfx.")]
        public async Task ReadAsyncBufferedCompletesSynchronously()
        {
            string fileName = GetTestFilePath();

            using (var fs = new FileStream(fileName, FileMode.Create))
            {
                fs.Write(TestBuffer, 0, TestBuffer.Length);
                fs.Write(TestBuffer, 0, TestBuffer.Length);
            }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, TestBuffer.Length * 2, useAsync: true))
            {
                byte[] buffer = new byte[TestBuffer.Length];

                // prime the internal buffer
                Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 0, buffer.Length));
                Assert.Equal(TestBuffer, buffer);

                Array.Clear(buffer, 0, buffer.Length);

                // read should now complete synchronously since it is serviced by the read buffer filled in the first request
                Assert.Equal(TestBuffer.Length, FSAssert.CompletesSynchronously(fs.ReadAsync(buffer, 0, buffer.Length)));
                Assert.Equal(TestBuffer, buffer);
            }
        }

        [Fact]
        public async Task ReadAsyncExistingFile()
        {
            string fileName = GetTestFilePath();
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                fs.Write(TestBuffer, 0, TestBuffer.Length);
            }

            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                byte[] buffer = new byte[TestBuffer.Length];
                Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 0, buffer.Length));
                Assert.Equal(TestBuffer, buffer);

                // ReadAsync with too large buffer at front of buffer
                fs.Position = 0;
                buffer = new byte[TestBuffer.Length * 2];
                Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 0, buffer.Length));
                Assert.Equal(TestBuffer, buffer.Take(TestBuffer.Length));
                // Remainder of buffer should be untouched.
                Assert.Equal(new byte[buffer.Length - TestBuffer.Length], buffer.Skip(TestBuffer.Length));

                // ReadAsync with too large buffer in middle of buffer
                fs.Position = 0;
                buffer = new byte[TestBuffer.Length * 2];
                Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 2, buffer.Length - 2));
                Assert.Equal(TestBuffer, buffer.Skip(2).Take(TestBuffer.Length));
                // Remainder of buffer should be untouched.
                Assert.Equal(new byte[2], buffer.Take(2));
                Assert.Equal(new byte[buffer.Length - TestBuffer.Length - 2], buffer.Skip(2 + TestBuffer.Length));
            }
        }

        [Fact]
        public async Task ReadAsyncCancelledFile()
        {
            string fileName = GetTestFilePath();
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                while(fs.Length < 128 * 1024)
                    fs.Write(TestBuffer, 0, TestBuffer.Length);
            }

            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                byte[] buffer = new byte[fs.Length];
                CancellationTokenSource cts = new CancellationTokenSource();
                Task<int> readTask = fs.ReadAsync(buffer, 0, buffer.Length, cts.Token);
                cts.Cancel();
                try
                {
                    await readTask;
                    // we may not have canceled before the task completed.
                }
                catch(OperationCanceledException oce)
                {
                    // Ideally we'd be doing an Assert.Throws<OperationCanceledException>
                    // but since cancellation is a race condition we accept either outcome
                    Assert.Equal(cts.Token, oce.CancellationToken);
                }
            }
        }

        [Fact, OuterLoop]
        public async Task ReadAsyncMiniStress()
        {
            TimeSpan testRunTime = TimeSpan.FromSeconds(10);
            const int MaximumReadSize = 16 * 1024;
            const int NormalReadSize = 4 * 1024;

            Random rand = new Random();
            DateTime testStartTime = DateTime.UtcNow;

            // Generate file data
            byte[] readableFileContents = new byte[MaximumReadSize * 16];
            rand.NextBytes(readableFileContents);

            // Create and fill file
            string readableFilePath = GetTestFilePath();
            using (var stream = new FileStream(readableFilePath, FileMode.CreateNew, FileAccess.Write))
            {
                await stream.WriteAsync(readableFileContents, 0, readableFileContents.Length);
            }

            using (var stream = new FileStream(readableFilePath, FileMode.Open, FileAccess.Read))
            {
                // Create a new token that expires between 100-1000ms
                CancellationTokenSource tokenSource = new CancellationTokenSource();
                tokenSource.CancelAfter(rand.Next(100, 1000));

                int currentPosition = 0;
                byte[] buffer = new byte[MaximumReadSize];
                do
                {
                    try
                    {
                        // 20%: random read size
                        int bytesToRead = (rand.NextDouble() < 0.2 ? rand.Next(16, MaximumReadSize) : NormalReadSize);

                        int bytesRead;
                        if (rand.NextDouble() < 0.1)
                        {
                            // 10%: Sync read
                            bytesRead = stream.Read(buffer, 0, bytesToRead);
                        }
                        else
                        {
                            // 90%: Async read
                            bytesRead = await stream.ReadAsync(buffer, 0, bytesToRead, tokenSource.Token);
                        }

                        // 10%: Verify data (burns a lot of CPU time)
                        if (rand.NextDouble() < 0.1)
                        {
                            // Validate data read
                            Assert.True(bytesRead + currentPosition <= readableFileContents.Length, "Too many bytes read");
                            Assert.Equal(readableFileContents.Skip(currentPosition).Take(bytesRead), buffer.Take(bytesRead));
                        }

                        // Advance position and reset if we are at the end
                        currentPosition += bytesRead;
                        if (currentPosition >= readableFileContents.Length)
                        {
                            currentPosition = 0;
                            stream.Seek(0, SeekOrigin.Begin);
                        }
                    }
                    catch (TaskCanceledException)
                    {
                        // Once the token has expired, generate a new one
                        Assert.True(tokenSource.Token.IsCancellationRequested, "Received cancellation exception before token expired");
                        tokenSource = new CancellationTokenSource();
                        tokenSource.CancelAfter(rand.Next(100, 1000));
                    }
                } while (DateTime.UtcNow - testStartTime <= testRunTime);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// 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 org.apache.tapestry5.annotations;

import org.apache.tapestry5.ioc.annotations.UseWith;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.apache.tapestry5.ioc.annotations.AnnotationUseContext.*;

/**
 * Method annotation used for methods that should be invoked when the page is first attached to a request. This is
 * useful for initializations that should occur on each request that involves the page. Often, such initializations will
 * be balanced by cleanups when the page is detached.
 *
 * PageAttached methods should take no parameters and return void. They must either have this annotation, or be named
 * "pageAttached".
 *
 * To be clear: methods with this annotation (or name) are still invoked even in Tapestry 5.2, which does away with
 * the page pool.
 *
 * @see PageDetached
 */
@Target(METHOD)
@Retention(RUNTIME)
@Documented
@UseWith({COMPONENT, MIXIN, PAGE})
public @interface PageAttached
{

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ceské Houby 4-5: 671 (1922)

#### Original name
Polyporus ustalis Velen., 1922

### Remarks
null


text:
import fontFromBuffer from '@next/font/dist/fontkit'
import type { AdjustFontFallback, FontLoader } from 'next/font'

import { promisify } from 'util'
import { validateData } from './utils'
import { calculateFallbackFontValues } from '../utils'

const NORMAL_WEIGHT = 400
const BOLD_WEIGHT = 700

function getWeightNumber(weight: string) {
  // Weight can be 'normal', 'bold' or a number https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-weight
  return weight === 'normal'
    ? NORMAL_WEIGHT
    : weight === 'bold'
    ? BOLD_WEIGHT
    : Number(weight)
}
function getDistanceFromNormalWeight(weight?: string) {
  if (!weight) return 0

  const [firstWeight, secondWeight] = weight
    .trim()
    .split(/ +/)
    .map(getWeightNumber)

  if (Number.isNaN(firstWeight) || Number.isNaN(secondWeight)) {
    throw new Error(
      `Invalid weight value in src array: \`${weight}\`.\nExpected \`normal\`, \`bold\` or a number.`
    )
  }

  // Not a variable font
  if (!secondWeight) {
    return firstWeight - NORMAL_WEIGHT
  }

  // Normal weight is within variable font range
  if (firstWeight <= NORMAL_WEIGHT && secondWeight >= NORMAL_WEIGHT) {
    return 0
  }

  // Return the distance of normal weight to the variable font range
  const firstWeightDistance = firstWeight - NORMAL_WEIGHT
  const secondWeightDistance = secondWeight - NORMAL_WEIGHT
  if (Math.abs(firstWeightDistance) < Math.abs(secondWeightDistance)) {
    return firstWeightDistance
  }
  return secondWeightDistance
}

const fetchFonts: FontLoader = async ({
  functionName,
  variableName,
  data,
  emitFontFile,
  resolve,
  fs,
}) => {
  const {
    src,
    display,
    fallback,
    preload,
    variable,
    adjustFontFallback,
    declarations,
    weight: defaultWeight,
    style: defaultStyle,
  } = validateData(functionName, data[0])

  const fontFiles = await Promise.all(
    src.map(async ({ path, style, weight, ext, format }) => {
      const resolved = await resolve(path)
      const fileBuffer = await promisify(fs.readFile)(resolved)
      const fontUrl = emitFontFile(fileBuffer, ext, preload)

      let fontMetadata: any
      try {
        fontMetadata = fontFromBuffer(fileBuffer)
      } catch (e) {
        console.error(`Failed to load font file: ${resolved}\n${e}`)
      }

      const fontFaceProperties = [
        ...(declarations
          ? declarations.map(({ prop, value }) => [prop, value])
          : []),
        ['font-family', variableName],
        ['src', `url(${fontUrl}) format('${format}')`],
        ['font-display', display],
        ...(weight ?? defaultWeight
          ? [['font-weight', weight ?? defaultWeight]]
          : []),
        ...(style ?? defaultStyle
          ? [['font-style', style ?? defaultStyle]]
          : []),
      ]

      return {
        css: `@font-face {
${fontFaceProperties
  .map(([property, value]) => `${property}: ${value};`)
  .join('\n')}
}\n`,
        fontMetadata,
        weight,
        style,
      }
    })
  )

  // Add fallback font
  let adjustFontFallbackMetrics: AdjustFontFallback | undefined
  if (adjustFontFallback !== false) {
    // Pick the font file to generate a fallback font from.
    // Prefer the file closest to normal weight, this will typically make up most of the text on a page.
    const fallbackFontFile = fontFiles.reduce(
      (usedFontFile, currentFontFile) => {
        if (!usedFontFile) return currentFontFile

        const usedFontDistance = getDistanceFromNormalWeight(
          usedFontFile.weight
        )
        const currentFontDistance = getDistanceFromNormalWeight(
          currentFontFile.weight
        )

        // Prefer normal style if they have the same weight
        if (
          usedFontDistance === currentFontDistance &&
          (typeof currentFontFile.style === 'undefined' ||
            currentFontFile.style === 'normal')
        ) {
          return currentFontFile
        }

        const absUsedDistance = Math.abs(usedFontDistance)
        const absCurrentDistance = Math.abs(currentFontDistance)

        // Use closest absolute distance to normal weight
        if (absCurrentDistance < absUsedDistance) return currentFontFile

        // Prefer the thinner font if both are the same absolute distance from normal weight
        if (
          absUsedDistance === absCurrentDistance &&
          currentFontDistance < usedFontDistance
        ) {
          return currentFontFile
        }

        return usedFontFile
      }
    )

    if (fallbackFontFile.fontMetadata) {
      adjustFontFallbackMetrics = calculateFallbackFontValues(
        fallbackFontFile.fontMetadata,
        adjustFontFallback === 'Times New Roman' ? 'serif' : 'sans-serif'
      )
    }
  }

  return {
    css: fontFiles.map(({ css }) => css).join('\n'),
    fallbackFonts: fallback,
    weight: src.length === 1 ? src[0].weight : undefined,
    style: src.length === 1 ? src[0].style : undefined,
    variable,
    adjustFontFallback: adjustFontFallbackMetrics,
  }
}

export default fetchFonts


text:
package org.jetbrains.idea.maven.server;

import java.rmi.RemoteException;

public class RuntimeRemoteException extends RuntimeException {
  public RuntimeRemoteException(RemoteException cause) {
    super(cause);
  }

  @Override
  public RemoteException getCause() {
    return (RemoteException)super.getCause();
  }
}


text:
package org.aktin.broker.admin.standalone;

import java.io.IOException;
import java.nio.file.Path;

import javax.sql.DataSource;

import org.aktin.broker.server.auth.AuthProvider;

public interface Configuration {

	// configuration to specify external class implementing HeaderAuthentication
	AuthProvider getAuthProvider() throws IOException;

	long getWebsocketIdleTimeoutMillis();

	Path getBasePath();

	//default String getDatabasePath() {return getBasePath().resolve("broker").toString();}
	default String getAggregatorDataPath() {return getBasePath().resolve("aggregator-data").toString();}
	default String getBrokerDataPath()  {return getBasePath().resolve("broker-data").toString();}
	default String getTempDownloadPath() {return getBasePath().resolve("download-temp").toString();}

	Class<? extends DataSource> getJdbcDataSourceClass() throws ClassNotFoundException;
	String getJdbcUrl();

	/**
	 * local TCP port to listen to
	 * @return port number
	 */
	int getPort();
}


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    // [START compute_v1_generated_Routers_Update_async]
    using Google.Cloud.Compute.V1;
    using System.Threading.Tasks;
    using lro = Google.LongRunning;

    public sealed partial class GeneratedRoutersClientSnippets
    {
        /// <summary>Snippet for UpdateAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task UpdateRequestObjectAsync()
        {
            // Create client
            RoutersClient routersClient = await RoutersClient.CreateAsync();
            // Initialize request argument(s)
            UpdateRouterRequest request = new UpdateRouterRequest
            {
                RequestId = "",
                Region = "",
                Router = "",
                RouterResource = new Router(),
                Project = "",
            };
            // Make the request
            lro::Operation<Operation, Operation> response = await routersClient.UpdateAsync(request);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = await routersClient.PollOnceUpdateAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END compute_v1_generated_Routers_Update_async]
}


text:
package model.experiments.tuningRuns;

import agents.firm.Firm;
import agents.firm.cost.InputCostStrategy;
import agents.firm.personell.HumanResources;
import agents.firm.production.Plant;
import agents.firm.production.control.TargetAndMaximizePlantControl;
import agents.firm.production.control.maximizer.SetTargetThenTryAgainMaximizer;
import agents.firm.production.control.maximizer.algorithms.marginalMaximizers.MarginalMaximizerWithUnitPID;
import agents.firm.production.control.targeter.PIDTargeterWithQuickFiring;
import agents.firm.production.technology.LinearConstantMachinery;
import agents.firm.sales.SalesDepartment;
import agents.firm.sales.SalesDepartmentAllAtOnce;
import agents.firm.sales.SalesDepartmentFactory;
import agents.firm.sales.exploration.SimpleBuyerSearch;
import agents.firm.sales.exploration.SimpleSellerSearch;
import agents.firm.sales.pricing.pid.SimpleFlowSellerPID;
import au.com.bytecode.opencsv.CSVWriter;
import goods.DifferentiatedGoodType;
import goods.UndifferentiatedGoodType;
import model.MacroII;
import model.scenario.MonopolistScenario;
import model.utilities.ActionOrder;
import sim.engine.SimState;
import sim.engine.Steppable;

import java.io.FileWriter;
import java.io.IOException;

/**
 *
Description

 *

 *

 *

 *
Notes

 * Created with IntelliJ
 *

 *

 *
References

 *
 * @author carrknight
 * @version 2013-02-26
 * @see
 */
public class MarginalMaximizerWithUnitPIDTuning {

    /**
     * Runs the supply chain with no GUI and writes a big CSV file
     * @param args
     */
    public static void main(String[] args)
    {

        CSVWriter writer = null;
        try {
            writer = new CSVWriter(new FileWriter("tuningUnit.csv"));
            writer.writeNext(new String[]{"proportional","integrative","derivative","maxFound","deviance","variance"});

        } catch (IOException e) {

        }

        final float[] pidParameters = new float[3];
        for(pidParameters[0] = 0.01f; pidParameters[0] <=2f; pidParameters[0] += 0.10f ){
            for(pidParameters[1] = 0.01f; pidParameters[1] <=2f; pidParameters[1] += 0.10f ){
                for(pidParameters[2]= 0f; pidParameters[2]<=0.1f; pidParameters[2] += 0.001f ){
                    float futureTargetAverage =0f;
                    double deviation = 0;
                    double variance = 0;
                    for(int i=0; i< 5; i++){

                        final MacroII macroII = new MacroII(System.currentTimeMillis());
                        MonopolistScenario scenario1 = new MonopolistScenario(macroII)
                        {
                            //override the monopolist construction in order to sweep through the pid parameters
                            @Override
                            public Firm buildFirm() {
                                //only one seller
                                final Firm built = new Firm(getModel());
                                built.receiveMany(UndifferentiatedGoodType.MONEY,100000000);
                                //set up the firm at time 1
                                getModel().scheduleSoon(ActionOrder.DAWN, new Steppable() {
                                    @Override
                                    public void step(SimState simState) {
                                        //sales department
                                        SalesDepartment dept = SalesDepartmentFactory.incompleteSalesDepartment(built, goodMarket,
                                                new SimpleBuyerSearch(goodMarket, built), new SimpleSellerSearch(goodMarket, built),
                                                SalesDepartmentAllAtOnce.class);
                                        built.registerSaleDepartment(dept, UndifferentiatedGoodType.GENERIC);
                                        dept.setAskPricingStrategy(new SimpleFlowSellerPID(dept)); //set strategy to PID

                                        //add the plant
                                        Plant plant = new Plant(blueprint, built);
                                        plant.setPlantMachinery(new LinearConstantMachinery(DifferentiatedGoodType.CAPITAL, built, 0, plant));
                                        plant.setCostStrategy(new InputCostStrategy(plant));
                                        built.addPlant(plant);

                                        //human resources
                                        HumanResources hr;
                                        //set up!
                                        hr = HumanResources.getEmptyHumanResources(1000000000, built, laborMarket, plant);
                                        TargetAndMaximizePlantControl control = TargetAndMaximizePlantControl.emptyTargetAndMaximizePlantControl(hr);
                                        control.setTargeter(new PIDTargeterWithQuickFiring(hr,control));
                                        MarginalMaximizerWithUnitPID algorithm = new MarginalMaximizerWithUnitPID(hr,control,plant,plant.getOwner(),
                                                model.random, hr.getPlant().getNumberOfWorkers());
                                        SetTargetThenTryAgainMaximizer<MarginalMaximizerWithUnitPID> maximizer =
                                                new SetTargetThenTryAgainMaximizer<MarginalMaximizerWithUnitPID>
                                                (hr,control,algorithm);
                                        control.setMaximizer(maximizer);
                                        hr.setPricingStrategy(control);
                                        hr.setControl(control);

                                        //       seller.registerHumanResources(plant, hr);
                                        hr.setFixedPayStructure(isFixedPayStructure());
                                        hr.start(model);

                                    }
                                });

                                getAgents().add(built);
                                return built;
                            }
                        };

                        macroII.setScenario(scenario1);
                        macroII.start();

                        int oldWorkers = 0;
                        while(macroII.schedule.getTime()<3500)
                        {

                            macroII.schedule.step(macroII);
                            variance += Math.pow(scenario1.getMonopolist().getTotalWorkers()-oldWorkers,2);
                            deviation += Math.pow(scenario1.getMonopolist().getTotalWorkers()-22,2);

                        }

                        futureTargetAverage+= scenario1.getMonopolist().getTotalWorkers();
                    }
                    futureTargetAverage= futureTargetAverage/5f;
                    deviation = deviation/5f;
                    variance = variance/5f;
                    writer.writeNext(new String[]{Float.toString((pidParameters[0])),Float.toString((pidParameters[1]))
                            ,Float.toString((pidParameters[2])),Float.toString(futureTargetAverage),Double.toString(deviation)
                            ,Double.toString(variance)});
                    try {
                        writer.flush();
                    } catch (IOException e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }

                }
            }
        }

    }

}


text:
package org.apache.spark.executor

import org.apache.spark.util.SparkExitCode._

/**
 * These are exit codes that executors should use to provide the master with information about
 * executor failures assuming that cluster management framework can capture the exit codes (but
 * perhaps not log files). The exit code constants here are chosen to be unlikely to conflict
 * with "natural" exit statuses that may be caused by the JVM or user code. In particular,
 * exit codes 128+ arise on some Unix-likes as a result of signals, and it appears that the
 * OpenJDK JVM may use exit code 1 in some of its own "last chance" code.
  *
  * 这些是退出代码,执行者应该使用它来向主机提供关于执行器故障的信息,
  * 假设集群管理框架可以捕获退出代码(但可能不是日志文件),这里的退出代码常量被选择为不太可能与由JVM或用户代码引起的"自然"退出状态相冲突,
  * 特别地,退出代码128+由于信号而在某些Unix喜好上出现,并且似乎OpenJDK JVM可能在其自己的"最后机会"代码中使用退出代码1。
 */
private[spark]
object ExecutorExitCode {

  /**
   *  DiskStore failed to create a local temporary directory after many attempts.
   *  DiskStore失败53次尝试后,创建一个本地临时目录
   *  */
  val DISK_STORE_FAILED_TO_CREATE_DIR = 53

  /**
   *  ExternalBlockStore failed to initialize after many attempts.
   *  扩展BlockStore初始化尝试多次失败
   *  */
  val EXTERNAL_BLOCK_STORE_FAILED_TO_INITIALIZE = 54

  /** ExternalBlockStore failed to create a local temporary directory after many attempts.
    * 多次尝试后,ExternalBlockStore无法创建本地临时目录 */
  val EXTERNAL_BLOCK_STORE_FAILED_TO_CREATE_DIR = 55

  def explainExitCode(exitCode: Int): String = {
    exitCode match {
      case UNCAUGHT_EXCEPTION => "Uncaught exception"
      case UNCAUGHT_EXCEPTION_TWICE => "Uncaught exception, and logging the exception failed"
      case OOM => "OutOfMemoryError"
      case DISK_STORE_FAILED_TO_CREATE_DIR =>
        "Failed to create local directory (bad spark.local.dir?)"
      // TODO: replace external block store with concrete implementation name
      case EXTERNAL_BLOCK_STORE_FAILED_TO_INITIALIZE => "ExternalBlockStore failed to initialize."
      // TODO: replace external block store with concrete implementation name
      case EXTERNAL_BLOCK_STORE_FAILED_TO_CREATE_DIR =>
        "ExternalBlockStore failed to create a local temporary directory."
      case _ =>
        "Unknown executor exit code (" + exitCode + ")" + (
          if (exitCode > 128) {
            " (died from signal " + (exitCode - 128) + "?)"
          } else {
            ""
          }
        )
    }
  }
}


text:
/**
 * This is used by the NestedList example to allow editing of an item in the Store
 */
Ext.define('Kitchensink.view.EditorPanel', {
    extend: 'Ext.form.Panel',
    id: 'editorPanel',
    config: {
        modal: true,
        hideOnMaskTap: false,
        centered: true,
        width: Ext.filterPlatform('ie10') ? '100%' : 300,
        scrollable: null,
        items: [{
            xtype: 'textfield',
            name: 'text',
            label: 'Name',
            listeners: {
                keyup: function(field) {
                    Ext.getCmp('changeButton').setDisabled(field.getValue() ? false : true);
                }
            }
        }, {
            docked: 'top',
            xtype: 'toolbar',
            title: 'Edit Item'
        }, {
            docked: 'bottom',
            ui: ((Ext.os.is.BlackBerry && Ext.os.version.getMajor() === 10)) ? 'plain' : 'light',
            xtype: 'toolbar',
            items: [
                {
                    text: 'Cancel',
                    handler: function() {
                        Ext.getCmp('changeButton').setDisabled(false);
                        Ext.getCmp('editorPanel').hide();
                    }
                }, {
                    xtype: 'spacer'
                }, {
                    text: 'Change',
                    id: 'changeButton',
                    ui: 'action',
                    handler: function() {
                        var formPanel = Ext.getCmp('editorPanel'),
                            formRecord = formPanel.getRecord(),
                            values = formPanel.getValues();

                        if (formRecord) {
                            formRecord.set(values);
                            formRecord.commit();
                        }

                        formPanel.hide();
                    }
                }
            ]
        }]
    }
});


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.14-5-4
description: >
    Object.keys - non-enumerable own accessor property of 'O' is not
    defined in returned array
---*/

        var obj = {};

        Object.defineProperty(obj, "prop1", {
            get: function () { },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(obj, "prop2", {
            get: function () { },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(obj, "prop3", {
            get: function () { },
            enumerable: true,
            configurable: true
        });

        var arr = Object.keys(obj);

        for (var p in arr) {
            if (arr.hasOwnProperty(p)) {
                assert.notSameValue(arr[p], "prop2", 'arr[p]');
            }
        }


text:
'use strict';
var webtestDriver = require('../src/web-test-driver');
const RE_STR  = '["]?([^\"]+)["]?'; // e.g. foo.bar, "foo.bar", or "foo bar"
const RE_STR_WITH_QUOTE = '[\'"]([\\s\\S]+)[\'"]'; //e.g. 'foo bar', "foo bar"

module.exports = {
  name: 'verify element value match',
  help: 'verify element <selector> value matches "<string>"',
  regExp: new RegExp(`^verify element ${RE_STR} value matches [to ]*${RE_STR_WITH_QUOTE}`),
  /** must return a Promise, so that it can be chained with next command*/
  func: function(selector, valueRE) {
    let cssSelector = `${selector}, [placeholder='${selector}']`;
    return webtestDriver.driver.wait( function() {
      return webtestDriver.driver.findElement({css: cssSelector})
        //.then(element => webtestDriver.showCircleOn(element))
        .getAttribute("value")
        .then( val => !!val.match(valueRE));
    }, webtestDriver.config.timeout);
  }
};


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LoginStateChangeEvent.Reason (android API)</title>
<meta name="date" content="2018-05-08">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

cn.jpush.im.android.api.event

Enum LoginStateChangeEvent.Reason

java.lang.Object

java.lang.Enum<LoginStateChangeEvent.Reason>

cn.jpush.im.android.api.event.LoginStateChangeEvent.Reason

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<LoginStateChangeEvent.Reason>

Enclosing class:

LoginStateChangeEvent

public static enum LoginStateChangeEvent.Reason
extends java.lang.Enum<LoginStateChangeEvent.Reason>

登陆状态变更原因。

Enum Constant Summary

Enum Constants

Enum Constant and Description

user_deleted

用户信息被服务器端删除。sdk将清除当前设备登陆的用户信息。

user_disabled

用户被服务器端禁用。sdk将清除当前设备登陆的用户信息。

user_login_status_unexpected

用户登陆状态异常,请重新登录。

user_logout

用户在其他设备登陆。sdk会自动登出当前设备的用户。

user_password_change

用户密码在其他端被修改,sdk会自动登出当前设备的用户

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static LoginStateChangeEvent.Reason
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static LoginStateChangeEvent.Reason[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

compareTo, equals, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

user_logout

public static final LoginStateChangeEvent.Reason user_logout

用户在其他设备登陆。sdk会自动登出当前设备的用户。

user_deleted

public static final LoginStateChangeEvent.Reason user_deleted

用户信息被服务器端删除。sdk将清除当前设备登陆的用户信息。

user_password_change

public static final LoginStateChangeEvent.Reason user_password_change

用户密码在其他端被修改,sdk会自动登出当前设备的用户

user_login_status_unexpected

public static final LoginStateChangeEvent.Reason user_login_status_unexpected

用户登陆状态异常,请重新登录。

user_disabled

public static final LoginStateChangeEvent.Reason user_disabled

用户被服务器端禁用。sdk将清除当前设备登陆的用户信息。

Since:

2.5.0

Method Detail

values

public static LoginStateChangeEvent.Reason[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (LoginStateChangeEvent.Reason c : LoginStateChangeEvent.Reason.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static LoginStateChangeEvent.Reason valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method


text:
'use strict';

const path = require('path');
const fse = require('fs-extra');
const _ = require('lodash');
const { isConfigurable } = require('../../utils/attributes');

module.exports = function createSchemaHandler(infos) {
  const { category, modelName, plugin, uid, dir, filename, schema } = infos;

  const initialState = {
    modelName,
    plugin,
    category,
    uid,
    dir,
    filename,
    schema: schema || {
      info: {},
      options: {},
      attributes: {},
    },
  };

  const state = _.cloneDeep(initialState);

  // always keep it the same to rollback
  Object.freeze(initialState.schema);

  let modified = false;
  let deleted = false;

  return {
    get modelName() {
      return initialState.modelName;
    },

    get plugin() {
      return initialState.plugin;
    },

    get category() {
      return initialState.category;
    },

    get kind() {
      return _.get(state.schema, 'kind', 'collectionType');
    },

    get uid() {
      return state.uid;
    },

    get writable() {
      return _.get(state, 'plugin') !== 'admin';
    },

    setUID(val) {
      modified = true;

      state.uid = val;
      return this;
    },

    setDir(val) {
      modified = true;

      state.dir = val;
      return this;
    },

    get schema() {
      return _.cloneDeep(state.schema);
    },

    setSchema(val) {
      modified = true;

      state.schema = _.cloneDeep(val);
      return this;
    },

    // get a particuar path inside the schema
    get(path) {
      return _.get(state.schema, path);
    },

    // set a particuar path inside the schema
    set(path, val) {
      modified = true;

      const value = _.defaultTo(val, _.get(state.schema, path));
      _.set(state.schema, path, value);

      return this;
    },

    // delete a particuar path inside the schema
    unset(path) {
      modified = true;

      _.unset(state.schema, path);

      return this;
    },

    delete() {
      deleted = true;
      return this;
    },

    getAttribute(key) {
      return this.get(['attributes', key]);
    },

    setAttribute(key, attribute) {
      return this.set(['attributes', key], attribute);
    },

    deleteAttribute(key) {
      return this.unset(['attributes', key]);
    },

    setAttributes(newAttributes) {
      // delete old configurable attributes
      for (let key in this.schema.attributes) {
        if (isConfigurable(this.schema.attributes[key])) {
          this.deleteAttribute(key);
        }
      }

      // set new Attributes
      for (let key in newAttributes) {
        this.setAttribute(key, newAttributes[key]);
      }

      return this;
    },

    removeContentType(uid) {
      const { attributes } = state.schema;

      Object.keys(attributes).forEach(key => {
        const attribute = attributes[key];

        if (attribute.target === uid) {
          this.deleteAttribute(key);
        }
      });

      return this;
    },

    // utils
    removeComponent(uid) {
      const { attributes } = state.schema;

      Object.keys(attributes).forEach(key => {
        const attr = attributes[key];

        if (attr.type === 'component' && attr.component === uid) {
          this.deleteAttribute(key);
        }

        if (
          attr.type === 'dynamiczone' &&
          Array.isArray(attr.components) &&
          attr.components.includes(uid)
        ) {
          const updatedComponentList = attributes[key].components.filter(val => val !== uid);
          this.set(['attributes', key, 'components'], updatedComponentList);
        }
      });

      return this;
    },

    updateComponent(uid, newUID) {
      const { attributes } = state.schema;

      Object.keys(attributes).forEach(key => {
        const attr = attributes[key];

        if (attr.type === 'component' && attr.component === uid) {
          this.set(['attributes', key, 'component'], newUID);
        }

        if (
          attr.type === 'dynamiczone' &&
          Array.isArray(attr.components) &&
          attr.components.includes(uid)
        ) {
          const updatedComponentList = attr.components.map(val => (val === uid ? newUID : val));

          this.set(['attributes', key, 'components'], updatedComponentList);
        }
      });

      return this;
    },

    // save the schema to disk
    async flush() {
      if (!this.writable) {
        return;
      }

      const initialPath = path.join(initialState.dir, initialState.filename);
      const filePath = path.join(state.dir, state.filename);

      if (deleted === true) {
        await fse.remove(initialPath);

        const list = await fse.readdir(initialState.dir);
        if (list.length === 0) {
          await fse.remove(initialState.dir);
        }

        return;
      }

      if (modified === true) {
        await fse.ensureFile(filePath);

        await fse.writeJSON(
          filePath,
          {
            kind: state.schema.kind,
            collectionName: state.schema.collectionName,
            info: state.schema.info,
            options: state.schema.options,
            pluginOptions: state.schema.pluginOptions,
            attributes: state.schema.attributes,
            config: state.schema.config,
          },
          { spaces: 2 }
        );

        // remove from oldPath
        if (initialPath !== filePath) {
          await fse.remove(initialPath);

          const list = await fse.readdir(initialState.dir);
          if (list.length === 0) {
            await fse.remove(initialState.dir);
          }
        }

        return;
      }

      return Promise.resolve();
    },

    // reset the schema to its initial value
    async rollback() {
      if (!this.writable) {
        return;
      }

      const initialPath = path.join(initialState.dir, initialState.filename);
      const filePath = path.join(state.dir, state.filename);

      // it was a creation so it needs to be deleted
      if (!initialState.uid) {
        await fse.remove(filePath);

        const list = await fse.readdir(state.dir);
        if (list.length === 0) {
          await fse.remove(state.dir);
        }
        return;
      }

      if (modified === true || deleted === true) {
        await fse.ensureFile(initialPath);
        await fse.writeJSON(initialPath, initialState.schema, { spaces: 2 });

        // remove
        if (initialPath !== filePath) {
          await fse.remove(filePath);

          const list = await fse.readdir(state.dir);
          if (list.length === 0) {
            await fse.remove(state.dir);
          }
        }
      }

      return Promise.resolve();
    },
  };
};


text:
'use strict';

// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
	// if the path tries to go above the root, `up` ends up > 0
	var up = 0;
	for (var i = parts.length - 1; i >= 0; i--) {
		var last = parts[i];
		if (last === '.') {
			parts.splice(i, 1);
		} else if (last === '..') {
			parts.splice(i, 1);
			up++;
		} else if (up) {
			parts.splice(i, 1);
			up--;
		}
	}

	// if the path is allowed to go above the root, restore leading ..s
	if (allowAboveRoot) {
		for (; up--; up) {
			parts.unshift('..');
		}
	}

	return parts;
}

// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe = /^(\/?)([\s\S]+\/(?!$)|\/)?((?:[\s\S]+?)?(\.[^.]*)?)$/;
function splitPath(filename) {
	var result = splitPathRe.exec(filename);
	return [ result[1] || '', result[2] || '', result[3] || '', result[4] || '' ];
}

// path.resolve([from ...], to)
exports.resolve = function () {
	var resolvedPath = '',
		resolvedAbsolute = false;

	for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
		// var path = (i >= 0) ? arguments[i] : process.cwd();
		var path = arguments[i];

		// Skip empty and invalid entries
		if (typeof path !== 'string' || !path) {
			continue;
		}

		resolvedPath = path + '/' + resolvedPath;
		resolvedAbsolute = path.charAt(0) === '/';
	}

	// At this point the path should be resolved to a full absolute path, but
	// handle relative paths to be safe (might happen when process.cwd() fails)

	// Normalize the path
	resolvedPath = normalizeArray(resolvedPath.split('/').filter(function (p) {
		return !!p;
	}), !resolvedAbsolute).join('/');

	return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};

// path.normalize(path)
exports.normalize = function (path) {
	var isAbsolute = path.charAt(0) === '/',
		trailingSlash = path.slice(-1) === '/';

	// Normalize the path
	path = normalizeArray(path.split('/').filter(function (p) {
		return !!p;
	}), !isAbsolute).join('/');

	if (!path && !isAbsolute) {
		path = '.';
	}
	if (path && trailingSlash) {
		path += '/';
	}

	return (isAbsolute ? '/' : '') + path;
};

exports.join = function () {
	var paths = Array.prototype.slice.call(arguments, 0);
	return exports.normalize(paths.filter(p => p && typeof p === 'string').join('/'));
};

// path.relative(from, to)
exports.relative = function (from, to) {
	from = exports.resolve(from).substr(1);
	to = exports.resolve(to).substr(1);

	function trim(arr) {
		var start = 0;
		for (; start < arr.length; start++) {
			if (arr[start] !== '') {
				break;
			}
		}

		var end = arr.length - 1;
		for (; end >= 0; end--) {
			if (arr[end] !== '') {
				break;
			}
		}

		if (start > end) {
			return [];
		}
		return arr.slice(start, end - start + 1);
	}

	var fromParts = trim(from.split('/'));
	var toParts = trim(to.split('/'));

	var length = Math.min(fromParts.length, toParts.length);
	var samePartsLength = length;
	for (let i = 0; i < length; i++) {
		if (fromParts[i] !== toParts[i]) {
			samePartsLength = i;
			break;
		}
	}

	var outputParts = [];
	for (let i = samePartsLength; i < fromParts.length; i++) {
		outputParts.push('..');
	}

	outputParts = outputParts.concat(toParts.slice(samePartsLength));

	return outputParts.join('/');
};

exports.dirname = function (path) {
	var result = splitPath(path),
		root = result[0],
		dir = result[1];

	if (!root && !dir) {
		// No dirname whatsoever
		return '.';
	}

	if (dir) {
		// It has a dirname, strip trailing slash
		dir = dir.substring(0, dir.length - 1);
	}

	return root + dir;
};

exports.basename = function (path, ext) {
	var f = splitPath(path)[2];
	if (ext && f.substr(-1 * ext.length) === ext) {
		f = f.substr(0, f.length - ext.length);
	}
	return f;
};

exports.extname = function (path) {
	return splitPath(path)[3];
};


text:
require File.dirname(__FILE__) + '/../spec_helper.rb'

describe "ActiveCouch::View #with_key method" do
  before(:each) do
    class ByName < ActiveCouch::View
      define :by_name, :for_db => 'people' do
        with_key 'name'
      end
    end
  end

  after(:each) do
    Object.send(:remove_const, :ByName)
  end

  it "should set @key correctly" do
    ByName.instance_variable_get("@key").should == 'name'
  end
end


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>Language Attribute Test</title>

The glyph for JHA should look different for Nepali and Hindi.

You First should change system Language to Nepali or Hindi

JHA झ


text:
<?php

abstract class Mleko_Model_List_Extension extends Mleko_Model_List_Plugin {

	abstract public function join(Zend_Db_Select $select, $fetchData = true);
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Linq;
using Xunit;

namespace System._Time.Tests
{
    public class DateMiscTests
    {
        [Fact]
        public void CanDetermineLeapYear_2000()
        {
            Assert.True(Date.IsLeapYear(2000));
        }

        [Fact]
        public void CanDetermineLeapYear_2001()
        {
            Assert.False(Date.IsLeapYear(2001));
        }

        [Fact]
        public void CanDetermineLeapYear_2004()
        {
            Assert.True(Date.IsLeapYear(2004));
        }

        [Fact]
        public void CanDetermineLeapYear_2100()
        {
            Assert.False(Date.IsLeapYear(2100));
        }

        [Fact]
        public void CannotDetermineLeapYear_TooSmall()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => Date.IsLeapYear(0));
        }

        [Fact]
        public void CannotDetermineLeapYear_TooLarge()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => Date.IsLeapYear(10000));
        }

        [Fact]
        public void CanDetermineDaysInMonth_LeapYear()
        {
            var expected = new[] {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

            var actual = Enumerable.Range(1, 12).Select(m => Date.DaysInMonth(2000, m)).ToArray();

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void CanDetermineDaysInMonth_NonLeapYear()
        {
            var expected = new[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

            var actual = Enumerable.Range(1, 12).Select(m => Date.DaysInMonth(2001, m)).ToArray();

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void CannoDetermineDaysInMonth_YearTooLarge()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => Date.DaysInMonth(10000, 1));
        }

        [Fact]
        public void CannoDetermineDaysInMonth_YearTooSmall()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => Date.DaysInMonth(0, 1));
        }

        [Fact]
        public void CannoDetermineDaysInMonth_MonthTooLarge()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => Date.DaysInMonth(2000, 13));
        }

        [Fact]
        public void CannoDetermineDaysInMonth_MonthTooSmall()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => Date.DaysInMonth(2000, 0));
        }

    }
}


text:
package com.twitter.sdk.android.tweetui.internal;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

public class SwipeToDismissTouchListener implements View.OnTouchListener {
    private int touchSlop;
    private float initialY;
    private final float maxTranslate;
    private final float closeThreshold;
    private Callback callback;
    private float lastX;
    private float lastY;
    private int pointerIndex;
    private boolean isMoving;

    public static SwipeToDismissTouchListener createFromView(View view, Callback listener) {
        return new SwipeToDismissTouchListener(listener,
                ViewConfiguration.get(view.getContext()).getScaledTouchSlop(),
                view.getContext().getResources().getDisplayMetrics().heightPixels * 0.5f);
    }

    SwipeToDismissTouchListener(Callback listener, int touchSlop, float maxTranslate) {
        // If swiping more than 20% of the max distance, trigger the dismiss listener.
        this(listener, touchSlop, maxTranslate, maxTranslate * 0.2f);
    }

    SwipeToDismissTouchListener(Callback listener, int touchSlop, float maxTranslate,
            float closeThreshold) {
        setCallback(listener);
        this.touchSlop = touchSlop;
        this.maxTranslate = maxTranslate;
        this.closeThreshold = closeThreshold;
    }

    @Override
    @SuppressLint("ClickableViewAccessibility")
    public boolean onTouch(View v, MotionEvent event) {
        boolean viewClosed = false;
        if (!(v instanceof SwipeableViewProvider) || ((SwipeableViewProvider) v).canBeSwiped() ||
                isMoving()) {
            viewClosed = handleTouchEvent(v, event);
        }

        // If the view is not being closed due to the touch event, give the touch event back to the
        // target view in case they have their own custom touch handling
        return viewClosed || v.onTouchEvent(event);
    }

    /**
     * Handles the incoming motion event, possibly translating or closing the swipeable view.
     *
     * @param event The incoming motion event.
     * @return true if the motion event results in the view closing, false otherwise.
     */
    boolean handleTouchEvent(View swipeableView, MotionEvent event) {
        boolean viewClosed = false;

        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: {
                lastX = event.getRawX();
                initialY = lastY = event.getRawY();
                isMoving = false;
                pointerIndex = event.getPointerId(event.getPointerCount() - 1);
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                final float currentX = event.getRawX();
                final float currentY = event.getRawY();
                final float initialDeltaY = currentY - initialY;
                final float deltaX = currentX - lastX;
                final float deltaY = currentY - lastY;
                lastX = currentX;
                lastY = currentY;
                if (isValidPointer(event) &&
                        (isMoving || (hasMovedEnoughInProperYDirection(initialDeltaY) &&
                                hasMovedMoreInYDirectionThanX(deltaX, deltaY)))) {
                    isMoving = true;
                    moveView(swipeableView, deltaY);
                }
                break;
            }
            case MotionEvent.ACTION_POINTER_DOWN:{
                settleView(swipeableView);
                isMoving = false;
                pointerIndex = -1; // invalidate pointer index until next ACTION_DOWN
                break;
            }
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL: {
                if (isValidPointer(event)) {
                    if (isMoving) {
                        viewClosed = settleOrCloseView(swipeableView);
                    }
                }
                isMoving = false;
                break;
            }
            default: {
                break;
            }
        }

        return viewClosed;
    }

    /**
     * @param initialDeltaY the delta between the initial Y position and the current Y position.
     * @return if the scroll has moved far enough in the proper direction to start tracking a swipe to dismiss.
     */
    boolean hasMovedEnoughInProperYDirection(float initialDeltaY) {
        return Math.abs(initialDeltaY) > touchSlop;
    }

    /**
     * @param deltaX the delta between the last X position and the current X position.
     * @param deltaY the delta between the last Y position and the current Y position.
     * @return if the swipe gesture has moved more in the Y direction than the X direction.
     */
    boolean hasMovedMoreInYDirectionThanX(float deltaX, float deltaY) {
        return Math.abs(deltaY) > Math.abs(deltaX);
    }

    /**
     * @return if we are currently tracking a swipe to dismiss gesture.
     */
    boolean isMoving() {
        return isMoving;
    }

    boolean isValidPointer(MotionEvent event) {
        return pointerIndex >= 0 && event.getPointerCount() == 1;
    }

    /**
     * Determines whether or not to settle or close the view based on the current view translation.
     *
     * @return true if the view was closed, otherwise false.
     */
    boolean settleOrCloseView(View swipeableView) {
        final float currentY = swipeableView.getTranslationY();
        if (currentY > closeThreshold || currentY < -closeThreshold) {
            if (callback != null) {
                callback.onDismiss();
            }

            return true;
        } else {
            settleView(swipeableView);
            return false;
        }
    }

    void settleView(View swipeableView) {
        if (swipeableView.getTranslationY() != 0) {
            final ObjectAnimator animator =
                    ObjectAnimator.ofFloat(swipeableView, View.TRANSLATION_Y, 0).setDuration(100);
            animator.addUpdateListener(animation -> {
                final float targetY = (Float) animation.getAnimatedValue();
                if (callback != null) {
                    callback.onMove(targetY);
                }
            });
            animator.start();
        }
    }

    void moveView(View swipeableView, float deltaY) {
        final float currentY = swipeableView.getTranslationY();
        final float deltaWithTension = (float) (deltaY * calculateTension(currentY));
        final float targetY = bound(currentY + deltaWithTension);
        swipeableView.setTranslationY(targetY);
        if (callback != null) {
            callback.onMove(targetY);
        }
    }

    double calculateTension(float targetY) {
        // energy = 1 / 2 * k * x^2
        // but since we only want a coefficient from 0 to 1 we can ignore the constants.
        final float distance = Math.abs(targetY);
        final float maxDistance = closeThreshold * 2f;
        final double tension = Math.pow(distance, 2);
        final double maxTension = Math.pow(maxDistance, 2);
        final double tensionCoeff = 1 - (tension / maxTension);
        return tensionCoeff;
    }

    float bound(float y) {
        if (y < -maxTranslate) {
            return -maxTranslate;
        } else if (y > maxTranslate) {
            return maxTranslate;
        }
        return y;
    }

    public void setCallback(Callback listener) {
        this.callback = listener;
    }

    public interface Callback {
        void onDismiss();

        void onMove(float translationY);
    }

    /**
     * Implement this interface to allow or disallow swipe to dismiss behavior
     */
    public interface SwipeableViewProvider {
        /**
         * Determines if a view can be swiped away
         * ATTENTION: this will be called on every touchEvent, don't do any expensive operation in this method
         *
         * @return true if the view can be moved/dismissed, false otherwise
         */
        boolean canBeSwiped();
    }
}


text:
using namespace Input::VirtualInput;

namespace Input
{
	namespace Joystick
	{
		//typedefs
		typedef unsigned char JoystickButton;
		//constants
		const int JOYSTICK_HARDWARE_BUTTON_MAX = 30; //max number of button indices we poll, currently an arbitrary value

		class JoystickRemapper
		{

		public:
			InputValue GetButtonMapping(char glfwButton);
			bool IsButtonMapped(char glfwButton);
			void MapButton(int vButton, char glfwButton);
			JoystickRemapper();
		private:
			char remap[FINAL_VIRTUAL_KEY_ENUM_VALUE];
		};

		class JoystickController : public IController
		{
		public:
			virtual InputInfo Poll();
			virtual void DebugDraw();
			int HardwareID();
			void HardwareID(int val);
			void SetRemapper(JoystickRemapper remapper);
		private:
			int hardwareID;
			char lastFrameHardwareButtons[JOYSTICK_HARDWARE_BUTTON_MAX];
			JoystickRemapper remapper;
		};

		//Todo add a joystick mapping system so people can write joystick data files to make custom JoystickButtonInfos
	}
}


text:
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
| Как принято в REST, запросы можно реализовать cURL или JS
|
| $app->get('/accounts', 'AccountsController@listAccounts');
| $app->post('/accounts', 'AccountsController@createAccount');
| $app->put('/accounts/{account_id}', 'AccountsController@editAccount');
| $app->delete('/accounts/{account_id}', 'AccountsController@deleteAccount');
| $app->get('/posts/{account_id}/{limit?}', 'AccountsController@listPosts');
|
| при удалении если удалять постом lumen ругается что запрос поститься, а данные постом не передаются. сделал гет
| В получение твитов надо как то передать limit.
| Тесть сделать постом и передавать параметр в теле, или добавить ище один гет параметр
| Сам принимать такие решения не могу, надо согласовывать с клиетом
| ->were() В люмене не работает, надо разбиратся с проверкой
|
*/
$app->get('/accounts', 'AccountsController@listAccounts');
$app->post('/accounts/new', 'AccountsController@createAccount');
$app->post('/accounts/{account_id}', 'AccountsController@editAccount');//->where('account_id', '[0-9]+');
$app->get('/accounts/{account_id}/delete', 'AccountsController@deleteAccount');//->where('account_id', '[0-9]+');
$app->get('/accounts/posts/{account_id}', 'AccountsController@listPosts');//->where('account_id', '[0-9]+');
$app->get('/accounts/gettwitterposts', 'AccountsController@getTwitterPosts');