Created by maoshuchen on 9/28/2016.
966134
function bindActionCreator(options, actionCreator, dispatch) {
  return (...args) => {
    const realActionCreator = actionCreator(...args);
    if(typeof realActionCreator != 'function'){
      throw new Error(
        'your actionCreator is not function, make sure your action return is defined as options => {} or options => (dispatch, getState) => {}'
      )
    }
    dispatch(realActionCreator(options));
  };
}
1339897
def register(self, *args, **kwargs):
        '''
        
        '''
        return {
            'name': zhihu.name,
            'display_name': zhihu.display_name,
            'author': zhihu.author,
            'email': zhihu.email,
            'description': zhihu.description,
            'meta': {
                # 爬取计划，参考 crontab 配置方法
                'crawl_schedule': '0 23 * * *',

                # 执行爬取的随机延时，单位秒，用于避免被 Ban
                'crawl_random_delay': str(60 * 60),

                'package_module': 'mobi',
                'language': 'zh-CN',
                'book_mode': 'periodical',  # 'periodical' | 'book'
                'img_cover': os.path.join(
                    _images_path, 'cv_zhihudaily.jpg'),
                'img_masthead': os.path.join(
                    _images_path, 'mh_zhihudaily.gif'),
                'image_filter': json.dumps(['zhihu.com/equation']),
                'css_package': os.path.join(
                    _css_path, 'package.css')
            }
        }
202402
function createDom(vnode, $thisContext) {

    if ( !vnode ) {
        return; // 不显示的家伙
    }
	
	let el, $$el;
	if (vnode.t) {
		if (vnode.m) { // HTML标准标准定义的标签以外，都按组件看待。推荐自定义标签名用半角减号连接，如my-tag

			// 子组件渲染
			let comp = new createComponentByVnode(vnode); // 属性作为配置选项直接全部传入(子虚拟节点也按属性$SLOT传入)
			vnode.o = comp; // 虚拟节点挂上组件实例

			el = comp.render(); // 渲染为DOM，初始配置已通过选项传入

			// 组件有ref属性时，建立关联关系 【refs:{ c:{组件}， e:{节点} }】
			let refs, cls;
			if ( vnode.a && vnode.a.ref ) {
                // 默认上下文是当前组件，但slot的话需要由原组件对象管理，slot的原组件对象在虚拟节点属性中
                let $context = vnode.a.$context || $thisContext;
				refs = ($context.$refs = $context.$refs || {});
				let ref = refs.c = refs.c || {};
				cls = ref[vnode.a.ref] = ref[vnode.a.ref] || uid('_ref_'); // 类名

                // TODO 挂载前也能取。。。
			}

			if ( el ) {
				$$el = $$(el);
				$$el.addClass(comp.$COMPONENT_ID); // 使用组件对象ID插入到组件根节点class上建立关联

				// 组件有ref属性时，建立关联关系 【refs:{ c:{组件}， e:{节点} }】
				cls && $$el.addClass(vnode.r = cls);			// r=cls. 查找时，通过引用名查得cls，由cls查得DOM，由DOM查得单个或复合虚拟节点，再遍历比较虚拟节点的r可找到对应的组件虚拟节点，最后拿到组件对象

                // 组件创建初期，根据@show设定hidden样式
                if ( vnode.a && vnode.a['@show'] !== undefined ) {
                    vnode.a['@show'] ? $$el.removeClass('hidden') : $$el.addClass('hidden');
                }            
            }

		} else {
			// <script>标签特殊处理，创建<script>标签直接加到head中
			if ( /^script$/i.test(vnode.t) ) {
				return loadScript(vnode.a);
			}
			// <link>标签特殊处理，创建<link>标签直接加到head中
			if ( /^link$/i.test(vnode.t) ) {
				return loadLink(vnode.a);
			}

			// 创建节点【g属性代表SVG标签或SVG子标签，SVG标签及其子标签都用createElementNS创建，其他操作雷同】
			el = vnode.g ? document.createElementNS('http://www.w3.org/2000/svg', vnode.t) : document.createElement(vnode.t);
			$$el = $$(el);

			// 属性设定
			if (vnode.a) {
				for (let k in vnode.a) {
					if ( k == 'ref' ) {
						// 对ref属性做特殊处理：添加相应类名便于查找
                        let $context = vnode.a.$context || $thisContext;
						let refs = $context.$refs = $context.$refs || {};
						let ref = refs.e = refs.e || {};
						let cls = ref[vnode.a[k]] = ref[vnode.a[k]] || uid('_ref_'); // 类名
						$$el.addClass(vnode.r = cls);	// r=cls，查找时，通过引用名查得cls，由cls查得DOM

                        // TODO 挂载前也能取。。。
                    }
					$$el.attr(k, vnode.a[k]);
				}
			}
			
			// 事件绑定
			if (vnode.e) {
				for (let k in vnode.e) {
					if ( isFunction(vnode.e[k]) ) {
						$$(el).on(k, vnode.e[k] );
					}else if ( vnode.e[k] == undefined ) {
						// 没有定义事件处理方法，忽略
					}else{
						console.error('invalid event handle:', k, '=', vnode.e[k]); // 绑定的不是方法
					}
				}
			}

			// 创建子组件
			if (vnode.c) {
                for ( let i=0,vn,dom; vn=vnode.c[i++]; ) {
                    dom = createDom(vn, $thisContext);  // 可能undefined。。。。。。<script>或<link>
                    dom && el.appendChild(dom);
                }
			}

            // TODO 含slot属性模板标签的特殊考虑

		}
	} else {
		el = document.createTextNode(vnode.s);
	}

	// 每个真实DOM节点都关联一个对应的虚拟节点
	el && domVnode(el, vnode);

	return el;
}
1334825
function(){

    var sprites = this.sprites;

    if (Object.keys(sprites).length === 0) {
      Log.debug('no image need merge');
      this.fire('finish:merge', {exit: true});
    } else {
      //拼图
      Api.mergeImages([this.get('file'), sprites], this._finishMerge, this);
    }
  }
850403
protected function onStart()
    {
        // 初始化目录
        umask(0);
        $statistic_dir = Config::$dataPath . $this->statisticDir;
        if(!is_dir($statistic_dir))
        {
            mkdir($statistic_dir, 0777, true);
        }
        $log_dir = Config::$dataPath . $this->logDir;
        if(!is_dir($log_dir))
        {
            mkdir($log_dir, 0777, true);
        }
        // 定时保存统计数据
        Timer::add(self::WRITE_PERIOD_LENGTH, array($this, 'writeStatisticsToDisk'));
        Timer::add(self::WRITE_PERIOD_LENGTH, array($this, 'writeLogToDisk'));
        // 定时清理不用的统计数据
        Timer::add(self::CLEAR_PERIOD_LENGTH, array($this, 'clearDisk'), array(Config::$dataPath . $this->statisticDir, self::EXPIRED_TIME));
        Timer::add(self::CLEAR_PERIOD_LENGTH, array($this, 'clearDisk'), array(Config::$dataPath . $this->logDir, self::EXPIRED_TIME));
        
    }
139659
private static void combineWords(Vertex[] wordNet, int start, int end, CoreDictionary.Attribute value)
    {
        if (start + 1 == end)   // 小优化，如果只有一个词，那就不需要合并，直接应用新属性
        {
            wordNet[start].attribute = value;
        }
        else
        {
            StringBuilder sbTerm = new StringBuilder();
            for (int j = start; j < end; ++j)
            {
                if (wordNet[j] == null) continue;
                String realWord = wordNet[j].realWord;
                sbTerm.append(realWord);
                wordNet[j] = null;
            }
            wordNet[start] = new Vertex(sbTerm.toString(), value);
        }
    }
598801
function () {
		// Create Layout
		this._el.attribution 				= TL.Dom.create('div', 'tl-attribution', this._el.container);
		this._el.line						= TL.Dom.create('div', 'tl-timenav-line', this._el.container);
		this._el.slider						= TL.Dom.create('div', 'tl-timenav-slider', this._el.container);
		this._el.slider_background			= TL.Dom.create('div', 'tl-timenav-slider-background', this._el.slider);
		this._el.marker_container_mask		= TL.Dom.create('div', 'tl-timenav-container-mask', this._el.slider);
		this._el.marker_container			= TL.Dom.create('div', 'tl-timenav-container', this._el.marker_container_mask);
		this._el.marker_item_container		= TL.Dom.create('div', 'tl-timenav-item-container', this._el.marker_container);
		this._el.timeaxis 					= TL.Dom.create('div', 'tl-timeaxis', this._el.slider);
		this._el.timeaxis_background 		= TL.Dom.create('div', 'tl-timeaxis-background', this._el.container);


		// Knight Lab Logo
		this._el.attribution.innerHTML = "<a href='http://timeline.knightlab.com' target='_blank'><span class='tl-knightlab-logo'></span>Timeline JS</a>"

		// Time Axis
		this.timeaxis = new TL.TimeAxis(this._el.timeaxis, this.options);

		// Swipable
		this._swipable = new TL.Swipable(this._el.slider_background, this._el.slider, {
			enable: {x:true, y:false},
			constraint: {top: false,bottom: false,left: (this.options.width/2),right: false},
			snap: 	false
		});
		this._swipable.enable();

	}
846232
private static ChronoUnit create(DateUnit dateUnit) {
        switch (dateUnit) {
            case YEAR:
                return ChronoUnit.YEARS;
            case MONTH:
                return ChronoUnit.MONTHS;
            case DAY:
                return ChronoUnit.DAYS;
            case HOUR:
                return ChronoUnit.HOURS;
            case MINUTE:
                return ChronoUnit.MINUTES;
            case SECOND:
                return ChronoUnit.SECONDS;
            default:
                throw new DateUtilException("没有单位：" + dateUnit);
        }
    }
1001777
public function create()
    {
        if ($this->bgImage && is_file($this->bgImage)) {
            // 从背景图片建立背景画布
            $this->img = imagecreatefrompng($this->bgImage);
        } else {
            // 手动建立背景画布,图像资源
            $this->img = imagecreatetruecolor($this->width, $this->height);

            //给画布填充矩形的背景色rgb(230, 255, 230);
            $bgColor = $this->bgColor;

            //背景色
            $bgColor = imagecolorallocate(
                $this->img, hexdec(substr($bgColor, 1, 2)),
                hexdec(substr($bgColor, 3, 2)), hexdec(substr($bgColor, 5, 2))
            );

            imagefilledrectangle($this->img, 0, 0, $this->width, $this->height, $bgColor);
        }

        //给资源画上边框-可选 rgb(153, 153, 255)
//        $borderColor = imagecolorallocate($this->img, 153, 153, 255); // 0-255
//        imagerectangle($this->img, 0, 0, $this->width-1, $this->height-1,$borderColor);

        $this->drawLine();
        $this->drawChar();
        $this->drawPixel();
        $this->drawChars();

        return $this;
    }
547904
function() {
    var self = this;

    // 遮罩层
    if (self.option('mask') && !self.mask) {
      self.mask = new Mask({
        autoShow: self.option('effect') === 'none',
        baseElement: self.option('baseElement'),
        container: self.element,
        css: {
          position: self.option('maskFixed') ? 'fixed' : self.option('css/position')
        },
        delegates: {
          'keydown': function(e) {
            (e.keyCode === 27) && self.close();
          },
          'click': function(e) {
            // shaking
            self.stop()
              .animate({
                left: '-=10'
              }, 40)
              .animate({
                left: '+=20'
              }, 80)
              .animate({
                left: '-=20'
              }, 80)
              .animate({
                left: '+=10'
              }, 40);
          }
        },
        effect: self.option('effect'),
        insert: function() {
          this.container.before(this.element);
        }
      });

      self.show(function() {
        this.mask && this.mask.show();
      }).hide(function() {
        this.mask && this.mask.hide();
      });
    }
  }
1126947
private Viterbi<PersonNode> getPersonNodeViterbi(Term[] terms) {
        Term first;
        PersonNatureAttr fPna;
        Term second;
        Term third;
        Term from;
        for (int i = 0; i < terms.length - 1; i++) {
            first = terms[i];

            if (first == null) {
                continue;
            }

            fPna = getPersonNature(first);
            setNode(first, A);

            if (fPna.getY() > 0) {
                setNode(first, Y);
            }

            if (!fPna.isActive()) {
                continue;
            }

            second = first.to();
            if (second.getOffe() == terms.length || second.getName().length() > 2) { //说明到结尾了,或者后面长度不符合规则
                continue;
            }

            third = second.to();
            from = first.from();


            //XD
            if (first.getName().length() == 2) {
                setNode(from, K);
                setNode(from, M);
                setNode(first, X);
                setNode(second, D);
                setNode(third, M);
                setNode(third, L);
                continue;
            }

            setNode(from, K);
            setNode(from, M);
            setNode(first, B);
            setNode(third, M);
            setNode(third, L);
            //BZ
            if (second.getName().length() == 2) {
                setNode(second, Z);
                continue;
            } else {//BE
                setNode(second, E);
            }


            if (third.getOffe() == terms.length || third.getName().length() > 1) { //说明到结尾了,或者后面长度不符合规则
                continue;
            }

            //BCD
            setNode(first, B);
            setNode(second, C);
            setNode(third, D);
            setNode(third.to(), M);
            setNode(third.to(), L);

        }
        PersonNatureAttr begin = DATDictionary.person("BEGIN");

        nodes[0][6] = null;
        nodes[0][4] = new PersonNode(4, "B", -Math.log(begin.getK()));
        nodes[0][10] = new PersonNode(10, "B", -Math.log(begin.getA()));

        PersonNatureAttr end = DATDictionary.person("END");
        nodes[terms.length][5] = new PersonNode(5, "E", -Math.log(end.getL()));
        nodes[terms.length][6] = null;
        nodes[terms.length][10] = new PersonNode(10, "E", -Math.log(end.getA()));

        return new Viterbi<PersonNode>(nodes, new Values<PersonNode>() {
            @Override
            public int step(Node<PersonNode> node) {
                return node.getObj().name.length();
            }

            @Override
            public double selfSscore(Node<PersonNode> node) {
                return node.getObj().score;
            }

        });
    }
1056048
public List<List<Vertex>> biSegment(char[] sSentence, int nKind, WordNet wordNetOptimum, WordNet wordNetAll)
    {
        List<List<Vertex>> coarseResult = new LinkedList<List<Vertex>>();
        ////////////////生成词网////////////////////
        generateWordNet(wordNetAll);
//        logger.trace("词网大小：" + wordNetAll.size());
//        logger.trace("打印词网：\n" + wordNetAll);
        ///////////////生成词图////////////////////
        Graph graph = generateBiGraph(wordNetAll);
//        logger.trace(graph.toString());
        if (HanLP.Config.DEBUG)
        {
            System.out.printf("打印词图：%s\n", graph.printByTo());
        }
        ///////////////N-最短路径////////////////////
        NShortPath nShortPath = new NShortPath(graph, nKind);
        List<int[]> spResult = nShortPath.getNPaths(nKind * 2);
        if (spResult.size() == 0)
        {
            throw new RuntimeException(nKind + "-最短路径求解失败，请检查上面的词网是否存在负圈或悬孤节点");
        }
//        logger.trace(nKind + "-最短路径");
//        for (int[] path : spResult)
//        {
//            logger.trace(Graph.parseResult(graph.parsePath(path)));
//        }
        //////////////日期、数字合并策略
        for (int[] path : spResult)
        {
            List<Vertex> vertexes = graph.parsePath(path);
            generateWord(vertexes, wordNetOptimum);
            coarseResult.add(vertexes);
        }
        return coarseResult;
    }
746147
function slide(x, y, duration, beforeCallback) {
  const self = this;
  if (beforeCallback) {
    beforeCallback();
  }

  /***
   * 滑动内部实现
   */
  function slideSub() {
    self.getPageJO().css({
      "transform": "translate3d(" + x + "," + y + ",0)",
      "-webkit-transform": "translate3d(" + x + "," + y + ",0)",
      "transition": "transform " + duration + "ms cubic-bezier(0.1,0.25,0.1,1)",
      "-webkit-transition": "transform " + duration + "ms cubic-bezier(0.1,0.25,0.1,1)"
    });
  }

  if (duration === 0) {
    slideSub();
  } else {
    window.setTimeout(slideSub, 100);
  }
}
1279776
def schedule2calendar(schedule, name='课表', using_todo=True):
    
    # https://zh.wikipedia.org/wiki/ICalendar
    # http://icalendar.readthedocs.io/en/latest
    # https://tools.ietf.org/html/rfc5545
    cal = icalendar.Calendar()
    cal.add('X-WR-TIMEZONE', 'Asia/Shanghai')
    cal.add('X-WR-CALNAME', name)
    cls = icalendar.Todo if using_todo else icalendar.Event
    for week, start, end, data in schedule:
        # "事件"组件更具通用性, Google 日历不支持"待办"组件
        item = cls(
            SUMMARY='第{:02d}周-{}'.format(week, data),
            DTSTART=icalendar.vDatetime(start),
            DTEND=icalendar.vDatetime(end),
            DESCRIPTION='起始于 {}, 结束于 {}'.format(start.strftime('%H:%M'), end.strftime('%H:%M'))
        )
        now = datetime.now()
        # 这个状态"事件"组件是没有的, 对于待办列表类应用有作用
        # https://tools.ietf.org/html/rfc5545#section-3.2.12
        if using_todo:
            if start < now < end:
                item.add('STATUS', 'IN-PROCESS')
            elif now > end:
                item.add('STATUS', 'COMPLETED')
        cal.add_component(item)
    return cal
228540
function randomDate(min, max) {
  min = min ? new Date(min) : new Date(0); // 1970-01-01

  if (max) {
    max = new Date(max);
  } else {
    max = new Date();
    max.setFullYear(max.getFullYear() + 10); // 10年后
  }

  return new Date(integer(max.getTime(), min.getTime()));
}
283688
function tree() {
  let bodyHeight = 400;
  let keyDef = d => d.id;
  let parentDef = d => d.parent;
  let defaultLevel = 99999;
  let nodeEnterFactory = () => {};
  let nodeMergeFactory = () => {};

  // Recursively append child nodes
  function nextLevel(selection, data) {
    if (!selection.select('.childlist').size()) {
      selection.append('ul')
        .classed('childlist', true)
        .style('list-style-type', 'none');
    }
    const items = selection.select('.childlist')
      .selectAll('li')
        .data(data, keyDef);
    items.exit().remove();
    items.enter()
      .append('li')
        .each(function (d) {
          d3.select(this).call(nodeEnterFactory, d.data);
        })
      .merge(items)
        .each(function (d) {
          const node = d3.select(this);
          node.call(nodeMergeFactory, d.data);
          if (d.hasOwnProperty('children')) {
            node.call(nextLevel, d.children)
              .select('.arrow')
                .text(d => d.depth - 1 >= defaultLevel ? '▶ ' : '▼ ')
                .on('click', function () {  // Collapse on click
                  const childList = node.select('.childlist');
                  const expanded = childList.style('display') !== 'none';
                  d3.select(this).text(expanded ? '▶ ' : '▼ ');
                  childList.style('display', expanded ? 'none' : 'inherit');
                });
            node.select('.childlist')
                .style('display',
                  d => d.depth - 1 >= defaultLevel ? 'none' : 'inherit');
          } else {
            node.select('.childlist').remove();
          }
        });
  }

  function _tree(selection, records) {
    const root = d3.stratify()
        .id(keyDef)
        .parentId(parentDef)(records);
    selection
        .style('overflow-y', 'scroll')
        .style('height', `${bodyHeight}px`);
    if (!selection.select('.body').size()) {
      selection.append('div').classed('body', true);
    }
    selection.select('.body')
        .call(nextLevel, root.children || []);
    selection.selectAll('.body > ul')
        .style('padding-left', 0);
    selection.selectAll('.body > ul > li')
        .classed('my-2', true);
  }

  _tree.bodyHeight = function (h) {
    bodyHeight = h;
    return _tree;
  };

  _tree.keyDef = function (f) {
    keyDef = f;
    return _tree;
  };

  _tree.defaultLevel = function (lv) {
    defaultLevel = lv;
    return _tree;
  };

  _tree.nodeEnterFactory = function (f) {
    nodeEnterFactory = f;
    return _tree;
  };

  _tree.nodeMergeFactory = function (f) {
    nodeMergeFactory = f;
    return _tree;
  };

  return _tree;
}
1014703
function makeRootDir(dest, cwd, savedir, callback) {
  let root = path.join(cwd, (savedir || ''), dest.split('/')[0]);
  console.log('delete: ', root)

  // 保存先フォルダがすでにある場合は一旦削除する
  let rm = 'if [ -e '+ root +' ]; then rm -rf ' + root + '; fi';
  let removed = exec(rm, (error, stdout, stderr) => {
    if (error !== null) throw ('[Error: makeRootDir:] ' + error);
  }).on('close', () => {
    // 削除後、保存先フォルダを作成
    let maked = exec('mkdir ' + root).on('close', () => {
      return callback && callback();
    });
  });
}