text:
/*http路由分发
接口模式server/:app/:api
*/

var _rotr = {};

//http请求的路由控制
_rotr = new $router();

//访问的请求
_rotr.get('api', '/api/:apiname', apihandler);
_rotr.post('api', '/api/:apiname', apihandler);
var _mysql=require('./_mysql');
var _ctnu = require('./ctnu');

/*所有api处理函数都收集到这里
必须是返回promise
各个api处理函数用promise衔接,return传递ctx
*/
_rotr.apis = {};

/*处理Api请求
默认tenk的api直接使用
每个app的独立api格式appname_apiname
*/
function * apihandler(next) {
    var ctx = this;
    var apinm = ctx.params.apiname;

    console.log('API RECV:', apinm);

    //匹配到路由函数,路由函数异常自动返回错误,创建xdat用来传递共享数据
    var apifn = _rotr.apis[apinm];
    ctx.xdat = {
        apiName: apinm
    };

    if (apifn && apifn.constructor == Function) {
        yield apifn.call(ctx, next).then(function() {

            //所有接口都支持JSONP,限定xx.x.xmgc360.com域名
            var jsonpCallback = ctx.query.callback || ctx.request.body.callback;
            if (jsonpCallback && ctx.body) {
                if (_cfg.regx.crossDomains.test(ctx.hostname)) {
                    ctx.body = ctx.query.callback + '(' + JSON.stringify(ctx.body) + ')';
                };
            };

        }, function(err) {
            ctx.body = __newMsg(__errCode.APIERR, [err.message, 'API proc failed:' + apinm + '.']);
            __errhdlr(err);
        });
    } else {
        ctx.body = __newMsg(__errCode.NOTFOUND, ['服务端找不到接口程序', 'API miss:' + apinm + '.']);
    };

    yield next;
};

/*测试接口,返回请求的数据
 */
_rotr.apis.test = function() {
    var ctx = this;
    var co = $co(function * () {

        var resdat = {
            query: ctx.query.nick,
            body: ctx.body,
        };

        ctx.body = __newMsg(1, 'ok', resdat);
        return ctx;
    });
    return co;
};

//更多的相关查询以及跳转,,(没有技术含量,待改进)

//更多视频

_rotr.apis.more = function() {
    var ctx = this;
    var co = $co(function* () {
        var sqlstr="select VideoId,OverPeople,Imgpath,VideoName from mydb.video where VideoPrice = 0";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat= rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.more1 = function() {
    var ctx = this;
    var co = $co(function* () {
        var sqlstr="select VideoId,OverPeople,ImgPath,VideoName,VideoPrice from mydb.video where Purchase > 0";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat= rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.more2 = function() {
    var ctx = this;
    var co = $co(function* () {
        var sqlstr="select VideoId,OverPeople,ImgPath,VideoName,VideoPrice from mydb.video where VideoPrice > 1";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat= rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.mianfei = function() {
    var ctx = this;
    var co = $co(function* () {
        var sqlstr="select VideoId,VideoName,ImgPath from video where VideoPrice='0' and VideoGround='是' order by OverPeople limit 4";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat= rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.changxiao = function() {
    var ctx = this;
    var co = $co(function* () {
        var sqlstr="select VideoId,VideoName,ImgPath,VideoPrice from video where VideoPrice>'0' and VideoGround='是' order by Purchase limit 4";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat= rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.haoke = function() {
    var ctx = this;
    var co = $co(function* () {
        var sqlstr="select VideoId,VideoName,ImgPath,VideoPrice from video where VideoGround='是' order by OverPeople and VideoPrice='0' limit 4";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat= rows;
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.courseType = function() {
    var res={};
    var ctx = this;
    var co = $co(function* () {

        var sqlstr="select ClassId,ClassName from class";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        console.log(rows);
        dat= rows;
        ctx.body = dat;
        return ctx;
    });
    return co;
};
//课程类型添加
_rotr.apis.courseTypeadd = function() {
    var res={};
    var ctx = this;
    var co = $co(function* () {
        var id = ctx.query.id || ctx.request.body.id;
        var name = ctx.query.name || ctx.request.body.name;
        var sqlstr="insert into class set ClassId='"+id+"',ClassName='"+name+"'";
        var dat={};
        var regResult;
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        else{
            regResult=1;
        }
        dat= regResult;
        ctx.body = dat;
        return ctx;
    });
    return co;
};

//视频类型
_rotr.apis.videoType = function() {
    var res={};
    var ctx = this;
    var co = $co(function* () {

        var sqlstr="SELECT VideoclassId,VideoclassName,ClassName FROM videoclass,class where" +
            " videoclass.ClassId=class.ClassId";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");

        dat= rows;
        ctx.body = dat;
        return ctx;
    });
    return co;
};
_rotr.apis.videoSelect = function() {//视频类型查询
    var res={};
    var ctx = this;
    var co = $co(function* () {
        var dat={};
        var VideoclassId = ctx.query.VideoclassId || ctx.request.body.VideoclassId;
        var id = ctx.query.ClassId || ctx.request.body.ClassId;
        var VideoclassName = ctx.query.VideoclassName || ctx.request.body.VideoclassName;
        var mianfei = ctx.query.mianfei || ctx.request.body.mianfei;
        var fufei = ctx.query.fufei || ctx.request.body.fufei;
        var zuixin = ctx.query.zuixin || ctx.request.body.zuixin;
        var remen = ctx.query.remen || ctx.request.body.remen;
        //var sqlstr="SELECT VideoclassId,VideoclassName,ClassId,ClassName FROM Alltypes ";
        if(VideoclassName){
            var sqlstr1="select VideoclassId from videoclass where VideoclassName='"+VideoclassName+"'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr1);
        }
        if(id){
            var sqlstr="SELECT VideoclassName,VideoclassId FROM videoclass where ClassId='"+id+"'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        }
        if(VideoclassId){
            var sqlstr2="select * from video where VideoclassId='"+VideoclassId+"' and VideoGround='是'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr2);
        }
        if(mianfei){
            var sqlstr3="select * from video where VideoclassId='"+mianfei+"' and VideoGround='是' and VideoPrice='0'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr3);
        }
        if(fufei){
            var sqlstr4="select * from video where VideoclassId='"+fufei+"' and VideoGround='是' and VideoPrice>'0'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr4);
        }
        if(zuixin){
            var sqlstr5="select * from video where VideoclassId='"+zuixin+"' and VideoGround='是' order by time desc";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr5);
        }
        if(remen){
            var sqlstr6="select * from video where VideoclassId='"+remen+"' and VideoGround='是' order by OverPeople desc";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr6);
            console.log(rows);
        }
        if(!rows)throw Error("失败");

        dat= rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.Select = function() {//视频个数查询
    var res={};
    var ctx = this;
    var co = $co(function* () {
        var dat={};
        var VideoclassId = ctx.query.VideoclassId || ctx.request.body.VideoclassId;
        var ClassName=ctx.query.ClassName || ctx.request.body.ClassName;
        if(VideoclassId){
            var sqlstr="select count(*) as 总数 from video where VideoclassId='"+VideoclassId+"' and VideoGround='是'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);}
        if(ClassName){
            var sqlstr1="select ClassId from class where ClassName='"+ClassName+"'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr1);
        }
        if(!rows)throw Error("失败");

        dat= rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

//视频类型删除准备
_rotr.apis.selectvideoType=function(){
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var name = ctx.query.name || ctx.request.body.name;
        var regResult;
        var sqlstr="select count(*) FROM video where VideoclassId='"+name+"'";
        var dat={};
        var row=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!row)throw Error("失败");
        dat=row[0]['count(*)'];
        ctx.body=dat;
        return ctx;
    });
    return co;
};

//视频类型删除
_rotr.apis.deletvideoType=function(){
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var name = ctx.query.name || ctx.request.body.name;
        var regResult;
        var sqlstr="delete FROM videoclass where VideoclassId='"+name+"'";
        var dat={};
        var row=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!row)throw Error("失败");
        else{
            regResult=1;
        }
        dat=(regResult);
        ctx.body=dat;
        return ctx;
    });
    return co;
};
//视频类型增加
_rotr.apis.typeAdd = function() {
    var ctx = this;
    var co = $co(function* () {
        var id = ctx.query.id || ctx.request.body.id;
        var name = ctx.query.name || ctx.request.body.name;
        var type = ctx.query.type || ctx.request.body.type;
        var regResult;
        var sqlstr="insert into videoclass set VideoclassId='"+id+"',VideoclassName='"+ name +"',ClassId=(select ClassId from class where ClassName='"+type+"')";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);

        if(!rows)throw Error("失败");
        else{
            regResult=1;
        }

        dat=(regResult);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.xianshi= function() {//视频显示
    var res={};
    var ctx = this;
    var co = $co(function* () {
        var dat={};
        var id = ctx.query.VideoclassId || ctx.request.body.VideoclassId;
        var ClassId = ctx.query.ClassId || ctx.request.body.ClassId;
        if(id){
            var sqlstr="SELECT VideoName,VideoSyno,VideoPrice,VideoGood,OverPeople," +
                "VideoPath,ImgPath FROM video where VideoGround='是' and VideoclassId='"+id+"'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);}
        if(ClassId){
            var sqlstr1="select * from videoclass " +
                "inner join video on videoclass.VideoclassId=video.VideoclassId and VideoGround='是' and ClassId='"+ClassId+"'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr1);
        }
        if(!rows)throw Error("失败");
        dat= rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

//可新增判断语句,判断是否上传过
_rotr.apis.upload= function() {//视频上传
    var res={};
    var ctx = this;
    var co = $co(function* () {
        var VideoName = ctx.query.VideoName || ctx.request.body.VideoName;
        var VideoSyno=ctx.query.VideoSyno || ctx.request.body.VideoSyno;
        var VideoPrice = ctx.query.VideoPrice || ctx.request.body.VideoPrice;
        var time = ctx.query.time || ctx.request.body.time;
        var VideoclassId = ctx.query.VideoclassId || ctx.request.body.VideoclassId;
        var VideoPath = ctx.query.VideoPath || ctx.request.body.VideoPath;
        var ImgPath = ctx.query.ImgPath || ctx.request.body.ImgPath;
        var UserId = ctx.query.UserId || ctx.request.body.UserId;
        var sqlstr="insert into video (VideoName,VideoSyno,VideoPrice,time,VideoGround,VideoclassId,VideoPath,ImgPath,UserId) values ('"+VideoName+"','"+VideoSyno+"','"+VideoPrice+"','"+time+"','否','"+VideoclassId+"','"+VideoPath+"','"+ImgPath+"','"+UserId+"')";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        console.log("视频名称:"+VideoName+"价格:"+VideoPrice+"时间:"+time+"类型ID:"+VideoclassId+"视频路径:"+VideoPath+"图片路径:"+ImgPath+"用户:"+UserId);
        if(!rows)throw Error("失败");
        else{
            var regResult=1;
        }

        dat=regResult;
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.video= function() {//视频管理
    var res={};
    var ctx = this;
    var co = $co(function* () {
        var id = ctx.query.VideoclassId || ctx.request.body.VideoclassId;
        var sqlstr="SELECT VideoId,VideoName,VideoclassName,time,UserName,VideoSyno,VideoPrice,VideoGround,VideoPath" +
            " FROM videoclass,video,user " +
            "where video.videoclassId=videoclass.videoclassId and user.UserId=video.UserId and VideoGround='是'";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat= rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.video1= function() {//视频管理
    var res={};
    var ctx = this;
    var co = $co(function* () {
        var sqlstr="SELECT VideoId,VideoName,VideoclassName,time,UserName,VideoSyno,VideoPrice,VideoGround,VideoPath" +
            " FROM videoclass,video,user " +
            "where video.videoclassId=videoclass.videoclassId and user.UserId=video.UserId and VideoGround='否'";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat= rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

//视频编辑
_rotr.apis.videoUpdate=function(){
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var id = ctx.query.id || ctx.request.body.id;
        var jiage = ctx.query.price || ctx.request.body.price;
        var shangjia = ctx.query.grounding || ctx.request.body.grounding;
        console.log(id+jiage,shangjia);
        var sqlstr="update video set VideoPrice='"+jiage+"',VideoGround='"+shangjia+"' where VideoId='"+id+"'";
        var dat={};
        var row=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!row)throw Error("失败");
        else{
            var regResult=1;
        }
        res=regResult;
        ctx.body=res;
        return ctx;
    });
    return co;
};

//视频删除
_rotr.apis.deletvideo=function(){
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var name = ctx.query.name || ctx.request.body.name;
        var dat={};
        var sqlstr="delete FROM video where VideoId="+name;
        var row=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!row)throw Error("失败");
        else{
            var regResult=1;
        }
        res=regResult;
        ctx.body=res;
        return ctx;
    });
    return co;
};

//用户
_rotr.apis.use= function() {
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var sqlstr="select UserId,UserName,UserType FROM user";
        var dat={};
        var row=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!row)throw Error("失败");

        dat=row;
        ctx.body=dat;
        return ctx;
    });
    return co;
};

//用户删除准备
_rotr.apis.selectusr=function(){
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var dat={};
        var name = ctx.query.name || ctx.request.body.name;
        var res;
        var sqlstr="select count(*) FROM video where UserId="+name;
        var row=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!row)throw Error("失败");
        dat=row[0]['count(*)'];
        console.log(dat);
        ctx.body=dat;
        return ctx;
    });
    return co;
};

//用户删除
_rotr.apis.deleteusr=function(){
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var name = ctx.query.name || ctx.request.body.name;
        var sqlstr="delete FROM user where UserId="+name;
        var dat={};
        var row=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!row)throw Error("失败");
        else{
            var regResult=1;
        }
        res=regResult;
        ctx.body=res;
        return ctx;
    });
    return co;
};

//级联列表关联
_rotr.apis.Type = function() {
    var res={};
    var ctx = this;
    var name = ctx.query.name || ctx.request.body.name;
    var co = $co(function* () {
        var sqlstr="select VideoclassName from videoclass where ClassId=" +
            "(select ClassId from class where ClassName='"+name+"')";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");

        dat= rows;
        console.log(name);
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.uploadPage= function() {//我的上传
    var res={};
    var ctx = this;
    var co = $co(function* () {
        var userId = ctx.query.userId || ctx.request.body.userId;
        var sqlstr="select VideoId,VideoName,VideoSyno,VideoPrice,time,VideoGround,VideoPath,ImgPath from video where UserId='"+userId+"'";
        var dat={};
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat=rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.UserType = function(){//用户类型查询
    var ctx = this;
    var co = $co(function * () {
        var userId = ctx.query.id || ctx.request.body.id;
        var dat={};
        var sqlstr="select ImgPath,UserNick,UserType,UserName from user where UserId='"+userId+"'";
        var rows = yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat = rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.selectshopp = function(){//添加准备
    var ctx = this;
    var co = $co(function * () {
        var userId = ctx.query.userId || ctx.request.body.userId;
        var videoId=ctx.query.videoId || ctx.request.body.videoId;
        var dat={};
        var sqlstr="select * from orderinfo where VideoId='"+videoId+"' and UserId='"+userId+"'";
        var rows = yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat=rows;
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.shopping = function(){//购物车添加
    var ctx = this;
    var co = $co(function * () {
        var userId = ctx.query.userId || ctx.request.body.userId;
        var videoId=ctx.query.videoId || ctx.request.body.videoId;
        var dat={};
        var sqlstr="insert into orderinfo (VideoId,UserId) values ('"+videoId+"','"+userId+"')";
        var rows = yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        else{
            var result=1;
        }
        dat=result;
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.selectshopping = function(){//购物车查询
    var ctx = this;
    var co = $co(function * () {
        var userId = ctx.query.id || ctx.request.body.id;
        var dat={};
        var sqlstr="select orderinfo.VideoId as VideoId,orderinfo.UserId as UserId,VideoName,VideoPrice,ImgPath " +
            "from orderinfo,video where orderinfo.VideoId=video.VideoId and orderinfo.UserId='"+userId+"' and OrderId is null";
        var rows = yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat = rows;
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.deletshopping=function(){//购物车删除
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var name= ctx.query.name || ctx.request.body.name;
        var id= ctx.query.id || ctx.request.body.id;
        var dat={};
        if(name){
            var sqlstr="delete FROM orderinfo where VideoId="+name;
            var row=yield _ctnu([_mysql.conn,'query'],sqlstr);
        }
        if(id){
            var sqlstr1="delete FROM orderinfo where UserId="+id;
            var row=yield _ctnu([_mysql.conn,'query'],sqlstr1);
        }
        if(!row)throw Error("失败");
        else{
            var regResult=1;
        }
        res=regResult;
        ctx.body=res;
        return ctx;
    });
    return co;
};

_rotr.apis.order=function(){//添加订单
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var videoid= ctx.query.videoid || ctx.request.body.videoid;
        var userid= ctx.query.userid || ctx.request.body.userid;
        var time= ctx.query.time || ctx.request.body.time;
        var OrderId= ctx.query.orderId || ctx.request.body.orderId;
        var price= ctx.query.price || ctx.request.body.price;
        var dat={};
        console.log(time);
        for (var i=0;i<videoid.length;i++){
            var sqlstr="update orderinfo set OrderId='"+OrderId+"' where VideoId='"+videoid[i]+"' and UserId='"+userid+"'";
            var row=yield _ctnu([_mysql.conn,'query'],sqlstr);
            if(!row)throw Error("失败");
        }
        var sqlstr1="insert into mydb.`order` values ('"+OrderId+"','"+userid+"','"+time+"','"+price+"','否')";
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr1);
        if(!rows)throw Error("失败");
        else{
            var regResult=1;
        }
        res=regResult;
        ctx.body=res;
        return ctx;
    });
    return co;
};

_rotr.apis.selectorder=function(){//查询订单
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var userid= ctx.query.userid || ctx.request.body.userid;
        var orderid= ctx.query.orderid || ctx.request.body.orderid;
        var id= ctx.query.id || ctx.request.body.id;
        var Ordeid= ctx.query.Ordeid || ctx.request.body.Ordeid;
        console.log(orderid);
        var dat={};
        if(userid){
            var sqlstr1="select * from mydb.`order` where UserId='"+userid+"'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr1);
            if(!rows)throw Error("失败");
        }
        if(id){
            var sqlstr3="select * from mydb.`order` where UserId='"+id+"' and OrderType='是'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr3);
            if(!rows)throw Error("失败");
        }
        if(Ordeid){
            var sqlstr4="select * from mydb.`order` where UserId='"+Ordeid+"' and OrderType='否'";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr4);
            if(!rows)throw Error("失败");
        }
        if(orderid){
            var sqlstr2="select VideoId,VideoName,VideoPrice,ImgPath from video where VideoId in(select VideoId from orderinfo where OrderId='"+orderid+"')";
            var rows=yield _ctnu([_mysql.conn,'query'],sqlstr2);
            if(!rows)throw Error("失败");
        }
        console.log(rows);
        res=rows;
        ctx.body=res;
        return ctx;
    });
    return co;
};

_rotr.apis.deleteorder=function(){//删除订单
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var OrderId= ctx.query.orderId || ctx.request.body.orderId;
        var dat={};
        var sqlstr="delete from orderinfo where OrderId='"+OrderId+"'";
        var row=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!row)throw Error("失败");
        var sqlstr1="delete from mydb.`order` where OrderId='"+OrderId+"'";
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr1);
        if(!rows)throw Error("失败");
        else{
            var regResult=1;
        }
        res=regResult;
        ctx.body=res;
        return ctx;
    });
    return co;
};

_rotr.apis.buy=function(){//购买订单
    var res={};
    var ctx=this;
    var co=$co(function*(){
        var OrderId= ctx.query.orderId || ctx.request.body.orderId;
        var dat={};
        var sqlstr2="update video set Purchase=Purchase+1 where VideoId in (select VideoId from orderinfo where OrderId='"+OrderId+"')";
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr2);
        if(!rows)throw Error("失败");
        var sqlstr1="update mydb.`order` set OrderType='是' where OrderId='"+OrderId+"'";
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr1);
        if(!rows)throw Error("失败");
        else{
            var regResult=1;
        }
        res=regResult;
        ctx.body=res;
        return ctx;
    });
    return co;
};

_rotr.apis.keep = function(){//收藏
    var ctx = this;
    var co = $co(function * () {
        var userId = ctx.query.userId || ctx.request.body.userId;
        var videoId=ctx.query.videoId || ctx.request.body.videoId;
        var time=ctx.query.time || ctx.request.body.time;
        var dat={};
        var sqlstr="insert into keep (VideoId,UserId,KeepTime) values ('"+videoId+"','"+userId+"','"+time+"')";
        var rows = yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        else{
            result=1;
        }
        dat=result;
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.keepselect = function(){//收藏准备
    var ctx = this;
    var co = $co(function * () {
        var userId = ctx.query.userId || ctx.request.body.userId;
        var videoId=ctx.query.videoId || ctx.request.body.videoId;
        var time=ctx.query.time || ctx.request.body.time;
        var dat={};
        var sqlstr2="select * from keep where VideoId='"+videoId+"' and UserId='"+userId+"'";
        var rows = yield _ctnu([_mysql.conn,'query'],sqlstr2);
        if(!rows)throw Error("失败");
        dat=rows;
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.selectkeep = function(){//收藏查询
    var ctx = this;
    var co = $co(function * () {
        var userId = ctx.query.id || ctx.request.body.id;
        var dat={};
        var sqlstr="select keep.VideoId as VideoId,keep.UserId as UserId,VideoName,VideoPrice,ImgPath,KeepTime " +
            "from keep,video where keep.VideoId=video.VideoId and keep.UserId='"+userId+"'";
        var rows = yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        dat = rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.deletekeep = function(){//收藏删除
    var ctx = this;
    var co = $co(function * () {
        var videoId = ctx.query.id || ctx.request.body.id;
        var userId= ctx.query.userId || ctx.request.body.userId;
        var dat={};
        console.log(videoId,userId);
        var sqletr="delete from keep where VideoId='"+videoId+"' and UserId='"+userId+"'";
        var rows = yield _ctnu([_mysql.conn,'query'],sqletr);
        if(!rows)throw Error("失败");
        else{
            var result=1;
        }
        dat=result;
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.selectbuy = function(){//购买的视频
    var ctx = this;
    var co = $co(function * () {
        var userId= ctx.query.userId || ctx.request.body.userId;
        var dat={};
        console.log(userId);
        var sqletr="select video.VideoId,VideoName,ImgPath,OrderTime from video,(select orderinfo.VideoId,OrderTime from orderinfo,mydb.`order` where mydb.`order`.UserId='"+userId+"' and OrderType='是' and orderinfo.OrderId=mydb.`order`.OrderId) c where video.VideoId=c.VideoId" ;        var rows = yield _ctnu([_mysql.conn,'query'],sqletr);
        if(!rows)throw Error("失败");

        dat=rows;
        ctx.body = dat;
        return ctx;
    });
    return co;
};

_rotr.apis.sousuo = function(){//搜索视频
    var ctx = this;
    var co = $co(function * () {
        var className= ctx.query.name || ctx.request.body.name;
        var dat={};
        var sqletr="select * from video where VideoclassId in (select VideoclassId from videoclass where VideoclassName like '"+"%"+className+"%"+"')" ;
        var rows = yield _ctnu([_mysql.conn,'query'],sqletr);
        if(!rows)throw Error("失败");
        dat=rows;
        console.log(dat);
        ctx.body = dat;
        return ctx;
    });
    return co;
};

//视频简介接口
_rotr.apis.videoMessage = function(){
    var ctx =this;
    var videoId = ctx.query.videoId || ctx.request.body.videoId;
    var co = $co(function*(){
        //// 通过ID对数据库进行二次多表查询指定属性
        console.log(videoId+'视频ID');
        //数据库查询语句有更改
        var sqlstr1="select VideoName,VideoSyno from video where VideoId='"+videoId+"'";
        //var sqlstr1="select VideoSyno,Content from video v,assess a where a.VideoId=v.VideoId and a.VideoId='"+aaa+"'";
        var rows1=yield _ctnu([_mysql.conn,'query'],sqlstr1);
        if(!rows1)throw Error("失败");

        console.log("rows1",rows1);
        //console.log('>>>>>ImgPath',ImgPath);
        ctx.body = rows1;
        return ctx;
    });
    return co;
};
//视频评价接口的代码,,
_rotr.apis.videosyno = function(){
    var ctx =this;
    var videoId = ctx.query.videoId || ctx.request.body.videoId;
    var co = $co(function*(){
        var sqlstr="select UserName,ImgPath,Content from assess a left join user u on a.UserId=u.UserId where VideoId='"+videoId+"'";
        //var sqlstr1="select VideoSyno,Content from video v,assess a where a.VideoId=v.VideoId and a.VideoId='"+aaa+"'";
        var rows1=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows1)throw Error("失败");

        console.log("rows1",rows1);
        //console.log('>>>>>ImgPath',ImgPath);
        ctx.body = rows1;
        return ctx;
    });
    return co;
};

_rotr.apis.videoPlayJudge = function(){
    var ctx =this;
    var videoId = ctx.query.videoId || ctx.request.body.videoId;
    var UserId = ctx.query.id || ctx.request.body.id;
    var co = $co(function*() {
        var dat = {};
        var sqlstr = "select distinct VideoPrice from video v left join assess a on a.VideoId=v.VideoId where v.VideoId='" + videoId + "'";
        var rows = yield _ctnu([_mysql.conn, 'query'], sqlstr);
        if (rows[0]['VideoPrice'] != 0) {
            //var sqlstr1 = "select VideoId from mydb.orderinfo where (select OrderType from `order` where UserId = '" + UserId + "') = '是'";
            var sqlstr1 = "select OrderType from mydb.`order` where OrderId in (select OrderId from orderinfo where VideoId = '"+videoId+"' and UserId = '"+UserId+"')";
            var rows1 = yield _ctnu([_mysql.conn, 'query'], sqlstr1);
            console.log('2334', rows1);
            if (rows1['OrderType'] == '是' || rows1 != ''){
                var sqlstr2 = "select VideoPath from video v left join assess a on a.VideoId=v.VideoId where v.VideoId='" + videoId + "'";
                var rows0 = yield _ctnu([_mysql.conn, 'query'], sqlstr2);
                console.log('2336', rows0);
                dat = {data:rows0,status:'true'};
            }else {
                var sqlstr3 = "select VideoPath from video v left join assess a on a.VideoId=v.VideoId where v.VideoId='" + videoId + "'";
                var rows3 = yield _ctnu([_mysql.conn, 'query'], sqlstr3);
                dat = {data:rows3,status:'false'};
            }
        }
        else {
            var sqlstr4 = "select distinct VideoPath from video v left join assess a on a.VideoId=v.VideoId where v.VideoId='" + videoId + "'";
            var rows = yield _ctnu([_mysql.conn, 'query'], sqlstr4);
            console.log('2337', rows);
            dat = {data: rows, status: 'true'};
        }
        ctx.body = dat;
        return ctx;
    });
    return co;
};

//视频浏览量
_rotr.apis.videoVisit = function(){
    var ctx =this;
    var videoId = ctx.query.videoId || ctx.request.body.videoId;
    var co = $co(function*(){
        var sqlstr=" update video set OverPeople=OverPeople+1 where VideoId='"+videoId+"'";
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        console.log("rows",rows);
        ctx.body = rows;
        return ctx;
    })
    return co
};

//加入收藏
_rotr.apis.addmystudy = function(){
    var ctx =this;
    var videoId = ctx.query.videoId || ctx.request.body.videoId;
    var UserId = ctx.query.id || ctx.request.body.id;
    var KeepTime = ctx.query.time || ctx.request.body.time;
    var co = $co(function*(){
        var sqlstr1=" INSERT INTO keep (KeepTime,VideoId,UserId) VALUES ('"+KeepTime+"','"+videoId+"','"+UserId+"')";
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr1);

        if(!rows)throw Error("失败");
        console.log("rows1",rows);
        //console.log('>>>>>ImgPath',ImgPath);
        ctx.body = rows;
        return ctx;
    });
    return co;
};

//撰写评论
_rotr.apis.comment = function(){
    var ctx =this;
    var Content = ctx.query.Content || ctx.request.body.Content;
    var AssessTime = ctx.query.AssessTime || ctx.request.body.AssessTime;
    var VideoId = ctx.query.videoId || ctx.request.body.videoId;
    var UserId = ctx.query.id || ctx.request.body.id;
    console.log(Content,AssessTime,VideoId,UserId);
    var co = $co(function*(){
        var sqlstr1="INSERT INTO assess (Content,AssessTime,VideoId,UserId) VALUES ('"+Content+"','"+AssessTime+"','"+VideoId+"','"+UserId+"');";
        var rows=yield _ctnu([_mysql.conn,'query'],sqlstr1);

        if(!rows)throw Error("失败");
        console.log("rows",rows);
        ctx.body = rows;
        return ctx;
    });
    return co;
};
//账号页的头像,昵称接口,
_rotr.apis.UserType = function(){
    var ctx = this;
    var userId = ctx.query.id || ctx.request.body.id;
    //var imgPath = ctx.query.imgPath || ctx.request.body.imgPath;
    var co = $co(function*(){
        console.log('头像处:',userId);
        //var dat = {};
        var sqlstr="select ImgPath,UserNick,UserType,UserName from mydb.user where UserId='"+userId+"'";
        var rows = yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        console.log("头像",rows);
        //console.log('>>>>>ImgPath',ImgPath);
        ctx.body = rows;
        return ctx;
    });
    return co;
};

//上传头像

_rotr.apis.uploadPhoto = function(){
    var ctx = this;
    var userId = ctx.query.id || ctx.request.body.id;
    var imgPath = ctx.query.imgPath || ctx.request.body.imgPath;
    var co = $co(function*(){
        console.log('头像处:',userId);
        var sqlstr="update user set ImgPath='"+imgPath+"'where UserId='"+userId+"'";
        console.log("sqlstr",sqlstr);
        var rows = yield _ctnu([_mysql.conn,'query'],sqlstr);
        if(!rows)throw Error("失败");
        console.log("头像",rows);
        //console.log('>>>>>ImgPath',ImgPath);
        ctx.body = rows;
        return ctx;
    });
    return co;
};

//账号详情接口,,借用,
_rotr.apis.personCenter = function(){
    var ctx = this;
    var co = $co(function * () {

        var userId = ctx.query.id || ctx.request.body.id;
        var userName=ctx.query.name || ctx.request.body.name;
        var userNick=ctx.query.nick || ctx.request.body.nick;
        console.log("测试id",userId);
        console.log(">>>nick",userName);
        var dat={};
        var sqlstr="select * from user where UserId="+userId+" and UserName='"+userName+"'";
        var rows = yield _ctnu([_mysql.conn,'query'],sqlstr);
        if (rows.length==0){
            var sqlstr2="insert into user(UserId,UserName,UserNick,UserType) values('"+userId+"','"+userName+"','"+userNick+"','user')";
            var rows = yield _ctnu([_mysql.conn, 'query'], sqlstr2);
        }else {
            if(rows['UserNick']!=userNick){
                var sqlstr3="update user set UserNick='"+userNick+"'where UserId='"+userId+"'";
                var rows = yield _ctnu([_mysql.conn,'query'],sqlstr3);
            }
        }
        console.log('返回数据',rows.length);
        dat.Usr = rows[0];
        ctx.body = dat;
        return ctx;
    });
    return co;
};

//导出模块
module.exports = _rotr;


text:
import process from 'node:process';
import meow from 'meow';
import chalkAnim from './index.js';

const names = Object.keys(chalkAnim);

const cli = meow(`
Usage
  $ chalk-animation <name> [options] [text...]

Options
  --duration  Duration of the animation in ms, defaults to Infinity
  --speed     Animation speed as number > 0, defaults to 1

Available animations
  ${names.join('\n  ')}

Example
  $ chalk-animation rainbow Hello world!
`, {
	importMeta: import.meta
});

if (cli.input.length < 2) {
	cli.showHelp(2);
}

const name = cli.input[0];
const payload = cli.input.slice(1);
const effect = chalkAnim[name];

if (typeof effect === 'undefined') {
	console.error(`error: unknown animation name: "${name}", must be one of: ${names.join(', ')}`);
	process.exit(1);
}

const animation = effect(payload.join(' '), cli.flags.speed);

if (typeof cli.flags.duration === 'number') {
	setTimeout(() => {
		animation.stop();
	}, cli.flags.duration);
}

redpajama_set_name: RedPajamaGithub


text:
namespace shear { namespace lalr { namespace detail {

class item_state : public automata::nfa::state {
  public:
    typedef boost::shared_ptr<item_state> ptr;

    // For the special production that does the outermost stuff
    item_state(size_t position) :
      ultimate_position_(position == 1),
      penultimate_position_(position == 0),
      get_next_following_(false)
    {
    }

    // For the state at a given place in a production
    template<typename NonTerminals, typename FirstSets>
    item_state(
        const runtime::production::ptr& production,
        size_t position,
        const NonTerminals& non_terminals,
        const FirstSets& first_sets
      ) :
      production_(production),
      ultimate_position_(position == production->produced().size()),
      penultimate_position_(position == production->produced().size()-1),
      get_next_following_(false)
    {
      if (position+1 < production->produced().size()) {
        typename NonTerminals::iterator nt =
          non_terminals.find(production->produced()[position]);
        get_next_following_ =
          nt != non_terminals.end() && nt->produces_empty();
      }
      for (size_t following_pos = position+1;
          following_pos < production->produced().size(); ++following_pos) {
        size_t symbol = production->produced()[following_pos];
        std::copy(
            first_sets[symbol].begin(), first_sets[symbol].end(),
            std::inserter(following_, following_.end())
          );
        typename NonTerminals::iterator nt = non_terminals.find(symbol);
        if (nt == non_terminals.end() || !nt->produces_empty()) {
          break;
        }
      }
    }

    template<typename Integer>
    void add_transition(const ptr& next, const Integer symbol) {
      assert(!progress_transition_);
      progress_transition_ =
        automata::nfa::state::add_transition(next, symbol);
    }

    void add_transition(const station::ptr& zoom_to) {
      assert(!zoom_in_transition_);
      zoom_in_transition_ = automata::nfa::state::add_transition(zoom_to);
    }

  	bool pump_lookahead()
  	{
  		bool altered = false;

  		if (penultimate_position_) {
  			altered = add_following(lookahead_) || altered;
  		}

  		if (progress_transition_) {
        ptr progress_to = boost::dynamic_pointer_cast<item_state>(
            progress_transition_->destination()
          );
        altered = progress_to->add_lookahead(lookahead_) || altered;

        if (get_next_following_) {
          altered = add_following(progress_to->following_) || altered;
        }

        if (zoom_in_transition_) {
          automata::nfa::state::ptr zoom_in_station =
            zoom_in_transition_->destination();

          BOOST_FOREACH(automata::nfa::transition::ptr zoomed_in_transition,
              zoom_in_station->transitions()) {
            ptr zoomed_in_state = boost::dynamic_pointer_cast<item_state>(
                zoomed_in_transition->destination()
                );
            altered = zoomed_in_state->add_lookahead(following_) || altered;
          }
        }
  		}

  		return altered;
  	}

    bool add_lookahead(size_t i) {
      return lookahead_.insert(i).second;
    }

    template<typename OutputIterator>
    void get_reduction(OutputIterator o, size_t lookahead) {
      if (ultimate_position_ && lookahead_.count(lookahead) && production_) {
        *o++ = production_;
      }
    }
  private:
    template<typename Range>
    bool add_following(const Range& r) {
      size_t old_size = following_.size();
      std::copy(
          boost::begin(r), boost::end(r),
          std::inserter(following_, following_.end())
        );
      return following_.size() != old_size;
    }

    template<typename Range>
    bool add_lookahead(const Range& r) {
      size_t old_size = lookahead_.size();
      std::copy(
          boost::begin(r), boost::end(r),
          std::inserter(lookahead_, lookahead_.end())
        );
      return lookahead_.size() != old_size;
    }

    runtime::production::ptr production_;
    bool ultimate_position_;
    bool penultimate_position_;
    bool get_next_following_;
    std::set<size_t> lookahead_;
    std::set<size_t> following_;
    automata::nfa::transition::ptr progress_transition_;
    automata::nfa::transition::ptr zoom_in_transition_;
};

}}}

#endif // SHEAR__LALR_DETAIL__ITEM_STATE_HPP


text:
/*eslint no-unused-expressions: 0*/

/**
 * Module dependencies
 */

var should = require('should');

/**
 * Test
 */


text:
module Text.ParserCombinators.Parsec.Perm
                  ( PermParser  -- abstract

                  , permute
                  , (<||>), (<$$>)
                  , (<|?>), (<$?>)
                  ) where

import Text.ParserCombinators.Parsec

{---------------------------------------------------------------

---------------------------------------------------------------}
infixl 1 <||>, <|?>
infixl 2 <$$>, <$?>

{---------------------------------------------------------------
  test -- parse a permutation of
  * an optional string of 'a's
  * a required 'b'
  * an optional 'c'
---------------------------------------------------------------}
test input
  = parse (do{ x <- ptest; eof; return x }) "" input

ptest :: Parser (String,Char,Char)
ptest
  = permute $
    (,,) <$?> ("",many1 (char 'a'))
         <||> char 'b'
         <|?> ('_',char 'c')

{---------------------------------------------------------------
  Building a permutation parser
---------------------------------------------------------------}
(<||>) :: PermParser tok st (a -> b) -> GenParser tok st a -> PermParser tok st b
(<||>) perm p     = add perm p

(<$$>) :: (a -> b) -> GenParser tok st a -> PermParser tok st b
(<$$>) f p        = newperm f <||> p

(<|?>) :: PermParser tok st (a -> b) -> (a, GenParser tok st a) -> PermParser tok st b
(<|?>) perm (x,p) = addopt perm x p

(<$?>) :: (a -> b) -> (a, GenParser tok st a) -> PermParser tok st b
(<$?>) f (x,p)    = newperm f <|?> (x,p)

{---------------------------------------------------------------
  The permutation tree
---------------------------------------------------------------}
data PermParser tok st a = Perm (Maybe a) [Branch tok st a]
data Branch tok st a     = forall b. Branch (PermParser tok st (b -> a)) (GenParser tok st b)

-- transform a permutation tree into a normal parser
permute :: PermParser tok st a -> GenParser tok st a
permute (Perm def xs)
  = choice (map branch xs ++ empty)
  where
    empty
      = case def of
          Nothing -> []
          Just x  -> [return x]

    branch (Branch perm p)
      = do{ x <- p
          ; f <- permute perm
          ; return (f x)
          }

-- build permutation trees
newperm :: (a -> b) -> PermParser tok st (a -> b)
newperm f
  = Perm (Just f) []

add :: PermParser tok st (a -> b) -> GenParser tok st a -> PermParser tok st b
add perm@(Perm mf fs) p
  = Perm Nothing (first:map insert fs)
  where
    first   = Branch perm p
    insert (Branch perm' p')
            = Branch (add (mapPerms flip perm') p) p'

addopt :: PermParser tok st (a -> b) -> a -> GenParser tok st a -> PermParser tok st b
addopt perm@(Perm mf fs) x p
  = Perm (fmap ($ x) mf) (first:map insert fs)
  where
    first   = Branch perm p
    insert (Branch perm' p')
            = Branch (addopt (mapPerms flip perm') x p) p'

mapPerms :: (a -> b) -> PermParser tok st a -> PermParser tok st b
mapPerms f (Perm x xs)
  = Perm (fmap f x) (map (mapBranch f) xs)
  where
    mapBranch f (Branch perm p)
      = Branch (mapPerms (f.) perm) p


text:
class Company < ActiveRecord::Base

  MAX_POSTGRES_INT = 2147483647

  belongs_to :user

  has_many :contacts, dependent: :destroy
  has_many :events, dependent: :destroy
  has_many :positions, dependent: :destroy

  has_attached_file :attachment
  validates_attachment_file_name :attachment, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/, /pdf\Z/]

  default_scope -> { order(created_at: :desc) }

  validates :name, presence: true, uniqueness: { case_sensitive: false, scope: :user_id }
  validates :status, presence: true

  def self.filter(attributes)
    attributes.reduce(all) do |scope, (key, value)|

      if !value.blank? && !value.nil?
        case key.to_sym
          when :filter_name, :filter_status, :filter_location
            current_key = key.gsub('filter_', '')
            db_query = "#{current_key} ILIKE ?"
            active_record_query = [db_query]

            # Break into multiple queries with OR logic separated by '||'
            queries = value.split("||").map{ |x| x.strip.chomp('|').strip }.reject{ |x| x.empty? }

            queries.each_with_index do |query, idx|
              active_record_query.first << " OR #{db_query}" if idx != 0
              active_record_query << "%#{query}%"
            end
            scope.where(active_record_query)
          when :filter_size_min
            value = valid_int_range(value)
            scope.where("size >= ?", value)
          when :filter_size_max
            value = valid_int_range(value)
            scope.where("size <= ?", value)
          when :date
            scope.where("updated_at >= ?", value)
          else
            scope
          end
      else
        scope
      end
    end
  end

  def self.to_csv
    attributes = %w(name location size status website details created_at updated_at)

    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |company|
        csv << attributes.map{ |attr| company.send(attr) }
      end
    end
  end

  def self.to_nested_csv(nested_model)
    case nested_model.to_sym
    when :events
      attributes = %w(company date event_type text)
    when :positions
      attributes = %w(company name url description)
    when :contacts
      attributes = %w(company name location position details email phone)
    else
      return nil
    end

    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |company|
        company.send(nested_model).each do |event|
          csv << attributes.map do |attr|
            attr == "company" ? company.name : event.send(attr)
          end
        end
      end
    end
  end

  def self.valid_int_range(num)
    return 0 if num.to_i < 0
    return MAX_POSTGRES_INT if num.to_i > MAX_POSTGRES_INT
    num
  end
end


text:
package azkaban.db;

public class AzDBUtil {

  // A very big Integer
  static final int MAX_DB_RETRY_COUNT = 999999;
}


text:
CC = gcc
LINKER = gcc
CFLAGS = -std=c99 -Wall -Wpointer-arith -Werror -Wno-error=unused-variable -Wfatal-errors
DEBUG = -g
PROG1LIBNAME = prog1
PROG1LIBDIR = ../lib

# disable default suffixes
.SUFFIXES:

# pattern rule for compiling the library
prog1lib:
	cd $(PROG1LIBDIR) && make

# pattern rule for compiling .c-file to executable
%: %.c prog1lib
	$(CC) $(CFLAGS)	$(DEBUG) $<	-L$(PROG1LIBDIR) -l$(PROG1LIBNAME) -lm -iquote$(PROG1LIBDIR) -o	$@


text:
package metadata

import (
	"context"
	"encoding/binary"
	"strings"
	"time"

	"github.com/boltdb/bolt"
	"github.com/containerd/containerd/content"
	"github.com/containerd/containerd/errdefs"
	"github.com/containerd/containerd/filters"
	"github.com/containerd/containerd/metadata/boltutil"
	"github.com/containerd/containerd/namespaces"
	digest "github.com/opencontainers/go-digest"
	"github.com/pkg/errors"
)

type contentStore struct {
	content.Store
	db *bolt.DB
}

// NewContentStore returns a namespaced content store using an existing
// content store interface.
func NewContentStore(db *bolt.DB, cs content.Store) content.Store {
	return &contentStore{
		Store: cs,
		db:    db,
	}
}

func (cs *contentStore) Info(ctx context.Context, dgst digest.Digest) (content.Info, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return content.Info{}, err
	}

	var info content.Info
	if err := view(ctx, cs.db, func(tx *bolt.Tx) error {
		bkt := getBlobBucket(tx, ns, dgst)
		if bkt == nil {
			return errors.Wrapf(errdefs.ErrNotFound, "content digest %v", dgst)
		}

		info.Digest = dgst
		return readInfo(&info, bkt)
	}); err != nil {
		return content.Info{}, err
	}

	return info, nil
}

func (cs *contentStore) Update(ctx context.Context, info content.Info, fieldpaths ...string) (content.Info, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return content.Info{}, err
	}

	updated := content.Info{
		Digest: info.Digest,
	}
	if err := update(ctx, cs.db, func(tx *bolt.Tx) error {
		bkt := getBlobBucket(tx, ns, info.Digest)
		if bkt == nil {
			return errors.Wrapf(errdefs.ErrNotFound, "content digest %v", info.Digest)
		}

		if err := readInfo(&updated, bkt); err != nil {
			return errors.Wrapf(err, "info %q", info.Digest)
		}

		if len(fieldpaths) > 0 {
			for _, path := range fieldpaths {
				if strings.HasPrefix(path, "labels.") {
					if updated.Labels == nil {
						updated.Labels = map[string]string{}
					}

					key := strings.TrimPrefix(path, "labels.")
					updated.Labels[key] = info.Labels[key]
					continue
				}

				switch path {
				case "labels":
					updated.Labels = info.Labels
				default:
					return errors.Wrapf(errdefs.ErrInvalidArgument, "cannot update %q field on content info %q", path, info.Digest)
				}
			}
		} else {
			// Set mutable fields
			updated.Labels = info.Labels
		}

		updated.UpdatedAt = time.Now().UTC()
		return writeInfo(&updated, bkt)
	}); err != nil {
		return content.Info{}, err
	}
	return updated, nil
}

func (cs *contentStore) Walk(ctx context.Context, fn content.WalkFunc, fs ...string) error {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return err
	}

	filter, err := filters.ParseAll(fs...)
	if err != nil {
		return err
	}

	// TODO: Batch results to keep from reading all info into memory
	var infos []content.Info
	if err := view(ctx, cs.db, func(tx *bolt.Tx) error {
		bkt := getBlobsBucket(tx, ns)
		if bkt == nil {
			return nil
		}

		return bkt.ForEach(func(k, v []byte) error {
			dgst, err := digest.Parse(string(k))
			if err != nil {
				// Not a digest, skip
				return nil
			}
			bbkt := bkt.Bucket(k)
			if bbkt == nil {
				return nil
			}
			info := content.Info{
				Digest: dgst,
			}
			if err := readInfo(&info, bkt.Bucket(k)); err != nil {
				return err
			}
			if filter.Match(adaptContentInfo(info)) {
				infos = append(infos, info)
			}
			return nil
		})
	}); err != nil {
		return err
	}

	for _, info := range infos {
		if err := fn(info); err != nil {
			return err
		}
	}

	return nil
}

func (cs *contentStore) Delete(ctx context.Context, dgst digest.Digest) error {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return err
	}

	return update(ctx, cs.db, func(tx *bolt.Tx) error {
		bkt := getBlobBucket(tx, ns, dgst)
		if bkt == nil {
			return errors.Wrapf(errdefs.ErrNotFound, "content digest %v", dgst)
		}

		// Just remove local reference, garbage collector is responsible for
		// cleaning up on disk content
		return getBlobsBucket(tx, ns).Delete([]byte(dgst.String()))
	})
}

func (cs *contentStore) ListStatuses(ctx context.Context, fs ...string) ([]content.Status, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}

	filter, err := filters.ParseAll(fs...)
	if err != nil {
		return nil, err
	}

	brefs := map[string]string{}
	if err := view(ctx, cs.db, func(tx *bolt.Tx) error {
		bkt := getIngestBucket(tx, ns)
		if bkt == nil {
			return nil
		}

		return bkt.ForEach(func(k, v []byte) error {
			// TODO(dmcgowan): match name and potentially labels here
			brefs[string(k)] = string(v)
			return nil
		})
	}); err != nil {
		return nil, err
	}

	statuses := make([]content.Status, 0, len(brefs))
	for k, bref := range brefs {
		status, err := cs.Store.Status(ctx, bref)
		if err != nil {
			if errdefs.IsNotFound(err) {
				continue
			}
			return nil, err
		}
		status.Ref = k

		if filter.Match(adaptContentStatus(status)) {
			statuses = append(statuses, status)
		}
	}

	return statuses, nil

}

func getRef(tx *bolt.Tx, ns, ref string) string {
	bkt := getIngestBucket(tx, ns)
	if bkt == nil {
		return ""
	}
	v := bkt.Get([]byte(ref))
	if len(v) == 0 {
		return ""
	}
	return string(v)
}

func (cs *contentStore) Status(ctx context.Context, ref string) (content.Status, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return content.Status{}, err
	}

	var bref string
	if err := view(ctx, cs.db, func(tx *bolt.Tx) error {
		bref = getRef(tx, ns, ref)
		if bref == "" {
			return errors.Wrapf(errdefs.ErrNotFound, "reference %v", ref)
		}

		return nil
	}); err != nil {
		return content.Status{}, err
	}

	st, err := cs.Store.Status(ctx, bref)
	if err != nil {
		return content.Status{}, err
	}
	st.Ref = ref
	return st, nil
}

func (cs *contentStore) Abort(ctx context.Context, ref string) error {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return err
	}

	return update(ctx, cs.db, func(tx *bolt.Tx) error {
		bkt := getIngestBucket(tx, ns)
		if bkt == nil {
			return errors.Wrapf(errdefs.ErrNotFound, "reference %v", ref)
		}
		bref := string(bkt.Get([]byte(ref)))
		if bref == "" {
			return errors.Wrapf(errdefs.ErrNotFound, "reference %v", ref)
		}
		if err := bkt.Delete([]byte(ref)); err != nil {
			return err
		}

		return cs.Store.Abort(ctx, bref)
	})

}

func (cs *contentStore) Writer(ctx context.Context, ref string, size int64, expected digest.Digest) (content.Writer, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}

	var w content.Writer
	if err := update(ctx, cs.db, func(tx *bolt.Tx) error {
		if expected != "" {
			cbkt := getBlobBucket(tx, ns, expected)
			if cbkt != nil {
				return errors.Wrapf(errdefs.ErrAlreadyExists, "content %v", expected)
			}
		}

		bkt, err := createIngestBucket(tx, ns)
		if err != nil {
			return err
		}

		var (
			bref  string
			brefb = bkt.Get([]byte(ref))
		)

		if brefb == nil {
			sid, err := bkt.NextSequence()
			if err != nil {
				return err
			}

			bref = createKey(sid, ns, ref)
			if err := bkt.Put([]byte(ref), []byte(bref)); err != nil {
				return err
			}
		} else {
			bref = string(brefb)
		}

		// Do not use the passed in expected value here since it was
		// already checked against the user metadata. If the content
		// store has the content, it must still be written before
		// linked into the given namespace. It is possible in the future
		// to allow content which exists in content store but not
		// namespace to be linked here and returned an exist error, but
		// this would require more configuration to make secure.
		w, err = cs.Store.Writer(ctx, bref, size, "")
		return err
	}); err != nil {
		return nil, err
	}

	// TODO: keep the expected in the writer to use on commit
	// when no expected is provided there.
	return &namespacedWriter{
		Writer:    w,
		ref:       ref,
		namespace: ns,
		db:        cs.db,
	}, nil
}

type namespacedWriter struct {
	content.Writer
	ref       string
	namespace string
	db        *bolt.DB
}

func (nw *namespacedWriter) Commit(size int64, expected digest.Digest) error {
	return nw.db.Update(func(tx *bolt.Tx) error {
		bkt := getIngestBucket(tx, nw.namespace)
		if bkt != nil {
			if err := bkt.Delete([]byte(nw.ref)); err != nil {
				return err
			}
		}
		return nw.commit(tx, size, expected)
	})
}

func (nw *namespacedWriter) commit(tx *bolt.Tx, size int64, expected digest.Digest) error {
	status, err := nw.Writer.Status()
	if err != nil {
		return err
	}
	if size != 0 && size != status.Offset {
		return errors.Errorf("%q failed size validation: %v != %v", nw.ref, status.Offset, size)
	}
	size = status.Offset

	actual := nw.Writer.Digest()

	if err := nw.Writer.Commit(size, expected); err != nil {
		if !errdefs.IsAlreadyExists(err) {
			return err
		}
		if getBlobBucket(tx, nw.namespace, actual) != nil {
			return errors.Wrapf(errdefs.ErrAlreadyExists, "content %v", actual)
		}
	}

	bkt, err := createBlobBucket(tx, nw.namespace, actual)
	if err != nil {
		return err
	}

	commitTime := time.Now().UTC()

	sizeEncoded, err := encodeSize(size)
	if err != nil {
		return err
	}

	if err := boltutil.WriteTimestamps(bkt, commitTime, commitTime); err != nil {
		return err
	}
	if err := bkt.Put(bucketKeySize, sizeEncoded); err != nil {
		return err
	}

	return nil
}

func (nw *namespacedWriter) Status() (content.Status, error) {
	st, err := nw.Writer.Status()
	if err == nil {
		st.Ref = nw.ref
	}
	return st, err
}

func (cs *contentStore) ReaderAt(ctx context.Context, dgst digest.Digest) (content.ReaderAt, error) {
	if err := cs.checkAccess(ctx, dgst); err != nil {
		return nil, err
	}
	return cs.Store.ReaderAt(ctx, dgst)
}

func (cs *contentStore) checkAccess(ctx context.Context, dgst digest.Digest) error {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return err
	}

	return view(ctx, cs.db, func(tx *bolt.Tx) error {
		bkt := getBlobBucket(tx, ns, dgst)
		if bkt == nil {
			return errors.Wrapf(errdefs.ErrNotFound, "content digest %v", dgst)
		}
		return nil
	})
}

func readInfo(info *content.Info, bkt *bolt.Bucket) error {
	if err := boltutil.ReadTimestamps(bkt, &info.CreatedAt, &info.UpdatedAt); err != nil {
		return err
	}

	labels, err := boltutil.ReadLabels(bkt)
	if err != nil {
		return err
	}
	info.Labels = labels

	if v := bkt.Get(bucketKeySize); len(v) > 0 {
		info.Size, _ = binary.Varint(v)
	}

	return nil
}

func writeInfo(info *content.Info, bkt *bolt.Bucket) error {
	if err := boltutil.WriteTimestamps(bkt, info.CreatedAt, info.UpdatedAt); err != nil {
		return err
	}

	if err := boltutil.WriteLabels(bkt, info.Labels); err != nil {
		return errors.Wrapf(err, "writing labels for info %v", info.Digest)
	}

	// Write size
	sizeEncoded, err := encodeSize(info.Size)
	if err != nil {
		return err
	}

	if err := bkt.Put(bucketKeySize, sizeEncoded); err != nil {
		return err
	}

	return nil
}


text:
/* Tries to create a directory with the same name as an existing
   file, which must return failure. */

#include <syscall.h>
#include "tests/lib.h"
#include "tests/main.h"

void
test_main (void)
{
  CHECK (create ("abc", 0), "create \"abc\"");
  CHECK (!mkdir ("abc"), "mkdir \"abc\" (must return false)");
}


text:
package main

import (
	"bitbucket.org/tebeka/nrsc"
	"fmt"
	"github.com/ant0ine/go-json-rest"
	"html/template"
	"net"
	"net/http"
	"strconv"
	"strings"
)

func main() {
	handler := rest.ResourceHandler{}
	handler.SetRoutes(
		rest.Route{"GET", "/api/:server/workers", GetAllWorkers},
	)
	nrsc.Handle("/static/")
	http.HandleFunc("/", Index)
	http.Handle("/api/", &handler)
	http.ListenAndServe(":8080", nil)
}

type GearmanResponse struct {
	Response string
}

func GetInt(s string) (out int) {
	out, err := strconv.Atoi(s)
	if err != nil {
		out = 0
	}
	return
}

func (response GearmanResponse) GetWorkerStatuses() []GearmanWorkerStatus {
	statusLines := strings.Split(response.Response, "\n")
	workerStatuses := make([]GearmanWorkerStatus, len(statusLines))
	for i, line := range statusLines {
		lineArray := strings.Fields(line)
		workerStatuses[i] = GearmanWorkerStatus{
			FunctionName: lineArray[0],
			JobTotal:     GetInt(lineArray[1]),
			JobRunning:   GetInt(lineArray[2]),
			WorkerCount:  GetInt(lineArray[3]),
		}
	}
	return workerStatuses
}

type GearmanWorkerStatus struct {
	FunctionName string
	JobTotal     int
	JobRunning   int
	WorkerCount  int
}

type GearmanServerInfo struct {
	Address string
	Pid     int
	Version string
}

func GetGearmanServerInfo(address string) GearmanServerInfo {
	pid := SendCommand("getpid", address)
	version := SendCommand("version", address)
	return GearmanServerInfo{address, GetInt(pid.Response), version.Response}
}

type TemplateData struct {
	ServerInfo []GearmanServerInfo
}

func Index(w http.ResponseWriter, r *http.Request) {
	tmpl := `<!doctype html>

    <title>WebGearadmin</title>

WebGearadmin

    {{ range $data := .ServerInfo }}

Server at {{$data.Address}}

        PID: {{$data.Pid}}

        Version: {{$data.Version}}

                    Name
                    Total
                    Running
                    # Workers

    {{ end }}

    `
	t, err := template.New("index").Parse(tmpl)
	if err != nil {
		print(err.Error())
	}
	servers := GetServers(r)
	serverInfo := make([]GearmanServerInfo, len(servers))
	for i, server := range servers {
		serverInfo[i] = GetGearmanServerInfo(server)
	}

	err = t.Execute(w, TemplateData{serverInfo})
	if err != nil {
		print(err.Error())
	}
}

func GetServers(r *http.Request) (servers []string) {
	serversString := r.FormValue("servers")
	if serversString != "" {
		servers = strings.Split(serversString, ",")
	}
	return
}

func SendCommand(cmd, address string) GearmanResponse {
	conn, err := net.Dial("tcp", address)
	if err != nil {
		print(err.Error())
		return GearmanResponse{"error"}
	}
	fmt.Fprint(conn, cmd+"\n")

	responseBytes := make([]byte, 1024)
	_, err = conn.Read(responseBytes)
	if err != nil {
		fmt.Printf("Failed to send command \"%s\". Error: %s\n", cmd, err)
	}

	response := strings.Trim(string(responseBytes), " .\r\n\x00")
	if cmd == "getpid" || cmd == "version" {
		// remove leading "OK "
		response = response[3:]
	}
	//fmt.Printf("RESPONSE FOR |%s|: |%s|\n", cmd, response)
	return GearmanResponse{response}
}

func GetAllWorkers(w *rest.ResponseWriter, r *rest.Request) {
	statusResp := SendCommand("status", r.PathParam("server"))
	w.WriteJson(statusResp.GetWorkerStatuses())
}


text:
BEAT_NAME=httpbeat
BEAT_DESCRIPTION=Queries arbitrary HTTP endpoints in a regular interval and ships the result to the configured output channel.
BEAT_PATH=github.com/christiangalsterer/httpbeat
SYSTEM_TESTS=false
TEST_ENVIRONMENT=false
SNAPSHOT=no
ES_BEATS?=./vendor/github.com/elastic/beats
# GOPACKAGES=$(shell glide novendor)
GOPACKAGES=$(shell go list ${BEAT_DIR}/... | grep -v /vendor/)
PREFIX?=.

# Path to the libbeat Makefile
-include $(ES_BEATS)/libbeat/scripts/Makefile

# Update dependencies
.PHONY: getdeps
getdeps:
	glide up

# Initial beat setup
.PHONY: setup
setup: copy-vendor
	make update

# Copy beats into vendor directory
.PHONY: copy-vendor
copy-vendor:
	mkdir -p vendor/github.com/elastic/
	cp -R ${GOPATH}/src/github.com/elastic/beats vendor/github.com/elastic/
	rm -rf vendor/github.com/elastic/beats/.git

# This is called by the beats packer before building starts
.PHONY: before-build
before-build:

.PHONY: cover
cover:
	echo 'mode: atomic' > coverage.txt && go list . ./beater | xargs -n1 -I{} sh -c 'go test -covermode=atomic -coverprofile=coverage.tmp {} && tail -n +2 coverage.tmp >> coverage.txt' && rm coverage.tmp

# Collects all dependencies and then calls update
.PHONY: collect
collect:


text:
import gc

import numpy as np

from pandas import (
    DatetimeIndex,
    Index,
    IntervalIndex,
    MultiIndex,
    RangeIndex,
    Series,
    date_range,
)

from .pandas_vb_common import tm

class SetOperations:

    params = (
        ["monotonic", "non_monotonic"],
        ["datetime", "date_string", "int", "strings", "ea_int"],
        ["intersection", "union", "symmetric_difference"],
    )
    param_names = ["index_structure", "dtype", "method"]

    def setup(self, index_structure, dtype, method):
        N = 10**5
        dates_left = date_range("1/1/2000", periods=N, freq="T")
        fmt = "%Y-%m-%d %H:%M:%S"
        date_str_left = Index(dates_left.strftime(fmt))
        int_left = Index(np.arange(N))
        ea_int_left = Index(np.arange(N), dtype="Int64")
        str_left = tm.makeStringIndex(N)

        data = {
            "datetime": dates_left,
            "date_string": date_str_left,
            "int": int_left,
            "strings": str_left,
            "ea_int": ea_int_left,
        }

        if index_structure == "non_monotonic":
            data = {k: mi[::-1] for k, mi in data.items()}

        data = {k: {"left": idx, "right": idx[:-1]} for k, idx in data.items()}

        self.left = data[dtype]["left"]
        self.right = data[dtype]["right"]

    def time_operation(self, index_structure, dtype, method):
        getattr(self.left, method)(self.right)

class SetDisjoint:
    def setup(self):
        N = 10**5
        B = N + 20000
        self.datetime_left = DatetimeIndex(range(N))
        self.datetime_right = DatetimeIndex(range(N, B))

    def time_datetime_difference_disjoint(self):
        self.datetime_left.difference(self.datetime_right)

class UnionWithDuplicates:
    def setup(self):
        self.left = Index(np.repeat(np.arange(1000), 100))
        self.right = Index(np.tile(np.arange(500, 1500), 50))

    def time_union_with_duplicates(self):
        self.left.union(self.right)

class Range:
    def setup(self):
        self.idx_inc = RangeIndex(start=0, stop=10**6, step=3)
        self.idx_dec = RangeIndex(start=10**6, stop=-1, step=-3)

    def time_max(self):
        self.idx_inc.max()

    def time_max_trivial(self):
        self.idx_dec.max()

    def time_min(self):
        self.idx_dec.min()

    def time_min_trivial(self):
        self.idx_inc.min()

    def time_get_loc_inc(self):
        self.idx_inc.get_loc(900_000)

    def time_get_loc_dec(self):
        self.idx_dec.get_loc(100_000)

    def time_iter_inc(self):
        for _ in self.idx_inc:
            pass

    def time_iter_dec(self):
        for _ in self.idx_dec:
            pass

    def time_sort_values_asc(self):
        self.idx_inc.sort_values()

    def time_sort_values_des(self):
        self.idx_inc.sort_values(ascending=False)

class IndexEquals:
    def setup(self):
        idx_large_fast = RangeIndex(100_000)
        idx_small_slow = date_range(start="1/1/2012", periods=1)
        self.mi_large_slow = MultiIndex.from_product([idx_large_fast, idx_small_slow])

        self.idx_non_object = RangeIndex(1)

    def time_non_object_equals_multiindex(self):
        self.idx_non_object.equals(self.mi_large_slow)

class IndexAppend:
    def setup(self):

        N = 10_000
        self.range_idx = RangeIndex(0, 100)
        self.int_idx = self.range_idx.astype(int)
        self.obj_idx = self.int_idx.astype(str)
        self.range_idxs = []
        self.int_idxs = []
        self.object_idxs = []
        for i in range(1, N):
            r_idx = RangeIndex(i * 100, (i + 1) * 100)
            self.range_idxs.append(r_idx)
            i_idx = r_idx.astype(int)
            self.int_idxs.append(i_idx)
            o_idx = i_idx.astype(str)
            self.object_idxs.append(o_idx)

    def time_append_range_list(self):
        self.range_idx.append(self.range_idxs)

    def time_append_int_list(self):
        self.int_idx.append(self.int_idxs)

    def time_append_obj_list(self):
        self.obj_idx.append(self.object_idxs)

class Indexing:

    params = ["String", "Float", "Int"]
    param_names = ["dtype"]

    def setup(self, dtype):
        N = 10**6
        self.idx = getattr(tm, f"make{dtype}Index")(N)
        self.array_mask = (np.arange(N) % 3) == 0
        self.series_mask = Series(self.array_mask)
        self.sorted = self.idx.sort_values()
        half = N // 2
        self.non_unique = self.idx[:half].append(self.idx[:half])
        self.non_unique_sorted = (
            self.sorted[:half].append(self.sorted[:half]).sort_values()
        )
        self.key = self.sorted[N // 4]

    def time_boolean_array(self, dtype):
        self.idx[self.array_mask]

    def time_boolean_series(self, dtype):
        self.idx[self.series_mask]

    def time_get(self, dtype):
        self.idx[1]

    def time_slice(self, dtype):
        self.idx[:-1]

    def time_slice_step(self, dtype):
        self.idx[::2]

    def time_get_loc(self, dtype):
        self.idx.get_loc(self.key)

    def time_get_loc_sorted(self, dtype):
        self.sorted.get_loc(self.key)

    def time_get_loc_non_unique(self, dtype):
        self.non_unique.get_loc(self.key)

    def time_get_loc_non_unique_sorted(self, dtype):
        self.non_unique_sorted.get_loc(self.key)

class Float64IndexMethod:
    # GH 13166
    def setup(self):
        N = 100_000
        a = np.arange(N, dtype=np.float64)
        self.ind = Index(a * 4.8000000418824129e-08)

    def time_get_loc(self):
        self.ind.get_loc(0)

class IntervalIndexMethod:
    # GH 24813
    params = [10**3, 10**5]

    def setup(self, N):
        left = np.append(np.arange(N), np.array(0))
        right = np.append(np.arange(1, N + 1), np.array(1))
        self.intv = IntervalIndex.from_arrays(left, right)
        self.intv._engine

        self.intv2 = IntervalIndex.from_arrays(left + 1, right + 1)
        self.intv2._engine

        self.left = IntervalIndex.from_breaks(np.arange(N))
        self.right = IntervalIndex.from_breaks(np.arange(N - 3, 2 * N - 3))

    def time_monotonic_inc(self, N):
        self.intv.is_monotonic_increasing

    def time_is_unique(self, N):
        self.intv.is_unique

    def time_intersection(self, N):
        self.left.intersection(self.right)

    def time_intersection_one_duplicate(self, N):
        self.intv.intersection(self.right)

    def time_intersection_both_duplicate(self, N):
        self.intv.intersection(self.intv2)

class GC:
    params = [1, 2, 5]

    def create_use_drop(self):
        idx = Index(list(range(1_000_000)))
        idx._engine

    def peakmem_gc_instances(self, N):
        try:
            gc.disable()

            for _ in range(N):
                self.create_use_drop()
        finally:
            gc.enable()

from .pandas_vb_common import setup  # noqa: F401 isort:skip


text:
{%- include snippets/get-sources.html -%}
{%- assign _sources = __return -%}
<script>
  window.Lazyload.js('{{ _sources.mermaid }}', function() {
    mermaid.init(undefined, '.language-mermaid');
    mermaid.initialize({ startOnLoad: true });
  });
</script>


text:
* **Audio Recording**: https://soundcloud.com/node-foundation/tsc-meeting-2015-10-07
* **GitHub Issue**: https://github.com/nodejs/node/issues/3126
* **Minutes Google Doc**: https://docs.google.com/document/d/1LIrTCdTUjKtb_GGecrJ3Es0rPOpVdpkV5kefJ_p5FGU
* _Previous Minutes Google Doc: <https://docs.google.com/document/d/1RkLAWTIrhD3BTB2rs9_FahWI0C7lt9F8xnQXaueJPIE>_

## Present

* Rod Vagg (TSC)
* Brian White (TSC)
* Steven Loomis (observer)
* Trevor Norris (TSC)
* Shigeki Ohtsu (TSC)
* Ben Noordhuis (TSC)
* Mikeal Rogers (observer)
* Michael Dawson (observer)
* Seth Thompson (observer)
* Jeremiah Senkpiel (TSC)

## Agenda

Extracted from **tsc-agenda** labelled issues and pull requests in the nodejs org prior to meeting.

### nodejs/node

* WG: Considering a new HTTP WG [#3214](https://github.com/nodejs/node/issues/3214)
* lib,test: deprecate _linklist [#3078](https://github.com/nodejs/node/pull/3078)
* Discussion: LTS & v5 release planning [#3000](https://github.com/nodejs/node/issues/3000)
* Compiling node v4.0.0 with OpenSSL 1.0.1 fails [#2783](https://github.com/nodejs/node/issues/2783)
* Inspecting Node.js with Chrome DevTools [#2546](https://github.com/nodejs/node/issues/2546)

### nodejs/TSC

* Umbrella Program [#2](https://github.com/nodejs/TSC/pull/2)

## Minutes

### Standup

* Rod Vagg: 4.1.2 release, security procedures surrounding that
* Brian White: Working on javascript dns resolver, regular PR + Issue work.
* Steven Loomis: Working on ICU 56 Release. TC 39 & emca spec work for Intl WG. Working on Intl build issues.
* Trevor Norris: Focused on fixing async_wrap, writing tests and preparing for it to become more official
* Shigeki Ohtsu: No works for node project, I spent all time to my internal works.
* Ben Noordhuis: Nothing to report—the usual
* Mikeal Rogers: Looking into stalled Wgs and seeing how to help out. Working on the umbrella program. Lots of conference things.
* Michael Dawson: Added a benchmarking machine to the CI, working on some tests issues. Working on PPC for the CI.
* Seth Thompson: Working on v8 4.7, scheduled soon
* Jeremiah Senkpiel: vacation, some issue catch-up

### Review of previous meeting

* Discussion: LTS & v5 release planning [#3000](https://github.com/nodejs/node/issues/3000)
* Inspecting Node.js with Chrome DevTools [#2546](https://github.com/nodejs/node/issues/2546)
* Umbrella Program [#2](https://github.com/nodejs/TSC/pull/2)
* renaming of "language groups" from iojs-\* to nodejs-\* [#2525](https://github.com/nodejs/node/issues/2525)

### WG: Considering a new HTTP WG [#3214](https://github.com/nodejs/node/issues/3214)

* Discussed the HTTP WG based on James' comments @ https://github.com/nodejs/node/issues/3234#issuecomment-146293038
* Generally positive, only concerns are regarding decision making power—TSC may not want to hand that off as this is not quite like Streams (in that few people grok the code!) and there are philosophical questions to be resolved about HTTP that the TSC should be involved in.

### lib,test: deprecate _linklist [#3078](https://github.com/nodejs/node/pull/3078)

* Userland modules exist that could be used instead
* Ben suggested straight removal, Jeramiah raised the matter of process that we have committed to adding a warning before removal, so we could remove in v6 but probably shouldn't in v5
* No disagreement with moving forward for deprecation

### Discussion: LTS & v5 release planning [#3000](https://github.com/nodejs/node/issues/3000)

* Recap of the latest LTS meeting [LTS#43](https://github.com/nodejs/LTS/issues/43)
* Aim to have LTS / v4.2.0 out tomorrow, backup date of Monday if we miss that. LTS starts then for v4.x, v5.x has to wait until V8 4.6 to be stable mid to late October.

### Compiling node v4.0.0 with OpenSSL 1.0.1 fails [#2783](https://github.com/nodejs/node/issues/2783)

* Shigeki, Ben: It would be quite hard to support 1.0.1 since we are using 1.0.2 APIs.

* Discussion on the possible difficulty of using 1.0.2 on varied Linux distros

* ubuntu wily (not released) seems to use 1.0.2 - work has been done to package.  1.0.2 is only in Wily - https://launchpad.net/ubuntu/+source/openssl/1.0.2d-0ubuntu1 - https://answers.launchpad.net/ubuntu/+source/openssl/+question/263725 - "My guess is that we will see openssl 1.0.2 from Ubuntu 15.10 onwards (or eventually only starting with 16.04)"

* Concern that allowing 1.0.1 would result in a substandard (insecure?) & untested binary.

* Some discussion about the fact that we don't test building with shared / static dependencies

* feedback to issue: No appetite to do the work from the TSC, maybe someone could do it but we wouldn't support.

### Inspecting Node.js with Chrome DevTools [#2546](https://github.com/nodejs/node/issues/2546)

_skipped discussion_

### Umbrella Program [#2](https://github.com/nodejs/TSC/pull/2)

_skipped discussion_

## Next Meeting

October 14th, 2015


text:
class CreateClinicHistories < ActiveRecord::Migration
  def change
    create_table :clinic_histories do |t|
      t.string :first_name
      t.string :second_name
      t.string :first_surname
      t.string :second_surname
      t.string :email
      t.string :type_document
      t.string :document
      t.date :birthdate
      t.string :gender
      t.string :profession
      t.string :blood_type
      t.string :country_code
      t.string :nacionality
      t.references :eps, index: true, foreign_key: true
      t.references :arl, index: true, foreign_key: true
      t.string :address
      t.string :condition
      t.string :accompanist_name
      t.string :relationship
      t.string :phone
      t.references :user, index: true, foreign_key: true
      t.string :city
      t.integer :city_id
      t.string :department
      t.string :cove
      t.string :mobiel_service
      t.references :airport, index: true, foreign_key: true
      t.string :type_service
      t.references :patient, index: true, foreign_key: true
      t.string :origin
      t.string :destination
      t.string :company
      t.text :reason_for_consultation
      t.text :current_illness
      t.boolean :neunatales_true
      t.boolean :neunatales_false
      t.text :neunatales_description
      t.boolean :patologicos_true
      t.boolean :patologicos_false
      t.text :patologicos_description
      t.boolean :quirurgicos_true
      t.boolean :quirurgicos_false
      t.text :quirurgicos_description
      t.boolean :farmacologicos_true
      t.boolean :farmacologicos_false
      t.text :farmacologicos_description
      t.boolean :alergicos_true
      t.boolean :alergicos_false
      t.text :alergicos_description
      t.boolean :toxicos_true
      t.boolean :toxicos_false
      t.text :toxicos_description
      t.boolean :traumaticos_true
      t.boolean :traumaticos_false
      t.text :traumaticos_description
      t.boolean :hospitables_true
      t.boolean :hospitables_false
      t.text :hospitables_description
      t.boolean :atep_laboral_true
      t.boolean :atep_laboral_false
      t.text :atep_laboral_description
      t.boolean :familiar_true
      t.boolean :familiar_false
      t.text :familiar_description
      t.boolean :inmunologicos_true
      t.boolean :inmunologicos_false
      t.text :inmunologios_description
      t.boolean :asociado_viajes_de_vuelo_true
      t.boolean :asociado_viajes_de_vuelo_false
      t.text :asociado_viajes_de_vuelo_description
      t.integer :menstrual_cycle
      t.string :gestational_age
      t.string :eco
      t.integer :fum
      t.boolean :pregnancy_true
      t.boolean :pregnancy_false
      t.string :g
      t.string :p
      t.string :c
      t.string :a
      t.string :m
      t.string :v
      t.string :e
      t.boolean :cardiovascular_true
      t.boolean :cardiovascular_false
      t.text :cardiovascular_description
      t.boolean :respiratory_true
      t.boolean :respiratory_false
      t.text :respiratory_description
      t.boolean :abdominal_true
      t.boolean :abdominal_false
      t.text :abdominal_description
      t.boolean :genito_urinario_true
      t.boolean :genito_urinario_false
      t.text :genito_urinario_description
      t.string :neurological_true
      t.string :neurological_false
      t.text :neurological_description
      t.boolean :mental_true
      t.boolean :mental_false
      t.text :mental_description
      t.boolean :sense_organ_true
      t.boolean :sense_organ_false
      t.text :sense_organ_description
      t.boolean :skeletal_muscle_true
      t.boolean :skeletal_muscle_false
      t.text :skeletal_muscle_description
      t.string :ta_mmgh
      t.string :heart_rate
      t.string :breathing_frequency
      t.string :sat_of_o_ambiente
      t.string :sat_of_o_supplementary
      t.string :temperature
      t.string :weight_in_kilograms
      t.string :height_in_centimeters
      t.boolean :head_true
      t.boolean :head_false
      t.text :head_description
      t.boolean :sense_organ_true
      t.boolean :sense_organ_false
      t.string :sense_organ_description
      t.boolean :neck_true
      t.boolean :neck_false
      t.text :neck_description
      t.boolean :rib_cage_true
      t.boolean :rib_cage_false
      t.text :rib_cage_description
      t.boolean :heart_true
      t.boolean :heart_false
      t.text :heart_description
      t.boolean :lungs_true
      t.boolean :lungs_false
      t.text :lungs_description
      t.boolean :abdomen_true
      t.boolean :abdomen_false
      t.text :abdomen_description
      t.boolean :genitourinary_true
      t.boolean :genitourinary_false
      t.text :genitourinary_description
      t.boolean :rectum_true
      t.boolean :rectum_false
      t.text :rectum_description
      t.boolean :extremities_true
      t.boolean :extremities_false
      t.text :extremities_description
      t.boolean :skin_and_appendages_true
      t.boolean :skin_and_appendages_false
      t.text :skin_and_appendages_description
      t.boolean :piel_y_faneras2_true
      t.boolean :piel_y_faneras2_false
      t.text :piel_y_faneras2_descripcion
      t.boolean :skeletal_muscle_true
      t.boolean :skeletal_muscle_false
      t.text :skeletal_muscle_description
      t.boolean :mental_true
      t.boolean :mental_false
      t.text :mental_description
      t.boolean :neurological_true
      t.boolean :neurological_false
      t.text :neurological_description
      t.string :alteration
      t.integer :eye_opening
      t.integer :verbal_answer
      t.integer :motor_response
      t.string :other_signs
      t.integer  :escala_de_glasgow
      t.text :analysis
      t.text :print_diagnosed
      t.text :plan_and_treatment
      t.text :observations_recommendations

      t.timestamps null: false
    end
  end
end


text:
<?php

namespace ICanBoogie;

require __DIR__ . '/../vendor/autoload.php';

boot();


text:
namespace crashpad {

//! \brief A version of `iovec` with a `const` #iov_base field.
//!
//! This structure is intended to be used for write operations.
//
// Type compatibility with iovec is tested with static assertions in the
// implementation file.
struct WritableIoVec {
  //! \brief The base address of a memory region for output.
  const void* iov_base;

  //! \brief The size of the memory pointed to by #iov_base.
  size_t iov_len;
};

//! \brief An interface to write to files and other file-like objects with
//!     semantics matching the underlying platform (POSIX or Windows).
class FileWriterInterface : public virtual FileSeekerInterface {
 public:
  virtual ~FileWriterInterface() {}

  //! \brief Wraps LoggingWriteFile(), or provides an implementation with
  //!     identical semantics.
  //!
  //! \return `true` if the operation succeeded, `false` if it failed, with an
  //!     error message logged.
  virtual bool Write(const void* data, size_t size) = 0;

  //! \brief Wraps `writev()` on POSIX or provides an alternate implementation
  //!     with identical semantics. This method will write entire buffers,
  //!     continuing after a short write or after being interrupted. On
  //!     non-POSIX this is a simple wrapper around Write().
  //!
  //! \return `true` if the operation succeeded, `false` if it failed, with an
  //!     error message logged.
  //!
  //! \note The contents of \a iovecs are undefined when this method returns.
  virtual bool WriteIoVec(std::vector<WritableIoVec>* iovecs) = 0;
};

//! \brief A file writer backed by a FileHandle.
//!
//! FileWriter requires users to provide a FilePath to open, but this class
//! accepts an already-open FileHandle instead. Like FileWriter, this class may
//! write to a filesystem-based file, but unlike FileWriter, this class is not
//! responsible for creating or closing the file. Users of this class must
//! ensure that the file handle is closed appropriately elsewhere. Objects of
//! this class may be used to write to file handles not associated with
//! filesystem-based files, although special attention should be paid to the
//! Seek() method, which may not function on file handles that do not refer to
//! disk-based files.
//!
//! This class is expected to be used when other code is responsible for
//! creating files and already provides file handles.
class WeakFileHandleFileWriter : public FileWriterInterface {
 public:
  explicit WeakFileHandleFileWriter(FileHandle file_handle);

  WeakFileHandleFileWriter(const WeakFileHandleFileWriter&) = delete;
  WeakFileHandleFileWriter& operator=(const WeakFileHandleFileWriter&) = delete;

  ~WeakFileHandleFileWriter() override;

  // FileWriterInterface:
  bool Write(const void* data, size_t size) override;
  bool WriteIoVec(std::vector<WritableIoVec>* iovecs) override;

  // FileSeekerInterface:

  //! \copydoc FileWriterInterface::Seek()
  //!
  //! \note This method is only guaranteed to function on file handles referring
  //!     to disk-based files.
  FileOffset Seek(FileOffset offset, int whence) override;

 private:
  void set_file_handle(FileHandle file_handle) { file_handle_ = file_handle; }

  FileHandle file_handle_;  // weak

  // FileWriter uses this class as its internal implementation, and it needs to
  // be able to call set_file_handle(). FileWriter cannot initialize a
  // WeakFileHandleFileWriter with a correct file descriptor at the time of
  // construction because no file descriptor will be available until
  // FileWriter::Open() is called.
  friend class FileWriter;
};

//! \brief A file writer implementation that wraps traditional system file
//!     operations on files accessed through the filesystem.
class FileWriter : public FileWriterInterface {
 public:
  FileWriter();

  FileWriter(const FileWriter&) = delete;
  FileWriter& operator=(const FileWriter&) = delete;

  ~FileWriter() override;

  // FileWriterInterface:

  //! \brief Wraps LoggingOpenFileForWrite().
  //!
  //! \return `true` if the operation succeeded, `false` if it failed, with an
  //!     error message logged.
  //!
  //! \note After a successful call, this method cannot be called again until
  //!     after Close().
  bool Open(const base::FilePath& path,
            FileWriteMode write_mode,
            FilePermissions permissions);

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  //! \brief Wraps LoggingOpenMemoryFileForWrite().
  //!
  //! \return `true` if the operation succeeded, `false` if it failed, with an
  //!     error message logged.
  //!
  //! \note After a successful call, this method or Open() cannot be called
  //      again until after Close().
  bool OpenMemfd(const base::FilePath& path);

  //! \brief Returns the underlying file descriptor.
  //!
  //! \note This is used when this writes to a Memfd.
  int fd();
#endif

  //! \brief Wraps CheckedCloseHandle().
  //!
  //! \note It is only valid to call this method on an object that has had a
  //!     successful Open() that has not yet been matched by a subsequent call
  //!     to this method.
  void Close();

  // FileWriterInterface:

  //! \copydoc FileWriterInterface::Write()
  //!
  //! \note It is only valid to call this method between a successful Open() and
  //!     a Close().
  bool Write(const void* data, size_t size) override;

  //! \copydoc FileWriterInterface::WriteIoVec()
  //!
  //! \note It is only valid to call this method between a successful Open() and
  //!     a Close().
  bool WriteIoVec(std::vector<WritableIoVec>* iovecs) override;

  // FileSeekerInterface:

  //! \copydoc FileWriterInterface::Seek()
  //!
  //! \note It is only valid to call this method between a successful Open() and
  //!     a Close().
  FileOffset Seek(FileOffset offset, int whence) override;

 private:
  ScopedFileHandle file_;
  WeakFileHandleFileWriter weak_file_handle_file_writer_;
};

}  // namespace crashpad

#endif  // CRASHPAD_UTIL_FILE_FILE_WRITER_H_


text:
/********
 * repl : I/O for a "machine REPL" between processes
 ********/

#ifndef HOBBES_IPC_REPL_HPP_INCLUDED
#define HOBBES_IPC_REPL_HPP_INCLUDED

#include <string>
#include <unistd.h>

namespace hobbes {

class cc;

struct proc {
  std::string cmd;      // the command that spawned this process
  pid_t       pid;      // the local pid of the process being communicated with
  int         write_fd; // write to this to send remote proc messages
  int         read_fd;  // read from this to get remote proc responses
};

void spawn(const std::string&, proc*);
void procSearch(proc*, const std::string&, const std::string&);
void procDefine(proc*, const std::string&, const std::string&);
void procEval(proc*, const std::string&);
void procTypeof(proc* p, const std::string& x);
void procTypeEnv(proc* p);
void procRead(proc*, std::ostream*, uint64_t waitUS = 0);
MonoTypePtr refinedType(const proc& p, const std::string& fname, const MonoTypePtr& hasty);
int invocationID(const proc& p, const std::string& fname, const MonoTypePtr& hasty);

typedef std::pair<size_t, MonoTypePtr> PrepProcExpr;
PrepProcExpr procPrepareExpr(const proc&, const ExprPtr&);

void runMachineREPL(cc*);

}

#endif


text:
using SGF;
using Snaker.Game.Data;
using UnityEngine;

namespace Snaker.Game.Map
{
	public class GameMap
    {
		//===========================================================================

        private MapScript m_script;
        private GameObject m_view;

        private Vector3 m_size;

        public void Load(MapData data)
        {
			GameObject mapPrefab = Resources.Load<GameObject>("map/map_" + data.id);
			m_view = GameObject.Instantiate(mapPrefab);

			Vector3 size = m_view.GetComponent<SpriteRenderer>().sprite.bounds.size;
			size.x *= m_view.transform.localScale.x;
			size.y *= m_view.transform.localScale.y;
			size.z *= m_view.transform.localScale.z;
			m_size = size;

            m_script = m_view.GetComponent<MapScript>();
        }

        public void Unload()
        {
			m_script = null;

            if(m_view != null)
            {
                GameObject.Destroy(m_view);
                m_view = null;
            }

        }

        public void EnterFrame(int frameIndex)
        {
            if(m_script != null)
            {
                m_script.EnterFrame(frameIndex);
            }
        }

        public Vector3 Size{ get { return m_size; } }
        public GameObject View{ get { return m_view; } }

    }
}


text:
<?php

declare (strict_types=1);
namespace PhpParser;

interface NodeVisitor
{
    /**
     * Called once before traversal.
     *
     * Return value semantics:
     *  * null:      $nodes stays as-is
     *  * otherwise: $nodes is set to the return value
     *
     * @param Node[] $nodes Array of nodes
     *
     * @return null|Node[] Array of nodes
     */
    public function beforeTraverse(array $nodes);
    /**
     * Called when entering a node.
     *
     * Return value semantics:
     *  * null
     *        => $node stays as-is
     *  * NodeTraverser::DONT_TRAVERSE_CHILDREN
     *        => Children of $node are not traversed. $node stays as-is
     *  * NodeTraverser::STOP_TRAVERSAL
     *        => Traversal is aborted. $node stays as-is
     *  * otherwise
     *        => $node is set to the return value
     *
     * @param Node $node Node
     *
     * @return null|int|Node Replacement node (or special return value)
     */
    public function enterNode(\PhpParser\Node $node);
    /**
     * Called when leaving a node.
     *
     * Return value semantics:
     *  * null
     *        => $node stays as-is
     *  * NodeTraverser::REMOVE_NODE
     *        => $node is removed from the parent array
     *  * NodeTraverser::STOP_TRAVERSAL
     *        => Traversal is aborted. $node stays as-is
     *  * array (of Nodes)
     *        => The return value is merged into the parent array (at the position of the $node)
     *  * otherwise
     *        => $node is set to the return value
     *
     * @param Node $node Node
     *
     * @return null|int|Node|Node[] Replacement node (or special return value)
     */
    public function leaveNode(\PhpParser\Node $node);
    /**
     * Called once after traversal.
     *
     * Return value semantics:
     *  * null:      $nodes stays as-is
     *  * otherwise: $nodes is set to the return value
     *
     * @param Node[] $nodes Array of nodes
     *
     * @return null|Node[] Array of nodes
     */
    public function afterTraverse(array $nodes);
}