text:
var   fs = require('graceful-fs')
    , path = require('path')
    , jsonic = require('jsonic')
    , nodeutil = require('util')
    , util = require('../util/util')
    , _prepare = require('./prepare')
    , _bake = require('./bake')
    , bars = require('handlebars')
    , glob = require('glob')
    , gate = require('json-gate')

var internal = {};
exports.default_name = 'project.flow';

exports.paths = {}
exports.init = function init(flow) {

    var success = true;

        //default to the system if no target specified,
        //but needs to watch for command lines calling target
    flow.target =
        flow.flags._next('build')   ||
        flow.flags._next('compile') ||
        flow.flags._next('launch')  ||
        flow.flags._next('run')     ||
        flow.flags._next('files')   ||
        flow.flags._next('package') ||
        flow.flags._next('clean')   ||
        flow.flags._next('info')    ||
        flow.flags._next('icons')   ||
        flow.flags._next('hooks')   ||
        flow.flags._next('setup')   ||
        flow.flags._next('sync')    ||
        flow.system;

    flow.target_arch = flow.project.find_arch(flow);

        //make sure these exist even if unset
    flow.target_cpp = false;
    flow.target_js = false;
    flow.target_neko = false;
    flow.target_desktop = false;
    flow.target_mobile = false;

    switch(flow.target) {
        case 'mac': case 'windows': case 'linux':
            flow.target_desktop = true;
        break;
        case 'ios': case 'android':
            flow.target_mobile = true;
        break;
    }

    var type = flow.config.build.target[flow.target];

    if(type == "cpp") flow.target_cpp = true;
    if(type == "js") flow.target_js = true;
    if(type == "neko") flow.target_neko = true;

    return success;

} //init

bars.registerHelper('toString', function( value ) {
    return ( value === void 0 ) ? 'undefined' : value.toString();
});

bars.registerHelper('packageClass', function( value ) {
    var _parts = value.split('.');
    return _parts[_parts.length-1];
});

bars.registerHelper('not_undefined', function( value ) {
    return ( value !== void 0 );
});

bars.registerHelper('is_undefined', function( value ) {
    return ( value === void 0 );
});

bars.registerHelper('upperFirst', function( value ) {
    return value.charAt(0).toUpperCase() + value.slice(1);
});

bars.registerHelper('if', function (v1, op_opt, v2, options) {

    if(options === void 0) {
        if(v2 === void 0) {
            return v1 ? op_opt.fn(this) : op_opt.inverse(this);
        }
    }

    var _true = false;
    switch (op_opt) {
        case '==':  _true = v1 == v2;   break;
        case '===': _true = v1 === v2;  break;
        case '!==': _true = v1 !== v2;  break;
        case '<':   _true = v1 < v2;    break;
        case '<=':  _true = v1 <= v2;   break;
        case '>':   _true = v1 > v2;    break;
        case '>=':  _true = v1 >= v2;   break;
        case '||':  _true = v1 || v2;   break;
        case '&&':  _true = v1 && v2;   break;
    }
    return _true ? options.fn(this) : options.inverse(this);
});

exports.find_flow_files = function(flow, root) {

    var list = [];

    glob( "*.flow" , { sync:true, cwd:root }, function(er, files) {
        list = list.concat(files);
    });

    return list;

} //find_flow_files

exports.verify = function verify(flow, project_path, project_root, is_dependency, quiet) {

    var project_file = project_path;
        project_root = project_root || process.cwd();

    project_root = path.resolve(project_root);

    var abs_path = '';

    function fail_verify(reason) {
        return {
            parsed : null,
            reason : reason,
            file : project_file,
            path : abs_path,
            root : project_root,
        };
    }

        //if no explicit project given, search for one
    if(!project_file) {

        flow.log(3, 'project - searching project root %s', project_root)

        var flow_files = exports.find_flow_files(flow, project_root);

        if(flow_files.length > 1) {
            return fail_verify('uh.. multiple *.flow files found, which one did you mean? use --project <your.flow> or keep a single flow file in the root of your project. root:' + project_root);
        } else if(flow_files.length == 0) {
            return fail_verify('cannot find any *.flow project files in '+project_root+'/ - run flow from your project root alongside your.flow file or use --project <your.flow>');
        } else {
            project_file = flow_files[0];
        }

    } //project_file

    abs_path = util.normalize(path.resolve(project_root, project_file));

    project_root = project_root || path.dirname(abs_path);
    project_root = util.normalize(project_root, true);

    if(!flow.quiet.project && !quiet) {
        flow.log(3, 'project - using project file %s', abs_path)
    }

    if(!fs.existsSync(abs_path)) {
        return fail_verify('cannot find project file at ' + abs_path);
    }

    var result;
    var parsed = null;
    var file_contents = fs.readFileSync( abs_path,'utf8' );

    if(!file_contents) {
        return fail_verify('file content is invalid for %s? content : ', abs_path, file_contents);
    }

    try {

        parsed = jsonic( file_contents );

    } catch(e) {

        var reason = 'syntax error in project file\n';
            reason += nodeutil.format(' > %s:%d:%d %s \n', project_file, e.line,e.column, e.message);

        return fail_verify(reason);

    } //catch

        //check that its valid
    if(!parsed || parsed.constructor != Object) {
        return fail_verify('flow projects are a json object, this appears to be : ' + parsed.constructor.name);
    }

        //now check that it has valid information
    if(!(parsed.project)) {
        return fail_verify('flow projects require a { project:{ name:"", version:"" } } minimum. missing "project"');
    }

    if(!(parsed.project.version)) {
        return fail_verify('flow projects require a { project:{ name:"", version:"" } } minimum. missing "version"');
    }

    if(!(parsed.project.name)) {
        return fail_verify('flow projects require a { project:{ name:"", version:"" } } minimum. missing "name"');
    }

        //then merge any base options from flow defaults into it,
        //unless it is a dependency project, those don't need this
    if(!is_dependency) {
        parsed.project = util.merge_unique(flow.project.defaults.project, parsed.project);
    } else {
        var dependency_defaults = { build:{} };
        parsed.project = util.merge_unique(dependency_defaults, parsed.project);
    }

    parsed.__root = project_root;
    parsed.__path = abs_path;
    parsed.__file = project_file;

    result = {
        parsed : parsed,
        root : project_root,
        path : abs_path,
        file : project_file
    };

    return result;

} //verify

//path utilities

exports.get_path_context = function(flow, prepared, target_arch) {

    var path_context = {
        app : {
            arch : target_arch,
            archtag : '',
            debugtag : flow.flags.debug ? '-debug' : '',
            iostag : 'os',
            boot : flow.config.build.boot,
            name : prepared.source.project.app.name
        },
        paths : flow.project.paths
    }

    if(target_arch == 'sim' || target_arch == 'sim64') {
        path_context.app.iostag = 'sim';
    }

        if(flow.target == 'android') {
            switch(target_arch) {
                case 'x86':
                    path_context.app.libabi = 'x86';
                break;
                case 'armv7':
                    path_context.app.libabi = 'armeabi-v7a';
                break;
                case 'arm64':
                    path_context.app.libabi = 'arm64-v8a';
                break;
                default:
                    path_context.app.libabi = 'armeabi';
                break;
            }
        }

        switch(target_arch) {
            case 'arm64':
            case 'sim64':
                path_context.app.archtag = '-64';
                break;
            case 'armv7':
                path_context.app.archtag = '-v7';
                break;
            case 'x86':
                path_context.app.archtag = '-x86';
                break;
            case 'armv7s':
                path_context.app.archtag = '-v7s';
                break;
        }

    return path_context;

} //get_path_context

exports.path_config_template = function(flow, prepared, path_template, context, norm) {
    var template = bars.compile(path_template);
    var result = template(context);
    return util.normalize(result, norm);
}

    //the final target path for the output
exports.get_path_root = function(flow, prepared, target_arch) {

    target_arch = exports.adjust_arch(flow, target_arch);
    var outpath = prepared.source.project.app.output;

    return util.normalize(outpath, true);

} //get_path_root

exports.get_path_output = function(flow, prepared, target_arch) {

    target_arch = exports.adjust_arch(flow, target_arch);
    var dest_folder = exports.get_path_root(flow, prepared);

    dest_folder = path.join(dest_folder, flow.target);

    if(flow.target_arch == '64') {
        dest_folder += '64';
    }

    if(flow.target == 'mac') {
        var from_xcode = process.env['XCODE_VERSION_ACTUAL'];
        if(from_xcode) {
            dest_folder = process.env['TARGET_BUILD_DIR'];
            flow.log(2, 'project - set build output path to Xcode build directory');
            flow.log(2, 'project -     - `%s`', dest_folder);
        }
    }

    var cli_outpath = flow.flags['output-path'];
    if(cli_outpath) {
        if(cli_outpath !== true) {
            dest_folder = cli_outpath;
        } else {
            flow.log(2, 'project - warning - cli specified output-path without a value. ignoring!');
        }
    }

    return util.normalize(dest_folder, true);

} //get_path_output

exports.get_path_build = function(flow, prepared, target_arch) {

    target_arch = exports.adjust_arch(flow, target_arch);
    var dest_folder = exports.get_path_root(flow, prepared);

    dest_folder = path.join(dest_folder, flow.target);

    if(flow.target_arch == '64') {
        dest_folder += '64';
    }

    dest_folder += '.build';

    return util.normalize(dest_folder, true);

} //get_path_build

exports.get_path_files = function(flow, prepared, target_arch) {

    target_arch = exports.adjust_arch(flow, target_arch);
    var dest_path = flow.config.build.files_dest_path;

    var plat = flow.config.build[flow.target];
    if(plat && plat.files_dest_path) {
        dest_path = plat.files_dest_path;
    }

        //work out the context needed
    var context = exports.get_path_context(flow, prepared, target_arch);
        //return the templated value
    return exports.path_config_template(flow, prepared, dest_path, context, true);

} //get_path_files

exports.get_path_binary_dest = function(flow, prepared, target_arch) {

    target_arch = exports.adjust_arch(flow, target_arch);
    var dest_path = flow.config.build.binary_dest_path;

    var plat = flow.config.build[flow.target];
    if(plat && plat.binary_dest_path) {
        dest_path = plat.binary_dest_path;
    }

        //work out the context needed
    var context = exports.get_path_context(flow, prepared, target_arch);
        //return the templated value
    return exports.path_config_template(flow, prepared, dest_path, context, true);

} //get_path_binary_dest

exports.get_path_binary_name = function(flow, prepared, target_arch) {

    target_arch = exports.adjust_arch(flow, target_arch);
    var dest_name = flow.config.build.binary_dest_name;

    var plat = flow.config.build[flow.target];
    if(plat && plat.binary_dest_name) {
        dest_name = plat.binary_dest_name;
    }

        //work out the context needed
    var context = exports.get_path_context(flow, prepared, target_arch);
        //return the templated value
    return exports.path_config_template(flow, prepared, dest_name, context);

} //get_path_binary_name

exports.get_path_binary_name_source = function(flow, prepared, target_arch) {

    target_arch = exports.adjust_arch(flow, target_arch);
    var src_name = flow.config.build.binary_source_name;

    var plat = flow.config.build[flow.target];
    if(plat && plat.binary_source_name) {
        src_name = plat.binary_source_name;
    }

        //work out the context needed
    var context = exports.get_path_context(flow, prepared, target_arch);
        //return the templated value
    return exports.path_config_template(flow, prepared, src_name, context);

} //get_path_binary_name_source

exports.get_path_binary_dest_full = function(flow, prepared, target_arch) {

    target_arch = exports.adjust_arch(flow, target_arch);

    var dest = exports.get_path_binary_dest(flow, prepared, target_arch);
    var file = exports.get_path_binary_name(flow, prepared, target_arch);

    return path.join(dest,file);

} //get_path_binary_full

exports.adjust_arch = function(flow, target_arch) {

    target_arch = target_arch || flow.target_arch;

    if(flow.target == 'ios' || flow.target == 'tvos') {
        if(target_arch == 'i386') target_arch = 'sim';
        if(target_arch == 'x86_64') target_arch = 'sim64';
    }

    return target_arch;

} //adjust_arch

exports.prepare = function prepare(flow) {

    return _prepare.prepare(flow);

} //exports.prepare

exports.do_prepare = function(flow) {

    if(flow.project.prepared) {
        return;
    }

    flow.quiet.prepare = true;
    flow.quiet.project = true;

        //if no project given, it will look for one
    var _current_project = flow.flags.project;
    var _current_project_root = flow.flags['project-root'];
    var project = flow.project.verify(flow, _current_project, _current_project_root);

        //if no valid project was found
    if(!project.parsed) {
        return internal._error_project(flow, project.reason);
    }

    flow.project.parsed = project.parsed;
    flow.project.root = path.dirname(project.path);
    flow.project.path = project.path;
    flow.project.file = project.file;

    exports.ensure_path(flow);

    flow.project.prepare(flow);

    if(flow.project.prepared) {
        flow.project.bake(flow);
    } else {
        flow.log(1, 'project - failed at prepare');
    }

} //do_prepare

exports.ensure_path = function(flow) {

        //ensure we are in the correct place to perform any operations

    flow.log(3, 'project - switch to run in %s', flow.project.root);
    process.chdir(flow.project.root);

} //ensure_path

internal._error_project = function(flow, reason){

    if(reason && reason.length > 0) {
        return 'project file error \n\n > ' + reason;
    } else {
        return 'unknown project error';
    }

} //_error_project

exports.bake = function bake(flow) {

    return _bake.bake(flow);

} //exports.bake

    //return the specific arch/debug etc tags
    //for the given flow state
internal.get_context_tags = function(flow, into_node) {

        if(flow.flags.debug) {
            into_node.debugtag = '-debug';
        }

        if(flow.target_arch == 'sim' || flow.target_arch == 'sim64') {
            into_node.iostag = 'sim';
        }

        if(flow.target_arch == 'arm64') {
            into_node.archtag = '-64';
        }

        if(flow.target_arch == 'sim64') {
            into_node.archtag = '-64';
        }

        if(flow.target_arch == 'armv7') {
            into_node.archtag = '-v7';
        }

        if(flow.target_arch == 'armv7s') {
            into_node.archtag = '-v7s';
        }

    return into_node;

} //get_context_tags

    //get a template context for a file template
exports.get_file_context = function(flow) {

    var result = {
        debug : flow.flags.debug || false,
        arch : flow.target_arch,
        archtag : '',
        debugtag : '',
        flow : {
            config : util.deep_copy(flow.config)
        }
    };

    result = internal.get_context_tags(flow, result);

    return result;

} //get_file_context

exports.find_arch = function(flow) {

    var config_arch = flow.config.build.arch[flow.target]
    if(config_arch) {
        return config_arch
    }

        //check if there is any explicit arch given
    if(flow.flags.arch) {

        var _arch = flow.flags.arch;

        if(_arch === true) {
            flow.log(1, '\nError\n--arch specified but no arch given\n\n> use --arch 32, --arch 64, --arch armv6 etc.\n');
            return null;
        } else {
            return String(_arch);
        }

    } //flags.arch

    var arch = 'unknown';

    if( flow.target == 'mac' ||
        flow.target == 'windows' ||
        flow.target == 'linux') {

            //https://coderwall.com/p/0eds7q
            //because windows is terrible at basics.
        var is64bit = process.arch === 'x64' ||
                      process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');

        if(is64bit) {

            arch = '64';

                //:todo: currently hxcpp doesn't bundle
                //the prebuilt Windows64/ libs. And might not build 64 bit?
                //to build these, use `neko ./build.n`
                //from within /path/to/hxcpp/project/ folder
                //and use --arch 64 explicitly
            if(flow.target == 'windows') {
                arch = '32';
            }

        } else if(process.arch == 'ia32') {
            arch = '32';
        }

    } //

        //if running from an xcode build
    if(process.env['XCODE_VERSION_ACTUAL']) {
        var env_arch = process.env['CURRENT_ARCH'];
        if(env_arch == 'i386' || env_arch == 'x86_64') {
            arch = 'sim';
            if(env_arch == 'x86_64') {
                arch += '64';
            }
        }
    }

    return arch;

} //arch


text:
var MultiStreamsMixer;

try {
    MultiStreamsMixer = require('multistreamsmixer');
}
catch(e) {
    MultiStreamsMixer = require('./MultiStreamsMixer.js');
}

const fakeMediaStream = {};

var mixer = new MultiStreamsMixer([ fakeMediaStream ]);
console.log('mixer: ', mixer);

process.exit()

redpajama_set_name: RedPajamaGithub


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

<title>T-Index</title>
<meta name="date" content="2016-06-14">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

C G M P R S T U V

T

testFileName() - Method in class TestJunit

Tests if the file name checking works

testFileName(String) - Method in class Utilities

Tests if the filename exists and it's not a directory

TestJunit - Class in <Unnamed>

Created by Tahnik Mustasin on 10/06/2016.

TestJunit() - Constructor for class TestJunit

testPackages() - Method in class TestJunit

Tests if the packages are added correctly

testPrintPackageDependencies() - Method in class TestJunit

Tests if the printing dependencies works

TestRunner - Class in <Unnamed>

Created by Tahnik Mustasin on 10/06/2016.

TestRunner() - Constructor for class TestRunner

testSplitLines() - Method in class TestJunit

Tests if the lines are split correctly

testverifyLine() - Method in class TestJunit

Tests different type of lines to verify

C G M P R S T U V

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package go_kindeditor

import (
	"bufio"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"time"
)

var _ sort.Interface = new(SorterFiles)

type SorterFiles struct {
	files  []os.FileInfo
	sortBy string
}

func (this *SorterFiles) Len() int {
	return len(this.files)
}

// Less reports whether the element with
// index i should sort before the element with index j.
func (this *SorterFiles) Less(i, j int) bool {
	switch strings.ToLower(this.sortBy) {
	case "size":
		return this.files[i].Size() < this.files[j].Size()
	case "name":
		return this.files[i].Name() < this.files[j].Name()
	case "type":
		iN, jN := this.files[i].Name(), this.files[j].Name()
		return iN[strings.Index(iN, ".")+1:] < jN[strings.Index(jN, ".")+1:]
	}
	return true
}

// Swap swaps the elements with indexes i and j.
func (this *SorterFiles) Swap(i, j int) {
	tmp := this.files[i]
	this.files[i] = this.files[j]
	this.files[j] = tmp
}

//图片扩展名
var imgFileTypes string = "gif,jpg,jpeg,png,bmp"
var (
	moveUpRegexp *regexp.Regexp = regexp.MustCompile("(.*?)[^\\/]+\\/$")
)

// 文件管理
// @rootDir : 根目录路径,相对路径
// @rootUrl : 根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
func fileManager(r *http.Request, rootDir, rootUrl string) ([]byte, error) {
	var currentPath = ""
	var currentUrl = ""
	var currentDirPath = ""
	var moveUpDirPath = ""
	var dirPath string = rootDir

	urlQuery := r.URL.Query()
	var dirName string = urlQuery.Get("dir")

	if len(dirName) != 0 {
		if dirName == "image" || dirName == "flash" ||
			dirName == "media" || dirName == "file" {
			dirPath += dirName + "/"
			rootUrl += dirName + "/"
			if _, err := os.Stat(dirPath); os.IsNotExist(err) {
				os.MkdirAll(dirPath, os.ModePerm)
			}
		} else {
			return nil, errors.New("Invalid Directory name")
		}
	}

	//根据path参数,设置各路径和URL
	var path string = urlQuery.Get("path")
	if len(path) == 0 {
		currentPath = dirPath
		currentUrl = rootUrl
		currentDirPath = ""
		moveUpDirPath = ""
	} else {
		currentPath = dirPath + path
		currentUrl = rootUrl + path
		currentDirPath = path
		moveUpDirPath = moveUpRegexp.ReplaceAllString(currentDirPath, "$1")
	}

	//不允许使用..移动到上一级目录
	if strings.Index(path, "\\.\\.") != -1 {
		return nil, errors.New("Access is not allowed.")
	}

	//最后一个字符不是/
	if path != "" && !strings.HasSuffix(path, "/") {
		return nil, errors.New("Parameter is not valid.")
	}
	//目录不存在或不是目录
	dir, err := os.Stat(currentPath)
	if os.IsNotExist(err) || !dir.IsDir() {
		return nil, errors.New("no such directory or file not directory,path:" + currentPath)
	}

	//排序形式,name or size or type
	var order string = strings.ToLower(urlQuery.Get("order"))

	//遍历目录取得文件信息
	var dirList *SorterFiles = &SorterFiles{
		files:  []os.FileInfo{},
		sortBy: order,
	}
	var fileList *SorterFiles = &SorterFiles{
		files:  []os.FileInfo{},
		sortBy: order,
	}

	// 遍历目录获取子目录和文件
	files, err := ioutil.ReadDir(currentPath)
	if err != nil {
		return nil, err
	}
	for _, v := range files {
		if v.IsDir() {
			dirList.files = append(dirList.files, v)
		} else {
			fileList.files = append(fileList.files, v)
		}
	}

	// 排序
	sort.Sort(dirList)
	sort.Sort(fileList)

	var result = make(map[string]interface{})
	result["moveup_dir_path"] = moveUpDirPath
	result["current_dir_path"] = currentDirPath
	result["current_url"] = currentUrl
	result["total_count"] = dirList.Len() + fileList.Len()
	var dirFileList = []map[string]interface{}{}
	for i := 0; i < dirList.Len(); i++ {
		hash := make(map[string]interface{})
		fs, _ := ioutil.ReadDir(currentPath + "/" + dirList.files[i].Name())
		fmt.Println("----", currentPath+"/"+dirList.files[i].Name())
		hash["is_dir"] = true
		hash["has_file"] = len(fs) > 0
		hash["is_photo"] = false
		hash["filetype"] = ""
		hash["filename"] = dirList.files[i].Name()
		hash["datetime"] = dirList.files[i].ModTime().Format("2006-01-02 15:04:05")
		dirFileList = append(dirFileList, hash)
	}

	var fN, ext string
	for i := 0; i < fileList.Len(); i++ {
		hash := make(map[string]interface{})
		fN = fileList.files[i].Name()
		ext = fN[strings.Index(fN, ".")+1:]
		hash["is_dir"] = false
		hash["has_file"] = false
		hash["filesize"] = fileList.files[i].Size()
		hash["is_photo"] = strings.Index(imgFileTypes, ext)
		hash["filetype"] = ext
		hash["filename"] = fN
		hash["datetime"] = fileList.files[i].ModTime().Format("2006-01-02 15:04:05")
		dirFileList = append(dirFileList, hash)
	}

	result["file_list"] = dirFileList
	return json.Marshal(result)
}

// 文件上传
func fileUpload(r *http.Request, savePath, rootPath string) (fileUrl string, err error) {

	//定义允许上传的文件扩展名
	var extTable map[string]string = map[string]string{
		"image": "gif,jpg,jpeg,png,bmp",
		"flash": "swf,flv",
		"media": "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb",
		"file":  "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,7z,pdf",
	}

	//最大文件大小
	const maxSize int64 = 1000000

	// 取得上传文件
	r.ParseMultipartForm(maxSize)
	f, header, err := r.FormFile("imgFile")
	if f == nil {
		return "", errors.New("no such upload file")
	}
	if err != nil {
		return "", err
	}

	var fileName string = header.Filename
	var fileExt string = strings.ToLower(fileName[strings.Index(fileName, ".")+1:])

	// 检查上传目录
	var dirPath string = rootPath
	var dirName string = r.URL.Query().Get("dir")
	if len(dirName) == 0 {
		dirName = "image"
	}
	if _, ok := extTable[dirName]; !ok {
		return "", errors.New("incorrent file type")
	}

	// 检查扩展名
	if strings.Index(extTable[dirName], fileExt) == -1 &&
		!strings.HasSuffix(extTable[dirName], fileExt) {
		return "", errors.New("上传文件扩展名是不允许的扩展名。\n只允许" + extTable[dirName] + "格式。")
	}

	// 检查上传超出文件大小
	if i, _ := strconv.Atoi(header.Header.Get("Content-Length")); int64(i) > maxSize {
		return "", errors.New("上传文件大小超过限制。")
	}

	//创建文件夹
	dirPath += dirName + "/"
	savePath += dirName + "/"

	var now = time.Now()
	var ymd string = now.Format("200601")
	dirPath += ymd + "/"
	savePath += ymd + "/"

	if _, err := os.Stat(savePath); os.IsNotExist(err) {
		os.MkdirAll(savePath, os.ModePerm)
	}

	var newFileName string = fmt.Sprintf("%d_%d.%s", now.Unix(),
		100+rand.Intn(899), fileExt)
	var filePath string = savePath + newFileName

	fi, err := os.OpenFile(filePath,
		os.O_CREATE|os.O_TRUNC|os.O_WRONLY,
		os.ModePerm)

	if err == nil {
		defer fi.Close()
		buf := bufio.NewWriter(fi)
		bufSize := 100
		buffer := make([]byte, bufSize)
		var n int
		var totalLen int
		for {
			if n, err = f.Read(buffer); err == io.EOF {
				break
			}

			if n != bufSize {
				buf.Write(buffer[:n])
			} else {
				buf.Write(buffer)
			}

			totalLen += n
		}
		buf.Flush()
	}

	return dirPath + newFileName, nil
}


text:
Wrapper for `mirscreencast` and `ffmpeg` to record Unity 8 desktop videos.

## Introduction

Using `mirscreencast` to capture recordings of a Unity 8 desktop session
on my Dell XPS15, which has a UHD display, requires *tens of Gigabytes of
storage per minute* because `mirscreencast` captures the native resolution
using rawvideo at 60fps.

This script automatically determines (hopefully) sane defaults for
`mirscreencast` and directs its output at a
[FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)),
then `ffmpeg` starts real-time encoding from the FIFO using similarly
sane defaults.

The result is that 1080p captures of a Unity 8 desktop session can now
be recorded using *tens of Megabytes per minute*.

## Requirements

Currently `mircapture` has only been tested on Ubuntu (Yakkety Yak) 16.10.

    apt install ffmpeg mir-utils netcat

## Usage

  * Clone this repository:
    * `git clone https://github.com/flexiondotorg/mircapture.git`

  * Log in to a Unity 8 desktop session.

  * Start a Terminal and run the following to capture the desktop:
    * `./mircapture`

  * When you've recorded what you want, return to the terminal where `mircapture` is running and just press `q` to stop `ffmpeg`.
    * `mircapture` will cleanly stop `mirscreencast` for you, no manual `pkill -9` required.

  * You'll have a new video in your home directory.
    * Named something like: `Mircapture_1920x1080-30.00fps-16304-0939-50.mp4`

## Changes

Summary of changes.

### 1.0

  * Initial release.
  * Local capture and encoding only.

## To Do

  * Add options for `-local`, `-tx`, `-rx` so that captures can optionally be streamed to a remote host for encoding.
  * Add optional audio input selection for recording voice overs.
  * Make `mircapture` a snap. May require the utility interface which is not yet available.


text:
package org.elasticsearch.index.translog.fs;

import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.Channels;
import org.elasticsearch.common.util.concurrent.ReleasableLock;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.index.translog.TranslogException;
import org.elasticsearch.index.translog.TranslogStream;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;

/**
 */
public final class BufferingFsTranslogFile extends FsTranslogFile {

    private volatile int operationCounter;
    private volatile long lastPosition;
    private volatile long lastWrittenPosition;

    private volatile long lastSyncPosition = 0;

    private byte[] buffer;
    private int bufferCount;
    private WrapperOutputStream bufferOs = new WrapperOutputStream();

    public BufferingFsTranslogFile(ShardId shardId, long id, ChannelReference channelReference, int bufferSize) throws IOException {
        super(shardId, id, channelReference);
        this.buffer = new byte[bufferSize];
        final TranslogStream stream = this.channelReference.stream();
        int headerSize = stream.writeHeader(channelReference.channel());
        this.lastPosition += headerSize;
        this.lastWrittenPosition += headerSize;
        this.lastSyncPosition += headerSize;
    }

    @Override
    public int totalOperations() {
        return operationCounter;
    }

    @Override
    public long sizeInBytes() {
        return lastWrittenPosition;
    }

    @Override
    public Translog.Location add(BytesReference data) throws IOException {
        try (ReleasableLock lock = writeLock.acquire()) {
            operationCounter++;
            long position = lastPosition;
            if (data.length() >= buffer.length) {
                flushBuffer();
                // we use the channel to write, since on windows, writing to the RAF might not be reflected
                // when reading through the channel
                data.writeTo(channelReference.channel());
                lastWrittenPosition += data.length();
                lastPosition += data.length();
                return new Translog.Location(id, position, data.length());
            }
            if (data.length() > buffer.length - bufferCount) {
                flushBuffer();
            }
            data.writeTo(bufferOs);
            lastPosition += data.length();
            return new Translog.Location(id, position, data.length());
        }
    }

    private void flushBuffer() throws IOException {
        assert writeLock.isHeldByCurrentThread();
        if (bufferCount > 0) {
            // we use the channel to write, since on windows, writing to the RAF might not be reflected
            // when reading through the channel
            Channels.writeToChannel(buffer, 0, bufferCount, channelReference.channel());
            lastWrittenPosition += bufferCount;
            bufferCount = 0;
        }
    }

    @Override
    protected void readBytes(ByteBuffer targetBuffer, long position) throws IOException {
        try (ReleasableLock lock = readLock.acquire()) {
            if (position >= lastWrittenPosition) {
                System.arraycopy(buffer, (int) (position - lastWrittenPosition),
                        targetBuffer.array(), targetBuffer.position(), targetBuffer.limit());
                return;
            }
        }
        // we don't have to have a read lock here because we only write ahead to the file, so all writes has been complete
        // for the requested location.
        Channels.readFromFileChannelWithEofException(channelReference.channel(), position, targetBuffer);
    }

    public FsChannelImmutableReader immutableReader() throws TranslogException {
        if (channelReference.tryIncRef()) {
            try (ReleasableLock lock = writeLock.acquire()) {
                flushBuffer();
                FsChannelImmutableReader reader = new FsChannelImmutableReader(this.id, channelReference, lastWrittenPosition, operationCounter);
                channelReference.incRef(); // for new reader
                return reader;
            } catch (Exception e) {
                throw new TranslogException(shardId, "exception while creating an immutable reader", e);
            } finally {
                channelReference.decRef();
            }
        } else {
            throw new TranslogException(shardId, "can't increment channel [" + channelReference + "] ref count");
        }
    }

    @Override
    public boolean syncNeeded() {
        return lastPosition != lastSyncPosition;
    }

    @Override
    public void sync() throws IOException {
        if (!syncNeeded()) {
            return;
        }
        try (ReleasableLock lock = writeLock.acquire()) {
            flushBuffer();
            lastSyncPosition = lastPosition;
        }
        channelReference.channel().force(false);
    }

    @Override
    protected void doClose() throws IOException {
        try {
            sync();
        } finally {
            super.doClose();
        }
    }

    @Override
    public void reuse(FsTranslogFile other) {
        if (!(other instanceof BufferingFsTranslogFile)) {
            return;
        }
        try (ReleasableLock lock = writeLock.acquire()) {
            try {
                flushBuffer();
                this.buffer = ((BufferingFsTranslogFile) other).buffer;
            } catch (IOException e) {
                throw new TranslogException(shardId, "failed to flush", e);
            }
        }
    }

    public void updateBufferSize(int bufferSize) {
        try (ReleasableLock lock = writeLock.acquire()) {
            if (this.buffer.length == bufferSize) {
                return;
            }
            flushBuffer();
            this.buffer = new byte[bufferSize];
        } catch (IOException e) {
            throw new TranslogException(shardId, "failed to flush", e);
        }
    }

    class WrapperOutputStream extends OutputStream {

        @Override
        public void write(int b) throws IOException {
            buffer[bufferCount++] = (byte) b;
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            // we do safety checked when we decide to use this stream...
            System.arraycopy(b, off, buffer, bufferCount, len);
            bufferCount += len;
        }
    }

}


text:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace SpiffCode
{
	/// <summary>
	/// Summary description for StripsForm.
	/// </summary>
	public class StripsForm : System.Windows.Forms.Form
	{
		private AnimDoc m_doc;
		private StripSet m_stps;
		private Strip m_stpActive;
		private System.Windows.Forms.ListView lstv;
		private System.Windows.Forms.ColumnHeader columnHeader1;
		private System.Windows.Forms.ColumnHeader columnHeader2;
		private System.Windows.Forms.MenuItem mniView;
		private System.Windows.Forms.MenuItem mniViewDetails;
		private System.Windows.Forms.MenuItem mniViewList;
		private System.Windows.Forms.MenuItem mniViewThumbnails;
		private System.Windows.Forms.ContextMenu mnuListView;
		private System.Windows.Forms.MenuItem mniNewStrip;
		private System.Windows.Forms.MenuItem menuItem2;
		private System.Windows.Forms.MenuItem mniDelete;
		private System.Windows.Forms.MenuItem mniRename;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem menuItem3;
		private System.Windows.Forms.MenuItem mniProperties;
		private System.Windows.Forms.MenuItem mniStripsSort;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public StripsForm(AnimDoc doc)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			// My constructor code

			Globals.ActiveDocumentChanged += new EventHandler(OnActiveDocumentChanged);
			Globals.ActiveStripChanged += new EventHandler(OnActiveStripChanged);
			m_doc = doc;
			m_stps = m_doc.StripSet;
			RefreshView();
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.mniViewList = new System.Windows.Forms.MenuItem();
			this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
			this.mniView = new System.Windows.Forms.MenuItem();
			this.mniViewThumbnails = new System.Windows.Forms.MenuItem();
			this.mniViewDetails = new System.Windows.Forms.MenuItem();
			this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
			this.mniRename = new System.Windows.Forms.MenuItem();
			this.mnuListView = new System.Windows.Forms.ContextMenu();
			this.mniNewStrip = new System.Windows.Forms.MenuItem();
			this.menuItem2 = new System.Windows.Forms.MenuItem();
			this.mniDelete = new System.Windows.Forms.MenuItem();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.menuItem3 = new System.Windows.Forms.MenuItem();
			this.mniProperties = new System.Windows.Forms.MenuItem();
			this.lstv = new System.Windows.Forms.ListView();
			this.mniStripsSort = new System.Windows.Forms.MenuItem();
			this.SuspendLayout();
			//
			// mniViewList
			//
			this.mniViewList.Index = 0;
			this.mniViewList.Text = "List";
			this.mniViewList.Click += new System.EventHandler(this.mniViewList_Click);
			//
			// columnHeader2
			//
			this.columnHeader2.Text = "# frames";
			//
			// mniView
			//
			this.mniView.Index = 5;
			this.mniView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					this.mniViewList,
																					this.mniViewThumbnails,
																					this.mniViewDetails});
			this.mniView.Text = "View";
			this.mniView.Popup += new System.EventHandler(this.mniView_Popup);
			//
			// mniViewThumbnails
			//
			this.mniViewThumbnails.Index = 1;
			this.mniViewThumbnails.Text = "Thumbnails";
			this.mniViewThumbnails.Click += new System.EventHandler(this.mniViewThumbnails_Click);
			//
			// mniViewDetails
			//
			this.mniViewDetails.Index = 2;
			this.mniViewDetails.Text = "Details";
			this.mniViewDetails.Click += new System.EventHandler(this.mniViewDetails_Click);
			//
			// columnHeader1
			//
			this.columnHeader1.Text = "Name";
			this.columnHeader1.Width = 90;
			//
			// mniRename
			//
			this.mniRename.Index = 3;
			this.mniRename.Text = "Rename";
			this.mniRename.Click += new System.EventHandler(this.mniRename_Click);
			//
			// mnuListView
			//
			this.mnuListView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						this.mniNewStrip,
																						this.menuItem2,
																						this.mniDelete,
																						this.mniRename,
																						this.menuItem1,
																						this.mniView,
																						this.mniStripsSort,
																						this.menuItem3,
																						this.mniProperties});
			this.mnuListView.Popup += new System.EventHandler(this.mnuListView_Popup);
			//
			// mniNewStrip
			//
			this.mniNewStrip.Index = 0;
			this.mniNewStrip.Text = "New Strip";
			this.mniNewStrip.Click += new System.EventHandler(this.mniNewStrip_Click);
			//
			// menuItem2
			//
			this.menuItem2.Index = 1;
			this.menuItem2.Text = "-";
			//
			// mniDelete
			//
			this.mniDelete.Index = 2;
			this.mniDelete.Shortcut = System.Windows.Forms.Shortcut.Del;
			this.mniDelete.Text = "Delete";
			this.mniDelete.Click += new System.EventHandler(this.mniDelete_Click);
			//
			// menuItem1
			//
			this.menuItem1.Index = 4;
			this.menuItem1.Text = "-";
			//
			// menuItem3
			//
			this.menuItem3.Index = 7;
			this.menuItem3.Text = "-";
			//
			// mniProperties
			//
			this.mniProperties.Index = 8;
			this.mniProperties.Text = "&Properties";
			this.mniProperties.Click += new System.EventHandler(this.mniProperties_Click);
			//
			// lstv
			//
			this.lstv.AllowColumnReorder = true;
			this.lstv.AllowDrop = true;
			this.lstv.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
																				   this.columnHeader1,
																				   this.columnHeader2});
			this.lstv.ContextMenu = this.mnuListView;
			this.lstv.Dock = System.Windows.Forms.DockStyle.Fill;
			this.lstv.FullRowSelect = true;
			this.lstv.HideSelection = false;
			this.lstv.LabelEdit = true;
			this.lstv.MultiSelect = false;
			this.lstv.Name = "lstv";
			this.lstv.Size = new System.Drawing.Size(320, 309);
			this.lstv.TabIndex = 0;
			this.lstv.View = System.Windows.Forms.View.Details;
			this.lstv.ItemActivate += new System.EventHandler(this.lstv_ItemActivate);
			this.lstv.DoubleClick += new System.EventHandler(this.lstv_DoubleClick);
			this.lstv.DragDrop += new System.Windows.Forms.DragEventHandler(this.lstv_DragDrop);
			this.lstv.AfterLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.lstv_AfterLabelEdit);
			this.lstv.DragEnter += new System.Windows.Forms.DragEventHandler(this.lstv_DragEnter);
			this.lstv.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.lstv_ItemDrag);
			this.lstv.BeforeLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.lstv_BeforeLabelEdit);
			this.lstv.SelectedIndexChanged += new System.EventHandler(this.lstv_SelectedIndexChanged);
			//
			// mniStripsSort
			//
			this.mniStripsSort.Index = 6;
			this.mniStripsSort.Text = "&Sort";
			this.mniStripsSort.Click += new System.EventHandler(this.mniStripsSort_Click);
			//
			// StripsForm
			//
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(320, 309);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.lstv});
			this.Name = "StripsForm";
			this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
			this.Text = "Strips";
			this.ResumeLayout(false);

		}
		#endregion

		private void OnActiveDocumentChanged(object obSender, EventArgs e) {
			m_doc = Globals.ActiveDocument;
			m_stps = m_doc.StripSet;
			RefreshView();
		}

		private void OnActiveStripChanged(object obSender, EventArgs e) {
			if (m_stpActive == Globals.ActiveStrip)
				return;

			m_stpActive = Globals.ActiveStrip;
			foreach (ListViewItem lvi in lstv.Items) {
				if (lvi.Tag == Globals.ActiveStrip) {
					lvi.Selected = true;
					break;
				}
			}
		}

		private void mniView_Popup(object sender, System.EventArgs e) {
			mniViewList.Checked = false;
			mniViewThumbnails.Checked = false;
			mniViewDetails.Checked = false;

			switch (lstv.View) {
			case View.List:
				mniViewList.Checked = true;
				break;

			case View.LargeIcon:
				mniViewThumbnails.Checked = true;
				break;

			case View.Details:
				mniViewDetails.Checked = true;
				break;
			}
		}

		private void mniViewDetails_Click(object sender, System.EventArgs e) {
			lstv.View = View.Details;
		}

		private void mniViewThumbnails_Click(object sender, System.EventArgs e) {
			lstv.View = View.LargeIcon;
		}

		private void mniViewList_Click(object sender, System.EventArgs e) {
			lstv.View = View.List;
		}

		private void RefreshView() {
			lstv.Items.Clear();
			if (m_stps == null)
				return;

			// Prep LargeImageList

			if (lstv.LargeImageList != null)
				lstv.LargeImageList.Dispose();
			lstv.LargeImageList = new ImageList();
			lstv.LargeImageList.ColorDepth = ColorDepth.Depth32Bit;
			lstv.LargeImageList.ImageSize = new Size(64, 64);

			// Prep SmallImageList

			if (lstv.SmallImageList != null)
				lstv.SmallImageList.Dispose();
			lstv.SmallImageList = new ImageList();
			lstv.SmallImageList.ColorDepth = ColorDepth.Depth32Bit;
			lstv.SmallImageList.ImageSize = new Size(16, 16);

			int i = 0;
			foreach (Strip stp in m_stps) {
				ListViewItem lvi = lstv.Items.Add(stp.Name);
				lvi.Tag = stp;

				if (stp == Globals.ActiveStrip)
					lvi.Selected = true;

				lvi.SubItems.Add(stp.Count.ToString());

				// UNDONE: cook up better thumbnails
				// UNDONE: have a 'blank' thumbnail for empty Strips

				if (stp.Count > 0) {
					if (stp[0].BitmapPlacers.Count > 0) {
                        XBitmap xbm = stp[0].BitmapPlacers[0].XBitmap;
						Bitmap bmThumb = xbm.MakeThumbnail(64, 64, false);
						lstv.LargeImageList.Images.Add(bmThumb);
						bmThumb = xbm.MakeThumbnail(16, 16, false);
						lstv.SmallImageList.Images.Add(bmThumb);
						lvi.ImageIndex = i++;
					}
				}
			}
		}

		private void mniNewStrip_Click(object sender, System.EventArgs e) {
			NewStrip();
		}

		public void NewStrip() {
			Strip stp = new Strip("untitled " + (m_stps.Count + 1).ToString());
			// UNDONE: undo
			m_stps.Add(stp);
			Globals.ActiveStrip = stp;
			m_doc.Dirty = true;
			RefreshView();
		}

		private void lstv_BeforeLabelEdit(object sender, System.Windows.Forms.LabelEditEventArgs e) {
			// We do this so the user can press the del key while in label editing mode
			// without it being intercepted by the context menu and used to delete the
			// entire Strip

			lstv.ContextMenu = null;
		}

		private void lstv_AfterLabelEdit(object sender, System.Windows.Forms.LabelEditEventArgs e) {

			// Restore the context menu so the command keys, etc will work again

			lstv.ContextMenu = mnuListView;

			Strip stp = (Strip)lstv.Items[e.Item].Tag;

			// No change or an invalid change

			if (e.Label == null || e.Label == "") {
				e.CancelEdit = true;
				return;
			}

			stp.Name = e.Label;
			m_doc.Dirty = true;
		}

		private void mnuListView_Popup(object sender, System.EventArgs e) {
			bool fAnySelected = lstv.SelectedItems.Count != 0;
			mniDelete.Enabled = fAnySelected;
			mniRename.Enabled = fAnySelected;
			mniProperties.Enabled = fAnySelected;
		}

		private void mniDelete_Click(object sender, System.EventArgs e) {
			Strip stp = (Strip)lstv.SelectedItems[0].Tag;
			int i = m_stps.IndexOf(stp);
			// UNDONE: undo
			m_stps.RemoveAt(i);
			lstv.Items.Remove(lstv.SelectedItems[0]);
			m_doc.Dirty = true;

			// Select a new Strip to be active

			i = Math.Min(i, m_stps.Count - 1);
			if (i >= 0)
				Globals.ActiveStrip = m_stps[i];
			else
				Globals.ActiveStrip = null;
		}

		private void mniRename_Click(object sender, System.EventArgs e) {
			MessageBox.Show(this, "Click on the name of the strip to select it then edit it in place.",
				"AniMax");
		}

		private void lstv_ItemActivate(object sender, System.EventArgs e) {
//			m_doc.ActiveStrip = (Strip)lstv.SelectedItems[0].Tag;
		}

		private void lstv_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
				e.Effect = DragDropEffects.Copy;
		}

		private void lstv_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
			string[] astrFiles = e.Data.GetData(DataFormats.FileDrop) as string[];
			if (astrFiles != null) {
				if (astrFiles.Length == 1)
					((MainForm)Globals.MainForm).CloseAndOpenDocument(astrFiles[0]);
				else
					MessageBox.Show(this, "Please, only drop one animation file.", "Too many files dropped", MessageBoxButtons.OK, MessageBoxIcon.Stop);
			}
#if false
			XBitmap[] axbm = e.Data.GetData(typeof(XBitmap[])) as XBitmap[];
			if (axbm == null)
				return;

			// Use the standard file naming convention to break the bitmaps down into
			// animations (e.g., *_fire_*_*), a single track (e.g., track 1), and a set
			// of TSprite keys (e.g., *_*_d_n)

			foreach (XBitmap xbm in axbm) {
				string strFile = xbm.FileName;
				string[] astr = strFile.Substring(strFile.LastIndexOf('\\') + 1).Split('_', '.');
				if (astr.Length != 5) {
					MessageBox.Show(this, String.Format("Warning: file {0} does not match the requisite naming pattern", strFile),
							"AniMax");
					continue;
				}

				// Find the appropriate animation

				Strip stp = null;
				Frame fr = null;
				string strName = astr[1] + " " + astr[2];
				foreach (Strip stpT in m_stps) {
					if (stpT.Name == strName) {
						stp = stpT;
						fr = stp[0];
						break;
					}
				}

				// If one isn't found, create a new stpmation and empty track

				if (stp == null) {
					stp = new Strip(strName);
					m_stps.Add(stp);
					tspr = new TSprite("track 1");
					stp.Add(tspr);
				}

				Sprite spr = new Sprite(xbm, 0, 0);
				Time t = 0;
				if (tspr.End != Time.tUndefined)
					t = tspr.End + m_doc.FrameRate;
				tspr.SetValue(t, spr);
			}

			m_doc.Dirty = true;
			RefreshView();
#endif
		}

		private void lstv_SelectedIndexChanged(object sender, System.EventArgs e) {
			if (lstv.SelectedItems.Count == 0)
				return;
			Globals.ActiveStrip = (Strip)lstv.SelectedItems[0].Tag;
		}

		private void lstv_DoubleClick(object sender, System.EventArgs e) {
			((StripForm)Globals.StripForm).ShowStripProperties((Strip)lstv.SelectedItems[0].Tag);
		}

		private void mniProperties_Click(object sender, System.EventArgs e) {
			((StripForm)Globals.StripForm).ShowStripProperties((Strip)lstv.SelectedItems[0].Tag);
		}

		private void lstv_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e) {
			DoDragDrop(lstv.SelectedItems[0].Tag, DragDropEffects.All);
		}

		private void mniStripsSort_Click(object sender, System.EventArgs e) {
			m_stps.Sort();
			RefreshView();
		}
	}
}


text:
package boofcv.factory.denoise;

import boofcv.alg.denoise.DenoiseWavelet;
import boofcv.alg.denoise.ShrinkThresholdRule;
import boofcv.alg.denoise.wavelet.DenoiseBayesShrink_F32;
import boofcv.alg.denoise.wavelet.DenoiseSureShrink_F32;
import boofcv.alg.denoise.wavelet.DenoiseVisuShrink_F32;
import boofcv.alg.denoise.wavelet.ShrinkThresholdSoft_F32;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.ImageGray;

/**
 * Factory for creating wavelet based image denoising classes.
 *
 *  @author Peter Abeles
 */
@SuppressWarnings({"unchecked"})
public class FactoryDenoiseWaveletAlg {

	/**
	 * Returns {@link DenoiseBayesShrink_F32 Bayes shrink} wavelet based image denoiser.
	 *
	 * @param rule Shrinkage rule. If null then a {@link ShrinkThresholdSoft_F32 soft threshold} rule will be used.
	 * @param imageType Type of image it will process.
	 * @return Bayes Shrink
	 */
	public static <T extends ImageGray> DenoiseWavelet<T> bayes(ShrinkThresholdRule<T> rule , Class<T> imageType )
	{
		if( rule == null ) {
			rule = (ShrinkThresholdRule<T>)new ShrinkThresholdSoft_F32();
		}

		if( imageType == GrayF32.class ) {
			return (DenoiseWavelet<T>)new DenoiseBayesShrink_F32((ShrinkThresholdRule<GrayF32>)rule);
		} else {
			throw new IllegalArgumentException("Unsupported image type "+imageType);
		}
	}

	/**
	 * Returns {@link DenoiseSureShrink_F32 sure shrink} wavelet based image denoiser.
	 *
	 * @param imageType Type of image it will process.
	 * @return Bayes Shrink
	 */
	public static <T extends ImageGray> DenoiseWavelet<T> sure(Class<T> imageType )
	{
		if( imageType == GrayF32.class ) {
			return (DenoiseWavelet<T>)new DenoiseSureShrink_F32();
		} else {
			throw new IllegalArgumentException("Unsupported image type "+imageType);
		}
	}

	/**
	 * Returns {@link DenoiseVisuShrink_F32 visu shrink} wavelet based image denoiser.
	 *
	 * @param imageType Type of image it will process.
	 * @return Bayes Shrink
	 */
	public static <T extends ImageGray> DenoiseWavelet<T> visu(Class<T> imageType )
	{
		if( imageType == GrayF32.class ) {
			return (DenoiseWavelet<T>)new DenoiseVisuShrink_F32();
		} else {
			throw new IllegalArgumentException("Unsupported image type "+imageType);
		}
	}
}


text:
package com.dmdirc.addons.mediasource_vlc;

import com.dmdirc.addons.nowplaying.MediaSource;
import com.dmdirc.addons.nowplaying.MediaSourceState;
import com.dmdirc.config.prefs.PluginPreferencesCategory;
import com.dmdirc.config.prefs.PreferencesCategory;
import com.dmdirc.config.prefs.PreferencesDialogModel;
import com.dmdirc.config.prefs.PreferencesSetting;
import com.dmdirc.config.prefs.PreferencesType;
import com.dmdirc.events.ClientPrefsOpenedEvent;
import com.dmdirc.interfaces.config.IdentityController;
import com.dmdirc.plugins.PluginDomain;
import com.dmdirc.plugins.PluginInfo;
import com.dmdirc.util.io.Downloader;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import net.engio.mbassy.listener.Handler;

/**
 * Retrieves information from VLC using its HTTP interface.
 */
public class VlcManager implements MediaSource {

    /** The information obtained from VLC. */
    private final Map<String, String> information = new HashMap<>();
    /** This plugin's plugin info. */
    private final PluginInfo pluginInfo;
    /** The identity controller to read settings from. */
    private final IdentityController identityController;
    /** Downloader to download files. */
    private final Downloader downloader;

    @Inject
    public VlcManager(
            @PluginDomain(VlcMediaSourcePlugin.class) final PluginInfo pluginInfo,
            final IdentityController identityController) {
        this.pluginInfo = pluginInfo;
        this.identityController = identityController;
        this.downloader = new Downloader();
    }

    @Override
    public MediaSourceState getState() {
        if (fetchInformation()) {
            final String output = information.get("state");
            if (output.equalsIgnoreCase("stop")) {
                return MediaSourceState.STOPPED;
            } else if (output.equalsIgnoreCase("playing")) {
                return MediaSourceState.PLAYING;
            } else if (output.equalsIgnoreCase("paused")) {
                return MediaSourceState.PAUSED;
            } else {
                return MediaSourceState.NOTKNOWN;
            }
        } else {
            return MediaSourceState.CLOSED;
        }
    }

    @Override
    public String getAppName() {
        return "VLC";
    }

    @Override
    public String getArtist() {
        return information.containsKey("artist") ? information.get("artist") : getFallbackArtist();
    }

    /**
     * Retrieves the fallback artist (parsed from the file name).
     *
     * @return The fallback artist
     */
    private String getFallbackArtist() {
        String result = "unknown";

        if (information.containsKey("playlist_current")) {
            try {
                final int item = Integer.parseInt(information.get(
                        "playlist_current"));
                String[] bits = information.get("playlist_item_" + item).split(
                        (File.separatorChar == '\\' ? "\\\\" : File.separator));
                result = bits[bits.length - 1];
                bits = result.split("-");
                if (bits.length > 1) {
                    result = bits[0];
                } else {
                    // Whole filename is the title, so no artist is known.
                    result = "unknown";
                }
            } catch (NumberFormatException nfe) {
                // DO nothing
            }
        }

        return result;
    }

    @Override
    public String getTitle() {
        return information.containsKey("title") ? information.get("title")
                : getFallbackTitle();
    }

    /**
     * Retrieves the fallback title (parsed from the file name).
     *
     * @return The fallback title
     */
    private String getFallbackTitle() {
        String result = "unknown";

        // Title is unknown, lets guess using the filename
        if (information.containsKey("playlist_current")) {
            try {
                final int item = Integer.parseInt(information.get(
                        "playlist_current"));
                result = information.get("playlist_item_" + item);

                final int sepIndex = result.lastIndexOf(File.separatorChar);
                final int extIndex = result.lastIndexOf('.');
                result = result.substring(sepIndex,
                        extIndex > sepIndex ? extIndex : result.length());

                final int offset = result.indexOf('-');
                if (offset > -1) {
                    result = result.substring(offset + 1).trim();
                }
            } catch (NumberFormatException nfe) {
                // Do nothing
            }
        }

        return result;
    }

    @Override
    public String getAlbum() {
        return information.containsKey("album/movie/show title")
                ? information.get("album/movie/show title") : "unknown";
    }

    @Override
    public String getLength() {
        // This is just seconds, could do with formatting.
        return information.containsKey("length") ? information.get("length")
                : "unknown";
    }

    @Override
    public String getTime() {
        // This is just seconds, could do with formatting.
        return information.containsKey("time") ? information.get("time")
                : "unknown";
    }

    @Override
    public String getFormat() {
        return information.containsKey("codec") ? information.get("codec")
                : "unknown";
    }

    @Override
    public String getBitrate() {
        return information.containsKey("bitrate") ? information.get("bitrate")
                : "unknown";
    }

    @Handler
    public void showConfig(final ClientPrefsOpenedEvent event) {
        final PreferencesDialogModel manager = event.getModel();
        final PreferencesCategory general = new PluginPreferencesCategory(
                pluginInfo, "VLC Media Source",
                "", "category-vlc");

        final PreferencesSetting setting = new PreferencesSetting(
                PreferencesType.LABEL, pluginInfo.getDomain(), "", "Instructions",
                "Instructions", manager.getConfigManager(), manager.getIdentity());
        setting.setValue("
"
                + "The VLC media source requires that VLC's web interface is"
                + " enabled. To do this, follow the steps below:
"
                + "
"
                + "
Open VLC's preferences dialog (found in the 'Tools' "
                + "menu)"
                + "
Set the 'Show settings' option to 'All'"
                + "
Expand the 'Interface' category by clicking on the plus "
                + "sign next to it"
                + "
Select the 'Main interfaces' category"
                + "
Check the box next to 'HTTP remote control interface'"
                + "
Expand the 'Main interfaces' category"
                + "
Select the 'HTTP' category"
                + "
In the 'Host address' field, enter 'localhost:8082'"
                + "
In the 'Source directory' field enter the path to VLC's"
                + " http directory
"
                + "
For Linux users this may be "
                + "/usr/share/vlc/http/"
                + "
For Windows users this will be under the main VLC "
                + "directory, e.g. C:\\Program Files\\VLC\\http

Click "
                + "'Save'
Restart VLC
");
        general.addSetting(setting);
        general.addSetting(new PreferencesSetting(PreferencesType.TEXT,
                pluginInfo.getDomain(), "host", "Hostname and port",
                "The host and port that VLC listens on for web connections",
                manager.getConfigManager(), manager.getIdentity()));

        manager.getCategory("Plugins").addSubCategory(general);
    }

    /**
     * Attempts to fetch information from VLC's web interface.
     *
     * @return True on success, false otherwise
     */
    private boolean fetchInformation() {
        information.clear();
        final List<String> res;
        final List<String> res2;

        try {
            final String host = identityController.getGlobalConfiguration()
                    .getOption(pluginInfo.getDomain(), "host");
            res = downloader.getPage("http://" + host + "/old/info.html");
            res2 = downloader.getPage("http://" + host + "/old/");
            parseInformation(res, res2);
            return true;
        } catch (IOException ex) {
            return false;
        }
    }

    /**
     * Parses the information from the two pages obtained from VLC's web interface.
     *
     * @param res  The first page of VLC info (/old/info.html)
     * @param res2 The second page of VLC info (/old/)
     */
    protected void parseInformation(final List<String> res,
            final List<String> res2) {
        for (String line : res) {
            final String tline = line.trim();

            if (tline.startsWith("
")) {
                final int colon = tline.indexOf(':');
                final String key = tline.substring(5, colon).trim()
                        .toLowerCase();
                final String value = tline.substring(colon + 1, tline.length()
                        - 5).trim();

                information.put(key, value);
            }
        }

        boolean isPlaylist = false;
        boolean isCurrent = false;
        boolean isItem = false;
        int playlistItem = 0;
        for (String line : res2) {
            final String tline = line.trim();

            if (isPlaylist) {
                if (tline.startsWith("
")) {
                    isPlaylist = false;
                    information.put("playlist_items", Integer.toString(
                            playlistItem));
                } else if (tline.equalsIgnoreCase("")) {
                    isCurrent = true;
                } else if (tline.equalsIgnoreCase("")) {
                    isCurrent = false;
                } else if (tline.startsWith("<a href=\"?control=play&amp")) {
                    isItem = true;
                } else if (isItem) {
                    String itemname = tline;
                    if (itemname.endsWith("")) {
                        itemname = itemname.substring(0, itemname.length() - 4);
                    }
                    if (!itemname.isEmpty()) {
                        if (isCurrent) {
                            information.put("playlist_current", Integer
                                    .toString(playlistItem));
                        }
                        information.put("playlist_item_" + Integer.toString(
                                playlistItem++), itemname);
                    }
                    isItem = false;
                }
            } else if (tline.equalsIgnoreCase("")) {
                isPlaylist = true;
            } else if (tline.startsWith("State:")) {
                information.put("state", tline.substring(6, tline.indexOf('<'))
                        .trim());
            } else if (tline.startsWith("got_")) {
                final int equals = tline.indexOf('=');

                information.put(tline.substring(4, equals).trim(),
                        tline.substring(equals + 1, tline.length() - 1).trim());
            }
        }
    }
}


text:
#include "wtf/text/WTFString.h"

#include "testing/gtest/include/gtest/gtest.h"
#include "wtf/MathExtras.h"
#include "wtf/text/CString.h"
#include <limits>

namespace WTF {

TEST(StringTest, CreationFromLiteral) {
  String stringFromLiteral("Explicit construction syntax");
  EXPECT_EQ(strlen("Explicit construction syntax"), stringFromLiteral.length());
  EXPECT_TRUE(stringFromLiteral == "Explicit construction syntax");
  EXPECT_TRUE(stringFromLiteral.is8Bit());
  EXPECT_TRUE(String("Explicit construction syntax") == stringFromLiteral);
}

TEST(StringTest, ASCII) {
  CString output;

  // Null String.
  output = String().ascii();
  EXPECT_STREQ("", output.data());

  // Empty String.
  output = emptyString().ascii();
  EXPECT_STREQ("", output.data());

  // Regular String.
  output = String("foobar").ascii();
  EXPECT_STREQ("foobar", output.data());
}

namespace {

void testNumberToStringECMAScript(double number, const char* reference) {
  CString numberString = String::numberToStringECMAScript(number).latin1();
  EXPECT_STREQ(reference, numberString.data());
}

}  // anonymous namespace

TEST(StringTest, NumberToStringECMAScriptBoundaries) {
  typedef std::numeric_limits<double> Limits;

  // Infinity.
  testNumberToStringECMAScript(Limits::infinity(), "Infinity");
  testNumberToStringECMAScript(-Limits::infinity(), "-Infinity");

  // NaN.
  testNumberToStringECMAScript(-Limits::quiet_NaN(), "NaN");

  // Zeros.
  testNumberToStringECMAScript(0, "0");
  testNumberToStringECMAScript(-0, "0");

  // Min-Max.
  testNumberToStringECMAScript(Limits::min(), "2.2250738585072014e-308");
  testNumberToStringECMAScript(Limits::max(), "1.7976931348623157e+308");
}

TEST(StringTest, NumberToStringECMAScriptRegularNumbers) {
  // Pi.
  testNumberToStringECMAScript(piDouble, "3.141592653589793");
  testNumberToStringECMAScript(piFloat, "3.1415927410125732");
  testNumberToStringECMAScript(piOverTwoDouble, "1.5707963267948966");
  testNumberToStringECMAScript(piOverTwoFloat, "1.5707963705062866");
  testNumberToStringECMAScript(piOverFourDouble, "0.7853981633974483");
  testNumberToStringECMAScript(piOverFourFloat, "0.7853981852531433");

  // e.
  const double e = 2.71828182845904523536028747135266249775724709369995;
  testNumberToStringECMAScript(e, "2.718281828459045");

  // c, speed of light in m/s.
  const double c = 299792458;
  testNumberToStringECMAScript(c, "299792458");

  // Golen ratio.
  const double phi = 1.6180339887498948482;
  testNumberToStringECMAScript(phi, "1.618033988749895");
}

TEST(StringTest, ReplaceWithLiteral) {
  // Cases for 8Bit source.
  String testString = "1224";
  EXPECT_TRUE(testString.is8Bit());
  testString.replace('2', "");
  EXPECT_STREQ("14", testString.utf8().data());

  testString = "1224";
  EXPECT_TRUE(testString.is8Bit());
  testString.replace('2', "3");
  EXPECT_STREQ("1334", testString.utf8().data());

  testString = "1224";
  EXPECT_TRUE(testString.is8Bit());
  testString.replace('2', "555");
  EXPECT_STREQ("15555554", testString.utf8().data());

  testString = "1224";
  EXPECT_TRUE(testString.is8Bit());
  testString.replace('3', "NotFound");
  EXPECT_STREQ("1224", testString.utf8().data());

  // Cases for 16Bit source.
  // U+00E9 (=0xC3 0xA9 in UTF-8) is e with accent.
  testString = String::fromUTF8("r\xC3\xA9sum\xC3\xA9");
  EXPECT_FALSE(testString.is8Bit());
  testString.replace(UChar(0x00E9), "e");
  EXPECT_STREQ("resume", testString.utf8().data());

  testString = String::fromUTF8("r\xC3\xA9sum\xC3\xA9");
  EXPECT_FALSE(testString.is8Bit());
  testString.replace(UChar(0x00E9), "");
  EXPECT_STREQ("rsum", testString.utf8().data());

  testString = String::fromUTF8("r\xC3\xA9sum\xC3\xA9");
  EXPECT_FALSE(testString.is8Bit());
  testString.replace('3', "NotFound");
  EXPECT_STREQ("r\xC3\xA9sum\xC3\xA9", testString.utf8().data());
}

TEST(StringTest, ComparisonOfSameStringVectors) {
  Vector<String> stringVector;
  stringVector.append("one");
  stringVector.append("two");

  Vector<String> sameStringVector;
  sameStringVector.append("one");
  sameStringVector.append("two");

  EXPECT_EQ(stringVector, sameStringVector);
}

TEST(WTF, SimplifyWhiteSpace) {
  String extraSpaces("  Hello  world  ");
  EXPECT_EQ(String("Hello world"), extraSpaces.simplifyWhiteSpace());
  EXPECT_EQ(String("  Hello  world  "),
            extraSpaces.simplifyWhiteSpace(WTF::DoNotStripWhiteSpace));

  String extraSpacesAndNewlines(" \nHello\n world\n ");
  EXPECT_EQ(String("Hello world"), extraSpacesAndNewlines.simplifyWhiteSpace());
  EXPECT_EQ(
      String("  Hello  world  "),
      extraSpacesAndNewlines.simplifyWhiteSpace(WTF::DoNotStripWhiteSpace));

  String extraSpacesAndTabs(" \nHello\t world\t ");
  EXPECT_EQ(String("Hello world"), extraSpacesAndTabs.simplifyWhiteSpace());
  EXPECT_EQ(String("  Hello  world  "),
            extraSpacesAndTabs.simplifyWhiteSpace(WTF::DoNotStripWhiteSpace));
}

struct CaseFoldingTestData {
  const char* sourceDescription;
  const char* source;
  const char** localeList;
  size_t localeListLength;
  const char* expected;
};

// \xC4\xB0 = U+0130 (capital dotted I)
// \xC4\xB1 = U+0131 (lowercase dotless I)
const char* turkicInput = "Isi\xC4\xB0 \xC4\xB0s\xC4\xB1I";
const char* greekInput =
    "\xCE\x9F\xCE\x94\xCE\x8C\xCE\xA3 \xCE\x9F\xCE\xB4\xCF\x8C\xCF\x82 "
    "\xCE\xA3\xCE\xBF \xCE\xA3\xCE\x9F o\xCE\xA3 \xCE\x9F\xCE\xA3 \xCF\x83 "
    "\xE1\xBC\x95\xCE\xBE";
const char* lithuanianInput =
    "I \xC3\x8F J J\xCC\x88 \xC4\xAE \xC4\xAE\xCC\x88 \xC3\x8C \xC3\x8D "
    "\xC4\xA8 xi\xCC\x87\xCC\x88 xj\xCC\x87\xCC\x88 x\xC4\xAF\xCC\x87\xCC\x88 "
    "xi\xCC\x87\xCC\x80 xi\xCC\x87\xCC\x81 xi\xCC\x87\xCC\x83 XI X\xC3\x8F XJ "
    "XJ\xCC\x88 X\xC4\xAE X\xC4\xAE\xCC\x88";

const char* turkicLocales[] = {
    "tr", "tr-TR", "tr_TR", "tr@foo=bar", "tr-US", "TR", "tr-tr", "tR",
    "az", "az-AZ", "az_AZ", "az@foo=bar", "az-US", "Az", "AZ-AZ",
};
const char* nonTurkicLocales[] = {
    "en", "en-US", "en_US", "en@foo=bar", "EN", "En",
    "ja", "el",    "fil",   "fi",         "lt",
};
const char* greekLocales[] = {
    "el", "el-GR", "el_GR", "el@foo=bar", "el-US", "EL", "el-gr", "eL",
};
const char* nonGreekLocales[] = {
    "en", "en-US", "en_US", "en@foo=bar", "EN", "En",
    "ja", "tr",    "az",    "fil",        "fi", "lt",
};
const char* lithuanianLocales[] = {
    "lt", "lt-LT", "lt_LT", "lt@foo=bar", "lt-US", "LT", "lt-lt", "lT",
};
// Should not have "tr" or "az" because "lt" and 'tr/az' rules conflict with
// each other.
const char* nonLithuanianLocales[] = {
    "en", "en-US", "en_US", "en@foo=bar", "EN", "En", "ja", "fil", "fi", "el",
};

TEST(StringTest, ToUpperLocale) {
  CaseFoldingTestData testDataList[] = {
      {
          "Turkic input", turkicInput, turkicLocales,
          sizeof(turkicLocales) / sizeof(const char*),
          "IS\xC4\xB0\xC4\xB0 \xC4\xB0SII",
      },
      {
          "Turkic input", turkicInput, nonTurkicLocales,
          sizeof(nonTurkicLocales) / sizeof(const char*),
          "ISI\xC4\xB0 \xC4\xB0SII",
      },
      {
          "Greek input", greekInput, greekLocales,
          sizeof(greekLocales) / sizeof(const char*),
          "\xCE\x9F\xCE\x94\xCE\x9F\xCE\xA3 \xCE\x9F\xCE\x94\xCE\x9F\xCE\xA3 "
          "\xCE\xA3\xCE\x9F \xCE\xA3\xCE\x9F \x4F\xCE\xA3 \xCE\x9F\xCE\xA3 "
          "\xCE\xA3 \xCE\x95\xCE\x9E",
      },
      {
          "Greek input", greekInput, nonGreekLocales,
          sizeof(nonGreekLocales) / sizeof(const char*),
          "\xCE\x9F\xCE\x94\xCE\x8C\xCE\xA3 \xCE\x9F\xCE\x94\xCE\x8C\xCE\xA3 "
          "\xCE\xA3\xCE\x9F \xCE\xA3\xCE\x9F \x4F\xCE\xA3 \xCE\x9F\xCE\xA3 "
          "\xCE\xA3 \xE1\xBC\x9D\xCE\x9E",
      },
      {
          "Lithuanian input", lithuanianInput, lithuanianLocales,
          sizeof(lithuanianLocales) / sizeof(const char*),
          "I \xC3\x8F J J\xCC\x88 \xC4\xAE \xC4\xAE\xCC\x88 \xC3\x8C \xC3\x8D "
          "\xC4\xA8 XI\xCC\x88 XJ\xCC\x88 X\xC4\xAE\xCC\x88 XI\xCC\x80 "
          "XI\xCC\x81 XI\xCC\x83 XI X\xC3\x8F XJ XJ\xCC\x88 X\xC4\xAE "
          "X\xC4\xAE\xCC\x88",
      },
      {
          "Lithuanian input", lithuanianInput, nonLithuanianLocales,
          sizeof(nonLithuanianLocales) / sizeof(const char*),
          "I \xC3\x8F J J\xCC\x88 \xC4\xAE \xC4\xAE\xCC\x88 \xC3\x8C \xC3\x8D "
          "\xC4\xA8 XI\xCC\x87\xCC\x88 XJ\xCC\x87\xCC\x88 "
          "X\xC4\xAE\xCC\x87\xCC\x88 XI\xCC\x87\xCC\x80 XI\xCC\x87\xCC\x81 "
          "XI\xCC\x87\xCC\x83 XI X\xC3\x8F XJ XJ\xCC\x88 X\xC4\xAE "
          "X\xC4\xAE\xCC\x88",
      },
  };

  for (size_t i = 0; i < sizeof(testDataList) / sizeof(testDataList[0]); ++i) {
    const char* expected = testDataList[i].expected;
    String source = String::fromUTF8(testDataList[i].source);
    for (size_t j = 0; j < testDataList[i].localeListLength; ++j) {
      const char* locale = testDataList[i].localeList[j];
      EXPECT_STREQ(expected, source.upper(locale).utf8().data())
          << testDataList[i].sourceDescription << "; locale=" << locale;
    }
  }
}

TEST(StringTest, ToLowerLocale) {
  CaseFoldingTestData testDataList[] = {
      {
          "Turkic input", turkicInput, turkicLocales,
          sizeof(turkicLocales) / sizeof(const char*),
          "\xC4\xB1sii is\xC4\xB1\xC4\xB1",
      },
      {
          "Turkic input", turkicInput, nonTurkicLocales,
          sizeof(nonTurkicLocales) / sizeof(const char*),
          // U+0130 is lowercased to U+0069 followed by U+0307
          "isii\xCC\x87 i\xCC\x87s\xC4\xB1i",
      },
      {
          "Greek input", greekInput, greekLocales,
          sizeof(greekLocales) / sizeof(const char*),
          "\xCE\xBF\xCE\xB4\xCF\x8C\xCF\x82 \xCE\xBF\xCE\xB4\xCF\x8C\xCF\x82 "
          "\xCF\x83\xCE\xBF \xCF\x83\xCE\xBF \x6F\xCF\x82 \xCE\xBF\xCF\x82 "
          "\xCF\x83 \xE1\xBC\x95\xCE\xBE",
      },
      {
          "Greek input", greekInput, nonGreekLocales,
          sizeof(greekLocales) / sizeof(const char*),
          "\xCE\xBF\xCE\xB4\xCF\x8C\xCF\x82 \xCE\xBF\xCE\xB4\xCF\x8C\xCF\x82 "
          "\xCF\x83\xCE\xBF \xCF\x83\xCE\xBF \x6F\xCF\x82 \xCE\xBF\xCF\x82 "
          "\xCF\x83 \xE1\xBC\x95\xCE\xBE",
      },
      {
          "Lithuanian input", lithuanianInput, lithuanianLocales,
          sizeof(lithuanianLocales) / sizeof(const char*),
          "i \xC3\xAF j j\xCC\x87\xCC\x88 \xC4\xAF \xC4\xAF\xCC\x87\xCC\x88 "
          "i\xCC\x87\xCC\x80 i\xCC\x87\xCC\x81 i\xCC\x87\xCC\x83 "
          "xi\xCC\x87\xCC\x88 xj\xCC\x87\xCC\x88 x\xC4\xAF\xCC\x87\xCC\x88 "
          "xi\xCC\x87\xCC\x80 xi\xCC\x87\xCC\x81 xi\xCC\x87\xCC\x83 xi "
          "x\xC3\xAF xj xj\xCC\x87\xCC\x88 x\xC4\xAF x\xC4\xAF\xCC\x87\xCC\x88",
      },
      {
          "Lithuanian input", lithuanianInput, nonLithuanianLocales,
          sizeof(nonLithuanianLocales) / sizeof(const char*),
          "\x69 \xC3\xAF \x6A \x6A\xCC\x88 \xC4\xAF \xC4\xAF\xCC\x88 \xC3\xAC "
          "\xC3\xAD \xC4\xA9 \x78\x69\xCC\x87\xCC\x88 \x78\x6A\xCC\x87\xCC\x88 "
          "\x78\xC4\xAF\xCC\x87\xCC\x88 \x78\x69\xCC\x87\xCC\x80 "
          "\x78\x69\xCC\x87\xCC\x81 \x78\x69\xCC\x87\xCC\x83 \x78\x69 "
          "\x78\xC3\xAF \x78\x6A \x78\x6A\xCC\x88 \x78\xC4\xAF "
          "\x78\xC4\xAF\xCC\x88",
      },
  };

  for (size_t i = 0; i < sizeof(testDataList) / sizeof(testDataList[0]); ++i) {
    const char* expected = testDataList[i].expected;
    String source = String::fromUTF8(testDataList[i].source);
    for (size_t j = 0; j < testDataList[i].localeListLength; ++j) {
      const char* locale = testDataList[i].localeList[j];
      EXPECT_STREQ(expected, source.lower(locale).utf8().data())
          << testDataList[i].sourceDescription << "; locale=" << locale;
    }
  }
}

TEST(StringTest, StartsWithIgnoringUnicodeCase) {
  // [U+017F U+212A i a] starts with "sk".
  EXPECT_TRUE(String::fromUTF8("\xC5\xBF\xE2\x84\xAAia")
                  .startsWith("sk", TextCaseUnicodeInsensitive));
}

TEST(StringTest, StartsWithIgnoringASCIICase) {
  String allASCII("LINK");
  String allASCIILowerCase("link");
  EXPECT_TRUE(allASCII.startsWith(allASCIILowerCase, TextCaseASCIIInsensitive));
  String allASCIIMixedCase("lInK");
  EXPECT_TRUE(allASCII.startsWith(allASCIIMixedCase, TextCaseASCIIInsensitive));
  String allASCIIDifferent("foo");
  EXPECT_FALSE(
      allASCII.startsWith(allASCIIDifferent, TextCaseASCIIInsensitive));
  String nonASCII = String::fromUTF8("LIN\xE2\x84\xAA");
  EXPECT_FALSE(allASCII.startsWith(nonASCII, TextCaseASCIIInsensitive));
  EXPECT_TRUE(allASCII.startsWith(nonASCII.lower(), TextCaseASCIIInsensitive));

  EXPECT_FALSE(nonASCII.startsWith(allASCII, TextCaseASCIIInsensitive));
  EXPECT_FALSE(
      nonASCII.startsWith(allASCIILowerCase, TextCaseASCIIInsensitive));
  EXPECT_FALSE(
      nonASCII.startsWith(allASCIIMixedCase, TextCaseASCIIInsensitive));
  EXPECT_FALSE(
      nonASCII.startsWith(allASCIIDifferent, TextCaseASCIIInsensitive));
}

TEST(StringTest, EndsWithIgnoringASCIICase) {
  String allASCII("LINK");
  String allASCIILowerCase("link");
  EXPECT_TRUE(allASCII.endsWith(allASCIILowerCase, TextCaseASCIIInsensitive));
  String allASCIIMixedCase("lInK");
  EXPECT_TRUE(allASCII.endsWith(allASCIIMixedCase, TextCaseASCIIInsensitive));
  String allASCIIDifferent("foo");
  EXPECT_FALSE(allASCII.endsWith(allASCIIDifferent, TextCaseASCIIInsensitive));
  String nonASCII = String::fromUTF8("LIN\xE2\x84\xAA");
  EXPECT_FALSE(allASCII.endsWith(nonASCII, TextCaseASCIIInsensitive));
  EXPECT_TRUE(allASCII.endsWith(nonASCII.lower(), TextCaseASCIIInsensitive));

  EXPECT_FALSE(nonASCII.endsWith(allASCII, TextCaseASCIIInsensitive));
  EXPECT_FALSE(nonASCII.endsWith(allASCIILowerCase, TextCaseASCIIInsensitive));
  EXPECT_FALSE(nonASCII.endsWith(allASCIIMixedCase, TextCaseASCIIInsensitive));
  EXPECT_FALSE(nonASCII.endsWith(allASCIIDifferent, TextCaseASCIIInsensitive));
}

TEST(StringTest, EqualIgnoringASCIICase) {
  String allASCII("LINK");
  String allASCIILowerCase("link");
  EXPECT_TRUE(equalIgnoringASCIICase(allASCII, allASCIILowerCase));
  String allASCIIMixedCase("lInK");
  EXPECT_TRUE(equalIgnoringASCIICase(allASCII, allASCIIMixedCase));
  String allASCIIDifferent("foo");
  EXPECT_FALSE(equalIgnoringASCIICase(allASCII, allASCIIDifferent));
  String nonASCII = String::fromUTF8("LIN\xE2\x84\xAA");
  EXPECT_FALSE(equalIgnoringASCIICase(allASCII, nonASCII));
  EXPECT_TRUE(equalIgnoringASCIICase(allASCII, nonASCII.lower()));

  EXPECT_FALSE(equalIgnoringASCIICase(nonASCII, allASCII));
  EXPECT_FALSE(equalIgnoringASCIICase(nonASCII, allASCIILowerCase));
  EXPECT_FALSE(equalIgnoringASCIICase(nonASCII, allASCIIMixedCase));
  EXPECT_FALSE(equalIgnoringASCIICase(nonASCII, allASCIIDifferent));
}

TEST(StringTest, FindIgnoringASCIICase) {
  String needle = String::fromUTF8("a\xCC\x88qa\xCC\x88");

  // Multiple matches, non-overlapping
  String haystack1 = String::fromUTF8(
      "aA\xCC\x88QA\xCC\x88sA\xCC\x88qa\xCC\x88rfi\xC3\xA4q\xC3\xA4");
  EXPECT_EQ(1u, haystack1.findIgnoringASCIICase(needle));
  EXPECT_EQ(7u, haystack1.findIgnoringASCIICase(needle, 2));
  EXPECT_EQ(kNotFound, haystack1.findIgnoringASCIICase(needle, 8));

  // Multiple matches, overlapping
  String haystack2 = String::fromUTF8("aA\xCC\x88QA\xCC\x88qa\xCC\x88rfi");
  EXPECT_EQ(1u, haystack2.findIgnoringASCIICase(needle));
  EXPECT_EQ(4u, haystack2.findIgnoringASCIICase(needle, 2));
  EXPECT_EQ(kNotFound, haystack2.findIgnoringASCIICase(needle, 5));
}

TEST(StringTest, Lower) {
  EXPECT_STREQ("link", String("LINK").lower().ascii().data());
  EXPECT_STREQ("link", String("lInk").lower().ascii().data());
  EXPECT_STREQ("lin\xE1k", String("lIn\xC1k").lower().latin1().data());
  // U+212A -> k
  EXPECT_STREQ("link",
               String::fromUTF8("LIN\xE2\x84\xAA").lower().utf8().data());
}

TEST(StringTest, Upper) {
  EXPECT_STREQ("CROSS", String("cross").upper().utf8().data());
  // U+017F -> S
  EXPECT_STREQ("CROSS", String::fromUTF8("cro\xC5\xBFs").upper().utf8().data());
}

TEST(StringTest, Ensure16Bit) {
  String string8("8bit");
  EXPECT_TRUE(string8.is8Bit());
  string8.ensure16Bit();
  EXPECT_FALSE(string8.is8Bit());
  EXPECT_EQ("8bit", string8);

  String string16(reinterpret_cast<const UChar*>(u"16bit"));
  EXPECT_FALSE(string16.is8Bit());
  string16.ensure16Bit();
  EXPECT_FALSE(string16.is8Bit());
  EXPECT_EQ("16bit", string16);

  String empty8(StringImpl::empty());
  EXPECT_TRUE(empty8.is8Bit());
  empty8.ensure16Bit();
  EXPECT_FALSE(empty8.is8Bit());
  EXPECT_TRUE(empty8.isEmpty());
  EXPECT_FALSE(empty8.isNull());

  String empty16(StringImpl::empty16Bit());
  EXPECT_FALSE(empty16.is8Bit());
  empty16.ensure16Bit();
  EXPECT_FALSE(empty16.is8Bit());
  EXPECT_TRUE(empty16.isEmpty());
  EXPECT_FALSE(empty16.isNull());

  String nullString;
  nullString.ensure16Bit();
  EXPECT_TRUE(nullString.isNull());
}

CString toCStringThroughPrinter(const String& string) {
  std::ostringstream output;
  output << string;
  const std::string& result = output.str();
  return CString(result.data(), result.length());
}

TEST(StringTest, StringPrinter) {
  EXPECT_EQ(CString("\"Hello!\""), toCStringThroughPrinter("Hello!"));
  EXPECT_EQ(CString("\"\\\"\""), toCStringThroughPrinter("\""));
  EXPECT_EQ(CString("\"\\\\\""), toCStringThroughPrinter("\\"));
  EXPECT_EQ(
      CString("\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\""),
      toCStringThroughPrinter(String("\x00\x01\x02\x03\x04\x05\x06\x07", 8)));
  EXPECT_EQ(
      CString("\"\\u0008\\t\\n\\u000B\\u000C\\r\\u000E\\u000F\""),
      toCStringThroughPrinter(String("\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F", 8)));
  EXPECT_EQ(
      CString("\"\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\""),
      toCStringThroughPrinter(String("\x10\x11\x12\x13\x14\x15\x16\x17", 8)));
  EXPECT_EQ(
      CString("\"\\u0018\\u0019\\u001A\\u001B\\u001C\\u001D\\u001E\\u001F\""),
      toCStringThroughPrinter(String("\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", 8)));
  EXPECT_EQ(CString("\"\\u007F\\u0080\\u0081\""),
            toCStringThroughPrinter("\x7F\x80\x81"));
  EXPECT_EQ(CString("\"\""), toCStringThroughPrinter(emptyString()));
  EXPECT_EQ(CString("<null>"), toCStringThroughPrinter(String()));

  static const UChar unicodeSample[] = {0x30C6, 0x30B9,
                                        0x30C8};  // "Test" in Japanese.
  EXPECT_EQ(CString("\"\\u30C6\\u30B9\\u30C8\""),
            toCStringThroughPrinter(
                String(unicodeSample, WTF_ARRAY_LENGTH(unicodeSample))));
}

}  // namespace WTF


text:
<?php

class CM_Http_Response_Page_EmbedTest extends CMTest_TestCase {

    public function testProcessHostRedirect() {
        $site = CM_Site_Abstract::factory();

        $response = CMTest_TH::createResponsePageEmbed('/mock7', array('host' => $site->getHost()));
        $response->process();
        $this->assertNull($response->getRedirectUrl());

        $response = CMTest_TH::createResponsePageEmbed('/mock7', array('host' => 'incorrect-host.org'));
        $response->process();
        $this->assertSame($site->getUrl() . '/mock7', $response->getRedirectUrl());
    }

    public function testProcessLanguageRedirect() {
        CMTest_TH::createLanguage('en');

        $response = CMTest_TH::createResponsePageEmbed('/en/mock7');
        $response->process();
        $this->assertNull($response->getRedirectUrl());

        $response = CMTest_TH::createResponsePageEmbed('/en/mock7', null, CMTest_TH::createUser());
        $response->process();
        $this->assertSame($response->getSite()->getUrl() . '/mock7', $response->getRedirectUrl());
    }
}

class CM_Page_Mock7 extends CM_Page_Abstract {

    public function getLayout(CM_Frontend_Environment $environment, $layoutName = null) {

        return new CM_Layout_Mock2();
    }
}

class CM_Layout_Mock2 extends CM_Layout_Abstract {

}


text:
var Backbone = require('backbone');

var VisBase = Backbone.Model.extend({
  removeKeys: function(keys) {
    keys.forEach(function(key) {
      if (this.get(key)) {
        this.get(key).remove();
      }
    }, this);
  },

  animateAttrKeys: function(keys, attrObj, speed, easing) {
    // either we animate a specific subset of keys or all
    // possible things we could animate
    keys = Object.assign(
      {},
      {
        include: ['circle', 'arrow', 'rect', 'path', 'text'],
        exclude: []
      },
      keys || {}
    );

    var attr = this.getAttributes();

    // safely insert this attribute into all the keys we want
    keys.include.forEach(function(key) {
      attr[key] = Object.assign(
        {},
        attr[key],
        attrObj
      );
    });

    keys.exclude.forEach(function(key) {
      delete attr[key];
    });

    this.animateToAttr(attr, speed, easing);
  }
});

exports.VisBase = VisBase;


text:
#include "Console.hpp"
#include "GameObject.hpp"

struct Config;
class Actor;

class Sidebar : public Console, public GameObject
{
public:
	explicit Sidebar(Config& config);

	void refresh(Actor& actor);

private:
	void drawLine(int y);

	void printCenter(int y, const std::wstring& string, const sf::Color& color);
	void printCommand(int x, int y, const std::wstring& command, const std::wstring& description);
};


text:
package io.bootique.junit5;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Used to annotate static {@link io.bootique.BQRuntime} instances in a unit test to instruct JUnit to start these
 * runtimes, and shut them down when all the tests in the class are finished. To activate requires @{@link BQTest}
 * annotation on the parent class.
 *
 * @since 2.0
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BQApp {

    BQTestScope value() default BQTestScope.IMPLIED;

    /**
     * If true, skips starting up the app. {@link io.bootique.BQRuntime} will still be shutdown at the end of
     * the test cycle to clean up any resources.
     */
    boolean skipRun() default false;

    /**
     * If true, shuts down the app {@link io.bootique.BQRuntime} immediately after the command exit. Usually
     * appropriate for non-"daemon" apps
     */
    boolean immediateShutdown() default false;
}


text:
package com.kregelbagel.android.drawer;

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

import com.kregelbagel.android.core.Config;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class CustomDrawerAdapter extends ArrayAdapter<DrawerItem> {

	Context context;
	List<DrawerItem> drawerItemList;
	int layoutResID;

	public CustomDrawerAdapter(Context context, int layoutResourceID, List<DrawerItem> listItems) {
		super(context, layoutResourceID, listItems);
		this.context = context;
		this.drawerItemList = listItems;
		this.layoutResID = layoutResourceID;

	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		DrawerItemHolder drawerHolder;
		View view = convertView;

		if (view == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			drawerHolder = new DrawerItemHolder();

			view = inflater.inflate(layoutResID, parent, false);
			drawerHolder.ItemName = (TextView) view.findViewById(R.id.drawer_itemName);
			drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);

			drawerHolder.spinner = (Spinner) view.findViewById(R.id.drawerSpinner);

			drawerHolder.title = (TextView) view.findViewById(R.id.drawerTitle);

			drawerHolder.headerLayout = (LinearLayout) view.findViewById(R.id.headerLayout);
			drawerHolder.itemLayout = (LinearLayout) view.findViewById(R.id.itemLayout);
			drawerHolder.spinnerLayout = (LinearLayout) view.findViewById(R.id.spinnerLayout);

			view.setTag(drawerHolder);

		} else {
			drawerHolder = (DrawerItemHolder) view.getTag();

		}

		DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);

		if (dItem.isSpinner()) {
			drawerHolder.headerLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.itemLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.spinnerLayout.setVisibility(LinearLayout.VISIBLE);

			List<SpinnerItem> userList = new ArrayList<SpinnerItem>();

			String Scontext = Context.ACCOUNT_SERVICE;

			AccountManager manager = (AccountManager) Config.context.getSystemService(Scontext);
			Account[] list = manager.getAccounts();
			String email = "This is an email feild";
			String type = "Default type";
			for (Account account : list) {
				if (account.type.contains("com.google")) {
					email = account.name;
					type = "Grayson Briggs";
					userList.add(new SpinnerItem(R.drawable.user1, type, email));

				}
			}

			CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(context,
					R.layout.custom_spinner_item, userList);

			drawerHolder.spinner.setAdapter(adapter);

			drawerHolder.spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					// TODO Auto-generated method stub
					Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub

				}
			});

		} else if (dItem.getTitle() != null) {
			drawerHolder.headerLayout.setVisibility(LinearLayout.VISIBLE);
			drawerHolder.itemLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.spinnerLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.title.setText(dItem.getTitle());
			Log.d("Getview", "Passed4");
		} else {

			drawerHolder.headerLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.spinnerLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.itemLayout.setVisibility(LinearLayout.VISIBLE);

			drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(dItem.getImgResID()));
			drawerHolder.ItemName.setText(dItem.getItemName());
			Log.d("Getview", "Passed5");
		}
		return view;
	}

	public static class DrawerItemHolder {
		TextView ItemName, title;
		ImageView icon;
		LinearLayout headerLayout, itemLayout, spinnerLayout;
		Spinner spinner;
	}
}


text:
cask v1: 'scratch' do
  version '437'
  sha256 '3615721aaffc5f94512887afd5a470488bd2d33c952137c1a89a3fa1830b91a5'

  url "https://scratch.mit.edu/scratchr2/static/sa/Scratch-#{version}.dmg"
  name 'Scratch'
  homepage 'https://scratch.mit.edu/scratch2download/'
  license :unknown    # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder

  installer script: 'Install Scratch 2.app/Contents/MacOS/Install Scratch 2',
            args: %w[-silent],
            sudo: true

  uninstall script: {
              executable: '/Applications/Utilities/Adobe AIR Application Installer.app/Contents/MacOS/Adobe AIR Application Installer',
              args: %w[-uninstall -silent /Applications/Scratch\ 2.app]
            }

  depends_on cask: 'adobe-air'
end


text:
Target

Test user gesture behavior during touch events.


text:
import {EntityChange} from "./EntityChange";
import {Column, JoinColumn, ManyToOne, MappedSuperclass} from "querydsl-typescript";
import {DeltaRecord, DeltaRecordApi, StubDeltaRecord} from "./DeltaRecord";
/**
 * Created by Papa on 9/15/2016.
 */

export interface AbstractFieldChangeApi<P> extends DeltaRecordApi {
	newValue:P;
	oldValue:P;
	entityRelationName: string;
	propertyName: string;
	entityChange: EntityChange;
}

@MappedSuperclass()
export abstract class AbstractFieldChange extends DeltaRecord {
	@Column({name: "ENTITY_RELATION_NAME"})
	entityRelationName: string;

	@Column({name: "PROPERTY_NAME"})
	propertyName: string;

	@ManyToOne()
	@JoinColumn({name: "ENTITY_CHANGE_ID", nullable: false})
	entityChange: EntityChange;

	static getFieldChangeId(
		propertyName: string,
		entityIdInGroup: number,
		createDeviceId: string,
		createDateTime: Date,
		createUserId: string
	): string {
		return `${entityIdInGroup}_${createDeviceId}_${createDateTime.getTime()}_${createUserId}_${propertyName}`;
	}

}


text:
{% extends 'templates/nhs_transaction_layout.html' %}
{% import 'includes/form_macros.html' as form_macros %}

{% block content %}

Back

         <form action="uc-element-income-handler" method="get" class="form">

Were your net earnings £935 or less during your assessment period?

  What is my assessment period?

Your assessment period will run for a calendar month from the date of your claim for Universal Credit (which will be shown on your award notice), and between the same dates each month after that.

        <fieldset>

              <input type="radio" id="yes" name="ucelementIncome" value="yes">

                Yes

              <input type="radio" id="no" name="ucelementIncome" value="no">

                No

        </fieldset>

    {{
      form_macros.button({
        label: 'Next'
      })
    }}

  </form>


text:
class UpdateResourceStateEventsConstraintToSupportEpicId < ActiveRecord::Migration[6.0]
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  disable_ddl_transaction!

  OLD_CONSTRAINT = 'resource_state_events_must_belong_to_issue_or_merge_request'
  CONSTRAINT_NAME = 'resource_state_events_must_belong_to_issue_or_merge_request_or_'

  def up
    remove_check_constraint :resource_state_events, OLD_CONSTRAINT
    add_check_constraint :resource_state_events, "(issue_id != NULL AND merge_request_id IS NULL AND epic_id IS NULL) OR " \
      "(issue_id IS NULL AND merge_request_id != NULL AND epic_id IS NULL) OR" \
      "(issue_id IS NULL AND merge_request_id IS NULL AND epic_id != NULL)", CONSTRAINT_NAME
  end

  def down
    remove_check_constraint :resource_state_events, CONSTRAINT_NAME
    add_check_constraint :resource_state_events, '(issue_id != NULL AND merge_request_id IS NULL) OR (merge_request_id != NULL AND issue_id IS NULL)', OLD_CONSTRAINT
  end
end


text: nohup node server.js &


text:
package librato

type Metric struct {
	Name        string  `json:"name"`
	Value       float64 `json:"value"`
	MeasureTime int64   `json:"measure_time,omitempty"`
	Source      string  `json:"source,omitempty"`
}

type Gauge struct {
	Name        string  `json:"name"`
	MeasureTime int64   `json:"measure_time,omitempty"`
	Source      string  `json:"source,omitempty"`
	Count       uint64  `json:"count"`
	Sum         float64 `json:"sum"`
	Max         float64 `json:"max,omitempty"`
	Min         float64 `json:"min,omitempty"`
	SumSquares  float64 `json:"sum_squares,omitempty"`
}

type Metrics struct {
	MeasureTime int64         `json:"measure_time,omitempty"`
	Source      string        `json:"source,omitempty"`
	Counters    []Metric      `json:"counters,omitempty"`
	Gauges      []interface{} `json:"gauges,omitempty"` // Values can be either Metric or Gauge
}

// PostMetrics submits measurements for new or existing metrics.
// http://dev.librato.com/v1/post/metrics
func (cli *Client) PostMetrics(metrics *Metrics) error {
	if len(metrics.Counters) == 0 && len(metrics.Gauges) == 0 {
		return nil
	}
	return cli.request("POST", metricsURL, metrics, nil)
}