text:
import React, {Component} from 'react';
import Page from 'material-ui/Paper';
import Dialog from 'material-ui/Dialog';
import IconButton from 'material-ui/IconButton';
import TextField from 'material-ui/TextField';
import CodeIcon from 'material-ui/svg-icons/action/code';
import {Toolbar, ToolbarGroup, ToolbarTitle,ToolbarSeparator} from 'material-ui/Toolbar';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
import FlatButton from 'material-ui/FlatButton';

import TkTest from 'material-ui/svg-icons/av/airplay';
import TkReset from 'material-ui/svg-icons/navigation/refresh';
import TkDownload from 'material-ui/svg-icons/file/cloud-download';
import TkUpload from 'material-ui/svg-icons/file/cloud-upload';
import TkAutomatic from 'material-ui/svg-icons/notification/adb';
import TkManual from 'material-ui/svg-icons/maps/directions-walk';
import TkMarkdown from 'material-ui/svg-icons/communication/swap-calls';
import TkBrowserEdit from 'material-ui/svg-icons/editor/mode-edit';

import TkHtmlViewer from './tkhtmlviewer';
import TkTestDailog from './tktest';
import TkMarkd from './tkmarkd';
import htmldom from './htmldom';
import {optionAuto,feildAuto} from './tkauto';

const checkColor = '#69F0AE';
const toolbarIconColor = '#616161';
const warningColor = '#EF9A9A';

//取得节点的属性,属性名称为attrName
function getAttribute(node,attrName){
    for(let i = 0;i < node.attributes.length;i++){
        if( node.attributes[i].name === attrName){
            return node.attributes[i];
        }
    }
    return null;
}
//遍历全部子节点,查找插入的节点
function forChildren(node,cb){
    if(cb(node))return;
    for(let i=0;i<node.children.length;i++){
        if(cb(node.children[i]))return;
        forChildren(node.children[i],cb);
    }
}

function getTypeString(id){
    switch(id){
        case 1:return "选择题";
        case 2:return "填空题";
        case 3:return "解答题";
        case 4:return "其他";
        case 5:return "连线题";
        case 6:return "排序";
        case -1:return "忽略";
        case 0:return "未处理";
    }
    return "";
}

function getTypeColor(id){
    switch(id){
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
            return '#69F0AE';
        case -1:
            return '#BDBDBD';
        case 0:
            return '#EF9A9A';
    }
    return '#E0E0E0';
}
/**
 * 具体的html编辑
 * type = (0:image,1:body,2:answer,3:analysis)
 * qid (问题id)
 * topicsType = (1选择题,2填空题,3解答题,4其他,-1忽略,0未处理)
 * content = (html content)
 * markd = (markd content)
 * source = (source html content)
 * seat = (0.source,1.content,2.markd)
 * answer (为了分析交互答案)
 * title = (标题)
 * index = 浏览模式下第几题的索引
 * 属性browser表示处于浏览模式
 */
class TkFrame extends Component{
	constructor(props){
		super(props);
        //确定模式
        this.isIFrameLoad = false;
        this.isFirstLoad = true;
        let mode = "html";
        let content = "";
        if('seat' in props){
            if(props.seat==0){
                content = props.source;
            }else if(props.seat==1){
                content = props.content;
            }else if(props.seat==2){
                mode = "markd";
            }else{
                content = props.content?props.content:props.source;
            }
        }else{
            content = props.content?props.content:props.source;
        }
        this.state={
            expendHTML:false,
            iframeHeight:0,
            isAuto:true,
            topicsType:props.topicsType,
            isContentChange:false,
            htmlContent:'',
            openTestDialog:false,
            testContent:"",
            mode:mode,
            content:content,
            markd:props.markd,
            seat:0,
            isMarkdContentChange:false,
        };
	}
    componentWillMount(){
    }
    componentDidMount(){
    }
    componentWillReceiveProps(nextProps){
        if(this.props.qid!=nextProps.qid||
            this.props.content!=nextProps.content||
            this.props.markd!=nextProps.markd||
            this.props.topicsType!=nextProps.topicsType){
            this.isIFrameLoad = false;
            this.isFirstLoad = true;
            //自动保存上一个
            if(!nextProps.browser)
                this.handleUpload();
            //新的加载
            if(!nextProps.hasBody){
                if(nextProps.topicsType>=1&&nextProps.topicsType<=3){
                    //自动根据标记的类型进自动转换
                }else{
                    //这里先做选择题判断
                    //不是判断题?
                }
            }else{
                //如果已经有过编辑设置手动
                this.setState({isAuto:false});
            }
            //确定模式
            let mode = "html";
            let content = "";
            if('seat' in nextProps){
                if(nextProps.seat==0){
                    content = nextProps.source;
                }else if(nextProps.seat==1){
                    content = nextProps.content;
                }else if(nextProps.seat==2){
                    mode = "markd";
                }else{
                    content = nextProps.content?nextProps.content:nextProps.source;
                }
            }else{
                content = nextProps.content?nextProps.content:nextProps.source;
            }
            this.setState({isContentChange:false,//新加载都是没有改变
                topicsType:nextProps.topicsType,
                mode:mode,
                content:content,
                seat:nextProps.seat,
                markd:nextProps.markd});
        }
    }
    componentWillUnmount(){
    }
    handleHTMLContent(){
        this.setState({expendHTML:!this.state.expendHTML});
    }
    recalcIFrameSize(){
        let height = 0;
        if(this.state.mode==="html"){
            for(let i = 0;i<this.body.children.length;i++){
                height += this.body.children[i].scrollHeight;
            }
        }else{
            height = this.markd.getHeight();
            if(!height)height=0;
            this.markd.doFullScreen();
        }
        this.setState({iframeHeight:height<32?32:height});
    }
    onHtmlContentChange(content){
        //去掉内部操作用的JavaScript代码,见tkeditor.toHtmlDocument
        let dom = htmldom.parseDOM(content);
        let newcontent = htmldom.writeHTML(dom,(node)=>{
            if(node.type=="script" && 'inner-script' in node.attribs){
                return null;
            }
            return node;
        });
        this.state.htmlContent = newcontent;
        this.setState({htmlContent:newcontent});
    }
    handleLoad(){
        if(this.state.mode=="html"){
            if(this.iframe&&this.iframe.contentDocument&&this.iframe.contentDocument.body){
                var id;
                var document = this.iframe.contentDocument;
                var body = document.body;
                this.content = body.outerHTML;
                this.document = document;
                this.body = body;
                this.isIFrameLoad = true; //标记已经装载
                if(this.isFirstLoad){
                    this.sourceContent = body.outerHTML;
                    this.isFirstLoad = false;
                }
                //this.state.htmlContent = this.content;
                this.onHtmlContentChange(this.content);
                var cb = (()=>{
                    clearInterval(id);
                    this.recalcIFrameSize();
                }).bind(this);
                /**
                 * 这里可能还没有计算出布局,因此scrollHeight可能不准确
                 * 如果在100ms秒后再设置一回height将会基本正常。
                 */
                cb();
                id = setInterval(cb,100);
                if(!this.props.browser){
                    /**
                     * 这里打开编辑功能
                     */
                    document.designMode = 'on';
                    document.contentEditable=true;
                    document.onkeyup=this.handleKeyup.bind(this);
                }
            }else{
                this.setState({iframeHeight:0,
                    topicsType:this.props.topicsType});
            }
        }else{//markd
            if(this.isIFrameLoad){
                return;
            }
            if(this.markd && this.markd.iframe){
                var id;
                var document = this.markd.iframe.contentDocument;
                var body = document.body;
                this.content = body.outerHTML;
                this.document = document;
                this.body = body;
                this.isIFrameLoad = true; //标记已经装载
                if(this.isFirstLoad){
                    this.sourceContent = body.outerHTML;
                    this.isFirstLoad = false;
                }
                var cb = (()=>{
                    clearInterval(id);
                    this.recalcIFrameSize();
                }).bind(this);
                cb();
                id = setInterval(cb,510);
            }else{
                this.setState({iframeHeight:0,
                    topicsType:this.props.topicsType});
            }
        }
    }
    //弹出原题
    handlePopUrl(){
        window.open(this.props.source);
    }
    //切换到自动
    handleAutoClick(){
        this.setState({isAuto:true});
        this.automaticOption();
    }
    //切换到手动
    handleManualClick(){
        this.setState({isAuto:false});
    }
    //选择题,填空题..., DropDownMenu选择
    handleDropDownMenuChange(event,index,value){
        if(this.state.mode=="html"){
            this.handleReset();
            //上面的调用将重新装载,并触发iframe.onLoad函数
            function cb(){
                if(this.isIFrameLoad) //已经加载完成
                    clearInterval(id);
                else
                    return; //继续等待知道加载完成

                if(value!=this.props.topicsType){
                    this.setState({isContentChange:true});
                }

                if(this.state.isAuto){
                    if(value==1){
                        this.automaticOption();
                    }else{
                        this.setState({isAuto:false});
                    }
                }
                if(value==3){
                    //自动在最后面插入输入横线
                    var lastNode = null;
                    for(let i = this.body.children.length-1;i>=0;i--){
                        if(this.body.children[i].tagName in {"DD":1,"DIV":1,"SPAN":1} ){
                            lastNode = this.body.children[i];
                        }
                    }
                    if(!lastNode)
                        lastNode = this.body;
                    let input = document.createElement('input');
                    input.setAttribute('type','text');
                    input.setAttribute('size','64');
                    input.setAttribute('answer-feild2','');
                    input.setAttribute('onchange','answer_onchange(this);');
                    input.setAttribute('onkeyup','answer_onchange(this);');
                    lastNode.appendChild(document.createElement('br'));
                    lastNode.appendChild(input);
                    this.onHtmlContentChange(this.body.outerHTML);
                    this.recalcIFrameSize();
                }
                this.setState({topicsType:value});
            }
            var id = setInterval(cb.bind(this),100);
        }else{//markd
            this.setState({isMarkdContentChange:true,topicsType:value});
        }
    }
    //将选择的内容转换为交互按键
    handleOptionClick(event){
        let option = event.target.textContent;
        let map1 = {'A':1,'B':2,'C':3,'D':4,'E':5,'F':6};
        let map2 = [' ','A','B','C','D','E','F'];
        let value = `#0${map1[option]}FFFF`;
        this.document.execCommand('backcolor',false,value);
        this.checkChange();

        forChildren(this.body,(node)=>{
            //发现要找的节点
            let attr = getAttribute(node,'style');
            if(attr){
                let patten = /background-color:\s*rgb\((\d+),\s*(\d+),\s*(\d+)\);/;
                let result = attr.nodeValue.match(patten);
                console.log(attr.nodeValue);
                if(result){
                    let r = Number(result[1]);
                    let option2 = map2[r];
                    node.removeAttribute('style');
                    node.setAttribute('option-btn',option2);
                    node.setAttribute('onclick','option_onclick(this);');
                    //通知改变并且调整编辑区大小
                    this.checkChange();
                    return true;
                }
            }
            return false;
        });
        console.log(option);
    }
    //将选择的内容转换为填空
    handleFeildClick(event){
        this.document.execCommand('cut',false,null);
        this.document.execCommand('inserthtml',false,
        '<input type="text" size="1" answer-feild="" onchange="answer_onchange(this);" onkeyup="answer_onchange(this);"></input>');
        this.checkChange();
        console.log("handleFeildClick");
    }
    /**
     * 分析this.props.content的内容,自动做选项转换操作
     * 如果成功返回true,失败返回false
     */
    automaticOption(){
        let [result,answer] = optionAuto(this.state.content,this.props.answer);
        if(result){
            this.isIFrameLoad = false;
            this.iframe.srcdoc = result;
            let a = answer ? `答案为${answer}`:'但未解析出正确答案';
            this.messageBar(`成功转化为选择题,${a}.`,1);
            this.state.isContentChange = true;
            this.setState({isContentChange:true});
        }else{
            this.messageBar('不能自动转换为选择题');
        }
    }
    //检查看看文档内容是不是改变了
    checkChange(){
        var id = setInterval((()=>{
            clearInterval(id);
            this.handleKeyup();
        }).bind(this),100);
    }
    //重新编辑
    handleReset(){
        if(this.state.mode=="html"){
            this.isIFrameLoad = false;
            this.iframe.srcdoc = this.props.source;
            this.setState({content:this.props.source});
            this.checkChange();
        }else{//markd
            this.setState({isMarkdContentChange:true,
                markd:this.props.markd});
        }
    }
    messageBar(msg,p){
        if(this.props.messageBar)
            this.props.messageBar(msg,p);
    }
    //上传
    handleUpload(event){
        if(this.state.mode=="html"){
            if(this.state.isContentChange){
                this.state.isContentChange = false;
                //因为使用handleKeyup不能侦测到全部的改变,这里强制更新
                this.onHtmlContentChange(this.body.outerHTML);
                var updateData = {mode:'html'};
                switch(this.props.type){
                    case 1: //body
                        updateData.state = this.state.topicsType;
                        updateData.seat_body = 1;
                        updateData.body = this.state.htmlContent;
                        break;
                    case 2: //answer
                        updateData.seat_answer = 1;
                        updateData.answer = this.state.htmlContent;
                        break;
                    case 3: //analysis
                        updateData.seat_analysis = 1;
                        updateData.analysis = this.state.htmlContent;
                        break;
                    case 4: //tag
                        updateData.seat_tag = 1;
                        updateData.tag = this.state.htmlContent;
                        break;
                }
                /**
                 * 通知更新
                 */
                if(this.props.onSave){
                    this.props.onSave(updateData);
                }
                /**
                 * 如果html模式下确保情况对应markd格式的数据
                 */
                fetch(`upload?QuestionID=${this.props.qid}`,
                    {method:'POST',
                    headers: {'Content-Type': 'application/json'},
                    body:JSON.stringify(updateData)}).then(function(responese){
                    return responese.text();
                }).then(function(data){
                    if(data!='ok'){
                        this.messageBar(data);
                    }else{
                        this.setState({isContentChange:false});
                        this.messageBar('成功保存',1);
                    }
                }.bind(this)).catch(function(e){
                    this.messageBar(e.toString());
                }.bind(this));
            }else if(event){
                this.messageBar('没有任何改变');
            }
        }else{//markd
            if(this.state.isMarkdContentChange){
                this.state.isMarkdContentChange = false;
                var updateData = {mode:'markd'};
                switch(this.props.type){
                    case 1: //body
                        updateData.seat_body = 2;
                        updateData.state = this.state.topicsType;
                        updateData.markd_body = this.markd.getMarkdown();
                        break;
                    case 2: //answer
                        updateData.seat_answer = 2;
                        updateData.markd_answer = this.markd.getMarkdown();
                        break;
                    case 3: //analysis
                        updateData.seat_analysis = 2;
                        updateData.markd_analysis = this.markd.getMarkdown();
                        break;
                    case 4: //tag
                        updateData.seat_tag = 2;
                        updateData.markd_tag = this.markd.getMarkdown();
                        break;
                }
                /**
                 * 通知更新
                 */
                if(this.props.onSave){
                    this.props.onSave(updateData);
                }
                fetch(`upload?QuestionID=${this.props.qid}`,
                    {method:'POST',
                    headers: {'Content-Type': 'application/json'},
                    body:JSON.stringify(updateData)}).then(function(responese){
                    return responese.text();
                }).then(function(data){
                    if(data!='ok'){
                        this.messageBar(data);
                    }else{
                        this.setState({isMarkdContentChange:false});
                        this.messageBar('成功保存',1);
                    }
                }.bind(this)).catch(function(e){
                    this.messageBar(e.toString());
                }.bind(this));
            }else if(event){
                this.messageBar('内容没有任何改变');
            }
        }
    }
    //加载上次上传
    handleLoadPrev(){
        if(this.state.mode=="html"){
            this.isIFrameLoad = false;
            this.iframe.srcdoc = this.props.content;
            this.setState({
                topicsType:this.props.topicsType,
                isContentChange:false});
        }else{//markd
            this.isIFrameLoad = false;
            this.setState({isMarkdContentChange:true,
                markd:this.props.markd});
        }
    }
    relayout(){
        var id;
        let cb = function(){
            clearInterval(id);
            if(this.body && this.body.onload)
                this.body.onload();
            this.recalcIFrameSize();
        };
        id = setInterval(cb.bind(this),200);
    }
    //使用keyup事件跟踪文档的变化
    handleKeyup(event){
        if(this.state.mode=="html"){
            if(this.body.outerHTML!=this.sourceContent || this.state.topicsType!=this.props.topicsType){
                this.setState({isContentChange:true});
            }else{
                this.setState({isContentChange:false});
            }
            if(this.body.outerHTML!=this.sourceContent){
                this.onHtmlContentChange(this.body.outerHTML);
                this.recalcIFrameSize();
            }
        }else{//markd
            //TkMarkd有改变
            let cur = this.markd.getMarkdown();
            if(cur!=this.props.markd && !(this.props.markd==null && cur.length==0)){
                this.setState({isMarkdContentChange:true});
            }else{
                this.setState({isMarkdContentChange:false});
            }
            this.recalcIFrameSize();
        }
    }
    //交互测试
    handleTest(event){
        if(this.state.mode=="html"){
            if(this.body && this.body.outerHTML){
                this.state.testContent = this.body.outerHTML;
                this.setState({openTestDialog:true});
            }else{
                this.messageBar("没有要测试的内容!");
            }
        }else{//markd
            if(this.markd){
                this.state.testContent = this.markd.getMarkdown();
                this.setState({openTestDialog:true});
            }else{
                this.messageBar("没有要测试的内容!");
            }
        }
    }
    handleTestClose(event){
        this.setState({openTestDialog:false});
    }
    //使用Markdown重新进行编辑
    handleMarkdown(){
        if(this.state.mode=="markd"){
            this.state.markd = this.markd.getMarkdown();
            this.setState({mode:"html",
            isContentChange:true,
            seat:1});
        }else if(this.state.mode=="html"){
            this.setState({mode:"markd",
            isMarkdContentChange:true,
            seat:2});
        }
    }
    //当在浏览模式下点击了编辑
    handleBrowserEdit(index,event){
        this.props.onEdit(index);
    }
	render(){
        let tool,saveTool,optionTool,topic_image,content;
       // if(!this.state.content || this.state.content.length===0){
       //     return null;
       // }
        if(this.props.type==0){
            topic_image = <p style={{textAlign:'center'}}>
                <img frameBorder={0}
            style={{margin:'auto',
            width:'60%'}}
            src={this.props.content}/>
            </p>;
            tool = <a href="javascript:;" onClick={this.handlePopUrl.bind(this)}>{this.props.tid}</a>;
        }
        if(this.props.type>=1 && this.props.type<=4){
            if(this.state.mode=="html"){
                content = (<iframe
                onLoad={this.handleLoad.bind(this)}
                ref = {(iframe)=>{this.iframe = iframe}}
                height = {this.state.iframeHeight}
                style={{width:'100%',border:0}}
                srcDoc={this.state.content}>
                </iframe>);
            }else if(this.state.mode=="markd"){
                content = <TkMarkd
                preview = {this.props.browser}
                qid = {this.props.qid}
                onLoad={this.handleLoad.bind(this)}
                ref = {(iframe)=>{this.markd = iframe}}
                content = {this.state.markd}
                onkeyup = {this.handleKeyup.bind(this)}
                height={this.state.iframeHeight<320?320:this.state.iframeHeight}>
                </TkMarkd>;
            }
        }
        if(this.props.type>=1 && this.props.type<=4){
                let c;
                if(this.state.mode=="html"){
                    c = this.state.isContentChange?warningColor:toolbarIconColor;
                }else{
                    c = this.state.isMarkdContentChange?warningColor:toolbarIconColor;
                }
                saveTool = [
                    <IconButton tooltip='重新编辑' onClick={this.handleReset.bind(this)}>
                        <TkReset color={toolbarIconColor}/>
                    </IconButton>/*,
                    <IconButton tooltip='装入上次编辑内容' onClick={this.handleLoadPrev.bind(this)}>
                        <TkDownload color={toolbarIconColor}/>
                    </IconButton>,
                    <IconButton tooltip='存储入库' onClick={this.handleUpload.bind(this)}>
                        <TkUpload  color={c}/>
                </IconButton>*/];
                /*
                if(this.props.type==1){
                    saveTool.push(
                        <IconButton tooltip='交互测试' onClick={this.handleTest.bind(this)}>
                            <TkTest  color={toolbarIconColor}/>
                        </IconButton>);
                }*/
                saveTool.push(
                    <IconButton tooltip='切换Markdown' onClick={this.handleMarkdown.bind(this)}>
                        <TkMarkdown  color={toolbarIconColor}/>
                    </IconButton>);
                saveTool.push(<ToolbarSeparator/>);
            if((this.state.topicsType==1 ||this.state.topicsType==2)&&this.state.mode=="html"){
                tool = [];
                if(this.state.topicsType==1){
                    tool.push(<FlatButton
                        label="自动"
                        backgroundColor = {this.state.isAuto?checkColor:undefined}
                        hoverColor = {this.state.isAuto?checkColor:undefined}
                        onClick={this.handleAutoClick.bind(this)}
                        style={{marginLeft:0,marginRight:0}}
                        icon={<TkAutomatic color={toolbarIconColor}/>}>
                    </FlatButton>);
                }
                tool.push(
                <FlatButton
                    label="手动"
                    backgroundColor = {this.state.isAuto?undefined:checkColor}
                    hoverColor = {this.state.isAuto?undefined:checkColor}
                    onClick={this.handleManualClick.bind(this)}
                    style={{marginLeft:0,marginRight:0}}
                    icon={<TkManual color={toolbarIconColor}/>}>
                </FlatButton>);
                tool.push(<ToolbarSeparator />);
            }
            if(this.state.topicsType==1&&this.state.mode=="html"){ //选择题
                if(!this.state.isAuto){ //手动
                    optionTool = ['A','B','C','D','E','F'].map((item)=>{
                        return <FlatButton
                            label={item}
                            onTouchTap={this.handleOptionClick.bind(this)}
                            style={{marginLeft:0,marginRight:0,minWidth:36}}>
                        </FlatButton>;
                    });
                }
            }else if(this.state.topicsType==2&&this.state.mode=="html"){ //填空题
                optionTool = [<FlatButton
                            label={'填空'}
                            onTouchTap={this.handleFeildClick.bind(this)}
                            style={{marginLeft:0,marginRight:0}}>
                        </FlatButton>];
            }
        }
		return (<Page
        transitionEnabled={false}
        style={{margin:32}}>
            <Toolbar style={{backgroundColor:getTypeColor(this.state.topicsType)}}>
                {!this.props.browser?
                <ToolbarGroup>
                    <ToolbarTitle text={this.props.title || 'None'} />
                    {saveTool}
                    {tool}
                    {optionTool}
                </ToolbarGroup>:<ToolbarGroup><ToolbarTitle text={getTypeString(this.state.topicsType)} /></ToolbarGroup>}
                <ToolbarGroup>
                {this.props.type==1 && !this.props.browser &&
                <DropDownMenu value={this.state.topicsType}
                    onChange={this.handleDropDownMenuChange.bind(this)}>
                    <MenuItem value={1} primaryText="选择题" />
                    <MenuItem value={2} primaryText="填空题" />
                    <MenuItem value={3} primaryText="解答题" />
                    <MenuItem value={5} primaryText="连线题" />
                    <MenuItem value={6} primaryText="排序" />
                    <MenuItem value={4} primaryText="其他" />
                    <MenuItem value={-1} primaryText="忽略" />
                    <MenuItem value={0} primaryText="未处理" />
                </DropDownMenu>
                }
                {this.state.mode=="html"&&!this.props.browser?
                    <IconButton touch={true} onTouchTap={this.handleHTMLContent.bind(this)}>
                        <CodeIcon />
                    </IconButton>:undefined}
                {this.props.browser?<IconButton tooltip='编辑' onClick={this.handleBrowserEdit.bind(this,this.props.index)}>
                        <TkBrowserEdit color={toolbarIconColor}/>
                    </IconButton>:undefined}
                </ToolbarGroup>
            </Toolbar>
            {<TkHtmlViewer expend={this.state.expendHTML}>{this.state.htmlContent}</TkHtmlViewer>}
            {topic_image}
            {content}
            <TkTestDailog
                type={this.state.mode=="html"?1:2}
                open={this.state.openTestDialog}
                content={this.state.testContent}
                closeme={this.handleTestClose.bind(this)}
                messageBar={this.messageBar.bind(this)}/>
		</Page>);
	}
};

export default TkFrame;


text:
<?php

namespace Sylius\Bundle\CoreBundle\OrderProcessing;

use Sylius\Bundle\CoreBundle\Model\OrderInterface;
use Sylius\Bundle\CoreBundle\Model\VariantInterface;
use Sylius\Bundle\InventoryBundle\Factory\InventoryUnitFactoryInterface;
use Sylius\Bundle\InventoryBundle\Model\InventoryUnitInterface;
use Sylius\Bundle\InventoryBundle\Operator\InventoryOperatorInterface;

/**
 * Order inventory handler.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
class InventoryHandler implements InventoryHandlerInterface
{
    /**
     * Inventory operator.
     *
     * @var InventoryOperatorInterface
     */
    protected $inventoryOperator;

    /**
     * Inventory unit factory.
     *
     * @var InventoryUnitFactoryInterface
     */
    protected $inventoryUnitFactory;

    /**
     * Constructor.
     *
     * @param InventoryOperatorInterface    $inventoryOperator
     * @param InventoryUnitFactoryInterface $inventoryUnitFactory
     */
    public function __construct(InventoryOperatorInterface $inventoryOperator, InventoryUnitFactoryInterface $inventoryUnitFactory)
    {
        $this->inventoryOperator = $inventoryOperator;
        $this->inventoryUnitFactory = $inventoryUnitFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function processInventoryUnits(OrderInterface $order)
    {
        foreach ($order->getItems() as $item) {
            $variant = $item->getVariant();
            $units = $order->getInventoryUnitsByVariant($variant);

            $quantity = $item->getQuantity();
            $unitsQuantity = count($units);

            if ($quantity > $unitsQuantity) {
                $this->addInventoryUnits($order, $variant, $quantity - $unitsQuantity);
            }
            if ($quantity < $unitsQuantity) {
                $this->removeInventoryUnits($order, $variant, $unitsQuantity - $quantity);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function updateInventory(OrderInterface $order)
    {
        foreach ($order->getItems() as $item) {
            $units = $order->getInventoryUnitsByVariant($item->getVariant());

            foreach ($units as $unit) {
                $unit->setInventoryState(InventoryUnitInterface::STATE_SOLD);
            }

            $this->inventoryOperator->decrease($units);
        }
    }

    /**
     * Add inventory units to order.
     *
     * @param OrderInterface   $order
     * @param VariantInterface $variant
     * @param integer          $quantity
     */
    protected function addInventoryUnits(OrderInterface $order, VariantInterface $variant, $quantity)
    {
        $units = $this->inventoryUnitFactory->create($variant, $quantity, InventoryUnitInterface::STATE_IN_CART);

        foreach ($units as $unit) {
            $order->addInventoryUnit($unit);
        }
    }

    /**
     * Remove inventory units from order.
     *
     * @param OrderInterface   $order
     * @param VariantInterface $variant
     * @param integer          $quantity
     */
    protected function removeInventoryUnits(OrderInterface $order, VariantInterface $variant, $quantity)
    {
        $units = $order->getInventoryUnitsByVariant($variant);

        for ($i = 0; $i < $quantity; $i++) {
            $order->removeInventoryUnit($units[$i]);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
Implementation based on algorithm described in:
The cache performance and optimizations of blocked algorithms
M. D. Lam, E. E. Rothberg, and M. E. Wolf
ASPLOS 1991
*/

#include <stdio.h>
#include <stdlib.h>

//Data Type
#define TYPE double

//Algorithm Parameters
#define row_size 64
#define col_size 64
#define N row_size*col_size
#define block_size 8
#define NUMOFBLOCKS N/block_size/block_size

//Define the input range to operate over
#define MIN 0.
#define MAX 1.0

//Set number of iterations to execute
#define MAX_ITERATION 1

void bbgemm(TYPE m1[N], TYPE m2[N], TYPE prod[N]);
////////////////////////////////////////////////////////////////////////////////
// Test harness interface code.

struct bench_args_t {
  TYPE m1[N];
  TYPE m2[N];
  TYPE prod[N];
};


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Common.Tools.Const
{
    public static class Dispatcher
    {
        public static readonly string PublischTypeName = "@@Type";
        public static readonly string PublischParameterName = "@@Parameter";
        public static readonly string PublischRealTimeName = "@@RealTime";
        public static readonly string PublischHistoryName = "@@History";

        public static readonly string Property_AgentId = "PropertyName_26738efb1a20403fb07383ed9c3ddd9a";
        public static readonly string Property_ContactId = "PropertyName_9dff8fbe54174a7ea84adb4e9a21c252";
        public static readonly string Property_ContactHistoId = "PropertyName_c2ec491a99ae4f65b28c8a5e23da1461";
        public static readonly string Property_InboundId = "PropertyName_eac5c8c32d39495dadbf1c6ebbe6dc96";
        public static readonly string Property_OutboundId = "PropertyName_e9c1c85647754d1789fae5b026398c87";
        public static readonly string Property_QueueId = "PropertyName_ee3490fc19b642cc80cc67f0bee1fac8";
    }
}


text:
<?php

namespace Rx\Functional;

use PHPUnit_Framework_ExpectationFailedException;
use Rx\Scheduler\VirtualTimeScheduler;
use Rx\TestCase;
use Rx\Testing\ColdObservable;
use Rx\Testing\HotObservable;
use Rx\Testing\Subscription;
use Rx\Testing\TestScheduler;

abstract class FunctionalTestCase extends TestCase
{
    /** @var  TestScheduler */
    protected $scheduler;

    public function setup()
    {
        $this->scheduler = $this->createTestScheduler();
    }

    public function assertMessages(array $expected, array $recorded)
    {
        if (count($expected) !== count($recorded)) {
            $this->fail(sprintf('Expected message count %d does not match actual count %d.', count($expected), count($recorded)));
        }

        for ($i = 0, $count = count($expected); $i < $count; $i++) {
            if (!$expected[$i]->equals($recorded[$i])) {
                $this->fail($expected[$i] . ' does not equal ' . $recorded[$i]);
            }
        }

        $this->assertTrue(true); // success
    }

    public function assertSubscription(HotObservable $observable, Subscription $expected)
    {
        $subscriptionCount = count($observable->getSubscriptions());

        if ($subscriptionCount === 0) {
            $this->fail('Observable has no subscriptions.');
        }

        if ($subscriptionCount > 1) {
            $this->fail('Observable has more than 1 subscription.');
        }

        list($actual) = $observable->getSubscriptions();

        if (!$expected->equals($actual)) {
            $this->fail(sprintf("Expected subscription '%s' does not match actual subscription '%s'", $expected, $actual));
        }

        $this->assertTrue(true); // success
    }

    public function assertSubscriptions(array $expected, array $recorded)
    {
        if (count($expected) !== count($recorded)) {
            $this->fail(sprintf('Expected subscription count %d does not match actual count %d.', count($expected), count($recorded)));
        }

        for ($i = 0, $count = count($expected); $i < $count; $i++) {
            if (!$expected[$i]->equals($recorded[$i])) {
                $this->fail($expected[$i] . ' does not equal ' . $recorded[$i]);
            }
        }

        $this->assertTrue(true); // success
    }

    /**
     * @param callable $callback
     */
    protected function assertException(callable $callback)
    {
        try {
            $callback();
        } catch (\Exception $e) {
            return;
        }
        $this->fail('Expected the callback to throw an exception.');
    }

    protected function createColdObservable(array $events)
    {
        return new ColdObservable($this->scheduler, $events);
    }

    protected function createHotObservable(array $events)
    {
        return new HotObservable($this->scheduler, $events);
    }

    protected function createTestScheduler()
    {
        return new TestScheduler();
    }
}


text:
using namespace std;

int main(int argc, char* argv[])
{
    GLASSERT(argc>=4);
    GLAutoContext __c;
    const char* inputfile = argv[1];
    const char* outputfile = argv[2];
    float scale = atof(argv[3]);
    GPPtr<GLBmp> src = new GLBmp(inputfile);
    printf("Origin Picture: %d X %d\n", src->width(), src->height());
    GPPtr<GLBmp> dst = new GLBmp(src->width()*scale, src->height()*scale);
    {
        GPPtr<GLBitmapWork> w = GLBitmapWorkFactory::create("Bicubic");
        w->set(src, dst);
        w->runOnePass();
    }
    dst->save(outputfile);
    return 1;
}


text:
import React, { Component } from 'react';
import ViewActors from './ViewActors';
import ReactMapboxGl, { Layer, Feature, Marker } from 'react-mapbox-gl';
import ReactTimeout from 'react-timeout';

/* ----- COMPONENT ----- */

class Scene extends Component {

  constructor() {
    super();
    this.state = {
      coords: [],
      style: '',
      zoom: 1,
    }
  }

  setInnerHTML(html) {
    return { __html: html }
  }

  setMapJSX(jsx) {
    return { __html: jsx }
  }

  componentWillReceiveProps(nextProps) {
    // to animate map, set initial zoom to something more zoomed out than the actual value
    if (nextProps.maps && nextProps.maps.length) {
      if (!this.state.coords.length) {
        let zoom = nextProps.maps[0].zoom;
        if (zoom > 12) zoom -= 9;
        else if (zoom > 6) zoom -= 3;
        else if (zoom > 2) zoom -= 2;

        this.setState({
          coords: nextProps.maps[0].coords.split(','),
          style: nextProps.maps[0].style,
          zoom: zoom
        });

      } else {
        this.setState({
          coords: nextProps.maps[0].coords.split(','),
          style: nextProps.maps[0].style,
          zoom: nextProps.maps[0].zoom
        });
      }
    } else {
      this.setState({
        coords: [],
        style: '',
        zoom: 1,
      });
    }
  }

  moveOnUp() {
    if (this.state.zoom !== this.props.maps[0].zoom) {
      this.setState({
        coords: this.props.maps[0].coords.split(','),
        style: this.props.maps[0].style,
        zoom: this.props.maps[0].zoom
      });
    }
  }

  render() {
    console.log("this.props", this.props);
    return (

          {
            this.state.style ? (
              <ReactMapboxGl
                style={`mapbox://styles/mapbox/${this.state.style}-v9`}
                accessToken="pk.eyJ1IjoiZm91cmVzdGZpcmUiLCJhIjoiY2oyY2VnbTN2MDJrYTMzbzgxNGV0OWFvdyJ9.whTLmuoah_lfoQhC_abI5w"
                zoom={[this.state.zoom]}
                pitch={30}
                center={this.state.coords}
                containerStyle={{
                  height: "100%",
                  width: "auto"
                }}
                onStyleLoad={this.moveOnUp.bind(this)}
              />
            ) : this.props.heroUnsplash ? (

                    <div
                      className="scene-hero-img-container"
                      style={{ backgroundImage: `url(${this.props.heroURL})` }}
                    />

Photo by {this.props.heroPhotog} / Unsplash

                ) : this.props.heroURL && this.props.heroURL !== 'Not found' ? (

                        <div
                          className="scene-hero-img-container"
                          style={{ backgroundImage: `url(${this.props.heroURL})` }}
                        />

Photo by {this.props.heroPhotog}

                    ) : null
          }

{this.props.storyTitle}

{this.props.currScene.title}

by {this.props.user ? this.props.user.display_name || this.props.user.username : 'anonymous'}

        {
          this.props.actors.length ? (

IN THIS SCENE

              <ViewActors />

          ) : (
              null
            )
        }

    );
  }
}

/* ----- CONTAINER ----- */

import { connect } from 'react-redux';

const mapStateToProps = store => ({
  html: store.displayState.currScene.paragraphsHTML[0],
  actors: store.displayState.currScene.actors,
  storyTitle: store.displayState.title,
  currScene: store.displayState.currScene,
  maps: store.displayState.currScene.maps,
  user: store.displayState.user,
  heroURL: store.displayState.currScene.heroURL,
  heroPhotog: store.displayState.currScene.heroPhotog,
  heroPhotogURL: store.displayState.currScene.heroPhotogURL,
  heroUnsplash: store.displayState.currScene.heroUnsplash
});

export default connect(mapStateToProps)(ReactTimeout(Scene));


text:
"""The logic for Flake8's integration with setuptools."""
from distutils import log
import os
from typing import List, Tuple

import setuptools

from flake8.main import application as app

UNSET = object()

class Flake8(setuptools.Command):
    """Run Flake8 via setuptools/distutils for registered modules."""

    description = "Run Flake8 on modules registered in setup.py"
    # NOTE(sigmavirus24): If we populated this with a list of tuples, users
    # could do something like ``python setup.py flake8 --ignore=E123,E234``
    # but we would have to redefine it and we can't define it dynamically.
    # Since I refuse to copy-and-paste the options here or maintain two lists
    # of options, and since this will break when users use plugins that
    # provide command-line options, we are leaving this empty. If users want
    # to configure this command, they can do so through config files.
    user_options = []  # type: List[str]

    def initialize_options(self):
        """Override this method to initialize our application."""
        self.flake8 = app.Application()
        self.flake8.initialize([])
        options = self.flake8.option_manager.options
        for option in options:
            if option.parse_from_config:
                setattr(self, option.config_name, UNSET)

    def finalize_options(self):
        """Override this to parse the parameters."""
        options = self.flake8.option_manager.options
        for option in options:
            if option.parse_from_config:
                name = option.config_name
                value = getattr(self, name, UNSET)
                if value is UNSET:
                    continue
                setattr(
                    self.flake8.options,
                    name,
                    option.normalize_from_setuptools(value),
                )

    def package_files(self):
        """Collect the files/dirs included in the registered modules."""
        seen_package_directories = ()  # type: Tuple[str, ...]
        directories = self.distribution.package_dir or {}
        empty_directory_exists = "" in directories
        packages = self.distribution.packages or []
        for package in packages:
            package_directory = package
            if package in directories:
                package_directory = directories[package]
            elif empty_directory_exists:
                package_directory = os.path.join(
                    directories[""], package_directory
                )

            # NOTE(sigmavirus24): Do not collect submodules, e.g.,
            # if we have:
            #  - flake8/
            #  - flake8/plugins/
            # Flake8 only needs ``flake8/`` to be provided. It will
            # recurse on its own.
            if package_directory.startswith(seen_package_directories):
                continue

            seen_package_directories += (package_directory + ".",)
            yield package_directory

    def module_files(self):
        """Collect the files listed as py_modules."""
        modules = self.distribution.py_modules or []
        filename_from = "{0}.py".format
        for module in modules:
            yield filename_from(module)

    def distribution_files(self):
        """Collect package and module files."""
        for package in self.package_files():
            yield package

        for module in self.module_files():
            yield module

        yield "setup.py"

    def run(self):
        """Run the Flake8 application."""
        self.flake8.run_checks(list(self.distribution_files()))
        self.flake8.formatter.start()
        self.flake8.report_errors()
        self.flake8.report_statistics()
        self.flake8.report_benchmarks()
        self.flake8.formatter.stop()
        try:
            self.flake8.exit()
        except SystemExit as e:
            # Cause system exit only if exit code is not zero (terminates
            # other possibly remaining/pending setuptools commands).
            if e.code:
                raise
        finally:
            self.announce(
                "WARNING: flake8 setuptools integration is deprecated and "
                "scheduled for removal in 4.x.  For more information, see "
                "https://gitlab.com/pycqa/flake8/issues/544",
                log.WARN,
            )


text:
@interface ICCollectionViewCell ()

@property (nonatomic, strong, readwrite) UILabel *textLabel;

@end

@implementation ICCollectionViewCell

- (UILabel *)textLabel {
    if (!_textLabel) {
        self.textLabel = [[UILabel alloc] init];
        [self.contentView addSubview:_textLabel];
    }
    return _textLabel;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    self.textLabel.frame = self.contentView.bounds;
}

@end


text:
import fs from 'fs';
import path from 'path';
import mkdirp from 'mkdirp';
import Promise from 'bluebird';
import { filter, includes, map, bind, template, each, extend } from 'lodash'

// The new seeds we're performing, typically called from the `knex.seed`
// interface on the main `knex` object. Passes the `knex` instance performing
// the seeds.
function Seeder(knex) {
  this.knex = knex;
  this.config = this.setConfig(knex.client.config.seeds);
}

// Runs all seed files for the given environment.
Seeder.prototype.run = Promise.method(function(config) {
  this.config = this.setConfig(config);
  return this._seedData()
    .bind(this)
    .spread(function(all) {
      return this._runSeeds(all);
    });
});

// Creates a new seed file, with a given name.
Seeder.prototype.make = function(name, config) {
  this.config = this.setConfig(config);
  if (!name) Promise.rejected(new Error('A name must be specified for the generated seed'));
  return this._ensureFolder(config)
    .bind(this)
    .then(this._generateStubTemplate)
    .then(this._writeNewSeed(name));
};

// Lists all available seed files as a sorted array.
Seeder.prototype._listAll = Promise.method(function(config) {
  this.config = this.setConfig(config);
  return Promise.promisify(fs.readdir, {context: fs})(this._absoluteConfigDir())
    .bind(this)
    .then(seeds =>
      filter(seeds, function(value) {
        const extension = path.extname(value);
        return includes(
          ['.co', '.coffee', '.eg', '.iced', '.js', '.litcoffee', '.ls', '.ts'], extension);
      }).sort()
    );
});

// Gets the seed file list from the specified seed directory.
Seeder.prototype._seedData = function() {
  return Promise.join(this._listAll());
};

// Ensures a folder for the seeds exist, dependent on the
// seed config settings.
Seeder.prototype._ensureFolder = function() {
  const dir = this._absoluteConfigDir();
  return Promise.promisify(fs.stat, {context: fs})(dir)
    .catch(() => Promise.promisify(mkdirp)(dir));
};

// Run seed files, in sequence.
Seeder.prototype._runSeeds = function(seeds) {
  return Promise.all(map(seeds, bind(this._validateSeedStructure, this)))
    .bind(this)
    .then(function(seeds) {
      return Promise.bind(this)
        .then(function() {
          return this._waterfallBatch(seeds);
        });
    });
};

// Validates seed files by requiring and checking for a `seed` function.
Seeder.prototype._validateSeedStructure = function(name) {
  const seed = require(path.join(this._absoluteConfigDir(), name));
  if (typeof seed.seed !== 'function') {
    throw new Error(`Invalid seed file: ${name} must have a seed function`);
  }
  return name;
};

// Generates the stub template for the current seed file, returning a compiled template.
Seeder.prototype._generateStubTemplate = function() {
  const stubPath = this.config.stub ||
    path.join(__dirname, 'stub', this.config.extension + '.stub');
  return Promise.promisify(fs.readFile, {context: fs})(stubPath).then(stub =>
    template(stub.toString(), {variable: 'd'})
  );
};

// Write a new seed to disk, using the config and generated filename,
// passing any `variables` given in the config to the template.
Seeder.prototype._writeNewSeed = function(name) {
  const { config } = this;
  const dir = this._absoluteConfigDir();
  return function(tmpl) {
    if (name[0] === '-') name = name.slice(1);
    const filename = name + '.' + config.extension;
    return Promise.promisify(fs.writeFile, {context: fs})(
      path.join(dir, filename),
      tmpl(config.variables || {})
    ).return(path.join(dir, filename));
  };
};

// Runs a batch of seed files.
Seeder.prototype._waterfallBatch = function(seeds) {
  const { knex } = this;
  const seedDirectory = this._absoluteConfigDir();
  let current = Promise.bind({failed: false, failedOn: 0});
  const log = [];
  each(seeds, function(seed) {
    const name = path.join(seedDirectory, seed);
    seed = require(name);

    // Run each seed file.
    current = current.then(() => seed.seed(knex, Promise)).then(function() {
      log.push(name);
    });
  });

  return current.thenReturn([log]);
};

Seeder.prototype._absoluteConfigDir = function() {
  return path.resolve(process.cwd(), this.config.directory);
};

Seeder.prototype.setConfig = function(config) {
  return extend({
    extension: 'js',
    directory: './seeds'
  }, this.config || {}, config);
};

export default Seeder;


text:
package org.kaaproject.kaa.server.admin.client.mvp.view.config;

import org.kaaproject.avro.ui.gwt.client.widget.grid.AbstractGrid;
import org.kaaproject.kaa.common.dto.ConfigurationSchemaDto;
import org.kaaproject.kaa.server.admin.client.mvp.view.base.BaseListViewImpl;
import org.kaaproject.kaa.server.admin.client.util.Utils;

public class ConfigurationSchemasViewImpl extends BaseListViewImpl<ConfigurationSchemaDto> {

    public ConfigurationSchemasViewImpl() {
        super(true);
    }

    @Override
    protected AbstractGrid<ConfigurationSchemaDto, String> createGrid() {
        return new ConfigSchemaGrid();
    }

    @Override
    protected String titleString() {
        return Utils.constants.configurationSchemas();
    }

    @Override
    protected String addButtonString() {
        return Utils.constants.addNewSchema();
    }

}


text:
// vim:ts=4:sw=4:expandtab
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <yajl/yajl_gen.h>
#include <yajl/yajl_version.h>

#include "i3status.h"

#if defined(LINUX)
#include <linux/ethtool.h>
#include <linux/sockios.h>
#define PART_ETHSPEED "E: %s (%d Mbit/s)"
#endif

#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
#include <net/if_media.h>

#define PART_ETHSPEED "E: %s (%s)"
#endif

#if defined(__OpenBSD__) || defined(__NetBSD__)
#include <errno.h>
#include <net/if_media.h>
#endif

static int print_eth_speed(char *outwalk, const char *interface) {
#if defined(LINUX)
    /* This code path requires root privileges */
    int ethspeed = 0;
    struct ifreq ifr;
    struct ethtool_cmd ecmd;

    ecmd.cmd = ETHTOOL_GSET;
    (void)memset(&ifr, 0, sizeof(ifr));
    ifr.ifr_data = (caddr_t)&ecmd;
    (void)strcpy(ifr.ifr_name, interface);
    if (ioctl(general_socket, SIOCETHTOOL, &ifr) == 0) {
        ethspeed = (ecmd.speed == USHRT_MAX ? 0 : ecmd.speed);
        return sprintf(outwalk, "%d Mbit/s", ethspeed);
    } else
        return sprintf(outwalk, "?");
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
    const char *ethspeed;
    struct ifmediareq ifm;
    (void)memset(&ifm, 0, sizeof(ifm));
    (void)strncpy(ifm.ifm_name, interface, sizeof(ifm.ifm_name));
    int ret;
#ifdef SIOCGIFXMEDIA
    ret = ioctl(general_socket, SIOCGIFXMEDIA, (caddr_t)&ifm);
    if (ret < 0)
#endif
        ret = ioctl(general_socket, SIOCGIFMEDIA, (caddr_t)&ifm);
    if (ret < 0)
        return sprintf(outwalk, "?");

    /* Get the description of the media type, partially taken from
     * FreeBSD's ifconfig */
    const struct ifmedia_description *desc;
    static struct ifmedia_description ifm_subtype_descriptions[] =
        IFM_SUBTYPE_ETHERNET_DESCRIPTIONS;

    if (IFM_TYPE(ifm.ifm_active) != IFM_ETHER)
        return sprintf(outwalk, "?");
    if (ifm.ifm_status & IFM_AVALID && !(ifm.ifm_status & IFM_ACTIVE))
        return sprintf(outwalk, "no carrier");
    for (desc = ifm_subtype_descriptions;
         desc->ifmt_string != NULL;
         desc++) {
        if (desc->ifmt_word == IFM_SUBTYPE(ifm.ifm_active))
            break;
    }
    ethspeed = (desc->ifmt_string != NULL ? desc->ifmt_string : "?");
    return sprintf(outwalk, "%s", ethspeed);
#elif defined(__OpenBSD__) || defined(__NetBSD__)
    const char *ethspeed;
    struct ifmediareq ifmr;

    (void)memset(&ifmr, 0, sizeof(ifmr));
    (void)strlcpy(ifmr.ifm_name, interface, sizeof(ifmr.ifm_name));

    if (ioctl(general_socket, SIOCGIFMEDIA, (caddr_t)&ifmr) < 0) {
        if (errno != E2BIG)
            return sprintf(outwalk, "?");
    }

    struct ifmedia_description *desc;
    struct ifmedia_description ifm_subtype_descriptions[] =
        IFM_SUBTYPE_DESCRIPTIONS;

    for (desc = ifm_subtype_descriptions; desc->ifmt_string != NULL; desc++) {
        /*
		 * Skip these non-informative values and go right ahead to the
		 * actual speeds.
		 */
        if (BEGINS_WITH(desc->ifmt_string, "autoselect") ||
            BEGINS_WITH(desc->ifmt_string, "auto"))
            continue;

        if (IFM_TYPE_MATCH(desc->ifmt_word, ifmr.ifm_active) &&
            IFM_SUBTYPE(desc->ifmt_word) == IFM_SUBTYPE(ifmr.ifm_active))
            break;
    }
    ethspeed = (desc->ifmt_string != NULL ? desc->ifmt_string : "?");
    return sprintf(outwalk, "%s", ethspeed);

#else
    return sprintf(outwalk, "?");
#endif
}

/*
 * Combines ethernet IP addresses and speed (if requested) for displaying
 *
 */
void print_eth_info(yajl_gen json_gen, char *buffer, const char *interface, const char *format_up, const char *format_down) {
    const char *walk;
    const char *ip_address = get_ip_addr(interface);
    char *outwalk = buffer;

    INSTANCE(interface);

    if (ip_address == NULL) {
        START_COLOR("color_bad");
        outwalk += sprintf(outwalk, "%s", format_down);
        goto out;
    }

    if (BEGINS_WITH(ip_address, "no IP"))
        START_COLOR("color_degraded");
    else
        START_COLOR("color_good");

    for (walk = format_up; *walk != '\0'; walk++) {
        if (*walk != '%') {
            *(outwalk++) = *walk;
            continue;
        }

        if (BEGINS_WITH(walk + 1, "ip")) {
            outwalk += sprintf(outwalk, "%s", ip_address);
            walk += strlen("ip");
        } else if (BEGINS_WITH(walk + 1, "speed")) {
            outwalk += print_eth_speed(outwalk, interface);
            walk += strlen("speed");
        }
    }

out:
    END_COLOR;
    OUTPUT_FULL_TEXT(buffer);
}


text:
echo "Running SQL Server docker image..."
docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=p@ssw0rd' --name "mssql-server" -d -p 1433:1433 mcr.microsoft.com/mssql/server:2017-CU12-ubuntu

docker ps | grep "mssql-server"
retVal=$?
if [ $retVal == 0 ]; then
    echo "SQL Server docker image is running."
else
    echo "SQL Server docker image failed to start."
    exit $retVal
fi

sudo docker exec -it mssql-server /opt/mssql-tools/bin/sqlcmd \
   -S localhost -U SA -P 'p@ssw0rd' -Q 'CREATE DATABASE audit;'

sudo docker exec -it mssql-server /opt/mssql-tools/bin/sqlcmd \
   -S localhost -U SA -P 'p@ssw0rd' -Q 'CREATE DATABASE saml;'

sudo docker exec -it mssql-server /opt/mssql-tools/bin/sqlcmd \
   -S localhost -U SA -P 'p@ssw0rd' -Q 'CREATE DATABASE samlidp;'

sudo docker exec -it mssql-server /opt/mssql-tools/bin/sqlcmd \
   -S localhost -U SA -P 'p@ssw0rd' -Q 'CREATE DATABASE services;'


text:
namespace Avalonia.LinuxFramebuffer.Output
{
    public interface IOutputBackend
    {
        PixelSize PixelSize { get; }
        double Scaling { get; set; }
    }
}


text:
![alt tag](http://i.imgur.com/yEJOsKH.png?1)

# Não Me Calo

O intuito do projeto Não Me Calo é mapear as áreas onde foram registrados assédios, tanto verbais como físicos, disponibilizando um espaço de compartilhamento de experiências, com depoimentos, rankings e avaliações dos estabelecimentos que possuem falhas na segurança para mulheres.
Além de registrar ocorrências de abusos e assédios, as mulheres usuárias do website podem pesquisar registros de outros locais e até responder ocorrências de outras mulheres, como uma forma de apoio à vítima ou complemento de informações.
Com base nas informações compartilhadas, podemos cobrar dos estabelecimentos avaliados que se responsabilizem por melhorias na segurança para as mulheres.

## Sobre o projeto

Não Me Calo é um projeto criado por um grupo de cinco meninas durante a edição brasileira do evento [Ignite International Girls Hackaton 2015](http://ignite.globalfundforwomen.org/) , que tem como tema "Como construir iniciativas que resultem em ambientes mais seguros para garotas?".

## Colabore

O Não Me Calo é um projeto de código aberto, ou seja, você pode usar nosso código-fonte em seus próprios projetos, ou nos ajudar a aprimorar o Não Me Calo!

Você pode baixar o projeto em formato .zip [clicando aqui](https://github.com/karenkgs/NaoMeCalo/archive/master.zip), ou pela linha de comando, usando o Git:

    $ git clone https://github.com/karenkgs/NaoMeCalo.git

Entrar na pasta do projeto:

    $ cd NaoMeCalo

E para executá-lo, basta abrir as páginas com a extensão .html em seu browser de preferência (Chrome, Firefox, Opera, etc).


text:
import {combineReducers} from 'redux';
import itemListReducer from './reducer-items';

const allReducers = combineReducers({
    itemList: itemListReducer
});

export default allReducers


text:
package gigasecond

import "time"

// Gigasecond - 10*9 seconds || 1 billion seconds
const Gigasecond = 1e9 * time.Second

// AddGigasecond - time + Gigasecond
func AddGigasecond(t time.Time) time.Time {
	return t.Add(Gigasecond)
}


text:
'use strict';

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.RedisCache = undefined;

var _extend = require('extend');

var _extend2 = _interopRequireDefault(_extend);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var DEFAULT_OPTIONS = {
	'expire': 60 * 60, // 1hr
	'json': true,
	'rejectOnNull': false,
	'prefix': null
};

var RedisCache = (function () {
	function RedisCache(client) {
		var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

		_classCallCheck(this, RedisCache);

		if (!client) throw new Error('redis client required');
		this._client = client;
		this._options = (0, _extend2.default)({}, DEFAULT_OPTIONS, options);
	}

	/**
  * Try to parse a JSON value or return the original value
 **/

	_createClass(RedisCache, [{
		key: '_parseJSON',
		value: function _parseJSON(value) {
			try {
				value = JSON.parse(value);
			} catch (e) {}
			return value;
		}

		/**
   * Try to stringify a JSON value or return the original value
  **/

	}, {
		key: '_stringifyJSON',
		value: function _stringifyJSON(value) {
			try {
				value = JSON.stringify(value);
			} catch (e) {}
			return value;
		}

		/**
   * Prefixes the key
  **/

	}, {
		key: '_prefix',
		value: function _prefix(key) {
			var prefix = arguments.length <= 1 || arguments[1] === undefined ? this._options.prefix : arguments[1];

			if (prefix !== null) key = prefix + key;
			return key;
		}

		/**
   * Fetch a key from the cache
  **/

	}, {
		key: 'fetch',
		value: function fetch(key) {
			var _this = this;

			var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

			options = (0, _extend2.default)({}, this._options, options);
			key = this._prefix(key, options.prefix);
			return new Promise(function (resolve, reject) {
				_this._client.get(key, function (err, reply) {
					if (err) return reject(err);
					if (options.rejectOnNull && reply === null) return reject(new Error('reply is null'));
					if (options.json) reply = _this._parseJSON(reply);
					return resolve(reply);
				});
			});
		}

		/**
   * Convenience method for fetch()
  **/

	}, {
		key: 'get',
		value: function get(key) {
			var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

			return this.fetch(key, options);
		}

		/**
   * Set a key in the cache
  **/

	}, {
		key: 'set',
		value: function set(key, value) {
			var _this2 = this;

			var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];

			options = (0, _extend2.default)({}, this._options, options);
			key = this._prefix(key, options.prefix);
			return new Promise(function (resolve, reject) {
				if (options.json) value = _this2._stringifyJSON(value);
				_this2._client.set(key, value, function (err, reply) {
					if (err) return reject(err);
					if (options.expire) _this2._client.expire(key, options.expire);
					return resolve(reply === 'OK' ? true : false);
				});
			});
		}

		/**
   * Delete a key from the cache
  **/

	}, {
		key: 'del',
		value: function del(key) {
			var _this3 = this;

			key = this._prefix(key);
			return new Promise(function (resolve, reject) {
				_this3._client.del(key, function (err, reply) {
					if (err) return reject(err);
					return resolve(reply);
				});
			});
		}

		/**
   * Get the Time-To-Live (TTL) for a key
  **/

	}, {
		key: 'ttl',
		value: function ttl(key) {
			var _this4 = this;

			key = this._prefix(key);
			return new Promise(function (resolve, reject) {
				_this4._client.ttl(key, function (err, reply) {
					if (err) return reject(err);
					if (_this4._options.rejectOnNull && reply === -2) return reject(new Error('key does not exist'));
					return resolve(reply);
				});
			});
		}

		/**
   * Check if a key exists
  **/

	}, {
		key: 'exists',
		value: function exists(key) {
			var _this5 = this;

			key = this._prefix(key);
			return new Promise(function (resolve, reject) {
				_this5._client.exists(key, function (err, reply) {
					if (err) return reject(err);
					return resolve(reply === 1 ? true : false);
				});
			});
		}

		/**
   * Set expiry time on a key
  **/

	}, {
		key: 'expire',
		value: function expire(key) {
			var _this6 = this;

			var _expire = arguments.length <= 1 || arguments[1] === undefined ? this._options.expire : arguments[1];

			key = this._prefix(key);
			return new Promise(function (resolve, reject) {
				_this6._client.expire(key, _expire, function (err, reply) {
					if (err) return reject(err);
					return resolve(reply === 1 ? true : false);
				});
			});
		}

		/**
   * Remove expiry on a key
  **/

	}, {
		key: 'persist',
		value: function persist(key) {
			var _this7 = this;

			key = this._prefix(key);
			return new Promise(function (resolve, reject) {
				_this7._client.persist(key, function (err, reply) {
					if (err) return reject(err);
					return resolve(reply == 1 ? true : false);
				});
			});
		}

		/**
   * Split the class into a new instance using the same Redis client
  **/

	}, {
		key: 'split',
		value: function split() {
			var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
			var useDefaultOptions = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];

			options = (0, _extend2.default)({}, useDefaultOptions ? DEFAULT_OPTIONS : this._options, options);
			return new RedisCache(this._client, options);
		}
	}]);

	return RedisCache;
})();

exports.RedisCache = RedisCache;


text:
      {% include "partials/menu.svg" %}

      {% include "partials/logo.svg" %}

      Add job


text:
const configuration = require("../config/config.js");

const auth = {
    login(email, password, callBack) {
      callBack = arguments[arguments.length - 1];
      if (localStorage.access_token) {
        if (callBack) {
          callBack(200);
        }
        return;
      }
      this._callLogin(email, password, callBack);
    },

    retrieveUser(encodedJWT, callBack) {
      const xhr = new XMLHttpRequest();

      xhr.onreadystatechange = (function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if (xhr.status < 200 || xhr.status > 299) {
            if (xhr.status === 400) {
              console.info('fail [' + xhr.status + ']');
            } else {
              console.info('fail [' + xhr.status + ']');
            }
          } else {
            // try to get a name out of the user response.
            const user = JSON.parse(xhr.responseText).user;
            this._writeLocalStorage(user);
            if (callBack) {
              callBack();
            }
          }
        }
      }).bind(this);

      configuration(function(config) {
        xhr.open('GET', config.fusionauth.backendUrl + '/api/user', true);
        xhr.setRequestHeader('Authorization', 'JWT ' + encodedJWT);
        xhr.send();
      });

    },

    logout(callBack) {
      delete localStorage.access_token;
      delete localStorage.userId;
      delete localStorage.email;
      delete localStorage.name;
      if (callBack) {
        callBack();
      }
    },

    loggedIn() {
      return !!localStorage.access_token;
    },

    register(email, password, firstName, lastName, callBack) {
      const requestBody = {
        user: {
          email: email,
          password: password,
          firstName: firstName,
          lastName: lastName
        }
      };

      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = (function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if (xhr.status < 200 || xhr.status > 299) {
            this._handleErrors(xhr, callBack, ['user.username']);
          } else {
            // After a successful registration, log the user in
            this.login(email, password, (status, response) => {
              if (status === 200) {
                localStorage.access_token = response.token;
                localStorage.userId = response.user.id;
                if (callBack) {
                  callBack(xhr.status);
                }
              }
            });
          }
        }
      }).bind(this);

      configuration(function(config) {
        xhr.open('POST', config.todo.url + '/api/fusionauth/register', true);
        xhr.setRequestHeader("Content-type", "application/json");

        const jsonRequest = JSON.stringify(requestBody);
        xhr.send(jsonRequest);
      });

    },

    _callToken(email, password, callBack) {
      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = (function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if (xhr.status < 200 || xhr.status > 299) {
            this._handleErrors(xhr, callBack, []);
          } else {
            // Success, parse the response and grab the token and then retrieve the user to get their name.
            if (xhr.status === 200) {
              const response = JSON.parse(xhr.responseText);
              this.retrieveUser(response.access_token, () => {
                if (callBack) {
                  callBack(xhr.status, response);
                }
              });
            } else {
              if (callBack) {
                callBack(xhr.status);
              }
            }
          }
        }
      }).bind(this);

      configuration(function(config) {
        const data = new FormData();
        data.append('loginId', email);
        data.append('password', password);
        data.append('grant_type', 'password');
        data.append('client_id', config.fusionauth.applicationId);

        xhr.open('POST', config.fusionauth.frontendUrl + '/oauth2/token', true);
        xhr.send(data);
      });

    },

    _callLogin(email, password, callBack) {
      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = (function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if (xhr.status === 404) {
            const errors = [];
            errors.push('[InvalidLogin]');
            callBack(xhr.status, errors);
          } else if (xhr.status < 200 || xhr.status > 299) {
            this._handleErrors(xhr, callBack, []);
          } else {
            // Success, parse the response and grab the token and then retrieve the user to get their name.
            if (xhr.status === 200) {
              const successResponse = JSON.parse(xhr.responseText);
              if (callBack) {
                this._writeLocalStorage(successResponse.user);
                callBack(xhr.status, successResponse);
              }
            } else {
              if (callBack) {
                callBack(xhr.status);
              }
            }
          }
        }
      }).bind(this);

      configuration(function(config) {
        const loginRequest = {
          loginId: email,
          password: password,
          applicationId: config.fusionauth.applicationId,
          device: 'Web Browser',
          metaData: {
            device: {
              description: 'IBM Cloud Web Example',
              type: 'BROWSER',
              name: 'Brian\'s Laptop'
            }
          }
        };
        xhr.open('POST', config.fusionauth.backendUrl + '/api/login', true);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.send(JSON.stringify(loginRequest));
      });

    },

    _handleErrors(xhr, callBack, ignoredFields) {
      if (xhr.status === 400) {
        const errors = [];
        const errorResponse = JSON.parse(xhr.responseText);
        this._parseErrors(errorResponse, errors, ignoredFields || []);

        if (callBack) {
          callBack(xhr.status, errors);
        }
      } else {
        console.info('fail [' + xhr.status + ']');
        if (callBack) {
          callBack(xhr.status);
        }
      }
    },

    _parseErrors(errorResponse, errors, ignoredFields) {
      if (errorResponse.generalErrors && errorResponse.generalErrors.length > 0) {
        errors.push(errorResponse.generalErrors[0].message);
      } else {
        // Using email for registration, ignore username errors
        for (let property in errorResponse.fieldErrors) {
          // Ignore errors if requested
          if (ignoredFields.indexOf(property) !== -1) {
            continue;
          }

          if (errorResponse.fieldErrors.hasOwnProperty(property)) {
            for (let i = 0; i < errorResponse.fieldErrors[property].length; i++) {

              errors.push(errorResponse.fieldErrors[property][i].code);
            }
          }
        }
      }
    },

    _writeLocalStorage(user) {
      localStorage.email = user.email;
      if (user.firstName && user.lastName) {
        localStorage.name = user.firstName + ' ' + user.lastName;
      } else if (user.firstName) {
        localStorage.name = user.firstName;
      } else if (user.username) {
        localStorage.name = user.username;
      } else {
        localStorage.name = user.email;
      }
    }
};

export default auth;


text:
namespace Exceptionless.Core.Queues.Models;

public class MailMessage {
    public string To { get; set; }
    public string From { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
}


text:
typedef enum {

    SWScrollViewPageControlAlimentRight,
    SWScrollViewPageControlAlimentCenter
}SWScrollViewPageControlAliment;

typedef enum {
    SWScrollViewPageControlStyleClassic,
    SWScrollViewPageControlStyleAnimated,
    SWScrollViewPageControlStyleNone
}SWScrollViewPageControlStyle;

@class SWScrollView ;

@protocol SWScrollViewDelegate <NSObject>

@optional
//点击图片回调
- (void)ScrollView:(SWScrollView *)scrollView didSelectItemAtIndex:(NSInteger)index;
//图片滚动回调
- (void)ScrollView:(SWScrollView *)scrollView didScrollToIndex:(NSInteger)index;

@end

@interface SWScrollView : UIView
//初始化
+ (instancetype)scrollViewWithFrame:(CGRect)frame delegate:(id<SWScrollViewDelegate>)delegate placeholderIamge:(UIImage *)placeholderImage;

+ (instancetype)scrollViewWithFrame:(CGRect)frame imageURLStringsGroup:(NSArray *)imageURLStringGroup;

//本地图片初始化
+ (instancetype)scrollViewWithframe:(CGRect)frame imageNamesGroup:(NSArray *)imageNamesGroup;
//本地初始化方式二,
+ (instancetype)scrollViewWithFrame:(CGRect)frame shouldInfiniteLoop:(BOOL)infiniteLoop imageNamesGroup:(NSArray *)imageNamesGroup;

///数据源接口///
@property (nonatomic, strong) NSArray *imageURLStringsGroup;

@property (nonatomic,strong) NSArray *titlesGroup;

@property (nonatomic,strong) NSArray *localizationImageNamesGroup;

///滚动视图接口///

///间隔时间
@property (nonatomic,assign) CGFloat  autoScrollTimeInterval;

///是否无线循环
@property (nonatomic,assign) BOOL infiniteLoop;

@property (nonatomic,assign) BOOL  autoScroll;

@property (nonatomic,assign) UICollectionViewScrollDirection  scrollDirection;

@property (nonatomic,weak) id<SWScrollViewDelegate> delegate;

@property (nonatomic,copy) void (^clickItemOperationBlock)(NSInteger currentIndex);

@property (nonatomic,copy) void (^itemDidScrollOperationBlcok)(NSInteger currentIndex);

//解决 viewWillAppear 时出现时轮播图卡在一半的问题,在控制器 viewWillApppear 时调用此方法

- (void)adjustWhenControllerViewWillAppear;

///自定义接口////

//轮播图片的 ContentMode ,默认为 UIviewContentModeScaleToFill///
@property (nonatomic,assign) UIViewContentMode  bannerImageViewContentMode;

//占位图
@property (nonatomic,strong) UIImage *placeholderImage;

@property (nonatomic,assign) BOOL showPageControl;

@property (nonatomic) BOOL hidesForSinglePage;

@property (nonatomic,assign) BOOL  onlyDisplayText;

@property (nonatomic,assign) SWScrollViewPageControlStyle pageControlStyle;

@property (nonatomic,assign) SWScrollViewPageControlAliment pageControlAliment;

//分页控件距离轮播图的底部间距
@property (nonatomic,assign) CGFloat pageControlBottomOffset;

//分页控件距离轮播图右边间距
@property (nonatomic,assign) CGFloat  pageControlRightOffset;

//图标大小
@property (nonatomic,assign) CGSize pageControlDotSize;
//分页控件图标颜色
@property (nonatomic,strong) UIColor *currentPageDotColor;
//其他控件颜色
@property (nonatomic,strong) UIColor *pageDotColor;
//当前控件图片
@property (nonatomic,strong) UIImage *currentPageDotImage;
//其他图片
@property (nonatomic,strong) UIImage *pageDotImage;
//文字 Label 字体颜色
@property (nonatomic,strong) UIColor *titleLabelTextColor;
//文字 label 字体大小
@property (nonatomic,strong) UIFont *titleLabelTextFont;
//文字 label 背景色
@property (nonatomic,strong) UIColor *titleLabelBackgroundColor;
//label 高度
@property (nonatomic,assign) CGFloat titleLabelHeight;
//label 对齐方式
@property (nonatomic,assign) NSTextAlignment titleLabelTextAlignment;

///清楚缓存接口

//清楚图片缓存
+ (void)clearImageCache;

//清除图片缓存
- (void)clearCache;

@end


text:
#pragma once

#include <string>
#include <vector>

#include "imports/std/optional"

#include "api.hpp"
#include "ActivationData.hpp"
#include "basic_Error.hpp"
#include "Customer.hpp"
#include "DataObject.hpp"
#include "RawLicenseKey.hpp"

namespace cryptolens_io {

namespace v20190401 {

class LicenseKeyChecker;

/**
 * This immutable class represents a license key.
 *
 * The class is constructed using the static factory make().
 *
 * The check() method can be used to create a LicenseKeyChecker,
 * which can be used to check properties of a license key in a
 * convenient fashion. I.e.
 *
 *     if (key.check().has_feature(1).has_not_feature(2)) {
 *       DO_SOMETHING();
 *     }
 */
class LicenseKeyInformation {
private:
  LicenseKeyInformation();

  int           product_id_;
  std::uint64_t created_;
  std::uint64_t expires_;
  int           period_;
  bool          block_;
  bool          trial_activation_;
  std::uint64_t sign_date_;
  bool          f1_;
  bool          f2_;
  bool          f3_;
  bool          f4_;
  bool          f5_;
  bool          f6_;
  bool          f7_;
  bool          f8_;

  optional<int>                         id_;
  optional<std::string>                 key_;
  optional<std::string>                 notes_;
  optional<int>                         global_id_;
  optional<Customer>                    customer_;
  optional<std::vector<ActivationData>> activated_machines_;
  optional<int>                         maxnoofmachines_;
  optional<std::string>                 allowed_machines_;
  optional<std::vector<DataObject>>     data_objects_;
public:
  LicenseKeyInformation(
    api::internal::main,
    int           product_id,
    std::uint64_t created,
    std::uint64_t expires,
    int           period,
    bool          block,
    bool          trial_activation,
    std::uint64_t sign_date,
    bool          f1,
    bool          f2,
    bool          f3,
    bool          f4,
    bool          f5,
    bool          f6,
    bool          f7,
    bool          f8,

    optional<int>                         id,
    optional<std::string>                 key,
    optional<std::string>                 notes,
    optional<int>                         global_id,
    optional<Customer>                    customer,
    optional<std::vector<ActivationData>> activated_machines,
    optional<int>                         maxnoofmachines,
    optional<std::string>                 allowed_machines,
    optional<std::vector<DataObject>>     data_objects
  );

#if 1
  static optional<LicenseKeyInformation> make(basic_Error & e, RawLicenseKey const& raw_license_key);
  static optional<LicenseKeyInformation> make(basic_Error & e, optional<RawLicenseKey> const& raw_license_key);
  static optional<LicenseKeyInformation> make_unsafe(basic_Error & e, std::string const& license_key);
#endif

  LicenseKeyChecker check() const;

  int           get_product_id() const;
  std::uint64_t get_created() const;
  std::uint64_t get_expires() const;
  int           get_period() const;
  bool          get_block() const;
  bool          get_trial_activation() const;
  std::uint64_t get_sign_date() const;
  bool          get_f1() const;
  bool          get_f2() const;
  bool          get_f3() const;
  bool          get_f4() const;
  bool          get_f5() const;
  bool          get_f6() const;
  bool          get_f7() const;
  bool          get_f8() const;

  optional<int>                         const& get_id() const;
  optional<std::string>                 const& get_key() const;
  optional<std::string>                 const& get_notes() const;
  optional<int>                         const& get_global_id() const;
  optional<Customer>                    const& get_customer() const;
  optional<std::vector<ActivationData>> const& get_activated_machines() const;
  optional<int>                         const& get_maxnoofmachines() const;
  optional<std::string>                 const& get_allowed_machines() const;
  optional<std::vector<DataObject>>     const& get_data_objects() const;
};

} // namespace v20190401

namespace v20180502 {

using LicenseKeyInformation = ::cryptolens_io::v20190401::LicenseKeyInformation;

} // namespace v20180502

namespace latest {

using LicenseKeyInformation = ::cryptolens_io::v20190401::LicenseKeyInformation;

} // namespace latest

} // namespace cryptolens_io


text:
const { isEmpty, set, forEach, get } = require('lodash')

const { getNextPath } = require('./helpers')
const { joinPaths } = require('../../lib/path')
const state = require('./state/current')
const { getErrors } = require('./errors')

const setJourneyDetails = (journey, currentStep, currentStepId) => {
  return (req, res, next) => {
    res.locals.journey = {
      currentStep,
      currentStepId,
      ...journey,
      key: joinPaths([req.baseUrl, journey.steps[0].path]),
    }

    next()
  }
}

const postDetails = async (req, res, next) => {
  const { currentStep, key } = res.locals.journey
  const errors = getErrors(currentStep.macro(res.locals).children, req.body)

  if (!isEmpty(errors)) {
    set(res.locals, 'form.errors.messages', errors)
    state.update(req.session, key, currentStep.path, { completed: false })
    return next()
  }

  if (currentStep.done) {
    const data = state.reduceSteps(req.session, key)

    try {
      const response = await currentStep.done.send(data)

      state.remove(req.session, key)
      req.flash('success', currentStep.done.message)
      res.redirect(
        joinPaths([res.locals.returnLink, currentStep.done.nextPath(response)])
      )
    } catch (err) {
      state.update(req.session, key, currentStep.path, { completed: false })
      if (err.statusCode === 400) {
        set(res.locals, 'form.errors.messages', err.error)
        return next()
      } else {
        return next(err)
      }
    }
  } else {
    const nextPath = getNextPath(currentStep, req.body)
    state.update(req.session, key, currentStep.path, {
      completed: true,
      nextPath,
    })
    res.redirect(joinPaths([req.baseUrl, nextPath]))
  }
}

const setBreadcrumbs = (req, res, next) => {
  const breadcrumbs = [
    ...(res.locals.journey.breadcrumbs || []),
    ...(res.locals.journey.currentStep.breadcrumbs || []),
  ]

  forEach(breadcrumbs, (breadcrumb) => {
    res.breadcrumb(breadcrumb.text, breadcrumb.href)
  })

  next()
}

const renderTemplate = (req, res) => {
  const { type, heading, macro } = res.locals.journey.currentStep

  res.render(`_layouts/${type}`, {
    heading,
    form: {
      ...res.locals.form,
      ...macro({
        ...res.locals,
        errors: get(res.locals, 'form.errors.messages'),
        state: get(res.locals, 'form.state'),
        returnLink: get(res.locals, 'form.returnLink'),
        returnText: get(res.locals, 'form.returnText'),
      }),
    },
  })
}

module.exports = {
  setJourneyDetails,
  postDetails,
  setBreadcrumbs,
  renderTemplate,
}


text:
import React from 'react'
import { storiesOf } from '@storybook/react'
import wrapStory from './decorators/wrapStory'

import Spinner from '../src/components/spinner/demos/Spinner.js'
import SpinnerSingleColor from '../src/components/spinner/demos/SpinnerSingleColor.js'

storiesOf('Spinner', module)
  .addDecorator(wrapStory)
  .add('Spinner', () => <Spinner />)
  .add('Spinner Single Color', () => <SpinnerSingleColor />)


text:
<?php
namespace Topxia\WebBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Topxia\Common\ArrayToolkit;

class LessonLessonPluginController extends BaseController
{

    public function listAction (Request $request)
    {
        $user = $this->getCurrentUser();
        list($course, $member) = $this->getCourseService()->tryTakeCourse($request->query->get('courseId'));

        $items = $this->getCourseService()->getCourseItems($course['id']);
        $learnStatuses = $this->getCourseService()->getUserLearnLessonStatuses($user['id'], $course['id']);

        $homeworkPlugin = $this->getAppService()->findInstallApp('Homework');
        $homeworkLessonIds =array();
        $exercisesLessonIds =array();

        $testpaperIds = array();
        array_walk($items, function($item, $key)use(&$testpaperIds){
            if($item['type'] == 'testpaper'){
                array_push($testpaperIds, $item['mediaId']);
            }
        });

        $testpapers = $this->getTestpaperService()->findTestpapersByIds($testpaperIds);

        if($homeworkPlugin) {
            $lessons = $this->getCourseService()->getCourseLessons($course['id']);
            $lessonIds = ArrayToolkit::column($lessons, 'id');
            $homeworks = $this->getHomeworkService()->findHomeworksByCourseIdAndLessonIds($course['id'], $lessonIds);
            $exercises = $this->getExerciseService()->findExercisesByLessonIds($lessonIds);
            $homeworkLessonIds = ArrayToolkit::column($homeworks,'lessonId');
            $exercisesLessonIds = ArrayToolkit::column($exercises,'lessonId');
        }

        return $this->render('TopxiaWebBundle:LessonLessonPlugin:list.html.twig', array(
            'course' => $course,
            'items' => $items,
            'learnStatuses' => $learnStatuses,
            'currentTime' => time(),
            'weeks' => array($this->getServiceKernel()->trans('日'),$this->getServiceKernel()->trans('一'),$this->getServiceKernel()->trans('二'),$this->getServiceKernel()->trans('三'),$this->getServiceKernel()->trans('四'),$this->getServiceKernel()->trans('五'),$this->getServiceKernel()->trans('六')),
            'homeworkLessonIds' => $homeworkLessonIds,
            'exercisesLessonIds' => $exercisesLessonIds,
            'member' => $member,
            'testpapers' => $testpapers
        ));
    }

    protected function getCourseService()
    {
        return $this->getServiceKernel()->createService('Course.CourseService');
    }

    protected function getAppService()
    {
        return $this->getServiceKernel()->createService('CloudPlatform.AppService');
    }

    protected function getHomeworkService()
    {
        return $this->getServiceKernel()->createService('Homework:Homework.HomeworkService');
    }

    protected function getExerciseService()
    {
        return $this->getServiceKernel()->createService('Homework:Homework.ExerciseService');
    }

    protected function getTestpaperService()
    {
        return $this->getServiceKernel()->createService('Testpaper.TestpaperService');
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Task Schema
 */
var TaskSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  name: {
    type: String,
    default: '',
    trim: true,
    required: 'You need to specify a name'
  },
  description: {
    type: String,
    default: '',
    trim: true
  },
  members: [{
    type: Schema.ObjectId,
    ref: 'User'
  }],
  list: {
    type: Schema.ObjectId,
    ref: 'List'
  },
  project: {
    type: Schema.ObjectId,
    ref: 'Project'
  }

});

mongoose.model('Task', TaskSchema);


text:
ACCEPTED

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

#### Published in
null

#### Original name
Pedilanthus jamaicensis Millsp. & Britton

### Remarks
null