设置 true 为开发模式，支持模板文件热加载
设置 false 为生产模式，不支持模板文件热加载，以达到更高的性能
507710
public Engine setDevMode(boolean devMode) {
		this.devMode = devMode;
		this.config.setDevMode(devMode);
		if (this.devMode) {
			removeAllTemplateCache();
		}
		return this;
	}
1104765
function (unloadedMods, errorList, stack, cache, ret) {
            var i, m, mod, modStatus,
                stackDepth,
                self = this;

            if ('@DEBUG@') {
                stack = stack || [];
            }
            ret = ret || [];
            // 提高性能，不用每个模块都再次全部依赖计算
            // 做个缓存，每个模块对应的待动态加载模块
            cache = cache || {};

            for (i = 0; i < unloadedMods.length; i++) {
                mod = unloadedMods[i];
                m = mod.name;

                if (cache[m]) {
                    continue;
                }

                if ('@DEBUG@') {
                    stackDepth = stack.length;
                }

                modStatus = mod.status;
                if (modStatus === ERROR) {
                    errorList.push(mod);
                    cache[m] = 1;
                    continue;
                }
                if (modStatus > LOADED) {
                    cache[m] = 1;
                    continue;
                } else if (modStatus !== LOADED && !mod.contains(self)) {
                    if (modStatus !== LOADING) {
                        mod.status = LOADING;
                        ret.push(mod);
                    }
                    mod.add(self);
                    self.wait(mod);
                }

                if ('@DEBUG@') {
                    // do not use indexOf, poor performance in ie8
                    if (stack[m]) {
                        S.log('find cyclic dependency between mods: ' + stack, 'warn');
                        cache[m] = 1;
                        continue;
                    } else {
                        stack[m] = 1;
                        stack.push(m);
                    }
                }

                self.calculate(mod.getNormalizedRequiredModules(), errorList, stack, cache, ret);
                cache[m] = 1;
                if ('@DEBUG@') {
                    for (var si = stackDepth; si < stack.length; si++) {
                        stack[stack[si]] = 0;
                    }
                    stack.length = stackDepth;
                }
            }

            return ret;
        }
773556
public function upBase64()
    {
        $base64Data = Yii::$app->request->post($this->fileField);
        $img = base64_decode($base64Data);
        $this->oriName = $this->config['oriName'];
        $this->fileSize = strlen($img);
        $this->fileType = $this->getExtension();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirName = dirname($this->filePath);

        if (!is_dir($dirName)) {//递归创建保存目录
            FileHelper::createDirectory($dirName, $this->dirMode, true);
        }
        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = Yii::t('attachment', 'The file size exceeds the site limit.');
            return false;
        }

        //移动文件
        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = Yii::t('attachment', 'An error occurred while saving the file.');
            return false;
        } else { //移动成功
            $this->saveModel();
            $this->stateInfo = 'SUCCESS';
            return true;
        }
    }
372273
public function _import($tag,$content,$isFile=false,$type='') {
        $file       =   isset($tag['file'])?$tag['file']:$tag['href'];
        $parseStr   =   '';
        $endStr     =   '';
        // 判断是否存在加载条件 允许使用函数判断(默认为isset)
        if (isset($tag['value'])) {
            $varArray  =    explode('|',$tag['value']);
            $name      =    array_shift($varArray);
            $name      =    $this->autoBuildVar($name);
            if (!empty($varArray))
                $name  =    $this->tpl->parseVarFunction($name,$varArray);
            else
                $name  =    'isset('.$name.')';
            $parseStr .=    '<?php if('.$name.'): ?>';
            $endStr    =    '<?php endif; ?>';
        }
        if($isFile) {
            // 根据文件名后缀自动识别
            $type  = $type?$type:(!empty($tag['type'])?strtolower($tag['type']):null);
            // 文件方式导入
            $array =  explode(',',$file);
            foreach ($array as $val){
                if (!$type || isset($reset)) {
                    $type = $reset = strtolower(substr(strrchr($val, '.'),1));
                }
                switch($type) {
                case 'js':
                    $parseStr .= '<script type="text/javascript" src="'.$val.'"></script>';
                    break;
                case 'css':
                    $parseStr .= '<link rel="stylesheet" type="text/css" href="'.$val.'" />';
                    break;
                case 'php':
                    $parseStr .= '<?php require_cache("'.$val.'"); ?>';
                    break;
                }
            }
        }else{
            // 命名空间导入模式 默认是js
            $type       =   $type?$type:(!empty($tag['type'])?strtolower($tag['type']):'js');
            $basepath   =   !empty($tag['basepath'])?$tag['basepath']:__ROOT__.'/Public';
            // 命名空间方式导入外部文件
            $array      =   explode(',',$file);
            foreach ($array as $val){
                if(strpos ($val, '?')) {
                    list($val,$version) =   explode('?',$val);
                } else {
                    $version = '';
                }
                switch($type) {
                case 'js':
                    $parseStr .= '<script type="text/javascript" src="'.$basepath.'/'.str_replace(array('.','#'), array('/','.'),$val).'.js'.($version?'?'.$version:'').'"></script>';
                    break;
                case 'css':
                    $parseStr .= '<link rel="stylesheet" type="text/css" href="'.$basepath.'/'.str_replace(array('.','#'), array('/','.'),$val).'.css'.($version?'?'.$version:'').'" />';
                    break;
                case 'php':
                    $parseStr .= '<?php import("'.$val.'"); ?>';
                    break;
                }
            }
        }
        return $parseStr.$endStr;
    }
1240495
private static void loadConf(String confFile) {
        InputStream in = WordConfTools.class.getClassLoader().getResourceAsStream(confFile);
        if(in == null){
            LOGGER.info("未找到配置文件："+confFile);
            return;
        }
        LOGGER.info("加载配置文件："+confFile);
        loadConf(in);
    }
163729
function addEntries(env, webpackConfig) {
    // 指定入口的 js 文件和 html 文件的路径, 默认相对于 src 目录(根目录)
    wieldyWebpack.createEntry('index/index.js', 'index.html', {
        env: env,
        // 有多个入口时, 在创建时需要设置 setChunks 为 true
        setChunks: true
    }).addToWebpackConfig(webpackConfig);

    // 使用 layout 机制
    wieldyWebpack.createEntry('about/about.js', 'about/about.html', {
        title: 'wieldy-webpack 多入口示例项目 about',
        env: env,
        setChunks: true
    }).useLayout('layout.html', {
        env: {
            __body_start__: '<p>测试</p>'
        }
    }).addToWebpackConfig(webpackConfig);

    // 使用 layout 机制时可以不指定入口的 html 文件
    wieldyWebpack.createEntry('login/login.js', '', {
        title: 'wieldy-webpack 多入口示例项目 login',
        env: env,
        setChunks: true
    }).useLayout('layout.html', {
        env: {
            __body_start__: `
                <h1>登录</h1>
                <ul>
                    <li><a href="/index.html">首页</a></li>
                    <li><a href="/about/about.html">关于</a></li>
                    <li><a href="/login/login.html">登录</a></li>
                </ul>
            `
        }
    }).addToWebpackConfig(webpackConfig);
}
843186
protected boolean processStream(MultipartRequestInputStream input) throws IOException {
		if (!isAllowedExtension()) {
			// 非允许的扩展名
			log.debug("Forbidden uploaded file [{}]", this.getFileName());
			size = input.skipToBoundary();
			return false;
		}
		size = 0;

		// 处理内存文件
		int memoryThreshold = setting.memoryThreshold;
		if (memoryThreshold > 0) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream(memoryThreshold);
			int written = input.copy(baos, memoryThreshold);
			data = baos.toByteArray();
			if (written <= memoryThreshold) {
				// 文件存放于内存
				size = data.length;
				return true;
			}
		}

		// 处理硬盘文件
		tempFile = FileUtil.createTempFile(TMP_FILE_PREFIX, TMP_FILE_SUFFIX, FileUtil.touch(setting.tmpUploadPath), false);
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
		if (data != null) {
			size = data.length;
			out.write(data);
			data = null; // not needed anymore
		}
		int maxFileSize = setting.maxFileSize;
		try {
			if (maxFileSize == -1) {
				size += input.copy(out);
				return true;
			}
			size += input.copy(out, maxFileSize - size + 1); // one more byte to detect larger files
			if (size > maxFileSize) {
				// 超出上传大小限制
				tempFile.delete();
				tempFile = null;
				log.debug("Upload file [{}] too big, file size > [{}]", this.getFileName(), maxFileSize);
				input.skipToBoundary();
				return false;
			}
		} finally {
			IoUtil.close(out);
		}
		// if (getFileName().length() == 0 && size == 0) {
		// size = -1;
		// }
		return true;
	}
324533
private static void extractText(Path file, BufferedWriter writer, String separator, boolean includePhrase){
        try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.toFile()),"utf-8"));){
            String line;
            while( (line = reader.readLine()) != null ){
                //去除首尾空白字符
                line = line.trim();
                //忽略空行
                if(!"".equals(line)){
                    //词和词之间以空格隔开
                    String[] words = line.split("\\s+");
                    if(words == null){
                        //忽略不符合规范的行
                        continue;
                    }
                    StringBuilder phrase = new StringBuilder();
                    int phraseCount=0;
                    boolean find=false;
                    for(String word : words){
                        String[] attr = word.split("/");
                        if(attr == null || attr.length < 1){
                            //忽略不符合规范的词
                            continue;
                        }
                        if(attr[0].trim().startsWith("[")){
                            find = true;
                        }                        
                        //去掉[和]
                        String item = attr[0].replace("[", "").replace("]", "").trim();
                        writer.write(item+separator);
                        if(find){
                            phrase.append(item);
                            phraseCount++;
                        }
                        //短语标注错误
                        if(phraseCount > 10){
                            find = false;
                            phraseCount = 0;
                            phrase.setLength(0);
                        }
                        if(find && attr.length > 1 && attr[1].trim().endsWith("]")){
                            find = false;
                            if(includePhrase){
                                writer.write(phrase.toString()+separator);
                            }
                            phrase.setLength(0);
                        }
                        //词数目
                        WORD_COUNT.incrementAndGet();
                        //字符数目
                        CHAR_COUNT.addAndGet(item.length());
                    }
                    //换行
                    writer.write("\n");
                }
            }
        }catch(Exception e){
            LOGGER.info("从语料库 "+file+" 中抽取文本失败：", e);
        }        
    }
1169814
function rudePackager(ret, pack, settings, opt) {
  var files = ret.src;
  var sources = _.toArray(files);

  // 生成映射表，方便快速查找！
  var idmapping = ret.idmapping = {};
  var urlmapping = ret.urlmapping = {};
  Object.keys(files).forEach(function(subpath) {
    var file = files[subpath];
    idmapping[file.id] = file;
    if (file.release) {
      urlmapping[file.getUrl()] = file;
    }
  });

  var includeList = [];
  // 如果有设置需要额外的模块加入到 resouceMap 当中
  if (settings.include) {
    var patterns = settings.include;
    if (!Array.isArray(patterns)) {
      patterns = [patterns];
    }

    
    patterns.forEach(function(pattern, index) {
      var exclude = typeof pattern === 'string' && pattern.substring(0, 1) === '!';

      if (exclude) {
        pattern = pattern.substring(1);

        // 如果第一个规则就是排除用法，都没有获取结果就排除，这是不合理的用法。
        // 不过为了保证程序的正确性，在排除之前，通过 `**` 先把所有文件获取到。
        // 至于性能问题，请用户使用时规避。
        index === 0 && (includeList = find('**'));
      }

      var mathes = find(pattern);
      includeList = _[exclude ? 'difference' : 'union'](includeList, mathes);
    });
  }

  Object.keys(files).forEach(function(subpath) {
    var file = files[subpath];

    compile(file);
  });

  function find(reg) {
    if (files[reg]) {
      return [files[reg]];
    } else if (reg === '**') {
      // do nothing
    } else if (typeof reg === 'string') {
      reg = _.glob(reg);
    }

    return sources.filter(function(file) {
      reg.lastIndex = 0;
      return (reg === '**' || reg.test(file.subpath));
    });
  }

  function compile(file) {
    var processor = rudePackager.lang[file.loaderLang] ||
      rudePackager.lang[settings.processor[file.ext]] ||
      rudePackager.lang.html;

    // 非 htmlLike 或者 没有处理器，或者已经处理过了，则跳过。
    if (file.release === false ||
        !file.isHtmlLike ||
        file.loaderLang === false ||
        file.loaderLang === null ||
        !processor ||
        file._resource) {
      return;
    }

    // 可以让 processor 调用。
    processor._compile = compile;

    // 修改之前先，先备份。
    file._rudeBackup = file.getContent();

    var resource = createResource(ret, file, settings);
    file._resource = resource;
    processor.init && processor.init(file, resource, settings);

    processor.beforePack && processor.beforePack(file, resource, settings, includeList);

    if (settings.allInOne) {
      allInOnePack(file, resource, ret, settings.allInOne === true ? {} : settings.allInOne);
    }

    processor.before && processor.before(file, resource, settings);
    processor(file, resource, settings);
    processor.after && processor.after(file, resource, settings);

    file.useCache = false; // 让其缓存失效，watch 的时候，下次需要重新发布过去。
    ret.pkg[file.subpath] = file;
  }
}
1192154
static boolean load(String path, AhoCorasickDoubleArrayTrie<String> trie, boolean reverse)
    {
        String datPath = path;
        if (reverse)
        {
            datPath += Predefine.REVERSE_EXT;
        }
        if (loadDat(datPath, trie)) return true;
        // 从文本中载入并且尝试生成dat
        TreeMap<String, String> map = new TreeMap<String, String>();
        if (!load(map, reverse, path)) return false;
        logger.info("正在构建AhoCorasickDoubleArrayTrie，来源：" + path);
        trie.build(map);
        logger.info("正在缓存双数组" + datPath);
        saveDat(datPath, trie, map.entrySet());
        return true;
    }
1127478
public function checkImg() {
		$extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION));
		/* 对图像文件进行严格检测 */
		if (in_array($extension, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']) && !in_array($this->getImageType($this->filename), [1, 2, 3, 4, 6, 13])) {
			return false;
		}
		return true;
	}
1226577
private static boolean isDicNeedUpdate(String mainPath, String path[])
    {
        if (HanLP.Config.IOAdapter != null &&
            !HanLP.Config.IOAdapter.getClass().getName().contains("com.hankcs.hanlp.corpus.io.FileIOAdapter"))
        {
            return false;
        }
        String binPath = mainPath + Predefine.BIN_EXT;
        File binFile = new File(binPath);
        if (!binFile.exists())
        {
            return true;
        }
        long lastModified = binFile.lastModified();
        //String path[] = HanLP.Config.CustomDictionaryPath;
        for (String p : path)
        {
            File f = new File(p);
            String fileName = f.getName();
            int cut = fileName.lastIndexOf(' ');
            if (cut > 0)
            {
                p = f.getParent() + File.separator + fileName.substring(0, cut);
            }
            f = new File(p);
            if (f.exists() && f.lastModified() > lastModified)
            {
                IOUtil.deleteFile(binPath); // 删掉缓存
                logger.info("已清除自定义词典缓存文件！");
                return true;
            }
        }
        return false;
    }
269363
function addFile(file) {
            var $li = $('<li id="' + file.id + '">' +
                '<p class="title">' + file.name + '</p>' +
                '<p class="imgWrap"></p>' +
                '<p class="progress"><span></span></p>' +
                '</li>'),

                $btns = $('<div class="file-panel">' +
                    '<span class="cancel">删除</span>' + '</div>').appendTo($li),
                $prgress = $li.find('p.progress span'),
                $wrap = $li.find('p.imgWrap'),
                $info = $('<p class="error"></p>'),

                showError = function(code) {
                    switch (code) {
                        case 'interrupt':
                            text = '上传暂停';
                            break;

                        default:
                            text = '上传失败，请重试';
                            break;
                    }

                    $info.text(text).appendTo($li);
                };

            if (file.getStatus() === 'invalid') {
                showError(file.statusText);
            } else {
                $wrap.text('不能预览');
                percentages[file.id] = [file.size, 0];
                file.rotation = 0;
            }

            file.on('statuschange', function(cur, prev) {
                if (prev === 'progress') {
                    $prgress.hide().width(0);
                } else if (prev === 'queued') {
                    $li.off('mouseenter mouseleave');
                    $btns.remove();
                }

                // 成功
                if (cur === 'error' || cur === 'invalid') {
                    showError(file.statusText);
                    percentages[file.id][1] = 1;
                } else if (cur === 'interrupt') {
                    showError('interrupt');
                } else if (cur === 'queued') {
                    percentages[file.id][1] = 0;
                } else if (cur === 'progress') {
                    $info.remove();
                    $prgress.css({
                        display: 'block',
                        width: '10%'
                    });
                } else if (cur === 'complete') {
                    $li.append('<span class="success"></span>');
                }

                $li.removeClass('state-' + prev).addClass('state-' + cur);
            });

            $li.on('mouseenter', function() {
                $btns.stop().animate({
                    height: 30
                });
            });

            $li.on('mouseleave', function() {
                $btns.stop().animate({
                    height: 0
                });
            });

            $btns.on('click', 'span', function() {
                uploader.removeFile(file);
            });

            $li.appendTo($queue);
        }
1247202
public void init() throws WatchException{
		//获取目录或文件路径
		if(false ==Files.exists(this.path, LinkOption.NOFOLLOW_LINKS)) {
			final Path lastPathEle = FileUtil.getLastPathEle(this.path);
			if(null != lastPathEle) {
				final String lastPathEleStr = lastPathEle.toString();
				//带有点表示有扩展名，按照未创建的文件对待。Linux下.d的为目录，排除之
				if(StrUtil.contains(lastPathEleStr, StrUtil.C_DOT) && false ==StrUtil.endWithIgnoreCase(lastPathEleStr, ".d")) {
					this.filePath = this.path;
					this.path = this.filePath.getParent();
				}
			}
			
			//创建不存在的目录或父目录
			try {
				Files.createDirectories(this.path);
			} catch (IOException e) {
				throw new IORuntimeException(e);
			}
		}else if(Files.isRegularFile(this.path, LinkOption.NOFOLLOW_LINKS)){
			this.filePath = this.path;
			this.path = this.filePath.getParent();
		}
		
		//初始化监听
		try {
			watchService = FileSystems.getDefault().newWatchService();
		} catch (IOException e) {
			throw new WatchException(e);
		}
		
		isClosed = false;
	}
588633
function abortUpload(rootError) {

    // 初始化MultipartUpload的时候报错，则直接触发error事件
    if (multipartUploadResult === null && multipartUploadID === null) {
      return ws.emit('error', rootError);
    }

    cachedClient.abortMultipartUpload({
      Bucket: multipartUploadResult.Bucket,
      Key: multipartUploadResult.Key,
      UploadId: multipartUploadID
    }, function (err) {
      if (err) {
        ws.emit('error', rootError + '\n Additionally failed to abort the multipart upload on OSS: ' + err);
      } else {
        ws.emit('error', rootError);
      }
    });
  }
117822
public boolean load(String path)
    {
        String binPath = path + Predefine.BIN_EXT;
        if (load(ByteArrayStream.createByteArrayStream(binPath))) return true;
        if (!loadTxt(path)) return false;
        try
        {
            logger.info("正在缓存" + binPath);
            DataOutputStream out = new DataOutputStream(IOUtil.newOutputStream(binPath));
            save(out);
            out.close();
        }
        catch (Exception e)
        {
            logger.warning("缓存" + binPath + "失败：\n" + TextUtility.exceptionToString(e));
        }

        return true;
    }
1125687
function copyExamp(path,pathLength){
	fs.readdir(path,function(err, files){
		if(err){
			console.log('examples read dir err:' + path);
		}else{
			// 遍历目录下所有子项
			files.forEach(function(item){
				var tmpPath = path + '/' + item;
				fs.stat(tmpPath,function(err, stat){
					if(stat.isFile()){
						// 判断文件类型,如果是.html则转化
						var htmlIndex = item.indexOf('.html');
						var jsIndex = item.indexOf('.js');
						var cssIndex = item.indexOf('.css');
						if(htmlIndex < 0 && (jsIndex > -1 || cssIndex > -1)){
							// 创建读取流
		                    readable = fs.createReadStream( tmpPath );
		                    // 创建写入流
		                    writable = fs.createWriteStream( 'examples/' + tmpPath.substring(pathLength) );
		                    // 通过管道来传输流
		                    readable.pipe(writable);
						}
						if(htmlIndex > -1){
							fs.readFile(tmpPath,function(err,data){
								var htmlStr = '';
								if(err){
									console.log('read html err:' + tmpPath)
								}else{
									htmlStr = data.toString();
								}
								var ctx = 'http://design.yonyoucloud.com/static/'
								var tpl = [
							        '<!DOCTYPE html>',
							        '<html lang="en">',
							        '<head>',
							        '<meta charset="UTF-8">',
							        '<meta name="viewport" content="width=device-width, initial-scale=1">',
							       	'<title>Title</title>',
									'<link rel="stylesheet" href="'+ ctx +'/font-awesome/css/font-awesome.css">',
							       	'<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/u.css">',
							       	'<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/u-extend.css">',
								    '<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/tree.css">',
							        '<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/grid.css">',
							        '<link rel="stylesheet" type="text/css" href="widget.css">',
							        '</head>',
							        '<body>',
							        htmlStr,
							        '<script src="'+ ctx +'/jquery/jquery-1.11.2.js"></script>',
							    	'<script src="'+ ctx +'/knockout/knockout-3.2.0.debug.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u-polyfill.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u-tree.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u-grid.js"></script>',
									'<script src="'+ ctx +'/requirejs/require.debug.js"></script>',
									'<script src="widget.js"></script>',
							        '</body>',
							        '</html>'
						        ]
					        	var tplStr = tpl.join('\r\n');
					        	fs.writeFile('examples/' + tmpPath.substring(pathLength),tplStr,function(err){
						        	if(err){
						        		console.log('write err:' + 'examples/' + item + '.html');
						        	}
						        })
					        })
						}
					}
					// 子项为目录创建目录
					if(stat.isDirectory()){
						var dirPath = 'examples/' + tmpPath.substring(pathLength);
						fs.exists(dirPath, function(exist) {
							if(!exist){
								fs.mkdirSync(dirPath);
							}
						});
						copyExamp(tmpPath,pathLength);
					}
				})
			})
		}
	})
}