text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.examstack.management.persistence.QuestionMapper">

	<!-- 试题列表部分 -->
	<select id="getQuestionList" resultType="com.examstack.common.domain.question.Question">
		select a.id,a.name,a.content,a.question_type_id,a.creator,a.answer,a.analysis,a.reference referenceName,group_concat(concat(d.field_name,'-',c.point_name)) pointName,
		e.name
		questionTypeName, examing_point examingPoint,
		(select group_concat(m.tag_name,' ') from et_tag m,et_question_2_tag n
		where m.tag_id=n.tag_id and n.question_id=a.id) tags from et_question
		a,et_question_2_point
		b,et_knowledge_point
		c,et_field d,et_question_type
		e
		<where>
			a.id=b.question_id and b.point_id=c.point_id and
			c.field_id=d.field_id
			and a.question_type_id=e.id
			<if test="filter.fieldId != 0">
				and c.field_id = #{filter.fieldId}
			</if>
			<if test="filter.tag != 0">
				and a.id in(select question_id from et_question_2_tag
				where tag_id=#{filter.tag})
			</if>
			<if test="filter.knowledge != 0">
				and c.point_id = #{filter.knowledge}
			</if>
			<if test="filter.questionType != 0">
				and a.question_type_id = #{filter.questionType}
			</if>
			<if test="filter.searchParam != '-1'">
				and instr(a.name,#{filter.searchParam})<>0
			</if>
		</where>
		group by a.id,a.name,a.content,a.question_type_id,a.creator,a.answer,a.analysis,a.reference,a.examing_point,e.`name`,a.examing_point,tags
		order by a.id desc
	</select>

	<select id="getAllField" resultType="com.examstack.common.domain.question.Field">
		select field_id
		fieldId,field_name fieldName,memo,state,
		case when exists(select 1 from
		et_knowledge_point m where m.field_id=a.field_id) then 0
		else 1 end
		removeable
		from et_field a order by field_id desc
	</select>

	<select id="getKnowledgePointByFieldId" resultType="com.examstack.common.domain.question.KnowledgePoint">
		select a.point_id pointId,a.point_name pointName,a.field_id
		fieldId,a.memo,a.state,b.field_name fieldName,
		case when exists(select
		1 from et_question_2_point m where m.point_id=a.point_id) then 0
		else 1
		end removeable
		from et_knowledge_point a,et_field b
		<where>
			a.field_id=b.field_id
			<if test="fieldId != 0">
				and a.field_id = #{fieldId}
			</if>
		</where>
	</select>

	<select id="getQuestionTypeList" resultType="com.examstack.common.domain.question.QuestionType">
		select
		id,name,subjective from et_question_type
	</select>
	<!-- 试题列表部分 -->

	<select id="getTagByUserId" resultType="com.examstack.common.domain.question.Tag">
		select tag_id
		tagId,tag_name tagName,is_private privatee,create_time createTime,
		creator,memo from et_tag where (creator=#{userId} or is_private=0)
	</select>
	<select id="getTags" resultType="com.examstack.common.domain.question.Tag">
		select tag_id
		tagId,tag_name
		tagName,is_private privatee,create_time createTime,
		creator,memo,(select user_name from et_user where user_id=creator)
		creatorName from et_tag order by tag_id desc
	</select>
	<select id="getQuestionTags" resultType="com.examstack.common.domain.question.Tag">
		select a.tag_id
		tagId,a.tag_name
		tagName,a.is_private privatee,a.create_time createTime,
		a.creator,a.memo,(select user_name from et_user where user_id=a.creator)
		creatorName from et_tag a,et_question_2_tag b where a.tag_id=b.tag_id and b.id=#{questionId} order by tag_id desc
	</select>
	<insert id="addTag" parameterType="com.examstack.common.domain.question.Tag"
		useGeneratedKeys="true" keyProperty="tagId">
		insert into
		et_tag(tag_name,creator,memo,is_private)
		values
		(#{tagName},#{creator},#{memo},#{privatee})
	</insert>

	<insert id="insertQuestion" parameterType="com.examstack.common.domain.question.Question"
		useGeneratedKeys="true" keyProperty="id">
		insert into et_question
		(name,content,question_type_id,create_time,creator,
		answer,analysis,reference,examing_point,keyword,points)
		values
		(#{name},#{content},#{question_type_id},#{create_time},#{creator},
		#{answer},#{analysis},#{referenceName},#{examingPoint},#{keyword},#{points})
	</insert>
	<update id="updateQuestion">
		update et_question
		<set>
			<if test="name != null">
				name = #{name},
			</if>
			<if test="content != null">
				content = #{content},
			</if>
			<if test="question_type_id != 0">
				question_type_id=#{question_type_id},
			</if>
			<if test="answer != null">
				answer = #{answer},
			</if>
			<if test="analysis != null">
				analysis = #{analysis},
			</if>
			<if test="referenceName != null">
				reference = #{referenceName},
			</if>
			<if test="examingPoint != null">
				examing_point = #{examingPoint},
			</if>
			<if test="keyword != null">
				keyword = #{keyword},
			</if>
			id = #{id}
		</set>
		<where>
			id = #{id}
		</where>
	</update>
	<insert id="addQuestionKnowledgePoint">
		insert into et_question_2_point
		(question_id,point_id)
		values
		(#{questionId},#{pointId})
	</insert>
	<insert id="addField" parameterType="com.examstack.common.domain.question.Field"
		useGeneratedKeys="true" keyProperty="fieldId">
		insert into
		et_field(field_name,memo,state) values (
		#{fieldName},#{memo},#{state}
		)
	</insert>

	<insert id="addKnowledgePoint" parameterType="com.examstack.common.domain.question.KnowledgePoint"
		useGeneratedKeys="true" keyProperty="pointId">
		insert into
		et_knowledge_point(point_name,memo,state,field_id) values (
		#{pointName},#{memo},#{state},#{fieldId}
		)
	</insert>

	<select id="getQuestionTagByQuestionIdAndUserId" resultType="com.examstack.common.domain.question.QuestionTag">
		select tag_id tagId,tag_name tagName,is_private privatee,create_time
		createTime,
		creator,memo from et_tag where (creator=#{userId} or
		is_private=0)
		and tag_id in(select tag_id from et_question_2_tag where
		question_id=#{questionId})
	</select>

	<insert id="addQuestionTag" parameterType="com.examstack.common.domain.question.QuestionTag"
		useGeneratedKeys="true">
		replace into et_question_2_tag(question_id,tag_id,creator)
		values
		<foreach collection="array" index="index" item="item" open=""
			close="" separator=",">
			(#{item.questionId},#{item.tagId},#{item.creator})
		</foreach>

	</insert>

	<delete id="deleteQuestionTag">
		delete from et_question_2_tag where
		<if test="array != null">
			tag_id not in
			<foreach collection="array" index="index" item="item" open="("
				close=")" separator=",">
				#{item}
			</foreach>
			and
		</if>
		question_id=#{questionId}

	</delete>

	<delete id="deleteQuestionPointByQuestionId">
		delete from et_question_2_point where
		question_id=#{questionId}
	</delete>

	<delete id="deleteFieldByIdList">
		delete from et_field where field_id in
		<foreach collection="array" open="(" close=")" index="index"
			item="item" separator=",">
			#{item}
		</foreach>
	</delete>

	<delete id="deleteKnowledgePointByIdList">
		delete from et_knowledge_point where point_id in
		<foreach collection="array" open="(" close=")" index="index"
			item="item" separator=",">
			#{item}
		</foreach>
	</delete>

	<delete id="deleteTagByIdList">
		delete from et_tag where tag_id in
		<foreach collection="array" open="(" close=")" index="index"
			item="item" separator=",">
			#{item}
		</foreach>
	</delete>

	<select id="getQuestionByQuestionId" resultType="com.examstack.common.domain.question.Question">
		select a.id,a.name,a.content,a.question_type_id,a.creator,a.answer,a.analysis,a.reference referenceName,a.keyword keyword,
		a.examing_point examingPoint from et_question a
		<where>
			a.id = #{questionId}
		</where>
	</select>

	<select id="getQuestionByTypeId" resultType="com.examstack.common.domain.question.Question">
		select * from et_question
		<where>
			question_type_id = #{questionTypeId}
		</where>
	</select>

	<select id="getQuestionAnalysisListByIdList"
		resultType="com.examstack.common.domain.question.QuestionQueryResult">
		SELECT a.id
		questionId,a.content,a.answer,a.analysis,a.question_type_id
		questionTypeId,a.reference
		referenceName,a.examing_point
		examingPoint,GROUP_CONCAT(d.field_name,'
		> ',c.point_name,' > ',
		a.examing_point ,case when a.keyword is
		null then '' else
		CONCAT('
		知识关键点:',a.keyword) end)
		pointName,GROUP_CONCAT(d.field_name)
		fieldName
		from et_question
		a,et_question_2_point
		b,et_knowledge_point
		c,et_field d
		<where>
			a.id=b.question_id and
			b.point_id=c.point_id and
			c.field_id=d.field_id
			<if test="array != null">
				and
				a.id in
				<foreach collection="array" open="(" close=")" index="index"
					item="item" separator=",">
					#{item}
				</foreach>
			</if>

		</where>
		group by
		a.id,a.content,a.answer,a.analysis,a.question_type_id,a.reference,
		a.examing_point
		order by a.question_type_id,a.id
	</select>

	<delete id="deleteQuestionByQuestionId">
		delete from et_question where id=#{questionId}
	</delete>

	<select id="getQuestionListByPointId" resultType="com.examstack.common.domain.question.QuestionStruts">
		select a.id questionId,a.expose_times exposeTimes, c.point_id
		pointId,a.difficulty difficulty,a.question_type_id questionTypeId,
		a.right_times rightTimes, a.wrong_times wrongTimes,a.points
		point,a.keyword from
		et_question a,et_question_2_point b
		,et_knowledge_point c
		<where>
			a.id=b.question_id and b.point_id=c.point_id
			<if test="array != null">
				and c.point_id in
				<foreach close=")" separator="," open="(" item="item" index="index"
					collection="array"> #{item} </foreach>
			</if>
		</where>
	</select>

	<select id="getTypeQuestionStaticByFieldId" resultType="com.examstack.common.domain.question.QuestionStatistic">
		select c.field_id fieldId,c.point_id pointId,c.point_name pointName,d.id questionTypeId,d.name questionTypeName,count(1) amount from et_question a,et_question_2_point b,et_knowledge_point c,et_question_type d
		where a.id=b.question_id and b.point_id=c.point_id and c.field_id=#{fieldId} and a.question_type_id=d.id group by c.field_id,c.point_id,c.point_name,d.id,d.name
	</select>

	<select id="getQuestionPoint" resultType="com.examstack.common.domain.question.KnowledgePoint">
		select a.point_id pointId,a.point_name pointName,a.field_id
		fieldId,a.memo,a.state,b.field_name fieldName
		from et_knowledge_point a,et_field b
		<where>
			a.field_id=b.field_id
			and a.point_id in(select m.point_id from et_question_2_point m where m.question_id=#{questionId})
		</where>
	</select>

	<select id="getPointCount" resultType="com.examstack.common.domain.question.PointStatistic">
		select a.field_id fieldId,a.field_name fieldName,b.point_id pointId,b.point_name pointName,count(1) amount from et_field a,et_knowledge_point b,et_question c,et_question_2_point d
		where a.field_id=b.field_id and b.field_id=#{fieldId} and c.id=d.question_id and d.point_id=b.point_id group by a.field_id,a.field_name, b.point_id,b.point_name
	</select>
</mapper>


text: test

redpajama_set_name: RedPajamaGithub


text:
package cgeo.geocaching.sorting;

import cgeo.geocaching.Geocache;

public class StorageTimeComparator extends AbstractCacheComparator {

    @Override
    protected int compareCaches(Geocache cache1, Geocache cache2) {
        if (cache1.getUpdated() < cache2.getUpdated()) {
            return -1;
        }
        if (cache1.getUpdated() > cache2.getUpdated()) {
            return 1;
        }
        return 0;
    }

}


text:
exports.view = function(req, res){
	res.render('addActivity');
};


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Smamako alpha</title>

	<canvas id="webgl" width="600" height="600" style="border: 0px none black;">Your browser does not support the HTML5 canvas element</canvas>
	<canvas id="fontCacheCanvas" width="512" height="512" style="display:none;"></canvas>


text:
package edu.ucdenver.ccp.datasource.identifiers.other;

import edu.ucdenver.ccp.datasource.identifiers.DataSource;
import edu.ucdenver.ccp.datasource.identifiers.StringDataSourceIdentifier;

public class DmdmId extends StringDataSourceIdentifier {
		public DmdmId(String id) {
			super(id, DataSource.DMDM);
}
	}


text:
using Xunit;
using System.IO;
using Moq;
using System.Web.Mvc;

namespace Postal
{
    public class FileSystemRazorViewTests
    {
        [Fact]
        public void GivenViewFoundOnce_WhenFileChanged_ThenViewIsReloaded()
        {
            var filename = Path.Combine(Path.GetTempPath(), "test.cshtml");
            File.WriteAllText(filename, "test-1");
            try
            {
                var view1 = new FileSystemRazorView(filename);
                var context = new Mock<ViewContext>();
                context.Setup(c => c.ViewData).Returns(new ViewDataDictionary(new object()));
                using (var writer = new StringWriter())
                {
                    view1.Render(context.Object, writer);
                    var first = writer.GetStringBuilder().ToString();
                    Assert.Equal("test-1", first);
                }

                // Overwrite the file with new content.
                File.WriteAllText(filename, "test-2");
                // Views are single-use, so create a new one.
                var view2 = new FileSystemRazorView(filename);
                using (var writer = new StringWriter())
                {
                    view2.Render(context.Object, writer);
                    var second = writer.GetStringBuilder().ToString();
                    Assert.Equal("test-2", second);
                }
            }
            finally
            {
                File.Delete(filename);
            }
        }
    }
}


text:
/* Thumbs Container */
/* globals $, hs*/

(function ($, hs) {
  var defaults = {
    AddThumbDelay: 10,
    AddThumbCount: 20,
    LoadThumbDelay: 100,
    LoadThumbSldownThresh: 10,

    VkPhotoPopupSettings: 'toolbar=yes,scrollbars=yes,resizable=yes,width=1024,height=600'
  };

  var PluginName = 'ThumbsViewer';
  var ThumbClass = '.ThumbsViewer-thumb';

  var thC = {

    //PUBLIC:
    //------------------------------------------------------

    ///initialize Thumbs Container
    init: function (opts) {
      var $this = $(this);

      var data = {
        disableSel: false,
        revSortOrder: false,
        albumMap: {},

        //private
        busy_dfrd__: $.Deferred(),
        abortTask__: false,
        thumbsSelCnt__: 0,
        thumbsCnt__: 0
      };
      data.busy_dfrd__.resolve();
      $.extend(data, defaults, opts);

      $this.data(PluginName, data);
      $this.addClass("ThumbsViewer-list");
      $this.on("click.ThumbsViewer", ThumbClass, function (event) {
        thC.onThumbClick.call(this, event, $this);
      });
      $this.on("click.ThumbsViewer", ".ThumbsViewer-zoomIco", function (event) {
        thC.onZoomClick.call(this, event, $this);
      });
    },

    ///removes $thumb div from container
    removeThumb: function ($thumb) {
      var $data = $(this).data(PluginName);
      if ($thumb.hasClass("selected")) {
        --$data.thumbsSelCnt__;
      }
      --$data.thumbsCnt__;
      $thumb.remove();
    },

    ///thumbsAr is expected to be non empty array of Vk API images
    ///returns Deferred which will be resolved when all thumbs are added to the
    ///container or job is aborted (added != loaded)
    addThumbList: function (thumbsAr) {
      var self = this;
      var $this = $(this);
      var $data = $this.data(PluginName);
      var d = $.Deferred();

      function addThumb__(queue) {
        for (var i = 0; i < $data.AddThumbCount; ++i) {
          if (!queue.length) {
            d.resolve();
            return;
          }
          thC.createThumb_.call(self, queue.shift());
          ++$data.thumbsCnt__;
        }
        setTimeout(function () {
          addThumb__(queue);
        }, $data.AddThumbDelay);
      }

      //abort prev job in progress
      $data.abortTask__ = true;

      //when prev job aborted, start new job
      $.when($data.busy_dfrd__).done(function () {
        $data.busy_dfrd__ = $.Deferred();
        $data.abortTask__ = false;
        addThumb__(thumbsAr.slice());
      });

      //start loading images when all thumbnais are added to the container
      d.done(function () {
        thC.loadImages.call(self);
      });

      return d.promise();
    },

    ///update album map (id -> description) with new records
    updateAlbumMap: function (albumMap) {
      var $this = $(this);
      var $data = $this.data(PluginName);

      $.extend($data.albumMap, albumMap);
    },

    ///disable/enable selection
    selectionDisable: function (disable) {
      var $this = $(this);
      var $data = $this.data(PluginName);
      $data.disableSel = disable;
    },

    ///select all thumbnails in container
    selectAll: function () {
      var $this = $(this);
      var $data = $this.data(PluginName);

      if ($data.disableSel) {
        return;
      }

      $data.thumbsSelCnt__ = 0;

      $this.find(ThumbClass).each(function () {
        $(this).addClass("selected");
        ++$data.thumbsSelCnt__;
      });
    },

    ///deselect all thumbnails in container
    selectNone: function () {
      var $this = $(this);
      var $data = $this.data(PluginName);

      if ($data.disableSel) {
        return;
      }

      $data.thumbsSelCnt__ = 0;
      $this.find(ThumbClass).removeClass("selected");
    },

    ///toggle selection of $thumb
    selectToggle: function ($thumb) {
      var $this = $(this);
      var $data = $this.data(PluginName);

      if ($data.disableSel) {
        return;
      }

      $thumb.toggleClass("selected");

      if ($thumb.hasClass("selected")) {
        ++$data.thumbsSelCnt__;
      } else {
        --$data.thumbsSelCnt__;
      }
    },

    ///select all if any one is selected, deselect all if all are selected
    selectToggleAll: function () {
      var $this = $(this);
      var $data = $this.data(PluginName);

      if ($data.disableSel) {
        return;
      }

      var thumbsSelCnt__ = 0;
      var thumbsTotal = 0;

      /*$this.find(ThumbClass).each(function () {
        ++thumbsTotal;
        if ($(this).hasClass("selected")) {
          ++thumbsSelCnt__;
        }
      });*/
      thumbsSelCnt__ = $data.thumbsSelCnt__;
      thumbsTotal = $data.thumbsCnt__;

      if (thumbsSelCnt__ == thumbsTotal) {
        $this.find(ThumbClass).removeClass("selected");
        $data.thumbsSelCnt__ = 0;
      } else {
        $this.find(ThumbClass).addClass("selected");
        $data.thumbsSelCnt__ = thumbsTotal;
      }
    },

    ///for currently visible on screen: select all if any one is selected, deselect all if all are selected
    selectToggleVisible: function () {
      var $this = $(this);
      var $data = $this.data(PluginName);

      if ($data.disableSel) {
        return;
      }

      var $thumbs = $this.find(ThumbClass);
      if (!$thumbs.length) { //no thumbs in container
        return;
      }

      //calculate which thumbs are currently visible based on
      //scroll position and container/image geometry
      var $parentDiv = $this.parent().first();
      var divHeight = $parentDiv.height();
      var divWidth = $parentDiv.width();
      var liHeight = $thumbs.first().outerHeight(true);
      var liWidth = $thumbs.first().outerWidth(true);
      var rowsScrolled = Math.round($parentDiv.scrollTop() / liHeight);
      var rowsOnScreen = Math.round(divHeight / liHeight);
      var thumbsInRow = Math.floor(divWidth / liWidth);

      var selFirstIndex = rowsScrolled * thumbsInRow;
      var selLastIndex = Math.min(selFirstIndex + rowsOnScreen * thumbsInRow, $thumbs.length);
      $thumbs = $thumbs.slice(selFirstIndex, selLastIndex);

      var thumbsSelCnt__ = 0;
      var thumbsTotal = 0;
      $thumbs.each(function () {
        ++thumbsTotal;
        if ($(this).hasClass("selected")) {
          ++thumbsSelCnt__;
        }
      });

      if (thumbsSelCnt__ == thumbsTotal) {
        $thumbs.removeClass("selected");
      } else {
        $thumbs.addClass("selected");
      }

      $data.thumbsSelCnt__ = $this.find(ThumbClass + ".selected").length;
    },

    ///returns array of 'data' associated with thumbnails in container
    getThumbsData: function (onlySelected) {
      var thumbData = [];
      var selector = onlySelected ? ThumbClass + ".selected" : ThumbClass;

      this.find(selector).each(function () {
        var $this = $(this);
        var item = {
          data: $this.data(PluginName),
          $thumb: $this
        };
        thumbData.push(item);
      });

      return thumbData;
    },

    ///returns number of thumbnails total/selected
    getThumbsCount: function () {
      var $data = $(this).data(PluginName);
      var total_ = $data.thumbsCnt__;
      var selected_ = $data.thumbsSelCnt__;
      return {
        total: total_,
        selected: selected_
      };
    },

    ///remove all thumbnails from the container
    empty: function () {
      var $this = $(this);
      var $data = $this.data(PluginName);
      $data.abortTask__ = true; //abort any job in progress(if any)

      hs.close();

      var d = $.Deferred();

      //when job aborted, clean container
      $.when($data.busy_dfrd__).done(function () {
        $this.empty();
        $data.thumbsSelCnt__ = 0;
        $data.thumbsCnt__ = 0;
        $data.albumMap = {};
        d.resolve();
      });

      return d.promise();
    },

    ///reorder thumbnails in the container (straight/reverse)
    reorder: function (revSort) {
      var self = this;
      var $this = $(this);
      var $data = $this.data(PluginName);

      //if sort order changed, resort thumbs
      if ($data.revSortOrder != revSort) {
        $data.revSortOrder = revSort;

        var $thumbs = $this.find(ThumbClass);
        $thumbs.detach();
        var thumbsLi = $thumbs.toArray().reverse();
        for (var i = 0; i < thumbsLi.length; ++i) {
          $this.append(thumbsLi[i]);
        }

        thC.loadImages.call(self);
      }
    },

    //shuffle - reorder randomly

    //PROTECTED:
    //------------------------------------------------------

    ///load images for the thumbnail objects in the container
    loadImages: function () {
      var $this = $(this);
      var $data = $(this).data(PluginName);

      var loadImgQueue = $this.find(ThumbClass + ".loading").toArray();
      var loadInProgressCnt = 0;

      function loadImg__() {
        //stop if no more images left or the task was aborted
        if ($data.abortTask__ || !loadImgQueue.length) {
          $data.busy_dfrd__.resolve();
          return;
        }

        var thumb = $(loadImgQueue.shift());
        if (!$.contains(document, thumb[0])) { //don't load image if element has already been removed
          return loadImg__();
        }

        ++loadInProgressCnt;
        var vk_img = thumb.data(PluginName).vk_img;
        var imgSrc = thC.getSelSizeUrl(vk_img, ['p', 'o', 'm', 's']);
        var thumb_img = $("");
        thumb_img.on('load', function () {
          --loadInProgressCnt;
          thumb.removeClass('loading');
          thumb.addClass('showphoto');
          thumb.css('background-image', 'url(' + imgSrc + ')');
          thumb_img.on('load', null);
        });
        thumb_img.attr("src", imgSrc);
        //thumb_img = null;

        //timeout depends on number of images being loaded
        var tmout = (loadInProgressCnt < $data.LoadThumbSldownThresh) ? $data.LoadThumbDelay : loadInProgressCnt * $data.LoadThumbDelay;
        setTimeout(function () {
          loadImg__();
        }, tmout);
      }

      loadImg__();
    },

    ///create new thumbnail object and append to the container
    ///expects VK API image object
    createThumb_: function (vk_img) {
      var $this = $(this);
      var $data = $(this).data(PluginName);
      var thumb_parent = $("
");

      var titleStr = thC.makeTitle_.call(this, vk_img);
      var captionStr = thC.makeCaption_.call(this, vk_img);
      var zoomImgSrc = thC.getSelSizeUrl(vk_img, ['y', 'x']);
      var aa = $("", {
        class: 'ThumbsViewer-hslink',
        href: zoomImgSrc,
        title: 'Увеличить',
        onclick: 'return hs.expand(this, hs.config1)'
      }).data({
        title: titleStr,
        caption: captionStr
      });
      var zoomIcon = $('
').append(aa);

      thumb_parent.append(zoomIcon);
      thumb_parent.attr("title", "Выбрать фото");
      thumb_parent.data(PluginName, {
        vk_img: vk_img
      });
      thC.oncreateThumb_.call(this, thumb_parent);
      thumb_parent.appendTo($this);
    },

    ///used by createThumb_ to create title for the photo
    makeTitle_: function (vk_img) {
      return 'Фото %1/%2:  ❤ ' + vk_img.likes.count;
    },

    ///used by createThumb_ to create caption for the photo
    makeCaption_: function (vk_img) {
      var $this = $(this);
      var $data = $this.data(PluginName);

      var album = "";
      if (vk_img.album_id in $data.albumMap) {
        album = $data.albumMap[vk_img.album_id];
      }

      //caption contains album name, link to original VK photo and description
      var origUrl = "//vk.com/photo" + vk_img.owner_id + "_" + vk_img.id;
      var onClickOrigUrl = "var myWindow = window.open('" + origUrl + "', 'vk_photo', '" + $data.VkPhotoPopupSettings + "', false); myWindow.focus();";

      // jshint multistr:true
      var caption = '\

\

Альбом: %1

Оригинал фото
\

\

%3
';

      caption = caption.replace("%1", album);
      caption = caption.replace("%2", onClickOrigUrl);
      caption = caption.replace("%3", vk_img.text);

      return caption;
    },

    ///retreive from VK Api image object a link to image with desired size szLiterPrefs
    getSelSizeUrl: function (vk_img, szLiterPrefs) {
      var src_alt = "logo150.png";

      if (("sizes" in vk_img) && vk_img.sizes.length) {
        src_alt = vk_img.sizes[0].src;
      } else if ("photo_130" in vk_img) {
        return vk_img.photo_130;
      } else if ("photo_75" in vk_img) {
        return vk_img.photo_75;
      } else {
        console.log(PluginName + ":getSelSizeUrl() - can't find vk image urls!");
      }

      for (var j = 0; j < szLiterPrefs.length; ++j) {
        for (var i = 0; i < vk_img.sizes.length; ++i) {
          if (vk_img.sizes[i].type == szLiterPrefs[j]) {
            return vk_img.sizes[i].src;
          }
        }
      }

      return src_alt;
    },

    ///createThumb_() calls this function modify $thumb object before insertion to the container
    oncreateThumb_: function ($thumb) {
      var vk_img = $thumb.data(PluginName).vk_img;
      var likesbox = '
❤ ' + vk_img.likes.count + '
';
      $thumb.append($(likesbox));
    },

    ///handle click on thumbnail area
    onThumbClick: function (event, parent) {
      event.stopPropagation();
      return false;
    },

    ///handle click on zoom icon
    onZoomClick: function (event, parent) {
      //do nothing here, using handler from
      event.stopPropagation();
      return false;
    }
  };

  $.fn.ThumbsViewer = function (method) {
    var args = arguments;

    if (method == "getThumbsData") {
      return thC.getThumbsData.apply(this, Array.prototype.slice.call(args, 1));
    } else if (method == "getThumbsCount") {
      return thC.getThumbsCount.apply(this, Array.prototype.slice.call(args, 1));
    } else if (method == "addThumbList") {
      return thC.addThumbList.apply(this, Array.prototype.slice.call(args, 1));
    }

    return this.each(function () {
      if (thC[method]) {
        return thC[method].apply(this, Array.prototype.slice.call(args, 1));
      } else if (typeof method === 'object' || !method) {
        return thC.init.apply(this, args);
      } else {
        $.error('Method ' + args + ' does not exist on jQuery.ThumbsViewer');
      }
    });
  };
})(jQuery, hs);


text:
import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit()

readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')

setup(
    name='mysql-statsd',
    version='0.1.4',
    description='Daemon that gathers statistics from MySQL and sends them to statsd.',
    long_description=readme + '\n\n' + history,
    author='Jasper Capel, Thijs de Zoete',
    author_email='jasper.capel@spilgames.com',
    url='https://github.com/spilgames/mysql-statsd',
    packages=[
        'mysql_statsd',
    ],
    package_dir={'mysql_statsd': 'mysql_statsd'},
    entry_points={
        'console_scripts': [
            'mysql_statsd = mysql_statsd:mysql_statsd.MysqlStatsd'
        ]
    },
    include_package_data=True,
    install_requires=[
        'MySQL-python==1.2.5',
        'pystatsd==0.1.10',
    ],
    license="BSD",
    zip_safe=False,
    keywords='mysql_statsd',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
    ],
    test_suite='tests',
)


text:
/* jshint undef: false */
'use strict';

generalLedgersModule.factory('GeneralLedgers', ['socketFactory', '$http', function (socketFactory, $http) {

	var prefix = 'generalLedgers';
	var restApiUrl = '/api/generalLedgers';

	var factory = {};

	var socket = socketFactory({
		prefix: '',
		ioSocket: io.connect()
	});

	var events = {
		CREATED: prefix + '.created',
		UPDATED: prefix + '.updated',
		DELETED: prefix + '.deleted',
		NET_WORTH_CHANGED: prefix + '.net_worth_changed'
	};

	factory.events = events;

	factory.on = function (eventName, callback) {
		socket.on(eventName, callback);
	};

	factory.removeListener = function (eventName, callback) {
		socket.removeListener(eventName, callback);
	};

	factory.get = function (id) {
		return $http.get(restApiUrl + '/' + id);
	};

	factory.list = function () {
		return $http.get(restApiUrl);
	};

	factory.create = function (data) {
		return $http.post(restApiUrl, data);
	};

	factory.update = function (id, data) {
		return $http.put(restApiUrl + '/' + id, data);
	};

	factory.delete = function (id) {
		return $http.delete(restApiUrl + '/' + id);
	};

	return factory;

}]);


text:
<?php

use Gwa\Wordpress\Template\Zero\Controller\Home as HomePage;

(new HomePage())->render();


text:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

          <title>ONJAG documentation</title>
          <meta name="description" content="ONJAG documentation" />
          <meta name="keywords" content="ONJAG documentation" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../lib/ref-index.css" media="screen" type="text/css" rel="stylesheet" />

lastSample

ImageMonitorProtocol

lastSwapRequestType

JaBeJaVertexContext

links

GraphVertexContext FindSubPartitionProtocolVertexContext KCorenessVertexContext


text:
<?php

namespace Dte\BtsBundle\Tests\Functional\Entity\Repository;

use Dte\BtsBundle\Entity\User;
use Dte\BtsBundle\Tests\FixturesWebTestCase;

use Symfony\Component\Security\Core\User\UserInterface;

class UserRepositoryTest extends FixturesWebTestCase
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    /**
     * {@inheritDoc}
     */
    public function setUp()
    {
        parent::setUp();

        $this->em = $this->client
            ->getKernel()
            ->getContainer()
            ->get('doctrine')
            ->getManager();
    }

    public function testLoadUserByUsername()
    {
        $user = $this->em
            ->getRepository('DteBtsBundle:User')
            ->loadUserByUsername('admin');

        $this->assertTrue($user instanceof UserInterface);
        $this->assertTrue($user instanceof User);
        $this->assertEquals(1, $user->getId());
    }

    /**
     * @expectedException        \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
     * @expectedExceptionMessage Unable to find an active admin DteBtsBundle:User object identified by "admin111".
     */
    public function testLoadUserByUsernameWithWrongUsername()
    {
        $this->em
            ->getRepository('DteBtsBundle:User')
            ->loadUserByUsername('admin111');
    }
}


text:
/*globals describe, it*/
var should   = require('should'),

    // Stuff we are testing
    formatResponse = require('../../../../server/controllers/frontend/format-response');

// To stop jshint complaining
should.equal(true, true);

describe('formatResponse', function () {
    describe('single', function () {
        it('should return the post object wrapped in a post key', function () {
            var formatted,
                postObject = {slug: 'sluggy-thing'};

            formatted = formatResponse.single(postObject);

            formatted.should.be.an.Object.with.property('post');
            formatted.post.should.eql(postObject);
        });
    });

    describe('channel', function () {
        it('should return posts and posts pagination as top level keys', function () {
            var formatted,
                data = {
                    posts: [{slug: 'a-post'}],
                    meta: {pagination: {}}
                };

            formatted = formatResponse.channel(data);

            formatted.should.be.an.Object.with.properties('posts', 'pagination');
            formatted.posts.should.eql(data.posts);
            formatted.pagination.should.eql(data.meta.pagination);
        });

        it('should flatten api read responses which have no pagination data', function () {
            var formatted,
                data = {
                    posts: [{slug: 'a-post'}],
                    meta: {pagination: {}},
                    data: {tag: [{name: 'video', slug: 'video', id: 1}]}
                };

            formatted = formatResponse.channel(data);

            formatted.should.be.an.Object.with.properties('posts', 'pagination', 'tag');
            formatted.tag.should.eql(data.data.tag[0]);
        });

        it('should remove the meta key from api browse responses', function () {
            var formatted,
                data = {
                    posts: [{slug: 'a-post'}],
                    meta: {pagination: {}},
                    data: {
                        featured: {
                            posts: [{id: 1, title: 'featured post 1', slug: 'featured-1'}],
                            meta: {pagination: {}}
                        }
                    }
                };

            formatted = formatResponse.channel(data);

            formatted.should.be.an.Object.with.properties('posts', 'pagination', 'featured');
            formatted.featured.should.be.an.Object.with.properties('posts', 'pagination');
        });
    });
});


text:
minetest.register_craftitem("mesecons_materials:glue", {
	image = "mesecons_glue.png",
	on_place_on_ground = minetest.craftitem_place_item,
    	description="Glue",
})

minetest.register_craftitem("mesecons_materials:fiber", {
	image = "mesecons_fiber.png",
	on_place_on_ground = minetest.craftitem_place_item,
    	description="Fiber",
})

minetest.register_craft({
	output = "mesecons_materials:glue 2",
	type = "cooking",
	recipe = "group:sapling",
	cooktime = 2
})

minetest.register_craft({
	output = "mesecons_materials:fiber 6",
	type = "cooking",
	recipe = "mesecons_materials:glue",
	cooktime = 4
})

-- Silicon
minetest.register_craftitem("mesecons_materials:silicon", {
	image = "mesecons_silicon.png",
	on_place_on_ground = minetest.craftitem_place_item,
    	description="Silicon",
})

minetest.register_craft({
	output = "mesecons_materials:silicon 4",
	recipe = {
		{"group:sand", "group:sand"},
		{"group:sand", "default:steel_ingot"},
	}
})


text:
package br.com.queridoautomovel.util.jsf;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 *
 * QueridoAutomovel
 *
 * @author Sérgio Junior - sergio.storinojr@gmail.com
 * 08/12/2015
 *
 */
public class FacesMessageUtil implements Serializable {

	private static final long serialVersionUID = 1L;

	public FacesMessageUtil() {
	}

	public static void addMsgError(String msgError){
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_ERROR, msgError, ""));

	}

	public static void addMsgInfo(String msgError){
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_INFO, msgError, ""));

	}

	public static void addMsgFatalError(String msgError){
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_FATAL, msgError, ""));

	}

}


text:
package statemachine

import (
	"fmt"
	"testing"
)

func compareChannelWithSlice(actual chan string, expected []string) (bool, string) {
	for s := range actual {
		if s != expected[0] {
			return false, fmt.Sprintf("Wrong state encountered. Expected %v, got %v", expected[0], s)
		}
		expected = expected[1:]
	}
	if len(expected) > 0 {
		return false, fmt.Sprintf("State machine terminated early, %v expected states not reached", len(expected))
	}
	return true, ""
}

func TestSimplestStateMachine(t *testing.T) {
	m := NewMachine()
	m.StateLog = make(chan string, 10)
	m.AddState("INIT", func() string { return "END" })
	success, err := m.Run()
	if !success {
		t.Error("State machine did not run successfully")
	}
	if err != nil {
		t.Error("State machine returned error")
	}
	if success, err := compareChannelWithSlice(m.StateLog, []string{"END"}); !success {
		t.Error(err)
	}
}

func TestUnknownState(t *testing.T) {
	m := NewMachine()
	m.AddState("INIT", func() string { return "BAR" })
	success, err := m.Run()
	if success != false {
		t.Error("State machine signalled success despite unknown state")
	}
	if err.Error() != "ERROR: No handler function registered for state: BAR" {
		t.Error("State machine didn't return correct error")
	}
}

func TestTickerAllowsToSyncStateMachine(t *testing.T) {
	m := NewMachine()
	m.AddState("INIT", func() string { return "FOO" })
	m.AddState("FOO", func() string { return "END" })
	ticker := make(chan bool)
	log := make(chan string, 10)
	m.Ticker = ticker
	m.StateLog = log
	go m.Run()

	if s := <-log; s != "FOO" {
		t.Errorf("Expected first state to be FOO, was %v", s)
	}
	select {
	case <-log:
		t.Errorf("New state was reached before ticker triggered")
	default:
		ticker <- true
	}
	if s := <-log; s != "END" {
		t.Errorf("Expected state after tick to be END, was %v", s)
	}
}

func ExampleThreeStateMachine() {
	m := NewMachine()
	m.AddState("INIT", func() string { return "FOO" })
	m.AddState("FOO", func() string { return "END" })
	m.Run()
	// Output:
	// statemachine: INFO: Starting in state: INIT
	// statemachine: INFO: State transition: INIT -> FOO
	// statemachine: INFO: State transition: FOO -> END
	// statemachine: INFO: Terminating
}


text:
import java.io.IOException;
import java.util.Optional;

class Test {

  interface Extractor<T> {
    T extractData() throws IOException;
  }

  public static <T> T query(Extractor<T> rse) {
    return null;
  }

  static {
    final Optional<String> query = query(() -> {
      final String type = Optional.<String>empty().orElseThrow(null);
      return null;
    });
  }
}


text:
from django.db import models
from django.forms import ModelForm
import socket

class NetworkAddress(models.Model):
    address = models.IPAddressField()
    network_size = models.PositiveIntegerField()
    description = models.CharField(max_length=400)
    parent = models.ForeignKey('self', null=True, blank=True)

    def __unicode__(self):
        return "%s/%d" % (self.address, self.network_size)

    @models.permalink
    def get_absolute_url(self):
        return ('networkaddress-display', (), {'address': '%s/%s' % (self.address, self.network_size)})

    def get_hostname(self):
        try:
            fqdn = socket.gethostbyaddr(str(self.address))[0]
        except:
            fqdn = ''
        return fqdn

    def get_formated_address(self):
        return str(self.address).replace('.', '_')

    def get_netmask(self):
        bit_netmask = 0;
        bit_netmask = pow(2, self.network_size) - 1
        bit_netmask = bit_netmask << (32 - self.network_size)
        nmask_array = []
        for c in range(4):
            dec = bit_netmask & 255
            bit_netmask = bit_netmask >> 8
            nmask_array.insert(0, str(dec))
        return ".".join(nmask_array)

class NetworkAddressAddForm(ModelForm):
    class Meta:
        model = NetworkAddress
        exclude = ('parent', )

class NetworkAddressModifyForm(ModelForm):
    class Meta:
        model = NetworkAddress
        fields = ('description',)

class DomainName(models.Model):
    name = models.CharField(max_length=100)
    comment = models.CharField(max_length=400)

    def __unicode__(self):
        return "%s (%s)" % (self.name, self.comment[:20])

# NETWORKDEVICE model classes

class NetworkDevice(models.Model):
    address = models.ForeignKey(NetworkAddress)
    community = models.CharField(max_length=255, null=True)
    username = models.CharField(max_length=255, null=True, blank=True)
    password = models.CharField(max_length=255, null=True, blank=True)
    fqdn = models.CharField(max_length=255, null=True, blank=True)
    manufacturer = models.CharField(max_length=50, null=True, blank=True)
    model = models.CharField(max_length=50, null=True, blank=True)
    ios = models.CharField(max_length=50, null=True, blank=True)
    description = models.CharField(max_length=400, null=True, blank=True)

    def __unicode__(self):
        return "%s %s %s %s" % (self.address, self.fqdn, self.community, self.model)


text:
package com.linkedin.databus.core.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * Helper functions for dealing with {@link java.util.Properties} .
 *
 * @author cbotev
 *
 */
public class PropertiesHelper
{
  public static final String MODULE = PropertiesHelper.class.getName();
  public static final Logger LOG = Logger.getLogger(MODULE);

  /**
   * Obtain the value of an optional integer property
   * @param  props          the property collection
   * @param  paramName      the property name
   * @param  defaultValue   default value if absent
   * @return the property value
   */
  public static int getOptionalIntParam(Properties props, String paramName, int defaultValue)
  {
    int result = defaultValue;

    String paramStr = props.getProperty(paramName);
    if (null != paramStr)
    {
      try
      {
        result = Integer.parseInt(paramStr);
      }
      catch (NumberFormatException nfe)
      {
        LOG.error("Invalid value for property " + paramName + ": " + paramStr);
      }
    }

    return result;
  }

  /**
   * Read a required integer property value or throw an exception if no such property is found
   * @param  props          The properties to read from
   * @param  name           The property name
   */
  public static int getRequiredIntParam(Properties props, String name)
                                        throws IllegalArgumentException
  {
    if(props.containsKey(name))
      return getRequiredIntParam(props, name, -1);
    else
      throw new IllegalArgumentException("Missing required property '" + name + "'");
  }

  /**
   * Read an integer from the properties instance
   * @param  props          The properties to read from
   * @param  name           The property name
   * @param  defaultValue   The default value to use if the property is not found
   * @return the integer value
   */
  public static int getRequiredIntParam(Properties props, String name, int defaultValue)
  {
    return getRequiredIntParamInRange(props, name, defaultValue, Integer.MIN_VALUE, Integer.MAX_VALUE);
  }

  /**
   * Read an integer from the properties instance. Throw an exception
   * if the value is not in the given range (inclusive)
   * @param props           The properties to read from
   * @param name            The property name
   * @param defaultValue    The default value to use if the property is not found
   * @param rangeMin        The minimum value of the range in which the value must fall (inclusive)
   * @param rangeMax        The maximum value of the range in which the value must fall (inclusive)
   * @throws IllegalArgumentException If the value is not in the given range
   * @return the integer value
   */
  public static int getRequiredIntParamInRange(Properties props, String name, int defaultValue,
                                               int rangeMin, int rangeMax)
                                               throws IllegalArgumentException
  {
    int value = defaultValue;
    if(props.containsKey(name))
        value = Integer.parseInt(props.getProperty(name));

    if(value < rangeMin || value > rangeMax)
      throw new IllegalArgumentException(name + " has value " + value + " which is not in the range (" + rangeMin + "," + rangeMax + ").");

    return value;
  }

  /**
   * Obtain the value of an optional long property
   * @param  props          the property collection
   * @param  paramName      the property name
   * @param  defaultValue   default value if absent
   * @return the property value
   */
  public static long getOptionalLongParam(Properties props, String paramName, long defaultValue)
  {
    long result = defaultValue;

    String paramStr = props.getProperty(paramName);
    if (null != paramStr)
    {
      try
      {
        result = Long.parseLong(paramStr);
      }
      catch (NumberFormatException nfe)
      {
        LOG.error("Invalid value for property " + paramName + ": " + paramStr);
      }
    }

    return result;
  }

  /**
   * Obtain the value of an optional double property
   * @param  props          the property collection
   * @param  paramName      the property name
   * @param  defaultValue   default value if absent
   * @return the property value
   */
  public static double getOptionalDoubleParam(Properties props, String paramName, double defaultValue)
  {
    double result = defaultValue;

    String paramStr = props.getProperty(paramName);
    if (null != paramStr)
    {
      try
      {
        result = Double.parseDouble(paramStr);
      }
      catch (NumberFormatException nfe)
      {
        LOG.error("Invalid value for property " + paramName + ": " + paramStr);
      }
    }

    return result;
  }

  /**
   * Obtain the value of an optional boolean property
   * @param  props          the property collection
   * @param  paramName      the property name
   * @param  defaultValue   default value if absent
   * @return the property value
   */
  public static boolean getOptionalBooleanParam(Properties props, String paramName,
                                                boolean defaultValue)
  {
    boolean result = defaultValue;

    String paramStr = props.getProperty(paramName);
    if (null != paramStr)
    {
      result = Boolean.parseBoolean(paramStr);
    }

    return result;
  }

  /**
   * Get a string property or throw and exception if no such property is defined.
   */
  public static String getRequiredStringParam(Properties props, String name)
                                              throws IllegalArgumentException
  {
    if(props.containsKey(name))
      return props.getProperty(name);
    else
      throw new IllegalArgumentException("Missing required property '" + name + "'");
  }

  /**
   * Read a properties file from the given path
   * @param filename The path of the file to read
   */
  public static Properties loadProps(String filename) {
    FileInputStream propStream = null;
    try
    {
      propStream = new FileInputStream(filename);
    }
    catch (FileNotFoundException e)
    {
      LOG.error("unable to open properties stream: " + e.getMessage(), e);
      return null;
    }
    Properties props = null;
    try
    {
      props = new Properties();
      props.load(propStream);
    }
    catch (IOException e)
    {
      LOG.error("unable to load properties: " + e.getMessage(), e);
    }
    finally
    {
      if (null != propStream)
      {
        try
        {
          propStream.close();
        }
        catch (Exception e)
        {
          LOG.error("unable to close property file stream:" + e.getMessage(), e);
        }
      }
    }
    return props;
  }

}


text:
using Grabacr07.KanColleWrapper;
using Grabacr07.KanColleWrapper.Models.Raw;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AMing.Plugins.Core.Extensions;

namespace AMing.Logger.Helper
{
    public class BattleLogsHelper : LogsHelperBase<Modes.BattleResultList, Modes.BattleResult>
    {
        #region Current

        private static BattleLogsHelper _current = new BattleLogsHelper();

        public static BattleLogsHelper Current
        {
            get { return _current; }
            set { _current = value; }
        }

        #endregion
        protected override int MaxSaveCount { get { return 5; } }
        protected override string FolderName { get { return "Battle"; } }

        protected override Modes.BattleResultList CreateNewList()
        {
            var newdata = base.CreateNewList();
            newdata.AdmiralList = new Modes.SimpleAdmiral[0];

            return newdata;
        }
        protected override void ClearList(Modes.BattleResultList list)
        {
            base.ClearList(list);
        }

        private Modes.BattleResult Append(KanColleClient kanColleClient, Modes.BattleResult newItem)
        {
            base.Append(list =>
            {
                var newlist = list.List.ToList();
                newlist.Add(newItem);
                list.List = newlist.ToArray();

                var admiral = new Modes.SimpleAdmiral(kanColleClient);
                if (!list.AdmiralList.Any(x => x.Id == admiral.Id))
                {
                    var newAdmiralList = list.AdmiralList.ToList();
                    newAdmiralList.Add(admiral);
                    list.AdmiralList = newAdmiralList.ToArray();
                }

                return true;
            });

            return newItem;
        }

        public Modes.BattleResult Append(KanColleClient kanColleClient, kcsapi_battleresult br, bool isFirstBattle)
        {
            var newItem = new Modes.BattleResult(kanColleClient, br) { IsFirstBattle = isFirstBattle };
            return Append(kanColleClient, newItem);
        }
        public Modes.BattleResult Append(KanColleClient kanColleClient, kcsapi_combined_battle_battleresult br, bool isFirstBattle)
        {
            var newItem = new Modes.BattleResult(kanColleClient, br) { IsFirstBattle = isFirstBattle };
            return Append(kanColleClient, newItem);
        }

        public void GetInfo(out IList<Modes.BattleResult> list, out IList<Modes.SimpleAdmiral> admiralList, out DateTime lastUpdateDate)
        {
            var allList = base.GetInfo(out list, out lastUpdateDate);

            admiralList = allList.SelectMany(x => x.AdmiralList).Distinct(x => x.Id).ToList();
        }

    }
}


text:
import {randomBase64} from '../fnUtils';
import should from 'should';

describe('fnUtils', () => {
  it('get different value in every invoke', () => {
    let tmp = [];
    const base64Encoded = randomBase64(0, 20);
    for(let i=0; i<1000;i++){
      tmp.push(randomBase64())
    }
    let index = tmp.indexOf(base64Encoded);
    should(index).lessThan(0);
  });

  it('fnUtils should return 5 chars default', () => {
    const base64Encoded = randomBase64();
    should(base64Encoded.length).equal(5);
  });

  it('should return spec number by spec param', () => {
    const base64Encoded = randomBase64(0, 6);
    should(base64Encoded.length).equal(6);
  })

  it('should return no more than 20 chars', () => {
    const base64Encoded = randomBase64(0);
    should(base64Encoded.length).belowOrEqual(20);
  })
  it('should return correct string in browser', () => {
    delete global.bota
    const base64Encoded = randomBase64(0);
    should(typeof base64Encoded).equal('string');
  })
})


text:
require 'test/unit'
require 'rubygems'
require 'active_support'
require 'active_support/test_case'
require 'active_record'
require 'active_record/test_case'
require 'active_record/connection_adapters/mysql_adapter'
require 'foreigner'


text:
package OptimizationTests.ShortLeafMethodsInlining.InvokeStatic_add_long_2addr_NVS_001;
class Main {
    final static int iterations = 10;

    public static long simple_method(long jj, long ii) {
        jj = ii + jj;
        jj = ii + jj;
        return jj;
    }

    public static void main(String[] args) {
        long workJ = 10;
        long workK = 15;

        System.out.println("Initial workJ value is " + workJ);

        for(long i = 0; i < iterations; i++) {
            workJ = simple_method(workJ, workK) + i;
        }

        System.out.println("Final workJ value is " + workJ);
    }
}


text:
package sk.lovasko.lucenec.mapper;

import sk.lovasko.lucenec.geom.Intersection;
import sk.lovasko.lucenec.geom.Point;
import sk.lovasko.lucenec.geom.Vector;
import sk.lovasko.lucenec.math.Double4;
import sk.lovasko.lucenec.math.Matrix;

public final class PlaneCoordinateMapper implements CoordinateMapper
{
	private final Matrix transformation;

	public PlaneCoordinateMapper (final Vector v1, final Vector v2)
	{
		final Vector normal = Vector.cross_product(v2, v1);

		transformation = new Matrix(
			new Double4(v1.get_x(), v2.get_x(), normal.get_x(), 0.0),
			new Double4(v1.get_y(), v2.get_y(), normal.get_y(), 0.0),
			new Double4(v1.get_z(), v2.get_z(), normal.get_z(), 0.0),
			new Double4(0.0,        0.0,        0.0,            1.0)).inverse();
	}

	public final Point get_coordinates (final Intersection intersection)
	{
		return transformation.multiply(intersection.get_local()).set_z(0.0);
	}
}


text:
'use strict';

const Q = require('q');
const rewire = require('rewire');

const u = rewire('./user');
const C = require('../../../chai');

/*global describe, it, expect, beforeEach, afterEach */
describe('CLI: user middleware', () => {
  let oldCn;
  let oldUtil;
  let result = [];
  let promptResult = {};
  let fns = [
    'createUser', 'login', 'changePassword', 'checkConfigured',
    'checkConfiguredAndLoggedIn'
  ];
  beforeEach(() => {
    oldCn = u.__get__('cn');
    oldUtil = u.__get__('util');
    u.__set__('cn', {
      login: () => result instanceof Error ?
        Q.reject(result) : Q.resolve(result)
    });
    u.__set__('util', {
      inquirerPrompt: () => promptResult instanceof Error ?
        Q.reject(result) : Q.resolve(result)
    });
  });

  afterEach(() => {
    u.__set__('cn', oldCn);
    result = [];
  });

  fns.forEach((fn) => {
    it(`${fn} should resolve if clusternator API resolves`, (done) => {
      C.check(u[fn], done);
    });

    it(`${fn} should swallow rejections if clusternator API rejects ` +
      '(CLI Endpoint)', (done) => {
      result  = new Error('test');
      C.check(u[fn], done);
    });

  });

});


text:
"""
Health checks for OpenShift clusters.
"""

import json
import operator
import os
import time
import collections

from abc import ABCMeta, abstractmethod, abstractproperty
from importlib import import_module

from ansible.module_utils import six
from ansible.module_utils.six.moves import reduce  # pylint: disable=import-error,redefined-builtin
from ansible.module_utils.six import string_types
from ansible.plugins.filter.core import to_bool as ansible_to_bool

class OpenShiftCheckException(Exception):
    """Raised when a check encounters a failure condition."""

    def __init__(self, name, msg=None):
        # msg is for the message the user will see when this is raised.
        # name is for test code to identify the error without looking at msg text.
        if msg is None:  # for parameter backward compatibility
            msg = name
            name = self.__class__.__name__
        self.name = name
        super(OpenShiftCheckException, self).__init__(msg)

class OpenShiftCheckExceptionList(OpenShiftCheckException):
    """A container for multiple errors that may be detected in one check."""
    def __init__(self, errors):
        self.errors = errors
        super(OpenShiftCheckExceptionList, self).__init__(
            'OpenShiftCheckExceptionList',
            '\n'.join(str(msg) for msg in errors)
        )

    # make iterable
    def __getitem__(self, index):
        return self.errors[index]

FileToSave = collections.namedtuple("FileToSave", "filename contents remote_filename")

# pylint: disable=too-many-instance-attributes; all represent significantly different state.
# Arguably they could be separated into two hashes, one for storing parameters, and one for
# storing result state; but that smells more like clutter than clarity.
@six.add_metaclass(ABCMeta)
class OpenShiftCheck(object):
    """A base class for defining checks for an OpenShift cluster environment.

    Optional init params: method execute_module, dict task_vars, and string tmp
    execute_module is expected to have a signature compatible with _execute_module
    from ansible plugins/action/__init__.py, e.g.:
    def execute_module(module_name=None, module_args=None, tmp=None, task_vars=None, *args):
    This is stored so that it can be invoked in subclasses via check.execute_module("name", args)
    which provides the check's stored task_vars and tmp.

    Optional init param: want_full_results
    If the check can gather logs, tarballs, etc., do so when True; but no need to spend
    the time if they're not wanted (won't be written to output directory).
    """

    def __init__(self, execute_module=None, task_vars=None, tmp=None, want_full_results=False):
        # store a method for executing ansible modules from the check
        self._execute_module = execute_module
        # the task variables and tmpdir passed into the health checker task
        self.task_vars = task_vars or {}
        self.tmp = tmp
        # a boolean for disabling the gathering of results (files, computations) that won't
        # actually be recorded/used
        self.want_full_results = want_full_results

        # mainly for testing purposes; see execute_module_with_retries
        self._module_retries = 3
        self._module_retry_interval = 5  # seconds

        # state to be recorded for inspection after the check runs:
        #
        # set to True when the check changes the host, for accurate total "changed" count
        self.changed = False
        # list of OpenShiftCheckException for check to report (alternative to returning a failed result)
        self.failures = []
        # list of FileToSave - files the check specifies to be written locally if so configured
        self.files_to_save = []
        # log messages for the check - tuples of (description, msg) where msg is serializable.
        # These are intended to be a sequential record of what the check observed and determined.
        self.logs = []

    @abstractproperty
    def name(self):
        """The name of this check, usually derived from the class name."""
        return "openshift_check"

    @property
    def tags(self):
        """A list of tags that this check satisfy.

        Tags are used to reference multiple checks with a single '@tagname'
        special check name.
        """
        return []

    @staticmethod
    def is_active():
        """Returns true if this check applies to the ansible-playbook run."""
        return True

    def is_first_master(self):
        """Determine if running on first master. Returns: bool"""
        masters = self.get_var("groups", "oo_first_master", default=None) or [None]
        return masters[0] == self.get_var("ansible_host")

    @abstractmethod
    def run(self):
        """Executes a check against a host and returns a result hash similar to Ansible modules.

        Actually the direction ahead is to record state in the attributes and
        not bother building a result hash. Instead, return an empty hash and let
        the action plugin fill it in. Or raise an OpenShiftCheckException.
        Returning a hash may become deprecated if it does not prove necessary.
        """
        return {}

    @classmethod
    def subclasses(cls):
        """Returns a generator of subclasses of this class and its subclasses."""
        # AUDIT: no-member makes sense due to this having a metaclass
        for subclass in cls.__subclasses__():  # pylint: disable=no-member
            yield subclass
            for subclass in subclass.subclasses():
                yield subclass

    def register_failure(self, error):
        """Record in the check that a failure occurred.

        Recorded failures are merged into the result hash for now. They are also saved to output directory
        (if provided) <check>.failures.json and registered as a log entry for context <check>.log.json.
        """
        # It should be an exception; make it one if not
        if not isinstance(error, OpenShiftCheckException):
            error = OpenShiftCheckException(str(error))
        self.failures.append(error)
        # duplicate it in the logs so it can be seen in the context of any
        # information that led to the failure
        self.register_log("failure: " + error.name, str(error))

    def register_log(self, context, msg):
        """Record an entry for the check log.

        Notes are intended to serve as context of the whole sequence of what the check observed.
        They are be saved as an ordered list in a local check log file.
        They are not to included in the result or in the ansible log; it's just for the record.
        """
        self.logs.append([context, msg])

    def register_file(self, filename, contents=None, remote_filename=""):
        """Record a file that a check makes available to be saved individually to output directory.

        Either file contents should be passed in, or a file to be copied from the remote host
        should be specified. Contents that are not a string are to be serialized as JSON.

        NOTE: When copying a file from remote host, it is slurped into memory as base64, meaning
        you should avoid using this on huge files (more than say 10M).
        """
        if contents is None and not remote_filename:
            raise OpenShiftCheckException("File data/source not specified; this is a bug in the check.")
        self.files_to_save.append(FileToSave(filename, contents, remote_filename))

    def execute_module(self, module_name=None, module_args=None, save_as_name=None, register=True):
        """Invoke an Ansible module from a check.

        Invoke stored _execute_module, normally copied from the action
        plugin, with its params and the task_vars and tmp given at
        check initialization. No positional parameters beyond these
        are specified. If it's necessary to specify any of the other
        parameters to _execute_module then that should just be invoked
        directly (with awareness of changes in method signature per
        Ansible version).

        So e.g. check.execute_module("foo", dict(arg1=...))

        save_as_name specifies a file name for saving the result to an output directory,
        if needed, and is intended to uniquely identify the result of invoking execute_module.
        If not provided, the module name will be used.
        If register is set False, then the result won't be registered in logs or files to save.

        Return: result hash from module execution.
        """
        if self._execute_module is None:
            raise NotImplementedError(
                self.__class__.__name__ +
                " invoked execute_module without providing the method at initialization."
            )
        result = self._execute_module(module_name, module_args, self.tmp, self.task_vars)
        if result.get("changed"):
            self.changed = True
        for output in ["result", "stdout"]:
            # output is often JSON; attempt to decode
            try:
                result[output + "_json"] = json.loads(result[output])
            except (KeyError, ValueError):
                pass

        if register:
            self.register_log("execute_module: " + module_name, result)
            self.register_file(save_as_name or module_name + ".json", result)
        return result

    def execute_module_with_retries(self, module_name, module_args):
        """Run execute_module and retry on failure."""
        result = {}
        tries = 0
        while True:
            res = self.execute_module(module_name, module_args)
            if tries > self._module_retries or not res.get("failed"):
                result.update(res)
                return result
            result["last_failed"] = res
            tries += 1
            time.sleep(self._module_retry_interval)

    def get_var(self, *keys, **kwargs):
        """Get deeply nested values from task_vars.

        Ansible task_vars structures are Python dicts, often mapping strings to
        other dicts. This helper makes it easier to get a nested value, raising
        OpenShiftCheckException when a key is not found.

        Keyword args:
          default:
            On missing key, return this as default value instead of raising exception.
          convert:
            Supply a function to apply to normalize the value before returning it.
            None is the default (return as-is).
            This function should raise ValueError if the user has provided a value
            that cannot be converted, or OpenShiftCheckException if some other
            problem needs to be described to the user.
        """
        if len(keys) == 1:
            keys = keys[0].split(".")

        try:
            value = reduce(operator.getitem, keys, self.task_vars)
        except (KeyError, TypeError):
            if "default" not in kwargs:
                raise OpenShiftCheckException(
                    "This check expects the '{}' inventory variable to be defined\n"
                    "in order to proceed, but it is undefined. There may be a bug\n"
                    "in Ansible, the checks, or their dependencies."
                    "".format(".".join(map(str, keys)))
                )
            value = kwargs["default"]

        convert = kwargs.get("convert", None)
        try:
            if convert is None:
                return value
            elif convert is bool:  # interpret bool as Ansible does, instead of python truthiness
                return ansible_to_bool(value)
            else:
                return convert(value)

        except ValueError as error:  # user error in specifying value
            raise OpenShiftCheckException(
                'Cannot convert inventory variable to expected type:\n'
                '  "{var}={value}"\n'
                '{error}'.format(var=".".join(keys), value=value, error=error)
            )

        except OpenShiftCheckException:  # some other check-specific problem
            raise

        except Exception as error:  # probably a bug in the function
            raise OpenShiftCheckException(
                'There is a bug in this check. While trying to convert variable \n'
                '  "{var}={value}"\n'
                'the given converter cannot be used or failed unexpectedly:\n'
                '{type}: {error}'.format(
                    var=".".join(keys),
                    value=value,
                    type=error.__class__.__name__,
                    error=error
                ))

    @staticmethod
    def normalize(name_list):
        """Return a clean list of names.

        The input may be a comma-separated string or a sequence. Leading and
        trailing whitespace characters are removed. Empty items are discarded.
        """
        if isinstance(name_list, string_types):
            name_list = name_list.split(',')
        return [name.strip() for name in name_list if name.strip()]

    @staticmethod
    def get_major_minor_version(openshift_image_tag):
        """Parse and return the deployed version of OpenShift as a tuple."""
        if openshift_image_tag and openshift_image_tag[0] == 'v':
            openshift_image_tag = openshift_image_tag[1:]

        # map major release versions across releases
        # to a common major version
        openshift_major_release_version = {
            "1": "3",
        }

        components = openshift_image_tag.split(".")
        if not components or len(components) < 2:
            msg = "An invalid version of OpenShift was found for this host: {}"
            raise OpenShiftCheckException(msg.format(openshift_image_tag))

        if components[0] in openshift_major_release_version:
            components[0] = openshift_major_release_version[components[0]]

        components = tuple(int(x) for x in components[:2])
        return components

    def find_ansible_mount(self, path):
        """Return the mount point for path from ansible_mounts."""

        # reorganize list of mounts into dict by path
        mount_for_path = {
            mount['mount']: mount
            for mount
            in self.get_var('ansible_mounts')
        }

        # NOTE: including base cases '/' and '' to ensure the loop ends
        mount_targets = set(mount_for_path.keys()) | {'/', ''}
        mount_point = path
        while mount_point not in mount_targets:
            mount_point = os.path.dirname(mount_point)

        try:
            mount = mount_for_path[mount_point]
            self.register_log("mount point for " + path, mount)
            return mount
        except KeyError:
            known_mounts = ', '.join('"{}"'.format(mount) for mount in sorted(mount_for_path))
            raise OpenShiftCheckException(
                'Unable to determine mount point for path "{}".\n'
                'Known mount points: {}.'.format(path, known_mounts or 'none')
            )

LOADER_EXCLUDES = (
    "__init__.py",
    "mixins.py",
    "logging.py",
)

def load_checks(path=None, subpkg=""):
    """Dynamically import all check modules for the side effect of registering checks."""
    if path is None:
        path = os.path.dirname(__file__)

    modules = []

    for name in os.listdir(path):
        if os.path.isdir(os.path.join(path, name)):
            modules = modules + load_checks(os.path.join(path, name), subpkg + "." + name)
            continue

        if name.endswith(".py") and name not in LOADER_EXCLUDES:
            modules.append(import_module(__package__ + subpkg + "." + name[:-3]))

    return modules


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 312956 $ -->

<phpdoc:varentry xmlns:phpdoc="http://php.net/ns/phpdoc" xml:id="reserved.variables.argc" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>$argc</refname>
  <refpurpose>The number of arguments passed to script</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <para>
   Contains the number of arguments passed to the current script when running
   from the <link linkend="features.commandline">command line</link>.
  </para>
  <note>
   <simpara>
    The script's filename is always passed as an argument to the script, therefore
    the minimum value of <varname>$argc</varname> is <literal>1</literal>.
   </simpara>
  </note>
  <note>
   <simpara>
    This variable is not available when <link linkend="ini.register-argc-argv">register_argc_argv</link>
    is disabled.
   </simpara>
  </note>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example xml:id="variable.argc.basic">
    <title><varname>$argc</varname> example</title>
    <programlisting role="php">
<![CDATA[
<?php
var_dump($argc);
?>
]]>
    </programlisting>
    <simpara>
     When executing the example with: php script.php arg1 arg2 arg3
    </simpara>
    &example.outputs.similar;
    <screen>
<![CDATA[
int(4)
]]>
    </screen>
   </example>
  </para>
 </refsect1>

</phpdoc:varentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
const Middleware = require('.');

singleton('Ivy/MiddlewareContainer', () => {
    return new Middleware;
});


text:
/**
 *
 */
package org.vaadin.special.client;

import com.google.gwt.event.dom.client.DomEvent;
import com.google.gwt.event.shared.EventHandler;
import com.vaadin.client.ui.VMediaBase;

/**
 * @author kamil
 *
 */
public class MediaEvents {

	public static final String PLAY = "play";
	public static final String PAUSE = "pause";

	public interface PlayHandler extends EventHandler {
		void onPlay(PlayEvent event);
	}

	public static class PlayEvent extends DomEvent<PlayHandler> {

		public static final Type<PlayHandler> TYPE = new Type<PlayHandler>(PLAY, new PlayEvent());

		protected PlayEvent() {
		}

		public PlayEvent(VMediaBase media) {
			setSource(media);
		}

		public VMediaBase getMediaBase() {
			return (VMediaBase) getSource();
		}

		@Override
		public Type<PlayHandler> getAssociatedType() {
			return TYPE;
		}

		@Override
		protected void dispatch(PlayHandler handler) {
			handler.onPlay(this);
		}
	}

	public interface PauseHandler extends EventHandler {
		void onPause(PauseEvent event);
	}

	public static class PauseEvent extends DomEvent<PauseHandler> {

		public static final Type<PauseHandler> TYPE = new Type<PauseHandler>(PAUSE, new PauseEvent());

		private double time;

		protected PauseEvent() {
		}

		public PauseEvent(VMediaBase media, double time) {
			setSource(media);
			this.time = time;
		}

		public VMediaBase getMediaBase() {
			return (VMediaBase) getSource();
		}

		public double getTime() {
			return time;
		}

		@Override
		public Type<PauseHandler> getAssociatedType() {
			return TYPE;
		}

		@Override
		protected void dispatch(PauseHandler handler) {
			handler.onPause(this);
		}
	}

}


text:
This is the partial for view 1.

    <input ng-model="user.name">
    {{user.name}}

    <form>
        Username:
        <input type="text" name="username" ng-maxlength="10"/>

        Password:
        <input type="password" name="password">
    </form>


text:
/**
 * Created by godsong on 16/10/12.
 */
const Fs = require('fs');
const Path = require('path');
const Inquirer = require('inquirer');
class Config {
  constructor(properties, path) {
    this.path = path;
    if (properties instanceof ConfigResolver) {
      let map = {};
      this.properties = [];
      for (let key in properties.def) {
        for (let propName in properties.def[key]) {
          if (!map[propName]) {
            this.properties.push({
              name: propName,
              desc: properties.def[key].desc || 'enter your ' + propName + ':'
            });
            map[propName] = true;
          }
        }
      }
    }
    else {
      this.properties = properties.split(',').map(prop=> {
        var splits = prop.split('|');
        return {
          name: splits[0],
          desc: splits[1] || 'enter your ' + splits[0] + ':'
        }
      });
    }
  }

  getConfig() {
    return new Promise((resolve, reject)=> {
      let config = {};
      try {
        config = require(this.path);
      }
      catch (e) {
      }
      var questions = [], answers = {};
      console.log('============build config============')
      this.properties.forEach(function (prop) {
        if (config[prop.name] !== undefined && config[prop.name] != '') {
          answers[prop.name] = config[prop.name];
          console.log(prop.name + '=>' + answers[prop.name]);
        }
        else {
          questions.push({
            type: 'input',
            message: prop.desc,
            name: prop.name
          })
        }
      });
      if (questions.length > 0) {
        Inquirer.prompt(questions)
          .then((answers) => {
            Object.assign(config, answers);
            Fs.writeFileSync(this.path, JSON.stringify(config, null, 4))
            resolve(config);
          })
      }
      else {
        console.log('if you want to change build config.please modify ' + Path.basename(this.path));
        resolve(config)
      }
    })

  }
}
class ConfigResolver {
  constructor(def) {
    this.def = def;
  }

  resolve(config, basePath) {
    basePath = basePath || process.cwd();
    for (let path in this.def) {
      if (this.def.hasOwnProperty(path)) {
        let targetPath = Path.join(basePath, path);
        let source = Fs.readFileSync(targetPath).toString();
        for (let key in this.def[path]) {
          if (this.def[path].hasOwnProperty(key)) {
            let configDef = this.def[path][key];
            if (Array.isArray(configDef)) {
              configDef.forEach((def)=> {
                source = _resolveConfigDef(source, def, config, key)
              })
            }
            else {
              source = _resolveConfigDef(source, configDef, config, key);
            }
          }
        }
        Fs.writeFileSync(targetPath, source);
      }

    }
  }
}
function _resolveConfigDef(source, configDef, config, key) {
  if (configDef.type) {
    if (config[key] === undefined) {
      throw new Error('Config:[' + key + '] must have a value!');
    }
    return replacer[configDef.type](source, configDef.key, config[key]);
  }
  else {
    return configDef.handler(source, config[key], replacer);
  }
}
const replacer = {
  plist(source, key, value){
    let r = new RegExp('(<key>' + key + '</key>\\s*<string>)[^<>]*?<\/string>', 'g');
    return source.replace(r, '$1' + value + '</string>')
  },
  xmlTag(source, key, value, tagName = 'string'){
    let r = new RegExp(`<${tagName} name="${key}">[^<]+?</${tagName}>`, 'g');
    return source.replace(r, `<${tagName} name="${key}">${value}</${tagName}>`);
  },
  xmlAttr(source, key, value, tagName = 'string'){
    let r = new RegExp(`<${tagName} name="${key}"\\s* value="[^"]*?"\\s*/>`, 'g');
    return source.replace(r, `<${tagName} name="${key}" value="${value}"/>`);
  },
  regexp(source, regexp, value){
    return source.replace(regexp, function (m, a, b) {
      return a + value + (b || '');
    })
  }
};

exports.Config = Config;
exports.ConfigResolver = ConfigResolver;
exports.androidConfigResolver = new ConfigResolver({
  'build.gradle': {
    AppId: {
      type: 'regexp',
      key: /(applicationId ")[^"]*(")/g
    }
  },
  'app/src/main/res/values/strings.xml': {
    AppName: {
      type: 'xmlTag',
      key: 'app_name'
    },
    SplashText: {
      type: 'xmlTag',
      key: 'dummy_content'
    }
  },
  'app/src/main/res/xml/app_config.xml': {
    WeexBundle: {
      handler: function (source, value, replacer) {
        if (/https?/.test(value)) {
          source = replacer.xmlAttr(source, 'launch_locally', 'false', 'preference');
          return replacer.xmlAttr(source, 'launch_url', value,'preference');
        }
        else {
          source = replacer.xmlAttr(source, 'launch_locally', 'true', 'preference');
          let name=value.replace(/\.(we|vue)$/, '.js');
          //Fs.writeFileSync(Path.join(process.cwd(), 'app/src/main/assets/'+name),Fs.readFileSync(Path.join(process.cwd(), '../../dist', name)));

          return replacer.xmlAttr(source, 'local_url', 'file://assets/dist/'+name,'preference');
        }
      }
    }
  }

});
exports.iOSConfigResolver = new ConfigResolver({
  'WeexDemo/WeexDemo-Info.plist': {
    AppName: {
      type: 'plist',
      key: 'CFBundleDisplayName'
    },
    Version: {
      type: 'plist',
      key: 'CFBundleShortVersionString'
    },
    BuildVersion: {
      type: 'plist',
      key: 'CFBundleVersion'
    },
    AppId: {
      type: 'plist',
      key: 'CFBundleIdentifier'
    }

  },
  'WeexDemo.xcodeproj/project.pbxproj': {
    CodeSign: [{
      type: 'regexp',
      key: /("?CODE_SIGN_IDENTITY(?:\[sdk=iphoneos\*])?"?\s*=\s*").*?(")/g
    }, {
      type: 'plist',
      key: 'CODE_SIGN_IDENTITY(\\[sdk=iphoneos\\*])?'
    }
    ],
    Profile: [
      {
        type: 'regexp',
        key: /(PROVISIONING_PROFILE\s*=\s*")[^"]*?(")/g
      },
      {
        type: 'plist',
        key: 'PROVISIONING_PROFILE'
      }
    ]
  }

})


text:
import has from 'lodash/has';
import {
    Fetch,
    Headers,
    RequestInit,
    Response,
} from './fetch';

class CachedHeaders implements Headers {
    private headers: Map<string, string>;

    constructor(headers: Headers) {
        this.headers = new Map<string, string>();
        // ugly workaround for node-fetch 1.6.0
        if (typeof (headers as any).raw === 'function') {
            const raw: {[key: string]: string[]} = (headers as any).raw();
            for (const prop in raw) {
                if (!has(raw, prop)) {
                    continue;
                }
                this.headers.set(prop, raw[prop].join(','));
            }
        } else {
            for (const [key, value] of headers.entries()) {
                this.headers.set(key, value);
            }
        }
    }

    get(key: string): string | null {
        const val = this.headers.get(key);
        return typeof val === 'undefined' ? null : val;
    }

    has(key: string): boolean {
        return this.headers.has(key);
    }

    entries(): IterableIterator<[string, string]> {
        return this.headers.entries();
    }
}

class CachedResponse implements Response {
    status: number;
    headers: CachedHeaders;
    private _json: Promise<any>;

    constructor(response: Response) {
        this.headers = new CachedHeaders(response.headers);
        this.status = response.status;
        this._json = response.json();
    }

    json(): Promise<any> {
        return this._json;
    }
}

function isCacheable(url: string, init?: RequestInit): boolean {
    if (init && init.method !== 'GET') {
        return false;
    }
    if (init && typeof init.body !== 'undefined') {
        return false;
    }
    return true;
}

function getCacheKey(url: string, init?: RequestInit): string {
    const out: string[] = [];
    out.push(JSON.stringify(url));

    if (init && init.headers) {
        const headerKeys = Object.keys(init.headers);
        headerKeys.sort();
        for (const key of headerKeys) {
            out.push(JSON.stringify([key, init.headers[key]]));
        }
    }

    return out.join('\n');
}

/**
 * Adapt a {@link Fetch} to use a cache with unbounded size.
 * Only successful responses (i.e. status code 200 - 299) to GET will be cached.
 */
export function adaptFetchCache(fetch: Fetch): Fetch {
    const cache = new Map<string, CachedResponse>();

    return async (url: string, init?: RequestInit): Promise<Response> => {
        if (!isCacheable(url, init)) {
            return (await fetch(url, init));
        }

        const cacheKey = getCacheKey(url, init);
        const cacheValue = cache.get(cacheKey);
        if (cacheValue) {
            return cacheValue; // cache hit
        }

        const resp = await fetch(url, init);
        if (resp.status < 200 || resp.status >= 300) {
            return resp; // unsuccessful response -- don't cache
        }

        const cachedResp = new CachedResponse(resp);
        cache.set(cacheKey, cachedResp);
        return cachedResp;
    };
}


text:
package com.jnape.palatable.lambda.monad.transformer.builtin;

import com.jnape.palatable.lambda.adt.Maybe;
import com.jnape.palatable.lambda.adt.Unit;
import com.jnape.palatable.lambda.functions.Fn1;
import com.jnape.palatable.lambda.functor.builtin.Identity;
import com.jnape.palatable.lambda.io.IO;
import com.jnape.palatable.traitor.annotations.TestTraits;
import com.jnape.palatable.traitor.runners.Traits;
import org.junit.Test;
import org.junit.runner.RunWith;
import testsupport.traits.*;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import static com.jnape.palatable.lambda.adt.Maybe.just;
import static com.jnape.palatable.lambda.adt.Unit.UNIT;
import static com.jnape.palatable.lambda.functor.builtin.Identity.pureIdentity;
import static com.jnape.palatable.lambda.io.IO.io;
import static com.jnape.palatable.lambda.monad.transformer.builtin.ReaderT.readerT;
import static org.junit.Assert.assertEquals;
import static testsupport.traits.Equivalence.equivalence;

@RunWith(Traits.class)
public class ReaderTTest {

    @TestTraits({FunctorLaws.class, ApplicativeLaws.class, MonadLaws.class, MonadReaderLaws.class, MonadRecLaws.class})
    public Equivalence<ReaderT<Integer, Identity<?>, Integer>> testSubject() {
        return equivalence(readerT(Identity::new), readerT -> readerT.runReaderT(1));
    }

    @Test
    public void profunctor() {
        assertEquals(new Identity<>(4),
                     ReaderT.<Integer, Identity<?>, Integer>readerT(Identity::new)
                             .diMap(String::length, x -> x + 1)
                             .runReaderT("123"));
    }

    @Test
    public void local() {
        assertEquals(new Identity<>(2),
                     ReaderT.<Integer, Identity<?>, Integer>readerT(Identity::new)
                             .local(x -> x + 1)
                             .runReaderT(1));
    }

    @Test
    public void mapReaderT() {
        assertEquals(just(3),
                     ReaderT.<String, Identity<?>, String>readerT(Identity::new)
                             .<Identity<String>, Maybe<?>, Integer>mapReaderT(id -> just(id.runIdentity().length()))
                             .runReaderT("foo"));
    }

    @Test
    public void andComposesLeftToRight() {
        ReaderT<Integer, Identity<?>, Float> intToFloat    = readerT(x -> new Identity<>(x.floatValue()));
        ReaderT<Float, Identity<?>, Double>  floatToDouble = readerT(f -> new Identity<>(f.doubleValue()));

        assertEquals(new Identity<>(1.),
                     intToFloat.and(floatToDouble).runReaderT(1));
    }

    @Test
    public void staticPure() {
        ReaderT<String, Identity<?>, Integer> readerT =
                ReaderT.<String, Identity<?>>pureReaderT(pureIdentity()).apply(1);
        assertEquals(new Identity<>(1), readerT.runReaderT("foo"));
    }

    @Test(timeout = 500)
    public void composedZip() {
        CountDownLatch latch = new CountDownLatch(2);
        IO<Unit> countdownAndAwait = io(() -> {
            latch.countDown();
            latch.await();
        });
        ReaderT<Unit, IO<?>, Unit> lifted = ReaderT.<Unit>liftReaderT().apply(countdownAndAwait);
        lifted.discardL(lifted)
                .<IO<Unit>>runReaderT(UNIT)
                .unsafePerformAsyncIO(Executors.newFixedThreadPool(2))
                .join();
    }

    @Test
    public void fmapInteractions() {
        AtomicInteger invocations = new AtomicInteger(0);
        ReaderT<Integer, Identity<?>, Integer> readerT = readerT(i -> {
            invocations.incrementAndGet();
            return new Identity<>(i);
        });

        Fn1<Integer, Integer> plusOne = x -> x + 1;
        readerT.fmap(plusOne).fmap(plusOne).fmap(plusOne).runReaderT(0);
        assertEquals(1, invocations.get());
    }

    @Test
    public void askRetrievesInput() {
        assertEquals(new Identity<>(1),
                ReaderT.<Integer, Identity<?>>ask(pureIdentity())
                        .<Identity<Integer>>runReaderT(1));
    }
}


text:
#ifndef __CSS_NODE_LIST_H
#define __CSS_NODE_LIST_H

#include <CSSLayout/ABI8_0_0CSSLayout.h>

ABI8_0_0CSS_EXTERN_C_BEGIN

typedef struct ABI8_0_0CSSNodeList * ABI8_0_0CSSNodeListRef;

ABI8_0_0CSSNodeListRef ABI8_0_0CSSNodeListNew(unsigned int initialCapacity);
void ABI8_0_0CSSNodeListFree(ABI8_0_0CSSNodeListRef list);
unsigned int ABI8_0_0CSSNodeListCount(ABI8_0_0CSSNodeListRef list);
void ABI8_0_0CSSNodeListAdd(ABI8_0_0CSSNodeListRef list, ABI8_0_0CSSNodeRef node);
void ABI8_0_0CSSNodeListInsert(ABI8_0_0CSSNodeListRef list, ABI8_0_0CSSNodeRef node, unsigned int index);
ABI8_0_0CSSNodeRef ABI8_0_0CSSNodeListRemove(ABI8_0_0CSSNodeListRef list, unsigned int index);
ABI8_0_0CSSNodeRef ABI8_0_0CSSNodeListDelete(ABI8_0_0CSSNodeListRef list, ABI8_0_0CSSNodeRef node);
ABI8_0_0CSSNodeRef ABI8_0_0CSSNodeListGet(ABI8_0_0CSSNodeListRef list, unsigned int index);

ABI8_0_0CSS_EXTERN_C_END

#endif


text:
import atexit
import logging
import sys
import os

import psutil

from irclogviewer import create_app, db
from irclogviewer.models import IrcLog
from irclogviewer.znc import ZncDirectory

logger = logging.getLogger(__name__)

def atexit_remove_pid_file(pid_file):
    def handler():
        if os.path.isfile(pid_file):
            logger.error(
                "Exit handler had to remove PID file {0}".format(pid_file)
            )
            os.remove(pid_file)
    return handler

def main():
    app = create_app()
    ctx = app.test_request_context()
    ctx.push()
    pid_file = app.config['CRAWLER_PID_FILE']

    if os.path.isfile(pid_file):
        with open(pid_file, 'r') as f:
            old_pid = int(f.read())
        if psutil.pid_exists(old_pid):
            logger.error(
                "PID {pid} written in PID file {pid_file} is still "
                "running. Crawl aborted.".format(pid=old_pid,
                                                 pid_file=pid_file)
            )
            sys.exit(1)
        else:
            os.remove(pid_file)
    else:
        with open(pid_file, 'w') as f:
            f.write(str(os.getpid()))
    atexit.register(atexit_remove_pid_file(pid_file))

    db.create_all()
    znc_directory = ZncDirectory(app.config['ZNC_DIRECTORY'])

    for user_directory in znc_directory.users.values():
        # Delete all the existing logs (because adding new IrcLog rows is
        # faster than merging existing entries).
        db.session.query(IrcLog)\
                  .filter(IrcLog.user == user_directory.name)\
                  .delete()

        db.session.commit()
        for log_file in user_directory.logs.all():
            irc_log = IrcLog(user=user_directory.name,
                             channel=log_file.channel,
                             date=log_file.date,
                             path=log_file.log_path,
                             last_modified=log_file.modified_time)
            db.session.add(irc_log)
        db.session.commit()

    os.remove(pid_file)


text: CREATE DATABASE `doge` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci


text:
namespace ash::assistant {

////////////////////////////////////////////////////////////////////////////////
// TimerDelegateImpl
////////////////////////////////////////////////////////////////////////////////

class TimerHost::TimerDelegateImpl : public libassistant::mojom::TimerDelegate {
 public:
  explicit TimerDelegateImpl(
      mojo::PendingReceiver<TimerDelegate> pending_receiver,
      ServiceContext* context)
      : receiver_(this, std::move(pending_receiver)), context_(*context) {}
  TimerDelegateImpl(const TimerDelegateImpl&) = delete;
  TimerDelegateImpl& operator=(const TimerDelegateImpl&) = delete;
  ~TimerDelegateImpl() override = default;

 private:
  // libassistant::mojom::TimerDelegate implementation:
  void OnTimerStateChanged(const std::vector<AssistantTimer>& timers) override {
    assistant_alarm_timer_controller().OnTimerStateChanged(timers);
  }

  AssistantAlarmTimerController& assistant_alarm_timer_controller() {
    auto* result = context_.assistant_alarm_timer_controller();
    DCHECK(result);
    return *result;
  }

  mojo::Receiver<TimerDelegate> receiver_;

  // Owned by the parent |Service|.
  ServiceContext& context_;
};

////////////////////////////////////////////////////////////////////////////////
// TimerHost
////////////////////////////////////////////////////////////////////////////////

TimerHost::TimerHost(ServiceContext* context) : context_(*context) {
  DCHECK(context);
}

TimerHost::~TimerHost() = default;

void TimerHost::Initialize(
    libassistant::mojom::TimerController* libassistant_controller,
    mojo::PendingReceiver<libassistant::mojom::TimerDelegate> delegate) {
  DCHECK(!libassistant_controller_);

  timer_delegate_ =
      std::make_unique<TimerDelegateImpl>(std::move(delegate), &context_);
  libassistant_controller_ = libassistant_controller;
}

void TimerHost::Stop() {
  timer_delegate_.reset();
  libassistant_controller_ = nullptr;
}

void TimerHost::AddTimeToTimer(const std::string& id,
                               base::TimeDelta duration) {
  libassistant_controller().AddTimeToTimer(id, duration);
}

void TimerHost::PauseTimer(const std::string& id) {
  libassistant_controller().PauseTimer(id);
}

void TimerHost::RemoveTimer(const std::string& id) {
  libassistant_controller().RemoveTimer(id);
}

void TimerHost::ResumeTimer(const std::string& id) {
  libassistant_controller().ResumeTimer(id);
}

libassistant::mojom::TimerController& TimerHost::libassistant_controller() {
  DCHECK(libassistant_controller_);
  return *libassistant_controller_;
}

}  // namespace ash::assistant


text:
addScriptToInject(function() {

chrome_comp.CompDetect.declareDetector(

'positioned_by_inline_elements',

chrome_comp.CompDetect.ScanDomBaseDetector,

null, // constructor

function checkNode(node, additionalData) {
  /*
  function isShrinkToFit(node) {
    var width = window.chrome_comp.getDefinedStylePropertyByName(node, true,
      'width');
    if (width && width != 'auto') return;
    var position = window.chrome_comp.getComputedStyle(node).position,
        cssFloat = window.chrome_comp.getComputedStyle(node)['float'],
        inlineBlock = window.chrome_comp.getComputedStyle(node).display,
        isAbsPosition = (position == 'absolute') || (position == 'fixed'),
        isFloat = (cssFloat == 'left') || (cssFloat == 'right'),
        isInlineBlock = inlineBlock == 'inline-block';
    return isAbsPosition || isFloat || isInlineBlock;
  }
  */

  if (Node.ELEMENT_NODE != node.nodeType ||
      chrome_comp.getComputedStyle(node).display != 'inline')
    return;
  if (chrome_comp.getComputedStyle(node).position != 'relative')
    return;
  for (var i = 0, j = node.getElementsByTagName('*'), k = j.length; i < k;
      i++) {
    var pos = chrome_comp.getComputedStyle(j[i]).position;
    var isCB = (pos == 'absolute' && j[i].offsetParent == node);
    if (!isCB)
      continue;
    this.addProblem('RM1020', [j[i]]);
  }
}
); // declareDetector

});