text:
package runtime;

import instructions.Allocate;
import instructions.Arithmetic;
import instructions.Assert;
import instructions.CallVariable;
import instructions.Cut;
import instructions.Deallocate;
import instructions.GetVariable;
import instructions.Instruction;
import instructions.Proceed;
import instructions.PutValue;
import instructions.Retract;
import instructions.RetryMeElse;
import instructions.TrustMe;
import instructions.TryMe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import compiler.CompiledClause;
import compiler.tokens.CompileToken;

/**
 * This class contains all the compiled Prolog code that the engine uses to answer queries.
 * @author Bas Testerink
 *
 */
public class CodeBase {
	private Map<String, List<List<CompileToken>>> tokens = new HashMap<String, List<List<CompileToken>>>(); // Contains all the compile tokens of the code, can be used for changing the code base and recompile it
	private Map<String, CodeClause> clauses = new HashMap<String, CodeClause>();
	private Map<String, CodeClause> builtin = new HashMap<String, CodeClause>();
	private CodeClause query = new CodeClause();							// The latest compiled query

	public CodeBase(){ makeBuiltIn(); }

	/** Add all the input tokens to the token based (appending after the current tokens in case of same predicates). */
	public Map<String, List<List<CompileToken>>> mergeTokens(Map<String, List<List<CompileToken>>> input){
		for(String f : input.keySet()){
			List<List<CompileToken>> clauses = tokens.get(f);
			if(clauses == null){
				clauses = new ArrayList<List<CompileToken>>();
				tokens.put(f, clauses);
			}
			clauses.addAll(input.get(f));
		}
		return tokens;
	}

	/** Override the current query. */
	public void setQuery(CompiledClause query){
		this.query.reset();
		this.query.setInstructions(query.getInstructions());
		this.query.setPrologString(query.getPrologString());
	}

	/** Override the current code. */
	public void setCode(Map<String,List<CompiledClause>> code){
		for(String f : code.keySet()){
			boolean initial = true;
			CodeClause clause = null;
			List<CompiledClause> clauses = code.get(f);
			for(CompiledClause c : clauses){
				CodeClause newClause = new CodeClause();
				newClause.belongsTo = c.getFunctor();
				newClause.setInstructions(c.getInstructions());
				newClause.setPrologString(c.getPrologString());
				newClause.setPrevious(clause);
				if (clause != null) clause.setNext(newClause);
				if(initial){
					this.clauses.put(f, newClause);
					initial = false;
				}
				clause = newClause;
			}
		}
	}

	/** Remove a fact. Used by retract. It is assumed that the to-be-retracted fact is fully substituted with
	 * the first possible fact. */
	public void removeFact(String functor, String fact){
		CodeClause clause = clauses.get(functor);
		while(!clause.getPrologString().equals(fact)){
			clause = clause.getNext();
			if(clause == null) return;
		}
		Instruction i = clause.getInstruction(0);

		if(i instanceof TryMe){
			Instruction i2 = clause.getNext().getInstruction(0);
			if(i2 instanceof RetryMeElse){
				// Remove first of >2 clauses
				clause.getNext().getInstructions().set(0, new TryMe(((TryMe)i).getArity()));
			} else if(i2 instanceof TrustMe){
				// Remove first of 2 clauses
				clause.getNext().getInstructions().remove(0); // Remove the TryMe instruction
			}
			clauses.put(functor, clause.getNext()); // Replace the top-of-list pointer
		} else if(i instanceof RetryMeElse){
			// Remove middle of >2 (do nothing, just remove the clause)
		} else if(i instanceof TrustMe){
			Instruction i2 = clause.getPrevious().getInstruction(0);
			if(i2 instanceof RetryMeElse){
				// Remove last of >2 clauses
				clause.getPrevious().getInstructions().set(0, new TrustMe()); // Set retry to trust
			} else if(i2 instanceof TryMe){
				clause.getPrevious().getInstructions().remove(0); // Remove the try_me instruction
			}
		} else {
			// Removed the last fact
			clauses.remove(functor);
		}
		clause.remove(); // Simply remove the clause
	}

	/** Add a code clause (used by assert). */
	public void addCodeClause(CompiledClause c){
		CodeClause newClause = new CodeClause();
		newClause.setInstructions(c.getInstructions());
		newClause.setPrologString(c.getPrologString());
		newClause.belongsTo = c.getFunctor();
		CodeClause clause = clauses.get(c.getFunctor());
		if(clause==null){
			// first of its kind
			clauses.put(c.getFunctor(), newClause);
		} else {
			while(clause.getNext()!=null)
				clause = clause.getNext(); // Go to last clause
			Instruction i = clause.getInstruction(0);
			if(i instanceof TrustMe){ // There was already a bunch of facts, so make new trust entry.
				clause.getInstructions().set(0,new RetryMeElse());
				newClause.getInstructions().add(0,new TrustMe());
			} else { // There was only one fact, add tryme and trustme
				int arity = Integer.parseInt(c.getFunctor().substring(c.getFunctor().lastIndexOf('/')+1,c.getFunctor().length()));
				clause.getInstructions().add(0,new TryMe(arity));
				newClause.getInstructions().add(0,new TrustMe());
			}
			clause.setNext(newClause);
			newClause.setPrevious(clause);
		}
	}

	// Setters/getters
	public void setQuery(CodeClause query){ this.query = query; }
	public CodeClause getQueryClause(){ return query; }

	/** Get the top clause for a functor. */
	public CodeClause getClause(String functor){
		CodeClause code = clauses.get(functor);
		while(code != null && code.isRetracted())
			code = code.getNext();
		if(code == null){
			return builtin.get(functor);
		}
		return code;
	}

	/** Make the special built-in code. */
	private void makeBuiltIn(){
		// Arithmetic
		CodeClause c = new CodeClause();
		List<Instruction> instr = new ArrayList<Instruction>();
		instr.add(new Arithmetic());
		c.setInstructions(instr);
		c.belongsTo = " is /2";
		builtin.put(" is /2", c);

		// Retract
		c = new CodeClause();
		instr = new ArrayList<Instruction>();
		instr.add(new TryMe(1));
		instr.add(new Allocate(1));
		instr.add(new GetVariable(-1, 0));
		instr.add(new CallVariable(-1));
		instr.add(new Cut());
		instr.add(new PutValue(-1, 0));
		instr.add(new Retract());
		instr.add(new Deallocate());
		instr.add(new TrustMe());
		instr.add(new Proceed());
		c.setInstructions(instr);
		c.belongsTo = "retract/1";
		builtin.put("retract/1", c);

		// Assert
		c = new CodeClause();
		instr = new ArrayList<Instruction>();
		instr.add(new Assert());
		c.setInstructions(instr);
		c.belongsTo = "assert/1";
		builtin.put("assert/1", c);
	}

	public String toString(){
		String s = "";
		for(String f : clauses.keySet()){
			s += f+":\r\n";
			CodeClause clause = clauses.get(f);
			int c = 0;
			while(clause != null){
				Instruction instruction;
				s += "\t Prolog: " + clause.getPrologString()+"\r\n";
				for(int i = 0; i < clause.size(); i++){
					instruction = clause.getInstruction(i);
					s += "\t" + c + ": "+ instruction + "\r\n";
					c++;
				}
				clause = clause.getNext();
			}
		}
		s +="Current query: "+query.getPrologString()+"\r\n";
		int c = 0;
		Instruction instruction;
		for(int i = 0; i < query.size(); i++){
			instruction = query.getInstruction(i);
			s += "\t" + c + ": "+ instruction + "\r\n";
			c++;
		}
		return s;
	}

}


text:
using System;
using System.Linq;
using Bytes2you.Validation.Extensions;
using Bytes2you.Validation.ValidationPredicates.NullablePredicates;

namespace Bytes2you.Validation
{
    public static class NullableArgumentFluentExtensions
    {
        public static IValidatableArgument<Nullable<T>> IsNull<T>(this IArgument<Nullable<T>> @argument)
            where T : struct
        {
            return @argument.AddValidationPredicate(NullableNullValidationPredicate<T>.Instance);
        }

        public static IValidatableArgument<Nullable<T>> IsNotNull<T>(this IArgument<Nullable<T>> @argument)
            where T : struct
        {
            return @argument.AddValidationPredicate(NullableNotNullValidationPredicate<T>.Instance);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package me.chanjar.weixin.cp.util.json;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.util.json.WxMenuGsonAdapter;

import java.lang.reflect.Type;

/**
 *

 * 企业号菜单json转换适配器
 * Created by Binary Wang on 2017-6-25.
 * @author  Binary Wang

 */
public class WxCpMenuGsonAdapter extends WxMenuGsonAdapter {

  @Override
  public WxMenu deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    return this.buildMenuFromJson(json.getAsJsonObject().get("button").getAsJsonArray());
  }
}


text:
import "es5-shim"
import "es5-shim/es5-sham"
import assign from "object-assign"

if(!Object.assign) {
  Object.assign = assign
}

const context = require.context("./src", true, /__tests__\/\S+\.js$/)
context.keys().forEach(context)


text:
package i5.las2peer.services.ocd.adapters.graphInput;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import org.junit.Ignore;
import org.junit.Test;

import i5.las2peer.services.ocd.adapters.AdapterException;
import i5.las2peer.services.ocd.graphs.CustomGraph;
import i5.las2peer.services.ocd.testsUtils.OcdTestConstants;

public class NodeContentEdgeListGraphInputAdapterTest {

	@Ignore
	@Test
	public void testOnUrch() throws AdapterException, FileNotFoundException, IllegalArgumentException, ParseException {
		Map<String, String> adapterParam = new HashMap<String, String>();
		adapterParam.put("startDate", "2006-04-01");
		adapterParam.put("endDate", "2006-04-30");
		adapterParam.put("path", "C:\\indexes\\urch2006");
		NodeContentEdgeListGraphInputAdapter inputAdapter =
				new NodeContentEdgeListGraphInputAdapter(new FileReader(OcdTestConstants.urchPostsEdgeListInputPath));
		inputAdapter.setParameter(adapterParam);
		CustomGraph graph = inputAdapter.readGraph();
		System.out.println(graph.nodeCount());
	}

	@Ignore
	@Test
	public void testOnOSS() throws AdapterException, FileNotFoundException, IllegalArgumentException, ParseException{
		Map<String, String> adapterParam = new HashMap<String, String>();
		adapterParam.put("startDate", "2006-04-01");
		adapterParam.put("endDate", "2006-04-30");
		adapterParam.put("path", "C:\\indexes\\jmol2004");
		NodeContentEdgeListGraphInputAdapter inputAdapter =
				new NodeContentEdgeListGraphInputAdapter(new FileReader(OcdTestConstants.jmolEdgeListInputPath));
		inputAdapter.setParameter(adapterParam);
		CustomGraph graph = inputAdapter.readGraph();
		System.out.println(graph.nodeCount());
	}
}


text:
import { GraphQLString, GraphQLBoolean } from "graphql"
import { mutationWithClientMutationId } from "graphql-relay"
import { ArtworkType } from "schema/v2/artwork/index"
import { ResolverContext } from "types/graphql"

export default mutationWithClientMutationId<any, any, ResolverContext>({
  name: "SaveArtwork",
  description:
    "Save (or remove) an artwork to (from) a users default collection.",
  inputFields: {
    artworkID: {
      type: GraphQLString,
    },
    remove: {
      type: GraphQLBoolean,
    },
  } /*
  FIXME: Generated by the snake_case to camelCase codemod.
         Either use this to fix inputs and/or remove this comment.
  {
    const {
      artworkID,
      ..._newFields
    } = newFields;
    const oldFields = {
      artworkID: artwork_id,
      ..._newFields
    };
  }
  */,
  outputFields: {
    artwork: {
      type: ArtworkType,
      resolve: ({ artwork_id }, _, { artworkLoader }) =>
        artworkLoader(artwork_id),
    },
  },
  mutateAndGetPayload: (
    { artworkID: artwork_id, remove },
    { userID, saveArtworkLoader, deleteSavedArtworkLoader }
  ) => {
    if (!deleteSavedArtworkLoader || !saveArtworkLoader) {
      return new Error("You need to be signed in to perform this action")
    }

    const loader = remove ? deleteSavedArtworkLoader : saveArtworkLoader
    return loader(artwork_id, { user_id: userID }).then(() => ({ artwork_id }))
  },
})


text:
package com.zhongshu.maintenanceexpert.activitity;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yalantis.ucrop.entity.LocalMedia;
import com.yalantis.ucrop.util.FunctionConfig;
import com.yalantis.ucrop.util.LocalMediaLoader;
import com.yalantis.ucrop.util.PictureConfig;
import com.zhongshu.maintenanceexpert.Constants;
import com.zhongshu.maintenanceexpert.MyApplication;
import com.zhongshu.maintenanceexpert.R;
import com.zhongshu.maintenanceexpert.adapter.GridImageAdapter1;
import com.zhongshu.maintenanceexpert.adapter.GridImageAdapter2;
import com.zhongshu.maintenanceexpert.bean.ImageVoiceBean;
import com.zhongshu.maintenanceexpert.bean.PhotoReleaseBean;
import com.zhongshu.maintenanceexpert.utils.FullyGridLayoutManager;
import com.zhongshu.maintenanceexpert.utils.PhoneNumUtils;
import com.zhongshu.maintenanceexpert.utils.ToastUtils;
import com.zhongshu.maintenanceexpert.views.DragView;
import com.zhongshu.maintenanceexpert.views.HKDialogLoading;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

import static com.zhongshu.maintenanceexpert.R.id.et_persion_photomenu;
import static com.zhongshu.maintenanceexpert.R.id.et_phone_photomenu;

public class PhotoReleaseActivity2 extends AppCompatActivity implements View.OnClickListener {

    private SharedPreferences preferences;
    private Button fabu;
    private EditText topTitle,description,location,persion,phone,price;
    private InputMethodManager imm;
    private int type=1;
    private List<String> imgFile = new ArrayList<>();
    private String img;

    private TextView title;
    private TextView leftTitle;
    private DragView dragView;
    private TextView text1,text2,text3;
    private RecyclerView pickPhoto,pickVideo;
    private ImageView ivBackground;
    private Animation animation1,animation2,animation3,animation4,animation5;
    private GridImageAdapter1 adapter1;
    private GridImageAdapter2 adapter2;
    private int selectMode = FunctionConfig.MODE_MULTIPLE;
    private int maxSelectNum = 4;// 图片最大可选数量
    private int maxSelectNum2 = 1;// 视屏最大可选数量
    private boolean isShow = true;
    private int selectType = LocalMediaLoader.TYPE_IMAGE;//图片选择
    private int selectType2 = LocalMediaLoader.TYPE_VIDEO;//视屏选择

    private int copyMode = FunctionConfig.COPY_MODEL_DEFAULT;//选择裁剪模式
    private boolean enablePreview = true;//图片预览
    private boolean isPreviewVideo = true;//视屏预览
    private boolean enableCrop = false;//是否可裁剪
    private boolean theme = false;
    private boolean selectImageType = false;
    private int cropW = 0;
    private int cropH = 0;
    private boolean isCompress = false;//是否压缩图片
    private boolean isCheckNumMode = false;//选择QQ主题 false 没选择 true 选择
    private List<LocalMedia> selectMedia = new ArrayList<>();
    private List<LocalMedia> selectMedia2 = new ArrayList<>();
    private FullyGridLayoutManager manager,manager2;

    private HKDialogLoading dialogLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_release2);
        MyApplication.getInstance().addActivity(this);
        preferences=getSharedPreferences("base64",MODE_APPEND);

        imm= (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        manager = new FullyGridLayoutManager(PhotoReleaseActivity2.this, 4, GridLayoutManager.VERTICAL, false);
        manager2 = new FullyGridLayoutManager(PhotoReleaseActivity2.this, 1, GridLayoutManager.VERTICAL, false);

        initView();
    }

    private void initView() {

        animation1 = AnimationUtils.loadAnimation(this, R.anim.text_translate);//价钱规格动画
        animation2 = AnimationUtils.loadAnimation(this, R.anim.touxiang_rotate1);//底部旋转图动画
        animation3 = AnimationUtils.loadAnimation(this, R.anim.text_down);
        animation4 = AnimationUtils.loadAnimation(this, R.anim.text_translate2);
        animation5 = AnimationUtils.loadAnimation(this, R.anim.text_translate3);
        animation1.setFillAfter(true);
        animation4.setFillAfter(true);
        animation5.setFillAfter(true);

        ivBackground= (ImageView) findViewById(R.id.iv_background_photoMenu);
        ivBackground.setAnimation(animation2);
//        group= (RadioGroup) findViewById(R.id.rg_photoMenu);
        text1= (TextView) findViewById(R.id.tv_yikoujia);
        text2= (TextView) findViewById(R.id.tv_daixieshang);
        text3= (TextView) findViewById(R. id.tv_daikancha);
        dragView= (DragView) findViewById(R.id.drag_view);

        fabu= (Button) findViewById(R.id.btn_fabu_sure);
        topTitle= (EditText) findViewById(R.id.et_title_photoMenu);
        description= (EditText) findViewById(R.id.editText2);
        location= (EditText) findViewById(R.id.et_address_photomenu);
        price= (EditText) findViewById(R.id.et_price_photoMenu);
        phone= (EditText) findViewById(et_phone_photomenu);
        persion= (EditText) findViewById(et_persion_photomenu);

        pickPhoto= (RecyclerView) findViewById(R.id.rv_pick_photo);
        pickVideo= (RecyclerView) findViewById(R.id.rv_pick_video);

        title = (TextView) findViewById(R.id.tv_title);
        leftTitle = (TextView) findViewById(R.id.tv_title_left);
        leftTitle.setVisibility(View.VISIBLE);
        title.setText("发布");
        leftTitle.setText("取消");
        leftTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        fabu.setOnClickListener(this);

        text1.setTextColor(Color.rgb(151,200,244));
        text1.startAnimation(animation1);

        dragView.setNodeSelectListener(new DragView.OnNodeSelect() {
            @Override
            public void onNodeSelect(int position) {
                switch (position){
                    case 0:
                        type=1;
                        text1.setTextColor(Color.rgb(151,200,244));
                        text2.setTextColor(Color.rgb(22,125,215));
                        text3.setTextColor(Color.rgb(22,125,215));
                        price.setText("¥: 0");
                        price.setEnabled(false);
                        animation4.cancel();
                        animation5.cancel();
                        text1.startAnimation(animation1);
                        break;
                    case 1:
                        type=2;
                        text2.setTextColor(Color.rgb(151,200,244));
//                        text2.setTextColor(Color.rgb(167,56,247));
                        text1.setTextColor(Color.rgb(22,125,215));
                        text3.setTextColor(Color.rgb(22,125,215));
                        price.setHint("请输入价钱");
                        price.setText("");
                        price.setEnabled(true);
                        animation1.cancel();
                        animation5.cancel();
                        text2.startAnimation(animation4);
                        break;
                    case 2:
                        type=3;
                        text3.setTextColor(Color.rgb(151,200,244));
                        text2.setTextColor(Color.rgb(22,125,215));
                        text1.setTextColor(Color.rgb(22,125,215));
                        price.setText("¥: 200");
                        price.setEnabled(false);
                        animation1.cancel();
                        animation4.cancel();
                        text3.startAnimation(animation5);
                        break;
                    default:
                        break;
                }
            }
        });
        adapter1 = new GridImageAdapter1(this,onAddPicClickListener);
        adapter1.setSelectMax(maxSelectNum);
        pickPhoto.setLayoutManager(manager);
        pickPhoto.setAdapter(adapter1);

        adapter2 = new GridImageAdapter2(this,onAddPicClickListener2);
        adapter2.setSelectMax(maxSelectNum2);
        pickVideo.setLayoutManager(manager2);
        pickVideo.setAdapter(adapter2);

        //点击预览图片
        adapter1.setOnItemClickListener(new GridImageAdapter1.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                // 这里可预览图片
                PictureConfig.getPictureConfig().externalPicturePreview(PhotoReleaseActivity2.this, position, selectMedia);
            }
        });
        //点击预览视屏
        adapter2.setOnItemClickListener(new GridImageAdapter2.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                // 这里可预览图片
                PictureConfig.getPictureConfig().externalPicturePreview(PhotoReleaseActivity2.this, position, selectMedia2);

//                Intent intent = new Intent(Intent.ACTION_VIEW);
//                intent.setDataAndType(selectMedia2.get(position).getPath(), "video/mp4");
//                startActivity(intent);

            }
        });

    }

    private GridImageAdapter1.onAddPicClickListener onAddPicClickListener = new GridImageAdapter1.onAddPicClickListener() {
        @Override
        public void onAddPicClick(int type, int position) {
            switch (type) {
                case 0:
                    // 进入相册
                    /**
                     * type --> 1图片 or 2视频
                     * copyMode -->裁剪比例,默认、1:1、3:4、3:2、16:9
                     * maxSelectNum --> 可选择图片的数量
                     * selectMode         --> 单选 or 多选
                     * isShow       --> 是否显示拍照选项 这里自动根据type 启动拍照或录视频
                     * isPreview    --> 是否打开预览选项
                     * isCrop       --> 是否打开剪切选项
                     * isPreviewVideo -->是否预览视频(播放) mode or 多选有效
                     * ThemeStyle -->主题颜色
                     * CheckedBoxDrawable -->图片勾选样式
                     * cropW-->裁剪宽度 值不能小于100  icon_check.png如果值大于图片原始宽高 将返回原图大小
                     * cropH-->裁剪高度 值不能小于100
                     * isCompress -->是否压缩图片
                     * setEnablePixelCompress 是否启用像素压缩
                     * setEnableQualityCompress 是否启用质量压缩
                     * setRecordVideoSecond 录视频的秒数,默认不限制
                     * setRecordVideoDefinition 视频清晰度  Constants.HIGH 清晰  Constants.ORDINARY 低质量
                     * setImageSpanCount -->每行显示个数
                     * setCheckNumMode 是否显示QQ选择风格(带数字效果)
                     * setPreviewColor 预览文字颜色
                     * setCompleteColor 完成文字颜色
                     * setPreviewBottomBgColor 预览界面底部背景色
                     * setBottomBgColor 选择图片页面底部背景色
                     * setCompressQuality 设置裁剪质量,默认无损裁剪
                     * setSelectMedia 已选择的图片
                     * 注意-->type为2时 设置isPreview or isCrop 无效
                     * 注意:Options可以为空,默认标准模式
                     */
                    int selector = R.drawable.select_cb;
                    FunctionConfig config = new FunctionConfig();
                    config.setType(selectType);
                    config.setCopyMode(copyMode);
                    config.setCompress(isCompress);
                    config.setEnablePixelCompress(true);
                    config.setEnableQualityCompress(true);
                    config.setMaxSelectNum(maxSelectNum);
                    config.setSelectMode(selectMode);
                    config.setShowCamera(isShow);
                    config.setEnablePreview(enablePreview);
                    config.setEnableCrop(enableCrop);
                    config.setPreviewVideo(isPreviewVideo);
                    config.setRecordVideoDefinition(FunctionConfig.HIGH);// 视频清晰度
                    config.setRecordVideoSecond(60);// 视频秒数
                    config.setCropW(cropW);
                    config.setCropH(cropH);
                    config.setCheckNumMode(isCheckNumMode);
                    config.setCompressQuality(100);
                    config.setImageSpanCount(4);
                    config.setSelectMedia(selectMedia);
                    if (theme) {
                        config.setThemeStyle(ContextCompat.getColor(PhotoReleaseActivity2.this, R.color.blue));
                        // 可以自定义底部 预览 完成 文字的颜色和背景色
                        if (!isCheckNumMode) {
                            // QQ 风格模式下 这里自己搭配颜色,使用蓝色可能会不好看
                            config.setPreviewColor(ContextCompat.getColor(PhotoReleaseActivity2.this, R.color.white));
                            config.setCompleteColor(ContextCompat.getColor(PhotoReleaseActivity2.this, R.color.white));
                            config.setPreviewBottomBgColor(ContextCompat.getColor(PhotoReleaseActivity2.this, R.color.blue));
                            config.setBottomBgColor(ContextCompat.getColor(PhotoReleaseActivity2.this, R.color.blue));
                        }
                    }
                    if (selectImageType) {
                        config.setCheckedBoxDrawable(selector);
                    }

                    // 先初始化参数配置,在启动相册
                    PictureConfig.init(config);
                    PictureConfig.getPictureConfig().openPhoto(PhotoReleaseActivity2.this, resultCallback);

                    break;
                case 1:
                    // 删除图片
                    selectMedia.remove(position);
                    adapter1.notifyItemRemoved(position);
                    break;
            }
        }
    };

    /**
     * 删除图片回调接口
     */
    private GridImageAdapter2.onAddPicClickListener onAddPicClickListener2 = new GridImageAdapter2.onAddPicClickListener() {
        @Override
        public void onAddPicClick(int type, int position) {
            switch (type) {
                case 0:
                    // 进入相册
                    /**
                     * type --> 1图片 or 2视频
                     * copyMode -->裁剪比例,默认、1:1、3:4、3:2、16:9
                     * maxSelectNum --> 可选择图片的数量
                     * selectMode         --> 单选 or 多选
                     * isShow       --> 是否显示拍照选项 这里自动根据type 启动拍照或录视频
                     * isPreview    --> 是否打开预览选项
                     * isCrop       --> 是否打开剪切选项
                     * isPreviewVideo -->是否预览视频(播放) mode or 多选有效
                     * ThemeStyle -->主题颜色
                     * CheckedBoxDrawable -->图片勾选样式
                     * cropW-->裁剪宽度 值不能小于100  如果值大于图片原始宽高 将返回原图大小
                     * cropH-->裁剪高度 值不能小于100
                     * isCompress -->是否压缩图片
                     * setEnablePixelCompress 是否启用像素压缩
                     * setEnableQualityCompress 是否启用质量压缩
                     * setRecordVideoSecond 录视频的秒数,默认不限制
                     * setRecordVideoDefinition 视频清晰度  Constants.HIGH 清晰  Constants.ORDINARY 低质量
                     * setImageSpanCount -->每行显示个数
                     * setCheckNumMode 是否显示QQ选择风格(带数字效果)
                     * setPreviewColor 预览文字颜色
                     * setCompleteColor 完成文字颜色
                     * setPreviewBottomBgColor 预览界面底部背景色
                     * setBottomBgColor 选择图片页面底部背景色
                     * setCompressQuality 设置裁剪质量,默认无损裁剪
                     * setSelectMedia 已选择的图片
                     * 注意-->type为2时 设置isPreview or isCrop 无效
                     * 注意:Options可以为空,默认标准模式
                     */
                    int selector = R.drawable.select_cb;
                    FunctionConfig config = new FunctionConfig();
                    config.setType(selectType2);
                    config.setCopyMode(copyMode);
                    config.setCompress(isCompress);
                    config.setEnablePixelCompress(true);
                    config.setEnableQualityCompress(true);
                    config.setMaxSelectNum(maxSelectNum2);
                    config.setSelectMode(selectMode);
                    config.setShowCamera(isShow);
                    config.setEnablePreview(enablePreview);
                    config.setEnableCrop(enableCrop);
                    config.setPreviewVideo(isPreviewVideo);
                    config.setRecordVideoDefinition(FunctionConfig.HIGH);// 视频清晰度
                    config.setRecordVideoSecond(20);// 视频秒数
                    config.setCropW(cropW);
                    config.setCropH(cropH);
                    config.setCheckNumMode(isCheckNumMode);
                    config.setCompressQuality(100);
                    config.setImageSpanCount(4); //打开相册后每行显示的照片数量
                    config.setSelectMedia(selectMedia2);
                    if (theme) {
                        config.setThemeStyle(ContextCompat.getColor(PhotoReleaseActivity2.this, R.color.blue));
                        // 可以自定义底部 预览 完成 文字的颜色和背景色
                        if (!isCheckNumMode) {
                            // QQ 风格模式下 这里自己搭配颜色,使用蓝色可能会不好看
                            config.setPreviewColor(ContextCompat.getColor(PhotoReleaseActivity2.this, R.color.white));
                            config.setCompleteColor(ContextCompat.getColor(PhotoReleaseActivity2.this, R.color.white));
                            config.setPreviewBottomBgColor(ContextCompat.getColor(PhotoReleaseActivity2.this, R.color.blue));
                            config.setBottomBgColor(ContextCompat.getColor(PhotoReleaseActivity2.this, R.color.blue));
                        }
                    }
                    if (selectImageType) {
                        config.setCheckedBoxDrawable(selector);
                    }

                    // 先初始化参数配置,在启动相册
                    PictureConfig.init(config);
                    PictureConfig.getPictureConfig().openPhoto(PhotoReleaseActivity2.this, resultCallback2);

                    break;
                case 1:
                    // 删除图片
                    selectMedia2.remove(position);
                    adapter2.notifyItemRemoved(position);
                    break;
            }
        }
    };

    /**
     * 图片回调方法
     */
    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> resultList) {
            selectMedia = resultList;
            if (selectMedia != null) {
                adapter1.setList(selectMedia);
                adapter1.notifyDataSetChanged();
            }
        }
    };
    /**
     * 视屏回调方法
     */
    private PictureConfig.OnSelectResultCallback resultCallback2 = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> resultList) {
            selectMedia2 = resultList;
            if (selectMedia2 != null) {
                adapter2.setList(selectMedia2);
                adapter2.notifyDataSetChanged();
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_fabu_sure:
                AlertDialog.Builder builder=new AlertDialog.Builder(PhotoReleaseActivity2.this);
                builder.setTitle("确认发布此订单").setIcon(R.mipmap.head).setCancelable(false).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        uploadToService();
//                        ToastUtils.showToast(PhotoReleaseActivity2.this,"GBFKAHL");
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
                break;

            default:
                break;
        }
    }

    private void uploadToService(){

//        HashMap<String,String> map=new HashMap<>();
        if (preferences.getString("uId","")!=null && preferences.getString("uId","").length()>0){
            if ((topTitle.getText().toString()!=null && topTitle.getText().toString().length()>0) && (description.getText().toString()!=null && description.getText().toString().length()>0)
                    && (phone.getText().toString()!=null && phone.getText().toString().length()>0) && (persion.getText().toString()!=null && persion.getText().toString().length()>0)
                    && (location.getText().toString()!=null && location.getText().toString().length()>0)){

                if (PhoneNumUtils.judgePhoneNums(phone.getText().toString())) {

                    showDialog();

                    if (selectMedia != null && selectMedia.size() > 0) {
                        Log.d("YYY", "uploadToService: 1111111" + selectMedia.size());
                        for (int i = 0; i < selectMedia.size(); i++) {
                            Log.d("YYY", "onClick:222222222 " + selectMedia.get(i).getPath());
                            sendServiceImg(selectMedia.get(i).getPath());

                        }
                    } else {
                        sendService();
                    }
                }else {
                    ToastUtils.showToast(this,"手机号格式不正确");
                }
//                    map.put("uid",preferences.getString("uId",""));
//                    map.put("title",topTitle.getText().toString().trim());
//                    map.put("details",description.getText().toString().trim());
//                    map.put("address",location.getText().toString().trim());
//                    map.put("type",type+"");
//                    map.put("price",price.getText().toString().trim());
//                    map.put("contact",persion.getText().toString().trim());
//                    map.put("mobile",phone.getText().toString().trim());
//                OkHttpUtils.post().url(Constants.PHOTO_RELEASE).params(map).build().execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                        ToastUtils.showToast(PhotoReleaseActivity2.this,"网络异常");
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        Log.d("ZZZ", "onResponse: "+response);
//                        PhotoReleaseBean bean=new Gson().fromJson(response,PhotoReleaseBean.class);
//                        if (bean.getCode()==200){
//                            ToastUtils.showToast(PhotoReleaseActivity2.this,"订单已提交");
//                        }
//                    }
//                });
            }else {
                ToastUtils.showToast(this,"信息不完整");
            }
        }else {
            ToastUtils.showToast(this,"未登录");
        }

    }

    //上传图片
    private void sendServiceImg(String path) {
        File file = new File(path);
        RequestParams params = new RequestParams(Constants.URL_IMG_UPLOAD);
        params.setMultipart(true);
        params.addBodyParameter("file", file);
        Callback.Cancelable c = x.http().request(HttpMethod.POST, params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result!=null && result.length()>0){
                    ImageVoiceBean bean=new Gson().fromJson(result,ImageVoiceBean.class);
                    if (bean.getCode()==200){
                        Log.i("TAG",bean.getUrl());
                        imgFile.add(bean.getUrl());
                        if (imgFile.size() == selectMedia.size()){
                            img = listParseJson(imgFile);
                            sendService();
                        }

                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("YYY", ex.toString());
                Toast.makeText(PhotoReleaseActivity2.this, "请检查网络", Toast.LENGTH_SHORT).show();
//                dialogLoading.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("YYY", "请检查网络");
                Toast.makeText(PhotoReleaseActivity2.this, "请检查网络", Toast.LENGTH_SHORT).show();
//                dialogLoading.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void sendService(){
        HashMap<String,String> map=new HashMap<>();
        map.put("uid",preferences.getString("uId",""));
        map.put("title",topTitle.getText().toString().trim());
        map.put("details",description.getText().toString().trim());
        map.put("address",location.getText().toString().trim());
        map.put("type",type+"");
        if (img != null && img.length() > 0) {
            map.put("img", img);
        }
        if (type == 1) {
            map.put("price", "0");
        }else if (type == 2){
            map.put("price", price.getText().toString().trim());
        }else if (type == 3){
            map.put("price", "200");
        }
        map.put("contact",persion.getText().toString().trim());
        map.put("mobile",phone.getText().toString().trim());
        OkHttpUtils.post().url(Constants.PHOTO_RELEASE).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showToast(PhotoReleaseActivity2.this,"网络异常");
                dialogLoading.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.d("ZZZ", "onResponse: "+response);
                PhotoReleaseBean bean=new Gson().fromJson(response,PhotoReleaseBean.class);
                if (bean.getCode()==200){
                    ToastUtils.showToast(PhotoReleaseActivity2.this,"订单已提交");
                    PhotoReleaseActivity2.this.finish();
                }else {
                    ToastUtils.showToast(PhotoReleaseActivity2.this,"提交失败,请检查网络");
                }
                dialogLoading.dismiss();
            }
        });
    }

    //将集合转为Json字符串
    private String listParseJson(List<String> list) {
        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            array.put(list.get(i).toString().trim());
        }
        try {
            object.put("imgString", array);
            imgFile.clear();
            return object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void showDialog() {
        dialogLoading = new HKDialogLoading(PhotoReleaseActivity2.this, R.style.HKDialog);
        dialogLoading.setCancelable(false);
        dialogLoading.show();
    }
}


text:
using System.Web.Mvc;

namespace Ext.Net.MVC.Examples.Areas.GridPanel_Miscellaneous.FilterQuery.Controllers
{
    public class FilterQueryController : Controller
    {
        public ActionResult Index()
        {
            return View(Companies.GetAllCompanies());
        }

        public ActionResult ApplyFilter()
        {
            var query = "company like \"The\" or price < 30";
            var store = X.GetCmp<Store>("Store1");

            store.AddFilter(new Ext.Net.FilterQuery(query));
            X.Toast("Server-filtered by query: " + query);

            return this.Direct();
        }
    }
}


text:
package org.nd4j.aeron.ipc.chunk;

import org.agrona.DirectBuffer;
import org.junit.Test;
import org.nd4j.aeron.ipc.NDArrayMessage;
import org.nd4j.aeron.util.BufferUtil;
import org.nd4j.linalg.factory.Nd4j;

import java.nio.ByteBuffer;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

/**
 * Created by agibsonccc on 11/20/16.
 */
public class NDArrayMessageChunkTests {

    @Test
    public void testChunkSerialization() {
        NDArrayMessage message = NDArrayMessage.wholeArrayUpdate(Nd4j.ones(1000));
        int chunkSize = 128;
        int numChunks = NDArrayMessage.numChunksForMessage(message, chunkSize);
        NDArrayMessageChunk[] chunks = NDArrayMessage.chunks(message, chunkSize);
        assertEquals(numChunks, chunks.length);
        for (int i = 1; i < numChunks; i++) {
            assertEquals(chunks[0].getMessageType(), chunks[i].getMessageType());
            assertEquals(chunks[0].getId(), chunks[i].getId());
            assertEquals(chunks[0].getChunkSize(), chunks[i].getChunkSize());
            assertEquals(chunks[0].getNumChunks(), chunks[i].getNumChunks());
        }

        ByteBuffer[] concat = new ByteBuffer[chunks.length];
        for (int i = 0; i < concat.length; i++)
            concat[i] = chunks[i].getData();

        DirectBuffer buffer = NDArrayMessage.toBuffer(message);
        //test equality of direct byte buffer contents vs chunked
        ByteBuffer byteBuffer = buffer.byteBuffer();
        ByteBuffer concatAll = BufferUtil.concat(concat, buffer.capacity());
        byte[] arrays = new byte[byteBuffer.capacity()];
        byteBuffer.rewind();
        byteBuffer.get(arrays);
        byte[] arrays2 = new byte[concatAll.capacity()];
        concatAll.rewind();
        concatAll.get(arrays2);
        assertArrayEquals(arrays, arrays2);
        NDArrayMessage message1 = NDArrayMessage.fromChunks(chunks);
        assertEquals(message, message1);

    }

}


text:
Dambreak flow - Collagrosi and Landrini (2003)
==============================================

Description
-----------
The problem comprises a 2D tank with dimensions  3.22m x 1.8m  (width x height).
The boundaries are considered closed, specifically as free slip walls, while the top boundary [y+] is set as an atmposphere.
The purpose of this case initially published by Collagrosi and Landrini (2003) is to examine a two phase flow in a 2D tank, where the 2 fluids are separated by sharp interfaces.
The initial condition of the fluid is a water column with dimensions  1.20m x 0.60m  (width x height). By the time the simulation starts, the column collapses under the action of gravity and impacts to a wall.

In the following figure, the geometry of the dambreak case is illustrated.

.. figure:: ./dambreakColagrossi.bmp
   :width: 100%
   :align: center

This case demonstrates the ability of Proteus to simulate the free-surface
evolution and forces / pressures on structures, according to data that
are available in the following references.  For more details, see
runfiles or references.

Running the test case
-----

To run the test case type:

```
parun dambreak.py --TwoPhaseFlow  -v -D result_folder
```

Dambreak and tank properties can be modified by the commandline, using for example:

```
parun dambreak.py --TwoPhaseFlow  -v -D result_folder -C "mwl=0.5"
```

To run in parallel (example with mpirun and 12 processors):

```
mpirun -np 12 parun -f dambreak.py --TwoPhaseFlow  -v -D result_folder -C "mwl=0.5"
```

To see guidance on parun options, you can type

```
parun -h
```

References
----------

- Colagrossi A and Landrini M (2003) Numerical simulation of
  interfacial flows by smoothed particle hydrodynamics, Journal of
  Computational Physics,191,448-475.

- Martin, J. C. & Moyce, W. J., (1952) Part IV. An Experimental Study
  of the Collapse of Liquid Columns on a Rigid Horizontal Plane
  Phil. Trans. R. Soc. Lond. A 244 (882) 312-324.

- Zhou, Z. Q., De Kat, J. O. and Buchner, B. (1999) A nonlinear 3-D
  approach to simulate green water dynamics on deck in: J. Piquet
  (Ed.), Proc. 7th Int. Conf. Num. Ship Hydrod., Nantes, 5.11, 15.


text:
/**
 *
 */
package com.trendrr.strest.tests.clients;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.trendrr.oss.DynMap;
import com.trendrr.oss.strest.models.StrestRequest;
import com.trendrr.oss.strest.models.StrestHeader.Method;
import com.trendrr.oss.strest.models.json.StrestJsonRequest;
import com.trendrr.zmq.client.ZMQClient;
import com.trendrr.zmq.client.ZMQClientMessageHandler;

/**
 * @author Dustin Norlander
 * @created Jun 4, 2012
 *
 */
public class ZMQEchoClient implements ZMQClientMessageHandler {

	protected static Log log = LogFactory.getLog(ZMQEchoClient.class);

	ZMQClient client;

	final Set<String> sent = Collections.synchronizedSet(new HashSet<String>());

	public ZMQEchoClient() {
		client = new ZMQClient("tcp://localhost:8092", this);
	}

	/**
	 * num waiting for response.
	 * @return
	 */
	public int size() {
		return sent.size();
	}
	/* (non-Javadoc)
	 * @see com.trendrr.zmq.client.ZMQClientMessageHandler#error(java.lang.Exception)
	 */
	@Override
	public void error(Exception arg0) {
		log.error("CAught", arg0);

	}

	/* (non-Javadoc)
	 * @see com.trendrr.zmq.client.ZMQClientMessageHandler#incoming(com.trendrr.zmq.client.ZMQClient, byte[])
	 */
	@Override
	public void incoming(ZMQClient client, byte[] message) {
		try {
			DynMap response = DynMap.instance(new String(message, "utf8"));
//			log.info("GOT RESPONSE: " + response);
			sent.remove(response.getString("content", ""));
		} catch (UnsupportedEncodingException e) {
			log.error("Caught", e);
		}

	}

	public void send(String message) {
		StrestRequest request = new StrestJsonRequest();
		request.setUri("echo");
		request.setMethod(Method.GET);
		DynMap params = new DynMap();
		params.put("echo", message);
		request.setParams(params);
		sent.add(message);
		client.send(request.toByteArray());
	}

	public void close() {
		client.close();
	}

}


text:
@font-face {
    font-family: 'digital-7_monomono';
    src: url('digital-7-mono.eot');
    src: url('digital-7-mono.eot?#iefix') format('embedded-opentype'),
         url('digital-7-mono.woff2') format('woff2'),
         url('digital-7-mono.woff') format('woff'),
         url('digital-7-mono.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;

}


text:
"""
Simple USB counter.

Usage: Send plaintext commands, separated by newline/cr or semicolon.
       An eventual reply comes terminated with cr+lf.

Important commands:

*IDN?     Returns device identifier
*RST      Resets device
TIME     <value>
          Set the gate time to <value> in msec.
          Default is 1000, minimum is 1, max 65535.
TIME?     Returns the current gate time.
COUNTS?   Triggers a counting window, and replies with the number of
          detected events as a list of space-separated integers.
TTL       Switches to TTL input levels.
NIM       Switches input to negative NIM levels.
LEVEL?    Returns the input level (NIM or TTL).
HELP      Print this help text.

"""

import serial

class Countercomm(object):
# Module for communicating with the mini usb IO board
	baudrate = 115200

	def __init__(self, port):
		self.serial = self._open_port(port)
		self._serial_write('a')# flush io buffer
		print self._serial_read() #will read unknown command

	def _open_port(self, port):
		ser = serial.Serial(port, timeout=1)
		return ser

	def _serial_write(self, string):
		self.serial.write(string + '\n')

	def _serial_read(self):
		msg_string = self.serial.readline()
		# Remove any linefeeds etc
		msg_string = msg_string.rstrip()
		return msg_string

	def reset(self):
		self._serial_write('*RST')
		return self._serial_read()

	def get_counts(self):
		self._serial_write('COUNTS?')
		counts = self._serial_read()
		return counts

	def get_gate_time(self):
		self._serial_write('TIME?')
		out = self._serial_read()
		return out

	def get_digital(self):
		self._serial_write('LEVEL?')
		level = self._serial_read()
		return level

	def set_gate_time(self,value):
		self._serial_write('TIME'+ str(int(value)))

	def set_TTL(self):
		self._serial_write('TTL')

	def set_NIM(self):
		self._serial_write('NIM')

	def serial_number(self):
		self._serial_write('*IDN?')
		return self._serial_read()

	def close(self):
		self.serial.close()


text:
namespace absl {
ABSL_NAMESPACE_BEGIN

std::ostream& operator<<(std::ostream& os, absl::LogSeverity s) {
  if (s == absl::NormalizeLogSeverity(s)) return os << absl::LogSeverityName(s);
  return os << "absl::LogSeverity(" << static_cast<int>(s) << ")";
}

std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtLeast s) {
  switch (s) {
    case absl::LogSeverityAtLeast::kInfo:
    case absl::LogSeverityAtLeast::kWarning:
    case absl::LogSeverityAtLeast::kError:
    case absl::LogSeverityAtLeast::kFatal:
      return os << ">=" << static_cast<absl::LogSeverity>(s);
    case absl::LogSeverityAtLeast::kInfinity:
      return os << "INFINITY";
  }
  return os;
}

std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtMost s) {
  switch (s) {
    case absl::LogSeverityAtMost::kInfo:
    case absl::LogSeverityAtMost::kWarning:
    case absl::LogSeverityAtMost::kError:
    case absl::LogSeverityAtMost::kFatal:
      return os << "<=" << static_cast<absl::LogSeverity>(s);
    case absl::LogSeverityAtMost::kNegativeInfinity:
      return os << "NEGATIVE_INFINITY";
  }
  return os;
}
ABSL_NAMESPACE_END
}  // namespace absl


text:
package cs.qa.enums;

import weka.classifiers.Classifier;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.functions.LibSVM;
import weka.classifiers.lazy.IBk;
import weka.classifiers.trees.J48;
import weka.classifiers.trees.RandomForest;

public enum ClassifierType {

	//Classifiers
	NAIVE_BAYES("NAIVE_BAYES"),
	LIB_SVM("LIB_SVM"),
	J48("J48"),
	RANDOM_FOREST("RANDOM_FOREST"),
	IBK("IBK");

	private String value;

	ClassifierType(String value){
		this.value = value;
	}

	public String getValue(){
		return value;
	}

	public static ClassifierType getByValue(String value){
	    for(ClassifierType type : values()){
	        if(type.getValue().equals(value)){
	            return type;
	        }
	    }
	    return null;
	}

	public static Classifier getClassifier(ClassifierType classifierType){
		Classifier classifier = null;
		switch(classifierType){
		case NAIVE_BAYES:
			classifier = new NaiveBayes();
			break;
		case LIB_SVM:
			classifier = new LibSVM();
			break;
		case J48:
			classifier = new J48();
			break;
		case RANDOM_FOREST:
			classifier = new RandomForest();
			break;
		case IBK:
			classifier = new IBk();
			break;
		default:
			classifier = new NaiveBayes();
		}
		return classifier;
	}

}


text:
package org.sleuthkit.autopsy.discovery.ui;

import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.event.ListSelectionListener;
import org.sleuthkit.autopsy.coreutils.ThreadConfined;
import org.sleuthkit.datamodel.AbstractFile;

/**
 * A JPanel to display document previews.
 */
final class DocumentPreviewViewer extends javax.swing.JPanel {

    private static final long serialVersionUID = 1L;
    private final DefaultListModel<DocumentWrapper> documentListModel = new DefaultListModel<>();

    /**
     * Creates new form DocumentViewer.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    DocumentPreviewViewer() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        documentScrollPane = new javax.swing.JScrollPane();
        documentList = new javax.swing.JList<>();

        documentList.setModel(documentListModel);
        documentList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        documentList.setCellRenderer(new DocumentPanel());
        documentScrollPane.setViewportView(documentList);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(documentScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(documentScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Clear the list of documents being displayed.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    void clearViewer() {
        documentListModel.removeAllElements();
        documentScrollPane.getVerticalScrollBar().setValue(0);
    }

    /**
     * Add a selection listener to the list of document previews being
     * displayed.
     *
     * @param listener The ListSelectionListener to add to the selection model.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    void addListSelectionListener(ListSelectionListener listener) {
        documentList.getSelectionModel().addListSelectionListener(listener);
    }

    /**
     * Get the list of AbstractFiles which are represented by the selected
     * document preview.
     *
     * @return The list of AbstractFiles which are represented by the selected
     *         document preview.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    List<AbstractFile> getInstancesForSelected() {
        if (documentList.getSelectedIndex() == -1) {
            return new ArrayList<>();
        } else {
            return documentListModel.getElementAt(documentList.getSelectedIndex()).getResultFile().getAllInstances();
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList<DocumentWrapper> documentList;
    private javax.swing.JScrollPane documentScrollPane;
    // End of variables declaration//GEN-END:variables

    /**
     * Add the preview for a document to the panel.
     *
     * @param documentWrapper The object which contains the document preview
     *                        which will be displayed.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    void addDocument(DocumentWrapper documentWrapper) {
        documentListModel.addElement(documentWrapper);
    }
}


text:
`cfn` has features that make it easier to break large stacks out into
individual files that are easier to read and maintain. An individual stack
will always have a `main.yaml` for the main stack, and optionally other
`<stackname>.yaml` files that are child resources of `main.yaml`.

The directory structure for `cfn` looks like this:
```
cloudconfig.yaml - project-wide settings
	cfn/
		<stackdefinition>/ - `cfn` creates a stack named after the subdirectory,
		  prefixed with `StackPrefix` if it's set in cloudconfig.yaml.
			main.yaml - the list of resources for this stack, may include
			  other stacks with resource names of <Something>Stack
			something.yaml - When main.yaml includes a <Something>Stack
			  resource, `cfn` gets the resources from `<something>.yaml`
			somethingelse.yaml
			...
		<stackdefinition>/
		...
```


text:
package org.gunisalvo.automatonWeb.resource;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

import org.gunisalvo.automaton.webHook.exception.JaxRsRequestFailedHandler;
import org.gunisalvo.automaton.webHook.exception.JaxRsServiceUnavailableHandler;

@ApplicationPath("/v0")
public class ApplicationRoot extends Application {

	@SuppressWarnings("unchecked")
	public Set<Class<?>> getClasses() {
		return new HashSet<Class<?>>(Arrays.asList(	ResourceInterface.class,
													JaxRsRequestFailedHandler.class,
													JaxRsServiceUnavailableHandler.class));
	}
}


text:
@implementation atomspace

@end


text:
from django import forms
from django.utils.safestring import mark_safe

class AdminImageWidget(forms.FileInput):
    """
    A ImageField Widget for admin that shows a thumbnail.
    """

    def __init__(self, attrs={}):
        super(AdminImageWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        output = []
        if value and hasattr(value, "url"):
            output.append((''
                           ' '
                           % (value.url, value.url)))
        output.append(super(AdminImageWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))


text:
""" Thread to perform creation of a service """

import os
import shutil
import traceback
from agent.lib.errors import Errors
from agent.lib.errors import AgentException
from agent.lib.utils import symlink
from agent.lib.agent_thread.download_helper import DownloadHelper
from agent.lib.package import PackageUtil

import logging
from agent.lib import utils, manifestutil

LOG = logging.getLogger(__name__)

class ManifestCreate(DownloadHelper):
    """ This thread will attempt to create new manifests.
    This means creating the directory.
    Downloading the packages, if necessary.
    Verifying the package.
    Untaring the package.
    verifying the untar'd package.
    """

    inProgressExt = '.inprogress'

    def __init__(self, threadMgr, service, manifest, packages, forcePackages = None, parentId = None):
        """ Constructor """
        DownloadHelper.__init__(self, threadMgr, cat = [manifestutil.serviceCat(service)], name = 'create_manifest', parentId = parentId)
        self.__manifest = manifest
        self.__service = service
        self.__packages = packages
        self.__forcePackages = forcePackages

    def doRun(self):
        """ Main body of the thread

        Progress Info:
        Look at the list of packages this manifest has and figure out the progress of this manifest
        Progress 1 = manifest directory created
        Progress 2-80 = all packages downloaded
        Progress 81-99 = all packages untarred
        Progress 100 = all links done
        """
        inProgressPath = ManifestCreate.inProgress(manifestutil.manifestPath(self.__service, self.__manifest))
        try:
            if self.__service != 'agent':
                utils.checkDiskFull()

            installedPkgPath = manifestutil.installedPkgRootPath(self.__service)

            # This should not happen but make sure there isn'trn already a manifest directory in progress
            if (os.path.isdir(inProgressPath)):
                # probably another manifest create thread died out half way.
                # Cleanup and reattempt manifest creation
                LOG.debug('Manifest inprogress found for service/manifest (%s/%s). Will cleanup and retry' % (self.__service, self.__manifest))
                shutil.rmtree(inProgressPath)

            # make sure that the service path and installed package path exists
            if (not os.path.isdir(manifestutil.manifestRootPath(self.__service)) or
                not os.path.isdir(manifestutil.installedPkgRootPath(self.__service))):
                errCode = Errors.SERVICE_NOT_FOUND
                msg = 'Service (%s) for manifest (%s) not found' % (self.__service, self.__manifest)
                self._updateStatus(httpStatus = 500, error = errCode, errorMsg = msg)
                return

            # ok create the manifest path
            os.mkdir(inProgressPath)

            self._updateProgress(1)

            # figure out which of the packages are already there
            remainingPackages = {}
            for pkgUri in self.__packages:
                pkgDict = PackageUtil.parseUri(pkgUri)
                pkgPath = os.path.join(installedPkgPath, pkgDict['packageName'], pkgDict['packageVersion'])
                pkgName = pkgDict['packageName']
                if (not os.path.exists(pkgPath)) or ((self.__forcePackages is not None) and pkgName in self.__forcePackages):
                    remainingPackages[pkgUri] = pkgDict
                else:
                    symlink(pkgPath, os.path.join(inProgressPath, pkgDict['packageName']))

            if len(remainingPackages) > 0:
                # now make sure all the packages are downloaded
                try:
                    self._downloadPackages(remainingPackages.keys())
                except AgentException as exc:
                    # check if it is download error, then modify exception appropriately
                    if exc.getCode() == Errors.DC_FAILED_DOWNLOAD:
                        exc = AgentException(Errors.MANIFEST_PACKAGE_DOWNLOAD_FAILED,
                                            'Manifest (%s/%s) failed downloading package - %s'
                                            % (self.__service, self.__manifest, exc.getMsg()))
                    raise exc

            LOG.info('Completed download all packages for (%s/%s)' % (self.__service, self.__manifest))

            # now untar the packages
            import re
            pkgSuffix = '.%s' % re.sub(r"\W", "", self.__manifest)
            self._untarPackages(remainingPackages, self.__service,
                                manifestutil.installedPkgRootPath(self.__service), 0, self.__forcePackages, pkgSuffix)
            LOG.info('Completed untar all packages for (%s/%s)' % (self.__service, self.__manifest))

            # now create the links
            for pkgDict in remainingPackages.itervalues():
                pkgPath = os.path.join(installedPkgPath, pkgDict['packageName'], pkgDict['packageVersion'])
                linkPath = os.path.join(inProgressPath, pkgDict['packageName'])
                # validate target folder does exist
                if not os.path.exists(pkgPath):
                    raise AgentException(Errors.PACKAGE_PATH_ERROR, 'invalid untarred package at %s' % pkgPath)
                symlink(pkgPath, linkPath)

            # now move the inProgressPath to the final path
            manifestContentPath = manifestutil.manifestContentPath(self.__service, self.__manifest)

            os.rename(inProgressPath, manifestutil.manifestPath(self.__service, self.__manifest))

            mfContentsFile = file(manifestContentPath, 'w')
            for pkgUri in self.__packages:
                mfContentsFile.write(('%s%s') % (pkgUri, os.linesep))
            mfContentsFile.close()
            LOG.info('Completed create manifest for (%s/%s)' % (self.__service, self.__manifest))

            self._updateStatus(progress = 100)

        except AgentException as exc:
            LOG.info(exc.getMsg())
            self._updateStatus(httpStatus = 500, error = exc.getCode(), errorMsg = exc.getMsg())

        except Exception as exc:
            errCode = Errors.UNKNOWN_ERROR
            msg = 'Unknown error for (%s/%s) - %s - %s' % (self.__service, self.__manifest,
                                                           str(exc), traceback.format_exc(2))
            LOG.info(msg)
            self._updateStatus(httpStatus = 500, error = errCode, errorMsg = msg)
        finally:
            # clean up intermediate progress
            try:
                shutil.rmtree(inProgressPath)
            except OSError:
                pass

    @staticmethod
    def inProgress(filename):
        """ return the inprogress version of the method """
        return filename + ManifestCreate.inProgressExt

    @staticmethod
    def isInProgress(filename):
        """ return True if object is in progress """
        return filename.endswith(ManifestCreate.inProgressExt)


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Media.Models
{
    /// <summary> The IP access control. </summary>
    internal partial class IPAccessControl
    {
        /// <summary> Initializes a new instance of IPAccessControl. </summary>
        public IPAccessControl()
        {
            AllowedIPs = new ChangeTrackingList<IPRange>();
        }

        /// <summary> Initializes a new instance of IPAccessControl. </summary>
        /// <param name="allowedIPs"> The IP allow list. </param>
        internal IPAccessControl(IList<IPRange> allowedIPs)
        {
            AllowedIPs = allowedIPs;
        }

        /// <summary> The IP allow list. </summary>
        public IList<IPRange> AllowedIPs { get; }
    }
}


text:
package main

type GraphvizData struct {
	Root       string
	Edges      []string
	GraphAttrs string
}


text:
<?php
namespace ATWS\AutotaskObjects;

class ChecklistLibrary extends Entity
{
    // Required
    public $Active;
    public $EntityType;
    public $Name;

    // Optional
    public $Description;
}


text:
<?xml version='1.0' encoding="UTF-8" standalone="no" ?>
<!-- The DTD (Document Type Definition) given here must correspond to the version number declared in the WMT_MS_Capabilities element below. -->
<!DOCTYPE WMT_MS_Capabilities SYSTEM
 "http://www.digitalearth.gov/wmt/xml/capabilities_1_1_0.dtd"
 [
 <!-- Vendor-specific elements are defined here if needed. -->
 <!-- If not needed, just leave this EMPTY declaration.  Do not
  delete the declaration entirely. -->
 <!ELEMENT VendorSpecificCapabilities EMPTY>
 ]>  <!-- end of DOCTYPE declaration -->

<!-- Note: this XML is just an EXAMPLE that attempts to show all
required and optional elements for illustration.  Consult the Web Map
Service 1.1.0 specification and the DTD for guidance on what to actually
include and what to leave out. -->

<!-- The version number listed in the WMT_MS_Capabilities element here must
correspond to the DTD declared above.  See the WMT specification document for
how to respond when a client requests a version number not implemented by the
server. -->
<WMT_MS_Capabilities version="1.1.0" updateSequence="0">
<!-- Service Metadata -->
<Service>
  <!-- The WMT-defined name for this type of service -->
  <Name>OGC:WMS</Name>
  <!-- Human-readable title for pick lists -->
  <Title>Acme Corp. Map Server</Title>
  <!-- Narrative description providing additional information -->
  <Abstract>WMT Map Server maintained by Acme Corporation.  Contact: webmaster@wmt.acme.com.  High-quality maps showing roadrunner nests and possible ambush locations.</Abstract>
  <KeywordList>
    <Keyword>bird</Keyword>
    <Keyword>roadrunner</Keyword>
    <Keyword>ambush</Keyword>
  </KeywordList>
  <!-- Top-level web address of service or service provider.  See also OnlineResource
  elements under <DCPType>. -->
  <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple"
   xlink:href="http://hostname/" />
  <!-- Contact information -->
  <ContactInformation>
    <ContactPersonPrimary>
      <ContactPerson>Jeff deLaBeaujardiere</ContactPerson>
      <ContactOrganization>NASA</ContactOrganization>
    </ContactPersonPrimary>
    <ContactPosition>Computer Scientist</ContactPosition>
    <ContactAddress>
      <AddressType>postal</AddressType>
      <Address>NASA Goddard Space Flight Center, Code 933</Address>
      <City>Greenbelt</City>
      <StateOrProvince>MD</StateOrProvince>
      <PostCode>20771</PostCode>
      <Country>USA</Country>
    </ContactAddress>
    <ContactVoiceTelephone>+1 301 286-1569</ContactVoiceTelephone>
    <ContactFacsimileTelephone>+1 301 286-1777</ContactFacsimileTelephone>
    <ContactElectronicMailAddress>delabeau@iniki.gsfc.nasa.gov</ContactElectronicMailAddress>
  </ContactInformation>
  <!-- Fees or access constraints imposed. -->
  <Fees>none</Fees>
  <AccessConstraints>none</AccessConstraints>
</Service>
<Capability>
  <Request>
    <GetCapabilities>
      <Format>application/vnd.ogc.wms_xml</Format>
      <DCPType>
        <HTTP>
          <Get>
            <!-- The URL here for invoking GetCapabilities using HTTP GET
            is only a prefix to which a query string is appended. -->
            <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
             xlink:type="simple"
             xlink:href="http://hostname:port/path" />
          </Get>
          <Post>
            <!-- The URL here for invoking GetCapabilities using HTTP POST
            includes the complete address to which a query would be sent in
            XML format.  This is here for future expansion; no POST encoding
	    has yet been defined. -->
            <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
             xlink:type="simple"
             xlink:href="http://hostname:port/path" />
          </Post>
        </HTTP>
      </DCPType>
    </GetCapabilities>
    <GetMap>
      <Format>image/gif</Format>
      <Format>image/png</Format>
      <Format>image/jpeg</Format>
      <DCPType>
        <HTTP>
          <Get>
            <!-- The URL here for invoking GetCapabilities using HTTP GET
            is only a prefix to which a query string is appended. -->
            <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
             xlink:type="simple"
             xlink:href="http://hostname:port/path" />
          </Get>
        </HTTP>
      </DCPType>
    </GetMap>
    <GetFeatureInfo>
      <Format>application/vnd.ogc.gml</Format>
      <Format>text/plain</Format>
      <Format>text/html</Format>
      <DCPType>
        <HTTP>
          <Get>
            <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
             xlink:type="simple"
             xlink:href="http://hostname:port/path" />
          </Get>
        </HTTP>
      </DCPType>
    </GetFeatureInfo>
    <DescribeLayer><!--optional; used only by SLD-enabled WMS-->
      <Format>application/vnd.ogc.gml</Format>
      <DCPType>
        <HTTP>
          <Get>
            <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
             xlink:type="simple"
             xlink:href="http://hostname:port/path" />
          </Get>
        </HTTP>
      </DCPType>
    </DescribeLayer>
  </Request>
  <Exception>
    <Format>application/vnd.ogc.se_xml</Format>
    <Format>application/vnd.ogc.se_inimage</Format>
    <Format>application/vnd.ogc.se_blank</Format>
  </Exception>
  <!-- Any text or markup is allowed here, as required to describe
       vendor-specific capabilities.  Please define elements and attributes
       in the DOCTYPE declaration at the start of the document. -->
  <!-- This example is empty because no VSPs were defined in preamble -->
  <VendorSpecificCapabilities />
  <!-- Place-holder for Styled Layer Descriptor (SLD)-enabled WMSes.
       This element is absent for a basic WMS. -->
  <UserDefinedSymbolization SupportSLD="1" UserLayer="1" UserStyle="1"
	RemoteWFS="1" />
  <Layer>
    <Title>Acme Corp. Map Server</Title>
    <SRS>EPSG:4326</SRS> <!-- all layers are available in at least this SRS -->
    <AuthorityURL name="DIF_ID">
      <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple"
       xlink:href="http://gcmd.gsfc.nasa.gov/difguide/whatisadif.html" />
    </AuthorityURL>
    <Layer>
      <!-- This parent layer has a Name and can therefore be requested from a Map Server, yielding a map of all subsidiary layers. -->
      <Name>ROADS_RIVERS</Name>
      <Title>Roads and Rivers</Title>
      <!-- See the spec to learn how some characteristics are inherited by
           subsidiary layers. -->
      <SRS>EPSG:26986</SRS> <!-- An additional SRS for this layer -->
      <LatLonBoundingBox minx="-71.63" miny="41.75" maxx="-70.78" maxy="42.90"/>
      <!-- The optional resx and resy attributes below indicate the X and Y spatial
           resolution in the units of that SRS. -->
      <!-- The EPSG:4326 BoundingBox duplicates some of the info in LatLonBoundingBox
           and is therefore optional, but using it here allows the additional
           resolution attributes. -->
      <BoundingBox SRS="EPSG:4326"
       minx="-71.63" miny="41.75" maxx="-70.78" maxy="42.90" resx="0.01" resy="0.01"/>
      <BoundingBox SRS="EPSG:26986"
       minx="189000" miny="834000" maxx="285000" maxy="962000" resx="1" resy="1" />
      <!-- Optional Title, URL and logo image of data provider. -->
      <Attribution>
        <Title>State College University</Title>
        <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple"
         xlink:href="http://www.university.edu/" />
        <LogoURL width="100" height="100">
          <Format>image/gif</Format>
          <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
           xlink:type="simple"
           xlink:href="http://www.university.edu/icons/logo.gif" />
        </LogoURL>
      </Attribution>
      <!-- Identifier whose meaning is defined in an AuthorityURL element -->
      <Identifier authority="DIF_ID">123456</Identifier>
      <FeatureListURL>
        <Format>application/vnd.ogc.se_xml"</Format>
        <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple"
         xlink:href="http://www.university.edu/data/roads_rivers.gml" />
      </FeatureListURL>
      <Style>
        <Name>USGS</Name>
        <Title>USGS Topo Map Style</Title>
        <Abstract>Features are shown in a style like that used in USGS topographic maps.</Abstract>
        <!-- A picture of a legend for a Layer in this Style -->
        <LegendURL width="72" height="72">
          <Format>image/gif</Format>
          <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
           xlink:type="simple"
           xlink:href="http://www.university.edu/legends/usgs.gif" />
        </LegendURL>
        <!-- An XSL stylesheet describing how GML feature data will rendered to create
             a map of this layer. -->
        <StyleSheetURL>
          <Format>text/xsl</Format>
          <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
           xlink:type="simple"
           xlink:href="http://www.university.edu/stylesheets/usgs.xsl" />
        </StyleSheetURL>
      </Style>
      <ScaleHint min="4000" max="35000"></ScaleHint>
      <Layer queryable="1">
	<Name>ROADS_1M</Name>
	<Title>Roads at 1:1M scale</Title>
	<Abstract>Roads at a scale of 1 to 1 million.</Abstract>
	<KeywordList>
          <Keyword>road</Keyword>
          <Keyword>transportation</Keyword>
          <Keyword>atlas</Keyword>
	</KeywordList>
	<Identifier authority="DIF_ID">123456</Identifier>
        <!-- Metadata specific to this particular layer.  The same FGDC metadata is offered in two formats. -->
	<MetadataURL type="FGDC">
          <Format>text/plain</Format>
          <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
           xlink:type="simple"
           xlink:href="http://www.university.edu/metadata/roads.txt" />
        </MetadataURL>
	<MetadataURL type="FGDC">
           <Format>text/xml</Format>
           <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
            xlink:type="simple"
            xlink:href="http://www.university.edu/metadata/roads.xml" />
        </MetadataURL>
        <!-- In addition to the Style specified in the parent Layer, this Layer is available in this style. -->
	<Style>
	  <Name>ATLAS</Name>
	  <Title>Road atlas style</Title>
	  <Abstract>Roads are shown in a style like that used in a commercial road atlas.</Abstract>
        <LegendURL width="72" height="72">
          <Format>image/gif</Format>
          <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
           xlink:type="simple"
           xlink:href="http://www.university.edu/legends/atlas.gif" />
        </LegendURL>
	</Style>
      </Layer>
      <Layer queryable="1">
	<Name>RIVERS_1M</Name>
	<Title>Rivers at 1:1M scale</Title>
	<Abstract>Rivers at a scale of 1 to 1 million.</Abstract>
	<KeywordList>
          <Keyword>river</Keyword>
          <Keyword>canal</Keyword>
          <Keyword>waterway</Keyword>
	</KeywordList>
      </Layer>
    </Layer>
    <Layer queryable="1">
      <Title>Weather Forecast Data</Title>
      <SRS>EPSG:4326</SRS> <!-- harmless repetition of common SRS -->
      <LatLonBoundingBox minx="-180" miny="-90" maxx="180" maxy="90" />
      <!-- These weather data are available daily from 1999-01-01 through
           2000-08-22. -->
      <Dimension name="time" units="ISO8601" />
      <Extent name="time" default="2000-08-22">1999-01-01/2000-08-22/P1D</Extent>
      <Layer>
	<Name>Clouds</Name>
	<Title>Forecast cloud cover</Title>
      </Layer>
      <Layer>
	<Name>Temperature</Name>
	<Title>Forecast temperature</Title>
      </Layer>
      <Layer>
	<Name>Pressure</Name>
	<Title>Forecast barometric pressure</Title>
        <!-- Pressure is available at several elevations.
         EPSG:5030 is WGS 84 ellipsoid, units in metres.
         Pressure is also available at several times.
         NOTE: first list all Dimension elements, then all Extent elements. -->
         <Dimension name="time" units="ISO8601" />
         <Dimension name="elevation" units="EPSG:5030" />
         <Extent name="time" default="2000-08-22">1999-01-01/2000-08-22/P1D</Extent>
         <Extent name="elevation" default="0">0,1000,3000,5000,10000</Extent>
      </Layer>
    </Layer>
    <!-- Example of a layer which is a static map of fixed
         size which the server cannot subset or make transparent -->
    <Layer opaque="1" noSubsets="1" fixedWidth="512" fixedHeight="256">
      <Name>ozone_image</Name>
      <Title>Global ozone distribution (1992)</Title>
      <LatLonBoundingBox minx="-180" miny="-90" maxx="180" maxy="90" />
      <Extent name="time" default="1992">1992</Extent>
    </Layer>
    <!-- Example of a layer which originated from another WMS and has been
         "cascaded" by this WMS. -->
    <Layer cascaded="1">
      <Name>population</Name>
      <Title>World population, annual</Title>
      <LatLonBoundingBox minx="-180" miny="-90" maxx="180" maxy="90" />
      <Extent name="time" default="2000">1990/2000/P1Y</Extent>
    </Layer>
  </Layer>
</Capability>
</WMT_MS_Capabilities>


text:
package com.imaginea.activegrid.core.models

import com.imaginea.activegrid.core.utils.{ActiveGridUtils => AGU}
import com.typesafe.scalalogging.Logger
import eu.fakod.neo4jscala.{EmbeddedGraphDatabaseServiceProvider, Neo4jWrapper}
import org.neo4j.graphdb._
import org.slf4j.LoggerFactory

import scala.collection.JavaConversions._

// scalastyle:ignore underscore.import

/**
  * Created by babjik on 23/9/16.
  */

object Neo4jRepository extends Neo4jWrapper with EmbeddedGraphDatabaseServiceProvider {
  val logger = Logger(LoggerFactory.getLogger(getClass.getName))

  def neo4jStoreDir: String = AGU.DBPATH

  def hasLabel(node: Node, label: String): Boolean = {
    withTx {
      neo =>
        node.hasLabel(label)
    }
  }

  def getProperty[T: Manifest](node: Node, name: String): Option[T] = {
    withTx {
      neo =>
        if (node.hasProperty(name)) Some(node.getProperty(name).asInstanceOf[T]) else None
    }
  }

  def getSingleNodeByLabelAndProperty(label: String, propertyKey: String, propertyValue: Any): Option[Node] = withTx { implicit neo =>
    logger.debug(s"finding $label's with property $propertyKey and value $propertyValue")
    val nodesIterator = findNodesByLabelAndProperty(label, propertyKey, propertyValue)
    nodesIterator.headOption
  }
  def getNodesByLabelAndProperty(label: String, propertyKey: String, propertyValue: Any): List[Node] = withTx { implicit neo =>
    logger.debug(s"finding $label's with property $propertyKey and value $propertyValue")
    findNodesByLabelAndProperty(label, propertyKey, propertyValue).toList

  }

  def saveEntity[T <: BaseEntity](label: String, id: Option[Long], map: Map[String, Any]): Node = withTx { implicit neo =>
    val node = getOrSaveEntity(label, id)
    map.foreach { case (key, value) =>
      logger.debug(s"Setting property to $label[${node.getId}]  $key -> $value")
      value match {
        case None => if (node.hasProperty(key)) node.removeProperty(key)
        case Some(x) => node.setProperty(key, x)
        case _ => node.setProperty(key, value)
      }
    }
    node
  }

  def getOrSaveEntity(label: String, id: Option[Long]): Node = withTx { implicit neo =>
    id match {
      case Some(nodeId) =>
        logger.info(s"fetching node with Id $nodeId")
        val node = getNodeById(nodeId)
        logger.info(s"deleting relationships for Node : $nodeId")
        deleteRelationships(node, isStart = true)
        node
      case None =>
        logger.info(s"creating node with label $label")
        createNode(label)
    }
  }

  def getNodesByLabel(label: String): List[Node] = withTx { neo =>
    val list = getAllNodesWithLabel(label)(neo).toList
    logger.debug(s"Size of nodes with label : $label : ${list.size}")
    list
  }

  def getProperties(node: Node, keys: String*): Map[String, Any] = withTx { neo =>
    keys.foldLeft(Map[String, Any]())((accum, i) => if (node.hasProperty(i)) accum + ((i, node.getProperty(i))) else accum)
  }

  def deleteChildNode(nodeId: Long): Option[Boolean] = withTx { implicit neo =>

    // get realtion with parent  (incoming relations)
    // delete incoming
    // delete node
    logger.debug(s"trying to delete node with id $nodeId")
    val node = getNodeById(nodeId)
    val incomingRelations = getRelationships(node, Direction.INCOMING)
    incomingRelations.foreach(incomingRelation => {
      logger.debug(s"Deleting incoming relation $incomingRelation  -- ${incomingRelation.getType}")
      incomingRelation.delete()
    })

    deleteEntity(nodeId)
    Some(true)
  }

  def deleteEntity(nodeId: Long): Unit = withTx { implicit neo =>
    val mayBeNode = findNodeById(nodeId)
    mayBeNode match {
      case Some(node) =>
        val relations = getRelationships(node, Direction.OUTGOING)
        logger.debug(s"found relations for node $nodeId - relations $relations")

        relations.foreach(outRelation => {
          logger.debug(s"deleting out relation $outRelation  -- ${outRelation.getType}")
          outRelation.delete()
        })

        logger.debug(s"finally deleting node $node")
        node.delete()
      case None =>
        logger.warn(s"Node with id $nodeId doesnot exists")
    }

  }

  def getRelationships(node: Node, direction: Direction): List[Relationship] = withTx { implicit neo =>
    logger.debug(s"fetching realtions of $node in the direction $direction")
    node.getRelationships(direction).toList
  }

  def deleteRelation(instanceId: String, parentEntity: BaseEntity, relationName: String): ExecutionStatus = withTx {
    implicit neo =>
      parentEntity.id match {
        case Some(id) => val parent = getNodeById(id)
          //Fetching relations that maps instance to site
          val relationList = parent.getRelationships(Direction.OUTGOING).toList.filter(relation => relation.getType.name.equals(relationName))

          //Deleting insatnce node and relation.
          relationList.foreach {
            relation => val instanceNode = relation.getEndNode
              if (instanceNode.getId == instanceId) {
                instanceNode.delete()
                relation.delete()
              }
          }
          ExecutionStatus(true, s"Instace ${instanceId} from ${parentEntity.id} removed successfully")
        // If parent id invalid
        case _ => ExecutionStatus(false, s"Parent node ${parentEntity.id} not available")
      }
  }

  def findNodeByLabelAndId(label: String, id: Long): Option[Node] = withTx { implicit neo =>
    val mayBeNode = findNodeById(id)

    mayBeNode match {
      case Some(node) => if (node.hasLabel(label)) mayBeNode else None
      case None => None
    }
  }
  def updateNodeByLabelAndId[T<:BaseEntity](label: String, id: Long,props:Map[String,Any]): Unit =
    withTx
    {
      implicit neo => Neo4jRepository.findNodeByLabelAndId(label,id).foreach {
      node =>
        for ((prop,value) <- props) { node.setProperty(prop,value) }
    }
  }

  def createRelation(label: String, fromNode: Node, toNode: Node): Relationship = withTx { neo =>
    logger.info(s"Relation:  ($fromNode) --> $label --> ($toNode) <")
    val relType = DynamicRelationshipType.withName(label)
    val relation: Relationship = fromNode.createRelationshipTo(toNode, relType)
    logger.debug(s"New Relation is ${relation.getType} [${relation.getId}]")
    relation
  }

  def getNodesWithRelation(fromNode: Node, relationLabel: String): List[Node] = withTx { neo =>
    logger.debug(s"Checking for the child's of $fromNode  with relation $relationLabel")
    val relType = DynamicRelationshipType.withName(relationLabel)
    fromNode.getRelationships(relType, Direction.OUTGOING).map(rel => rel.getEndNode).toList
  }

  def setGraphRelationship(fromNode: Node, toNode: Node, relation: String): Unit = withTx { neo =>
    val relType = DynamicRelationshipType.withName(relation)
    logger.debug(s"setting relationship : $relation")
    fromNode --> relType --> toNode
    /*start --> relType --> end <
     start.getSingleRelationship(relType, Direction.OUTGOING)*/
  }

  def getChildNodeId(parentNode: Long, relation: String): Option[Long] = withTx { neo =>
    val node = getNodeById(parentNode)(neo)
    try {
      Some(node.getSingleRelationship(relation, Direction.OUTGOING).getEndNode.getId)
    }
    catch {
      case ex: Exception =>
        logger.debug(s"does not have relationship $relation")
        None
    }
  }

  def getChildNodeIds(parentNodeId: Long, relation: String): List[Long] = withTx { neo =>
    try {
      val node = getNodeById(parentNodeId)(neo)
      val list = node.getRelationships(relation, Direction.OUTGOING).map(rel => rel.getEndNode.getId).toList
      list
    }
    catch {
      case ex: Exception =>
        logger.debug(s"does not have node with NodeId $parentNodeId")
        List.empty[Long]
    }
  }

  def getNodeByProperty(label: String, propertyName: String, propertyVal: Any): Option[Node] = withTx { neo =>
    val nodes = findNodesByLabelAndProperty(label, propertyName, propertyVal)(neo)
    nodes.headOption
  }

  def deleteRelationship(parentNodeId: Long, childNodeId: Long, relationshipName: String): Boolean = {
    withTx { neo =>
      val mayBeParentNode = findNodeById(parentNodeId)
      mayBeParentNode match {
        case Some(parentNode) =>
          if (parentNode.hasRelationship(relationshipName)) {
            val relationships = parentNode.getRelationships(relationshipName, Direction.OUTGOING)
            val relationshipToDelete = relationships.find(relationship => relationship.getEndNode.getId == childNodeId)
            relationshipToDelete match {
              case Some(relationship) =>
                relationship.delete()
                true
              case None => false
            }
          } else {
            false
          }
        case None => false
      }
    }
  }

  def findNodeById(id: Long): Option[Node] = withTx { implicit neo =>
    try {
      Some(getNodeById(id))
    } catch {
      case e: NotFoundException =>
        logger.warn(s"node with Id $id is not found", e)
        None
    }
  }

  def deleteRelationships(node: Node, isStart: Boolean = false): Unit = {
    val outGoingRelations = getRelationships(node, Direction.OUTGOING)
    if (outGoingRelations.nonEmpty) {
      outGoingRelations.foreach {
        relation =>
          deleteRelationships(relation.getEndNode)
      }
    }
    val incomingRelations = getRelationships(node, Direction.INCOMING)
    incomingRelations.foreach(relation => relation.delete())
    if (!isStart) {
      node.delete()
    }
  }

  def createRelationship(childId: Long, parentId: Long, relation: String): Unit = {
    val childNode = findNodeById(childId)
    val parentNode = findNodeById(parentId)
    for {
      child <- childNode
      parent <- parentNode
    } yield {
      createRelation(relation, parent, child)
    }
  }
}