text:
package org.gogoup.utilities.misc;

import com.fasterxml.uuid.Generators;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.UUID;

public class ShortUUID {

    public static String HMAC_UUID_SHA1 = "HmacSHA1";
    public static String HMAC_UUID_SHA256 = "HmacSHA256";
    public static String HMAC_UUID_SHA512 = "HmacSHA512";

    public static String randomUUID() {
        try {
            String id = new String(Base64.encodeBytes(toByteArray(UUID.randomUUID()), Base64.URL_SAFE)).toLowerCase();
            return id.replace("=", "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static byte[] toByteArray(UUID uuid) {
        if (null == uuid) {
            return null;
        }
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());
        return bb.array();
    }

    public static String generateOrderedTimeBasedUUID() {
        UUID uuid = Generators.timeBasedGenerator().generate();
        String uuidString = uuid.toString();
        String orderedUUIDString = uuidString.substring(14, 18)
                + uuidString.substring(9, 13)
                + uuidString.substring(0, 8)
                + uuidString.substring(19, 23)
                + uuidString.substring(24);
        return orderedUUIDString;
    }

    public static byte[] convertHexStringToBytes(String s) {
        if (null == s) {
            return null;
        }
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    public static byte[] convertBase64StringToBytes(String str) {
        if (null == str) {
            return null;
        }
        try {
            return Base64.decode(str, Base64.URL_SAFE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String convertBytesToHexString(byte[] bytes) {
        if (null == bytes) {
            return null;
        }
        char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        char[] hexChars = new char[bytes.length * 2];
        int v;
        for ( int j = 0; j < bytes.length; j++ ) {
            v = bytes[j] & 0xFF;
            hexChars[j*2] = hexArray[v/16];
            hexChars[j*2 + 1] = hexArray[v%16];
        }
        return new String(hexChars);
    }

    public static String generateBase64HMACUUID() {
        return generateBase64HMACUUID(ShortUUID.HMAC_UUID_SHA1);
    }

    public static String generateBase64HMACUUID(String algorithm) {
        try {
            return Base64.encodeBytes(generateHMACUUID(algorithm), Base64.URL_SAFE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String generateHexHMACUUID() {
        return convertBytesToHexString(generateHMACUUID(ShortUUID.HMAC_UUID_SHA1));
    }

    public static String generateHexHMACUUID(String algorithm) {
        return convertBytesToHexString(generateHMACUUID(algorithm));
    }

    private static byte[] generateHMACUUID(String algorithm) {
        return generateHMACUUID(ShortUUID.randomUUID(), algorithm);
    }

    public static byte[] generateFixedHMACUUID(String data, String algorithm) {
        if (null == data) {
            return null;
        }
        return generateHMACUUID(data.getBytes(), data, algorithm);
    }

    public static byte[] generateHMACUUID(String data, String algorithm) {
        SecureRandom random = new SecureRandom();
        byte[] key = new byte[24];
        random.nextBytes(key);
        return generateHMACUUID(key, data, algorithm);
    }

    private static byte[] generateHMACUUID(byte[] key, String data, String algorithm) {
        if (null == data) {
            return null;
        }
        try {
            SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
            Mac mac = Mac.getInstance(algorithm);
            mac.init(secretKey);
            return mac.doFinal(data.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

}


text:
 #region License
 //  Copyright 2010-2011 J.W.Marsden
 //
 //    Licensed under the Apache License, Version 2.0 (the "License");
 //    you may not use this file except in compliance with the License.
 //    You may obtain a copy of the License at
 //
 //        http://www.apache.org/licenses/LICENSE-2.0
 //
 //    Unless required by applicable law or agreed to in writing, software
 //    distributed under the License is distributed on an "AS IS" BASIS,
 //    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 //    See the License for the specific language governing permissions and
 //    limitations under the License.
 #endregion

using System;
using Kinetic;

namespace Kinetic.Math
{
	public class Transformation
	{
		Vector3f translation;
		Vector3f scale;
		Matrix3f rotation;
		Matrix4f transformation;

		public Transformation ()
		{
			translation = new Vector3f(0,0,0);
			scale = new Vector3f(1,1,1);
			rotation = Matrix3f.Identity();
			transformation = Matrix4f.Identity();
		}

		public Vector3f Translation
		{
			get { return translation; }
			set { translation = value; }
		}

		public Vector3f Scale
		{
			get { return scale; }
			set { scale = value; }
		}

		public Matrix3f Rotation
		{
			get { return rotation; }
			set { rotation = value; }
		}

		public Matrix4f Combine() {
			transformation = Matrix4f.Identity();

			transformation.m00 = scale.x * rotation.m00;
			transformation.m01 = scale.y * rotation.m01;
			transformation.m02 = scale.z * rotation.m02;

			transformation.m10 = scale.x * rotation.m10;
			transformation.m11 = scale.y * rotation.m11;
			transformation.m12 = scale.z * rotation.m12;

			transformation.m20 = scale.x * rotation.m20;
			transformation.m21 = scale.y * rotation.m21;
			transformation.m22 = scale.z * rotation.m22;

			transformation.m30 = translation.x;
			transformation.m31 = translation.y;
			transformation.m32 = translation.z;

			return transformation;
		}

		public Transformation Concat(ref Transformation additionalTransform) {
			Transformation transformation = new Transformation();

			translation.Add(ref additionalTransform.translation, ref transformation.translation);

			transformation.scale.X = scale.X * additionalTransform.scale.X;
			transformation.scale.Y = scale.Y * additionalTransform.scale.Y;
			transformation.scale.Z = scale.Z * additionalTransform.scale.Z;

			rotation.Multiply(ref additionalTransform.rotation, ref transformation.rotation);

			return transformation;
		}

		public Transformation Concat(ref Transformation additionalTransform, ref Transformation transformation) {

			translation.Add(ref additionalTransform.translation, ref transformation.translation);

			transformation.scale.X = scale.X * additionalTransform.scale.X;
			transformation.scale.Y = scale.Y * additionalTransform.scale.Y;
			transformation.scale.Z = scale.Z * additionalTransform.scale.Z;

			rotation.Multiply(ref additionalTransform.rotation, ref transformation.rotation);

			return transformation;
		}

		public Transformation CopyTo(ref Transformation transformation)
		{
			transformation.translation.CopyTo(ref translation);
			transformation.rotation.CopyTo(ref rotation);
			transformation.scale.CopyTo(ref scale);
			return transformation;
		}

		public Transformation CopyFrom(ref Transformation transformation)
		{
			translation.CopyTo(ref transformation.translation);
			rotation.CopyTo(ref transformation.rotation);
			scale.CopyTo(ref transformation.scale);
			return transformation;
		}

		public static Matrix3f CreateXRotationMatrix3f(float angle) {
			Matrix3f rotation = Matrix3f.Identity();
			rotation.m11 = QuickMath.Cos(angle);
			rotation.m22 = rotation.m11;
			rotation.m12 = (float) QuickMath.Sin(angle);
			rotation.m21 = -rotation.m12;
			return rotation;
		}

		public static Matrix3f CreateYRotationMatrix3f(float angle) {
			Matrix3f rotation = Matrix3f.Identity();
			rotation.m00 = QuickMath.Cos(angle);
			rotation.m22 = rotation.m00;
			rotation.m20 = (float) QuickMath.Sin(angle);
			rotation.m02 = -rotation.m20;
			return rotation;
		}

		public static Matrix3f CreateZRotationMatrix3f(float angle) {
			Matrix3f rotation = Matrix3f.Identity();
			rotation.m00 = QuickMath.Cos(angle);
			rotation.m11 = rotation.m00;
			rotation.m01 = (float) QuickMath.Sin(angle);
			rotation.m10 = -rotation.m01;
			return rotation;
		}

		public static Matrix4f CreateXRotationMatrix4f(float angle) {
			Matrix4f rotation = Matrix4f.Identity();
			rotation.m11 = QuickMath.Cos(angle);
			rotation.m22 = rotation.m11;
			rotation.m12 = (float) QuickMath.Sin(angle);
			rotation.m21 = -rotation.m12;
			return rotation;
		}

		public static Matrix4f CreateYRotationMatrix4f(float angle) {
			Matrix4f rotation = Matrix4f.Identity();
			rotation.m00 = QuickMath.Cos(angle);
			rotation.m22 = rotation.m00;
			rotation.m20 = (float) QuickMath.Sin(angle);
			rotation.m02 = -rotation.m20;
			return rotation;
		}

		public static Matrix4f CreateZRotationMatrix4f(float angle) {
			Matrix4f rotation = Matrix4f.Identity();
			rotation.m00 = QuickMath.Cos(angle);
			rotation.m11 = rotation.m00;
			rotation.m01 = (float) QuickMath.Sin(angle);
			rotation.m10 = -rotation.m01;
			return rotation;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
require 'statsd'
require 'time'

module LogParserNotifier
  class RailsRequestNotifier
    def initialize(log_file, slow_request_threshold = 500)
      @log_reader = LogReader.new log_file
      @slow_request_threshold = slow_request_threshold
      puts @slow_request_threshold
    end

    def parser
      @parser ||= RequestLogAnalyzer::Source::LogParser.new(RequestLogAnalyzer::FileFormat::Rails3.create)
    end

    def statsd
      @statsd ||= Statsd.new('localhost', 8125)
    end

    def parse_and_trigger_notifications
      parser.parse_stream @log_reader.log_io do |request|
        tags = %W(controller:#{request[:controller]} action:#{request[:action]} con_act:#{request[:controller]}##{request[:action]})

        LogParserNotifier.logger.debug("processing request for #{request[:controller]}##{request[:action]} with status: #{request[:status]} it is complete: #{request.completed?}")
        if request.completed? && request[:status] >= 200 && request[:status] < 400
          statsd.increment 'rails.requests', tags: tags
          statsd.timing 'rails.load_time', request[:duration] * 1000, tags: tags

          if request[:duration] * 1000 >= @slow_request_threshold
            log = request.lines.collect { |line_hash| RailsRequestNotifier.render_line(line_hash) }.join("\n")
            statsd.event(
              "#{request[:controller]}##{request[:action]} #{request[:method]} slow request #{request[:duration]} sec",
              log,
              {
                date_happened: Time.parse(request[:timestamp].to_s).to_i.to_s,
                aggregation_key: 'slow_request_rails',
                source_type_name: 'rails_log',
                alert_type: 'warning',
                tags: tags
              }
            )
          end
        else
          statsd.increment 'rails.failed_requests', tags: tags
        end
      end
    end

    def self.render_line(line_hash)
      case line_hash[:line_type]
      when :started
        %Q(Started #{line_hash[:method]} "#{line_hash[:path]}" for #{line_hash[:ip]} at #{Time.parse(line_hash[:timestamp].to_s)})
      when :processing
        %Q(Processing by #{line_hash[:controller]}##{line_hash[:action]} as #{line_hash[:format]})
      when :parameters
        %Q(Parameters: #{line_hash[:params].inspect})
      when :rendered
        "  Rendered #{line_hash[:rendered_file]} (#{line_hash[:partial_duration]}ms)"
      when :completed
        "Completed #{line_hash[:status]} OK in #{(line_hash[:duration] * 1000).to_i}ms (Views: #{(line_hash[:view] || 0) * 1000}ms | ActiveRecord: #{(line_hash[:db] || 0) * 1000}ms)"
      else
        line_hash.inspect
      end
    end
  end
end


text:
//
//package com.googlecode.com.github.kronenpj.iqtimesheet.IQTimeSheet.test;
//
//import android.test.ActivityInstrumentationTestCase2;
//
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
//import com.googlecode.com.github.kronenpj.iqtimesheet.IQTimeSheet.TimeSheetActivity;
//import com.jayway.android.robotium.solo.Solo;
//
//public class TimeSheetActivityRobotium extends
//		ActivityInstrumentationTestCase2<TimeSheetActivity> {
//  	private Log log = LogFactory.getLog(TimeSheetActivityRobotium.class);
//		private static final String TAG = "TimeSheetActivityRobotium";
//
//	private Solo solo;
//
//	public TimeSheetActivityTest() {
//		super("com.googlecode.com.github.kronenpj.iqtimesheet.IQTimeSheet", TimeSheetActivity.class);
//	}
//
//	public void setUp() throws Exception {
//		solo = new Solo(getInstrumentation(), getActivity());
//	}
//
//	public void testTextIsSaved() throws Exception {
//
//		solo.clickOnText("Other");
//		solo.clickOnButton("Edit");
//		assertTrue(solo.searchText("Edit Window"));
//		solo.enterText(1, "Some text for testing purposes");
//		solo.clickOnButton("Save");
//		assertTrue(solo.searchText("Changes have been made successfully"));
//		solo.clickOnButton("Ok");
//		assertTrue(solo.searchText("Some text for testing purposes"));
//	}
//
//	@Override
//	public void tearDown() throws Exception {
//
//		try {
//			solo.finalize();
//		} catch (Throwable e) {
//
//			e.printStackTrace();
//		}
//		getActivity().finish();
//		super.tearDown();
//
//	}
//}
///*
// * public class TimeSheetActivityTest extends TestCase {
// *
// * @Before public void setUp() { backup(); sql("TimeSheetDB.db",
// * "DELETE FROM tasks; " + "INSERT INTO tasks (task, active, usage) " +
// * "VALUES ('Get some milk', 1, 50); " +
// * "INSERT INTO tasks (task, active, usage) " +
// * "VALUES ('Nap in the hammock', 1, 40, 0); " +
// * "INSERT INTO tasks (task, active, usage) " +
// * "VALUES ('Walk the allegator', 0, 30, 0);" +
// * "INSERT INTO tasks (task, active, usage) " +
// * "VALUES ('Feed the cat', 1, 20, 0);"); sql("TimeSheetDB.db",
// * "DELETE FROM timesheet; ");
// * startActivity("com.googlecode.com.github.kronenpj.iqtimesheet.IQTimeSheet",
// * "com.googlecode.com.github.kronenpj.iqtimesheet.IQTimeSheet.TimeSheetActivity"); pause(); }
// *
// * @After public void tearDown() { restore(); }
// *
// * // http://code.google.com/p/autoandroid/issues/detail?id=7
// *
// * @Ignore // Only so the test can be committed while working on something else
// *
// * @Test public void shouldSelectFirstNoteWithArrowKeysEvenAfterFinishAll() {
// * press(DOWN); finishAll(); startActivity("com.googlecode.com.github.kronenpj.iqtimesheet.IQTimeSheet",
// * "com.googlecode.com.github.kronenpj.iqtimesheet.IQTimeSheet.TimeSheetActivity"); pause(); press(DOWN);
// * assertEquals(0, intAt("selectedItemPosition")); }
// *
// * @Test public void verifyOrderOfEntries() { assertEquals("Get some milk",
// * stringAt("listView.0.text")); assertEquals("Nap in the hammock",
// * stringAt("listView.1.text")); assertEquals("Feed the cat",
// * stringAt("listView.2.text")); }
// *
// * @Test public void shouldChangeSelectionWithTheArrowKeys() { press(DOWN, DOWN,
// * DOWN, UP); int selectedItemPosition = intAt("selectedItemPosition");
// * assertEquals("Nap in the hammock", stringAt(format("listView.%d.text",
// * selectedItemPosition))); }
// *
// * // @Test // public void shouldSelectByTouchingAnEntry() { //
// * touch("listView.1"); // assertTrue(waitFor("class.simpleName", "NoteEditor",
// * 500)); // assertEquals("Nap in the hammock", stringAt("#note.text")); // }
// *
// * }
// */


text:
package shardserver

import (
	"fmt"
	"log"
	"time"

	"github.com/huin/chunkymonkey/chunkstore"
	"github.com/huin/chunkymonkey/entity"
	"github.com/huin/chunkymonkey/gamerules"
	. "github.com/huin/chunkymonkey/types"
)

const chunksPerShard = ShardSize * ShardSize

// TODO Allow configuration of this.
const ticksBetweenSaves = TicksPerSecond * 60

// chunkXzToChunkIndex assumes that locDelta is offset relative to the shard
// origin.
func chunkXzToChunkIndex(locDelta *ChunkXz) int {
	return int(locDelta.X)*ShardSize + int(locDelta.Z)
}

// ChunkShard represents a square shard of chunks that share a master
// goroutine.
type ChunkShard struct {
	shardConnecter   gamerules.IShardConnecter
	chunkStore       chunkstore.IChunkStore
	entityMgr        *entity.EntityManager
	loc              ShardXz
	originChunkLoc   ChunkXz // The lowest X and Z located chunk in the shard.
	chunks           [chunksPerShard]*Chunk
	requests         chan iShardRequest
	ticksSinceUpdate Ticks
	ticksSinceSave   Ticks
	saveChunks       bool

	newActiveBlocks []BlockXyz
	newActiveShards map[uint64]*destActiveShard

	shardClients map[uint64]gamerules.IShardShardClient
	selfClient   shardSelfClient
}

func NewChunkShard(shardConnecter gamerules.IShardConnecter, chunkStore chunkstore.IChunkStore, entityMgr *entity.EntityManager, loc ShardXz) (shard *ChunkShard) {
	shard = &ChunkShard{
		shardConnecter:   shardConnecter,
		chunkStore:       chunkStore,
		entityMgr:        entityMgr,
		loc:              loc,
		originChunkLoc:   loc.ToChunkXz(),
		requests:         make(chan iShardRequest, 256),
		ticksSinceUpdate: 0,
		saveChunks:       chunkStore.SupportsWrite(),

		// Offset shard saves.
		ticksSinceSave: (31 * Ticks(loc.Key())) % ticksBetweenSaves,

		newActiveShards: make(map[uint64]*destActiveShard),

		shardClients: make(map[uint64]gamerules.IShardShardClient),
	}

	shard.selfClient.shard = shard

	return
}

// serve services shard requests in the foreground.
func (shard *ChunkShard) serve() {
	ticker := time.NewTicker(NanosecondsInSecond / TicksPerSecond)

	for {
		select {
		case <-ticker.C:
			shard.tick()

		case request := <-shard.requests:
			request.perform(shard)
		}
	}
}

// tick runs the shard for a single tick.
func (shard *ChunkShard) tick() {
	shard.ticksSinceUpdate++

	for _, chunk := range shard.chunks {
		if chunk != nil {
			chunk.tick()
		}
	}

	if shard.ticksSinceUpdate >= TicksPerSecond {
		for _, chunk := range shard.chunks {
			if chunk != nil {
				chunk.sendUpdate()
			}
		}
		shard.ticksSinceUpdate = 0
	}

	if shard.saveChunks && shard.chunkStore.SupportsWrite() {
		shard.ticksSinceSave++
		if shard.ticksSinceSave > ticksBetweenSaves {
			log.Printf("%s: Writing chunks.", shard)
			// TODO Stagger the per-chunk saves over multiple ticks.
			for _, chunk := range shard.chunks {
				if chunk != nil {
					chunk.save(shard.chunkStore)
				}
			}
			shard.ticksSinceSave = 0
		}
	}

	shard.transferActiveBlocks()
}

// clientForShard is used to get a IShardShardClient for a given shard, reusing
// IShardShardClient connections for use within the shard. Returns nil if the
// shard does not exist.
func (shard *ChunkShard) clientForShard(shardLoc ShardXz) (client gamerules.IShardShardClient) {
	var ok bool

	if shard.loc.Equals(&shardLoc) {
		return &shard.selfClient
	}

	shardKey := shardLoc.Key()

	if client, ok = shard.shardClients[shardKey]; !ok {
		client = shard.shardConnecter.ShardShardConnect(shardLoc)
		if client != nil {
			shard.shardClients[shardKey] = client
		}
	}

	return
}

// blockQuery performs a relatively fast query of the BlockId at the given
// location. known=true if the returned blockTypeId is valid.
func (shard *ChunkShard) blockQuery(chunkLoc ChunkXz, subLoc *SubChunkXyz) (blockTypeId BlockId, known bool) {

	chunkIndex, _, _, ok := shard.chunkIndexAndRelLoc(chunkLoc)

	if !ok {
		// blockLoc is in another shard.
		// TODO Have a good fast case to deal with this.
		return
	}

	chunk := shard.chunks[chunkIndex]

	if chunk == nil {
		// Chunk not loaded. Don't bother to load it just for a block query.
		return
	}

	blockIndex, _ := subLoc.BlockIndex()
	blockTypeId = chunk.blockId(blockIndex)
	known = true

	return
}

// transferActiveBlocks takes blocks marked as newly active by addActiveBlock,
// and informs the chunk in the destination shards.
func (shard *ChunkShard) transferActiveBlocks() {
	if len(shard.newActiveBlocks) == 0 {
		return
	}

	thisShardKey := shard.loc.Key()
	for shardKey, activeShard := range shard.newActiveShards {
		if shardKey == thisShardKey {
			shard.reqSetBlocksActive(activeShard.blocks)
		} else {
			if client := shard.clientForShard(activeShard.loc); client != nil {
				client.ReqSetActiveBlocks(activeShard.blocks)
			}
		}
	}
}

// reqSetBlocksActive sets each block in the given slice to be active within
// the chunk. Note: if a block is within a different shard, it is discarded.
func (shard *ChunkShard) reqSetBlocksActive(blocks []BlockXyz) {
	for _, block := range blocks {
		chunkXz := block.ToChunkXz()
		chunkIndex, _, _, isThisShard := shard.chunkIndexAndRelLoc(*chunkXz)
		if isThisShard {
			chunk := shard.chunks[chunkIndex]
			if chunk == nil {
				continue
			}
			chunk.AddActiveBlock(&block)
		}
	}
}

// addActiveBlock sets the given block to be active on the next tick. This
// works even if the block is not within the shard - it will be made active
// provided that the chunk that the block is within is loaded.
func (shard *ChunkShard) addActiveBlock(block *BlockXyz) {
	chunkXz := block.ToChunkXz()
	shardXz := chunkXz.ToShardXz()
	shardKey := shardXz.Key()
	activeShard, ok := shard.newActiveShards[shardKey]
	if ok {
		activeShard = &destActiveShard{
			loc:    shardXz,
			blocks: []BlockXyz{*block},
		}
		shard.newActiveShards[shardKey] = activeShard
	} else {
		activeShard.blocks = append(activeShard.blocks, *block)
	}
}

func (shard *ChunkShard) String() string {
	return fmt.Sprintf("ChunkShard[%#v/%#v]", shard.loc, shard.originChunkLoc)
}

func (shard *ChunkShard) chunkIndexAndRelLoc(loc ChunkXz) (index int, x, z ChunkCoord, ok bool) {
	x = loc.X - shard.originChunkLoc.X
	z = loc.Z - shard.originChunkLoc.Z

	if x < 0 || z < 0 || x >= ShardSize || z >= ShardSize {
		return 0, 0, 0, false
	}

	ok = true

	index = int(x*ShardSize + z)

	return
}

// Get returns the Chunk at at given coordinates, loading it if it is not
// already loaded.
func (shard *ChunkShard) chunkAt(loc ChunkXz) *Chunk {
	chunkIndex, dx, dz, ok := shard.chunkIndexAndRelLoc(loc)
	if !ok {
		log.Printf("%v.Get(%#v): ChunkXz outside of shard", shard, loc)
		return nil
	}

	chunk := shard.chunks[chunkIndex]

	// Chunk already loaded.
	if chunk != nil {
		return chunk
	}

	chunk = shard.loadChunk(loc, ChunkXz{dx, dz})

	if chunk == nil {
		// No chunk available at that location. (Return nil explicitly - interfaces
		// containing nil pointer don't equal nil).
		return nil
	}

	shard.chunks[chunkIndex] = chunk

	return chunk
}

// loadChunk loads the specified chunk from store, and returns it.
// loc - The absolute world position of the chunk.
// locDelta - The relative position of the chunk within the shard.
func (shard *ChunkShard) loadChunk(loc ChunkXz, locDelta ChunkXz) *Chunk {
	chunkResult := <-shard.chunkStore.ReadChunk(loc)
	chunkReader, err := chunkResult.Reader, chunkResult.Err
	if err != nil {
		if _, ok := err.(chunkstore.NoSuchChunkError); !ok {
			log.Printf("%v.load(%#v): chunk loading error: %v", shard, loc, err)
			return nil
		} else {
			// Chunk doesn't exist in store.
			return nil
		}
	}

	chunk := newChunkFromReader(chunkReader, shard)

	return chunk
}

// enqueueAllChunks runs a given function on all loaded chunks in the shard.
func (shard *ChunkShard) enqueueAllChunks(fn func(chunk *Chunk)) {
	shard.requests <- &runOnAllChunks{fn}
}

// enqueueOnChunk runs a function on the chunk at the given location. If the
// chunk does not exist, it does nothing.
func (shard *ChunkShard) enqueueOnChunk(loc ChunkXz, fn func(chunk *Chunk)) {
	shard.requests <- &runOnChunk{loc, fn}
}

func (shard *ChunkShard) enqueue(fn func()) {
	shard.requests <- &runGeneric{fn}
}

func (shard *ChunkShard) enqueueRequest(req iShardRequest) {
	shard.requests <- req
}

type destActiveShard struct {
	loc    ShardXz
	blocks []BlockXyz
}

// shardSelfClient implements IShardShardClient for a shard to efficiently talk
// to itself.
type shardSelfClient struct {
	shard *ChunkShard
}

func (client *shardSelfClient) Disconnect() {
}

func (client *shardSelfClient) ReqSetActiveBlocks(blocks []BlockXyz) {
	client.shard.reqSetBlocksActive(blocks)
}

func (client *shardSelfClient) ReqTransferEntity(loc ChunkXz, entity gamerules.INonPlayerEntity) {
	chunk := client.shard.chunkAt(loc)
	if chunk != nil {
		chunk.transferEntity(entity)
	}
}


text:
/* Worker File - LazyLoad - source: http://toddmotto.com/echo-js-simple-javascript-image-lazy-loading/ */
var windowElement, documentEl;

self.addEventListener('message', function(e){
  windowElement = e.data.windowElement;
  documentEl = e.data.documentEl;
	self.postMessage(e.data.msg);
}, false);

windowElement.echo = (function (windowElement, documentEl) {

  'use strict';

  /*
   * Constructor function
   */
  var Echo = function (elem) {
    this.elem = elem;
    this.render();
    this.listen();
  };

  /*
   * Images for echoing
   */
  var echoStore = [];

  /*
   * Element in viewport logic
   */
  var scrolledIntoView = function (element) {
    var coords = element.getBoundingClientRect();
    return ((coords.top >= 0 && coords.left >= 0 && coords.top) <= (windowElement.innerHeight || documentEl.documentElement.clientHeight));
  };

  /*
   * Changing src attr logic
   */
  var echoSrc = function (img, callback) {
    img.src = img.getAttribute('data-echo');
    if (callback) {
      callback();
    }
  };

  /*
   * Remove loaded item from array
   */
  var removeEcho = function (element, index) {
    if (echoStore.indexOf(element) !== -1) {
      echoStore.splice(index, 1);
    }
  };

  /*
   * Echo the images and callbacks
   */
  var echoImages = function () {
    for (var i = 0; i < echoStore.length; i++) {
      var self = echoStore[i];
      if (scrolledIntoView(self)) {
        echoSrc(self, removeEcho(self, i));
      }
    }
  };

  /*
   * Prototypal setup
   */
  Echo.prototype = {
    init : function () {
      echoStore.push(this.elem);
    },
    render : function () {
      if (documentEl.addEventListener) {
        documentEl.addEventListener('DOMContentLoaded', echoImages, false);
      } else {
        windowElement.onload = echoImages;
      }
    },
    listen : function () {
      windowElement.onscroll = echoImages;
    }
  };

  /*
   * Initiate the plugin
   */
  var lazyImgs = documentEl.querySelectorAll('img[data-echo]');
  for (var i = 0; i < lazyImgs.length; i++) {
    new Echo(lazyImgs[i]).init();
  }

})(windowElement, documentEl);


text:
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace Mash.AppSettings.DevSettings
{
    /// <summary>
    /// A setting loader that gets individual developer-specific settings for effortless local debugging
    /// </summary>
    public class DevSettingLoader : ISettingLoader
    {
        private Dictionary<string, dynamic> _devSettings = new Dictionary<string, dynamic>();
        private Dictionary<string, string> _connectionStrings = new Dictionary<string, string>();

        /// <summary>
        /// The path to the developer's setting file
        /// </summary>
        public string DevSettingFile { get; private set; }

        /// <summary>
        /// Creates an instance of DevSettingLoader
        /// </summary>
        /// <param name="dir">The path to files holding developer-specific settings, defaults to current directory</param>
        /// <param name="fileName">The developer's file to load, defaults to %username%.json</param>
        public DevSettingLoader(string dir = null, string fileName = null)
        {
            if (String.IsNullOrEmpty(dir))
            {
                dir = Environment.CurrentDirectory;
            }

            string fileType = ".json";
            if (String.IsNullOrWhiteSpace(fileName))
            {
                fileName = $"{Environment.UserName}{fileType}";
            }

            if (!fileName.EndsWith(fileType))
            {
                throw new ArgumentException("Mash.AppSettings.DevSettingLoader: Only JSON files are valid.", nameof(fileName));
            }

            DevSettingFile = Path.Combine(dir, fileName);
            Trace.TraceInformation($"Mash.AppSettings.DevSettingLoader: using dev setting file [{DevSettingFile}]");

            string fileContents = "";
            try
            {
                fileContents = File.ReadAllText(DevSettingFile);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning($"Mash.AppSettings.DevSettingLoader: Failed to load file {DevSettingFile} due to {ex}");
            }

            LoadSettings(fileContents);
        }

        /// <summary>
        /// Creates an instance of DevSetingLoader
        /// </summary>
        /// <param name="json">The json holding developer-specific settings</param>
        public DevSettingLoader(string json)
        {
            LoadSettings(json);
        }

        /// <summary>
        /// Gets the specified connection string
        /// </summary>
        /// <param name="connectionStringKey">The name of the connection string</param>
        /// <returns>The connection string</returns>
        public string GetConnectionString(string connectionStringKey)
        {
            _connectionStrings.TryGetValue(connectionStringKey, out string result);

            return result;
        }

        /// <summary>
        /// Gets all connection strings
        /// </summary>
        /// <returns>A dictionary of all connection strings</returns>
        public IDictionary<string, string> GetConnectionStrings()
        {
            return _connectionStrings;
        }

        /// <summary>
        /// Gets the specified setting
        /// </summary>
        /// <param name="settingKey">The name of the setting</param>
        /// <returns>The string value of the setting</returns>
        public string GetSetting(string settingKey)
        {
            dynamic value;
            if (!_devSettings.TryGetValue(settingKey, out value))
            {
                return null;
            }

            return value.ToString();
        }

        private void LoadSettings(string json)
        {
            if (String.IsNullOrWhiteSpace(json))
            {
                return;
            }

            _devSettings = JsonSerializer.Deserialize<Dictionary<string, dynamic>>(json);

            dynamic connectionStrings;
            if (_devSettings.TryGetValue("ConnectionStrings", out connectionStrings))
            {
                _connectionStrings = JsonSerializer.Deserialize<Dictionary<string, string>>(connectionStrings.ToString());
            }
            else
            {
                _connectionStrings = new Dictionary<string, string>();
            }
        }
    }
}


text:
import {
    AfterViewInit,
    Component,
    Input,
    OnChanges,
    OnInit,
    Output,
    EventEmitter,
    ExistingProvider,
    ViewChild,
    ViewEncapsulation,
    forwardRef
} from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { STYLE } from './select.component.style';
import { SelectDropdownComponent } from './select-dropdown.component';
import { Option } from './option';
import { OptionList } from './option-list';

export const SELECT_VALUE_ACCESSOR: ExistingProvider = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => SelectComponent),
    multi: true
};

@Component({
    selector: 'ng-select',
    templateUrl: './select.component.html',
    styles: [STYLE],
    providers: [SELECT_VALUE_ACCESSOR],
    encapsulation: ViewEncapsulation.None
})

export class SelectComponent
    implements AfterViewInit, ControlValueAccessor, OnChanges, OnInit {
    /** Keys. **/

    private KEYS: any = {
        BACKSPACE: 8,
        TAB: 9,
        ENTER: 13,
        ESC: 27,
        SPACE: 32,
        UP: 38,
        DOWN: 40
    };

    @Input() options: Array<any>;

    @Input() allowClear: boolean = false;
    @Input() disabled: boolean = false;
    @Input() highlightColor: string = '#2196f3';
    @Input() highlightTextColor: string = '#fff';
    @Input() multiple: boolean = false;
    @Input() noFilter: number = 0;
    @Input() notFoundMsg: string = 'No results found';
    @Input() placeholder: string = '';

    @Output() opened: EventEmitter<null> = new EventEmitter<null>();
    @Output() closed: EventEmitter<null> = new EventEmitter<null>();
    @Output() selected: EventEmitter<any> = new EventEmitter<any>();
    @Output() deselected: EventEmitter<any> = new EventEmitter<any>();
    @Output() typed: EventEmitter<any> = new EventEmitter<any>();

    @ViewChild('selection') selectionSpan: any;
    @ViewChild('dropdown') dropdown: SelectDropdownComponent;
    @ViewChild('filterInput') filterInput: any;

    private _value: Array<any> = [];
    optionList: OptionList;

    // Selection state variables.
    hasSelected: boolean = false;

    // View state variables.
    filterEnabled: boolean = true;
    filterInputWidth: number = 1;
    hasFocus: boolean = false;
    isBelow: boolean = true;
    isDisabled: boolean = false;
    isOpen: boolean = false;
    placeholderView: string = '';

    clearClicked: boolean = false;
    selectContainerClicked: boolean = false;

    // Width and position for the dropdown container.
    width: number;
    top: number;
    left: number;

    private onChange = (_: any) => { };
    private onTouched = () => { };

    /** Event handlers. **/

    // Angular lifecycle hooks.

    ngOnInit() {
        this.placeholderView = this.placeholder;
    }

    ngAfterViewInit() {
        this.updateFilterWidth();
    }

    ngOnChanges(changes: any) {
        if (changes.hasOwnProperty('options')) {
            this.updateOptionsList(changes['options'].isFirstChange());
        }
        if (changes.hasOwnProperty('noFilter')) {
            let numOptions: number = this.optionList.options.length;
            let minNumOptions: number = changes['noFilter'].currentValue;
            this.filterEnabled = numOptions >= minNumOptions;
        }
    }

    // Window.

    onWindowClick() {
        if (!this.selectContainerClicked) {
            this.closeDropdown();
        }
        this.clearClicked = false;
        this.selectContainerClicked = false;
    }

    onWindowResize() {
        this.updateWidth();
    }

    // Select container.

    onSelectContainerClick(event: any) {
        this.selectContainerClicked = true;
        if (!this.clearClicked) {
            this.toggleDropdown();
        }
    }

    onSelectContainerFocus() {
        this.onTouched();
    }

    onSelectContainerKeydown(event: any) {
        this.handleSelectContainerKeydown(event);
    }

    // Dropdown container.

    onDropdownOptionClicked(option: Option) {
        this.multiple ?
            this.toggleSelectOption(option) : this.selectOption(option);
    }

    onDropdownClose(focus: any) {
        this.closeDropdown(focus);
    }

    // Single filter input.

    onSingleFilterClick() {
        this.selectContainerClicked = true;
    }

    onSingleFilterInput(term: string) {
        setTimeout(() => {
            if (term.length > 2) {
                this.typed.emit(term);
            }
        }, 500);
        this.optionList.filter(term);
    }

    onSingleFilterKeydown(event: any) {
        this.handleSingleFilterKeydown(event);
    }

    // Multiple filter input.

    onMultipleFilterInput(event: any) {
        if (!this.isOpen) {
            this.openDropdown();
        }
        this.updateFilterWidth();
        setTimeout(() => {
            this.optionList.filter(event.target.value);
        });
    }

    onMultipleFilterKeydown(event: any) {
        this.handleMultipleFilterKeydown(event);
    }

    // Single clear select.

    onClearSelectionClick(event: any) {
        this.clearClicked = true;
        this.clearSelection();
        this.closeDropdown(true);
    }

    // Multiple deselect option.

    onDeselectOptionClick(option: Option) {
        this.clearClicked = true;
        this.deselectOption(option);
    }

    /** API. **/

    // TODO fix issues with global click/key handler that closes the dropdown.
    open() {
        this.openDropdown();
    }

    close() {
        this.closeDropdown();
    }

    clear() {
        this.clearSelection();
    }

    select(value: string) {
        this.optionList.getOptionsByValue(value).forEach((option) => {
            this.selectOption(option);
        });
        this.valueChanged();
    }

    /** ControlValueAccessor interface methods. **/

    writeValue(value: any) {
        this.value = value;
    }

    registerOnChange(fn: (_: any) => void) {
        this.onChange = fn;
    }

    registerOnTouched(fn: () => void) {
        this.onTouched = fn;
    }

    setDisabledState(isDisabled: boolean) {
        this.disabled = isDisabled;
    }

    /** Value. **/

    get value(): any {
        if (this._value.length === 0) {
            return '';
        } else {
            return this.multiple ? this._value : this._value[0];
        }
    }

    set value(v: any) {
        if (typeof v === 'undefined' || v === null || v === '') {
            v = [];
        } else if (typeof v === 'string') {
            v = [v];
        } else if (!Array.isArray(v)) {
            throw new TypeError('Value must be a string or an array.');
        }

        if (!OptionList.equalValues(v, this._value)) {
            this.optionList.value = v;
            this.valueChanged();
        }
    }

    private valueChanged() {
        this._value = this.optionList.value;

        this.hasSelected = this._value.length > 0;
        this.placeholderView = this.hasSelected ? '' : this.placeholder;
        this.updateFilterWidth();

        this.onChange(this.value);
    }

    /** Initialization. **/

    private updateOptionsList(firstTime: boolean) {
        let v: Array<string>;

        if (!firstTime) {
            v = this.optionList.value;
        }

        this.optionList = new OptionList(this.options);

        if (!firstTime) {
            this.optionList.value = v;
            this.valueChanged();
        }
    }

    /** Dropdown. **/

    private toggleDropdown() {
        if (!this.isDisabled) {
            this.isOpen ? this.closeDropdown(true) : this.openDropdown();
        }
    }

    private openDropdown() {
        if (!this.isOpen) {
            this.updateWidth();
            this.updatePosition();
            this.isOpen = true;
            if (this.multiple && this.filterEnabled) {
                this.filterInput.nativeElement.focus();
            }
            this.opened.emit(null);
        }
    }
    /* tslint:disable */
    private closeDropdown(focus: boolean = false) {
        if (this.isOpen) {
            this.clearFilterInput();
            this.isOpen = false;
            if (focus) {
                this.focus();
            }
            this.closed.emit(null);
        }
    }
    /* tslint:enable */
    /** Select. **/

    private selectOption(option: Option) {
        if (!option.selected) {
            this.optionList.select(option, this.multiple);
            this.valueChanged();
            this.selected.emit(option.undecoratedCopy());
            // Is this not allready done when setting the value??
            /*setTimeout(() => {
                if (this.multiple) {
                    this.updateFilterWidth();
                }
            });*/
        }
    }

    private deselectOption(option: Option) {
        if (option.selected) {
            this.optionList.deselect(option);
            this.valueChanged();
            this.deselected.emit(option.undecoratedCopy());
            setTimeout(() => {
                if (this.multiple) {
                    // this.updateFilterWidth();
                    this.updatePosition();
                    this.optionList.highlight();
                    if (this.isOpen) {
                        this.dropdown.moveHighlightedIntoView();
                    }
                }
            });
        }
    }

    private clearSelection() {
        let selection: Array<Option> = this.optionList.selection;
        if (selection.length > 0) {
            this.optionList.clearSelection();
            this.valueChanged();

            if (selection.length === 1) {
                this.deselected.emit(selection[0].undecoratedCopy());
            } else {
                this.deselected.emit(selection.map((option) => {
                    return option.undecoratedCopy();
                }));
            }
        }
    }

    private toggleSelectOption(option: Option) {
        option.selected ?
            this.deselectOption(option) : this.selectOption(option);
    }

    private selectHighlightedOption() {
        let option: Option = this.optionList.highlightedOption;
        if (option !== null) {
            this.selectOption(option);
            this.closeDropdown(true);
        }
    }

    private deselectLast() {
        let sel: Array<Option> = this.optionList.selection;

        if (sel.length > 0) {
            let option: Option = sel[sel.length - 1];
            this.deselectOption(option);
            this.setMultipleFilterInput(option.label + ' ');
        }
    }

    /** Filter. **/

    private clearFilterInput() {
        if (this.multiple && this.filterEnabled) {
            this.filterInput.nativeElement.value = '';
        } else {
            this.dropdown.clearFilterInput();
        }
    }

    private setMultipleFilterInput(value: string) {
        if (this.filterEnabled) {
            this.filterInput.nativeElement.value = value;
        }
    }

    private handleSelectContainerKeydown(event: any) {
        let key = event.which;

        if (this.isOpen) {
            if (key === this.KEYS.ESC ||
                (key === this.KEYS.UP && event.altKey)) {
                this.closeDropdown(true);
            } else if (key === this.KEYS.TAB) {
                this.closeDropdown();
            } else if (key === this.KEYS.ENTER) {
                this.selectHighlightedOption();
            } else if (key === this.KEYS.UP) {
                this.optionList.highlightPreviousOption();
                this.dropdown.moveHighlightedIntoView();
                if (!this.filterEnabled) {
                    event.preventDefault();
                }
            } else if (key === this.KEYS.DOWN) {
                this.optionList.highlightNextOption();
                this.dropdown.moveHighlightedIntoView();
                if (!this.filterEnabled) {
                    event.preventDefault();
                }
            }
        } else {
            if (key === this.KEYS.ENTER || key === this.KEYS.SPACE ||
                (key === this.KEYS.DOWN && event.altKey)) {

                /* FIREFOX HACK:
                 *
                 * The setTimeout is added to prevent the enter keydown event
                 * to be triggered for the filter input field, which causes
                 * the dropdown to be closed again.
                 */
                setTimeout(() => { this.openDropdown(); });
            }
        }

    }

    private handleMultipleFilterKeydown(event: any) {
        let key = event.which;

        if (key === this.KEYS.BACKSPACE) {
            if (this.hasSelected && this.filterEnabled &&
                this.filterInput.nativeElement.value === '') {
                this.deselectLast();
            }
        }
    }

    private handleSingleFilterKeydown(event: any) {
        let key = event.which;

        if (key === this.KEYS.ESC || key === this.KEYS.TAB
            || key === this.KEYS.UP || key === this.KEYS.DOWN
            || key === this.KEYS.ENTER) {
            this.handleSelectContainerKeydown(event);
        }
    }

    /** View. **/

    focus() {
        this.hasFocus = true;
        if (this.multiple && this.filterEnabled) {
            this.filterInput.nativeElement.focus();
        } else {
            this.selectionSpan.nativeElement.focus();
        }
    }

    blur() {
        this.hasFocus = false;
        this.selectionSpan.nativeElement.blur();
    }

    updateWidth() {
        this.width = this.selectionSpan.nativeElement.offsetWidth;
    }

    updatePosition() {
        let e = this.selectionSpan.nativeElement;
        this.left = e.offsetLeft;
        this.top = e.offsetTop + e.offsetHeight;
    }

    updateFilterWidth() {
        if (typeof this.filterInput !== 'undefined') {
            let value: string = this.filterInput.nativeElement.value;
            this.filterInputWidth = value.length === 0 ?
                1 + this.placeholderView.length * 10 : 1 + value.length * 10;
        }
    }
}


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

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="task" name="DC.Type" />
<meta name="DC.Title" content="Shutting down by using the API" />
<meta name="abstract" content="You can use the NetworkServerControl API to shut down the Network Server from within a Java application." />
<meta name="description" content="You can use the NetworkServerControl API to shut down the Network Server from within a Java application." />
<meta content="Network Server, shutting down using the API" name="DC.subject" />
<meta content="Network Server, shutting down using the API" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="tadminconfigshuttingdownthenetworkserver.html" />
<meta scheme="URI" name="DC.Relation" content="tadminconfig815333.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="tadminconfig815357" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Shutting down by using the API</title>

Shutting down by using the API

You can use the NetworkServerControl API to shut down the Network
Server from within a Java application.

The name of the method that you use to shut down the Network Server
is <samp class="codeph">shutdown()</samp>.

For example, the following command shuts down the Network Server
running on the current machine using the default port number (1527):

NetworkServerControl server = new NetworkServerControl();
server.shutdown();

To shut down a server running with user authentication, you need to use
a NetworkServerControl instance created with user credentials:

NetworkServerControl server = new NetworkServerControl(username, password);
server.shutdown();

Parent topic: Shutting down the Network Server

Related tasks

Shutting down by using the command line


text:
#import "NSString.h"

@interface NSString (ADEmbeddedAdServerStringAdditions)
- (id)md5;
@end


text:
<?php

class Google_Service_Dfareporting_OperatingSystemsListResponse extends Google_Collection
{
  protected $collection_key = 'operatingSystems';
  public $kind;
  protected $operatingSystemsType = 'Google_Service_Dfareporting_OperatingSystem';
  protected $operatingSystemsDataType = 'array';

  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  public function setOperatingSystems($operatingSystems)
  {
    $this->operatingSystems = $operatingSystems;
  }
  public function getOperatingSystems()
  {
    return $this->operatingSystems;
  }
}


text:
import React, { Component } from 'react';
import { Container } from '@extjs/ext-react';
import { Cartesian } from '@extjs/ext-react-charts';
import ChartToolbar from '../../ChartToolbar';
import storeData from './storeData';

export default class Spline extends Component {

    store = Ext.create('Ext.data.Store', {
        fields: ['theta', 'sin', 'cos', 'tan'],
        data: storeData
    })

    state = {
        theme: 'default'
    }

    changeTheme = theme => this.setState({ theme })

    render() {
        const { theme } = this.state;

        return (
            <Container padding={!Ext.os.is.Phone && 10} layout="fit">
                <ChartToolbar onThemeChange={this.changeTheme} theme={theme}/>
                <Cartesian
                    shadow
                    store={this.store}
                    theme={theme}
                    insetPadding="20 20 0 0"
                    axes={[{
                        type: 'numeric',
                        position: 'left',
                        title: 'Sin (Theta)',
                        grid: true,
                        fields: 'sin',
                        label: {
                            renderer: (axis, label) => Ext.util.Format.number(label, '0.00')
                        }
                    }, {
                        type: 'numeric',
                        position: 'bottom',
                        title: 'Theta',
                        grid: true,
                        fields: 'theta',
                        label: {
                            textPadding: 0,
                            rotate: {
                                degrees: -45
                            }
                        }
                    }]}
                    series={[{
                        type: 'line',
                        xField: 'theta',
                        yField: 'sin',
                        smooth: true,
                        highlight: true,
                        showMarkers: false
                    }]}
                />
            </Container>
        )
    }
}


text:
package com.squareup.javapoet;

import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Modifier;

import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import static com.squareup.javapoet.Util.checkState;

/** A generated constructor or method declaration. */
public final class MethodSpec {
  static final String CONSTRUCTOR = "<init>";

  public final String name;
  public final CodeBlock javadoc;
  public final List<AnnotationSpec> annotations;
  public final Set<Modifier> modifiers;
  public final List<TypeVariableName> typeVariables;
  public final TypeName returnType;
  public final List<ParameterSpec> parameters;
  public final boolean varargs;
  public final List<TypeName> exceptions;
  public final CodeBlock code;

  private MethodSpec(Builder builder) {
    CodeBlock code = builder.code.build();
    checkArgument(code.isEmpty() || !builder.modifiers.contains(Modifier.ABSTRACT),
        "abstract method %s cannot have code", builder.name);
    checkArgument(!builder.varargs || lastParameterIsArray(builder.parameters),
        "last parameter of varargs method %s must be an array", builder.name);

    this.name = checkNotNull(builder.name, "name == null");
    this.javadoc = builder.javadoc.build();
    this.annotations = Util.immutableList(builder.annotations);
    this.modifiers = Util.immutableSet(builder.modifiers);
    this.typeVariables = Util.immutableList(builder.typeVariables);
    this.returnType = builder.returnType;
    this.parameters = Util.immutableList(builder.parameters);
    this.varargs = builder.varargs;
    this.exceptions = Util.immutableList(builder.exceptions);
    this.code = code;
  }

  private boolean lastParameterIsArray(List<ParameterSpec> parameters) {
    return !parameters.isEmpty()
        && TypeName.arrayComponent(parameters.get(parameters.size() - 1).type) != null;
  }

  void emit(CodeWriter codeWriter, String enclosingName, Set<Modifier> implicitModifiers)
      throws IOException {
    codeWriter.emitJavadoc(javadoc);
    codeWriter.emitAnnotations(annotations, false);
    codeWriter.emitModifiers(modifiers, implicitModifiers);

    if (!typeVariables.isEmpty()) {
      codeWriter.emitTypeVariables(typeVariables);
      codeWriter.emit(" ");
    }

    if (isConstructor()) {
      codeWriter.emit("$L(", enclosingName);
    } else {
      codeWriter.emit("$T $L(", returnType, name);
    }

    boolean firstParameter = true;
    for (Iterator<ParameterSpec> i = parameters.iterator(); i.hasNext();) {
      ParameterSpec parameter = i.next();
      if (!firstParameter) codeWriter.emit(", ");
      parameter.emit(codeWriter, !i.hasNext() && varargs);
      firstParameter = false;
    }

    codeWriter.emit(")");
    if (!exceptions.isEmpty()) {
      codeWriter.emit(" throws");
      boolean firstException = true;
      for (TypeName exception : exceptions) {
        if (!firstException) codeWriter.emit(",");
        codeWriter.emit(" $T", exception);
        firstException = false;
      }
    }

    if (hasModifier(Modifier.ABSTRACT)) {
      codeWriter.emit(";\n");
    } else if (hasModifier(Modifier.NATIVE)) {
      // Code is allowed to support stuff like GWT JSNI.
      codeWriter.emit(code);
      codeWriter.emit(";\n");
    } else {
      codeWriter.emit(" {\n");

      codeWriter.indent();
      codeWriter.emit(code);
      codeWriter.unindent();

      codeWriter.emit("}\n");
    }
  }

  public boolean hasModifier(Modifier modifier) {
    return modifiers.contains(modifier);
  }

  public boolean isConstructor() {
    return name.equals(CONSTRUCTOR);
  }

  @Override public String toString() {
    StringWriter out = new StringWriter();
    try {
      CodeWriter codeWriter = new CodeWriter(out);
      emit(codeWriter, "Constructor", Collections.<Modifier>emptySet());
      return out.toString();
    } catch (IOException e) {
      throw new AssertionError();
    }
  }

  public static Builder methodBuilder(String name) {
    return new Builder(name);
  }

  public static Builder constructorBuilder() {
    return new Builder(CONSTRUCTOR);
  }

  public static final class Builder {
    private final String name;

    private final CodeBlock.Builder javadoc = CodeBlock.builder();
    private final List<AnnotationSpec> annotations = new ArrayList<>();
    private final List<Modifier> modifiers = new ArrayList<>();
    private List<TypeVariableName> typeVariables = new ArrayList<>();
    private TypeName returnType;
    private final List<ParameterSpec> parameters = new ArrayList<>();
    private final List<TypeName> exceptions = new ArrayList<>();
    private final CodeBlock.Builder code = CodeBlock.builder();
    private boolean varargs;

    private Builder(String name) {
      checkArgument(name.equals(CONSTRUCTOR) || SourceVersion.isName(name),
          "not a valid name: %s", name);
      this.name = name;
      this.returnType = name.equals(CONSTRUCTOR) ? null : TypeName.VOID;
    }

    public Builder addJavadoc(String format, Object... args) {
      javadoc.add(format, args);
      return this;
    }

    public Builder addAnnotations(Collection<AnnotationSpec> annotationSpecs) {
      checkArgument(annotationSpecs != null, "annotationSpecs == null");
      this.annotations.addAll(annotationSpecs);
      return this;
    }

    public Builder addAnnotation(AnnotationSpec annotationSpec) {
      this.annotations.add(annotationSpec);
      return this;
    }

    public Builder addAnnotation(ClassName annotation) {
      this.annotations.add(AnnotationSpec.builder(annotation).build());
      return this;
    }

    public Builder addAnnotation(Class<?> annotation) {
      return addAnnotation(ClassName.get(annotation));
    }

    public Builder addModifiers(Modifier... modifiers) {
      Collections.addAll(this.modifiers, modifiers);
      return this;
    }

    public Builder addTypeVariables(Collection<TypeVariableName> typeVariables) {
      checkArgument(typeVariables != null, "typeVariables == null");
      this.typeVariables.addAll(typeVariables);
      return this;
    }

    public Builder addTypeVariable(TypeVariableName typeVariable) {
      typeVariables.add(typeVariable);
      return this;
    }

    public Builder returns(TypeName returnType) {
      checkState(!name.equals(CONSTRUCTOR), "constructor cannot have return type.");
      this.returnType = returnType;
      return this;
    }

    public Builder returns(Type returnType) {
      return returns(TypeName.get(returnType));
    }

    public Builder addParameters(Collection<ParameterSpec> parameterSpecs) {
      checkArgument(parameterSpecs != null, "parameterSpecs == null");
      this.parameters.addAll(parameterSpecs);
      return this;
    }

    public Builder addParameter(ParameterSpec parameterSpec) {
      this.parameters.add(parameterSpec);
      return this;
    }

    public Builder addParameter(TypeName type, String name, Modifier... modifiers) {
      return addParameter(ParameterSpec.builder(type, name, modifiers).build());
    }

    public Builder addParameter(Type type, String name, Modifier... modifiers) {
      return addParameter(TypeName.get(type), name, modifiers);
    }

    public Builder varargs() {
      this.varargs = true;
      return this;
    }

    public Builder addExceptions(Collection<TypeName> exceptions) {
      checkArgument(exceptions != null, "exceptions == null");
      this.exceptions.addAll(exceptions);
      return this;
    }

    public Builder addException(TypeName exception) {
      this.exceptions.add(exception);
      return this;
    }

    public Builder addException(Type exception) {
      return addException(TypeName.get(exception));
    }

    public Builder addCode(String format, Object... args) {
      code.add(format, args);
      return this;
    }

    public Builder addCode(CodeBlock codeBlock) {
      code.add(codeBlock);
      return this;
    }

    /**
     * @param controlFlow the control flow construct and its code, such as "if (foo == 5)".
     * Shouldn't contain braces or newline characters.
     */
    public Builder beginControlFlow(String controlFlow, Object... args) {
      code.beginControlFlow(controlFlow, args);
      return this;
    }

    /**
     * @param controlFlow the control flow construct and its code, such as "else if (foo == 10)".
     *     Shouldn't contain braces or newline characters.
     */
    public Builder nextControlFlow(String controlFlow, Object... args) {
      code.nextControlFlow(controlFlow, args);
      return this;
    }

    public Builder endControlFlow() {
      code.endControlFlow();
      return this;
    }

    /**
     * @param controlFlow the optional control flow construct and its code, such as
     *     "while(foo == 20)". Only used for "do/while" control flows.
     */
    public Builder endControlFlow(String controlFlow, Object... args) {
      code.endControlFlow(controlFlow, args);
      return this;
    }

    public Builder addStatement(String format, Object... args) {
      code.addStatement(format, args);
      return this;
    }

    public MethodSpec build() {
      return new MethodSpec(this);
    }
  }
}


text:
require 'active_record'

module PronosticosDashboard
  class Sale < ActiveRecord::Base

    has_many :games

    validates_presence_of [:agency, :date]

    def self.monthly_totals
      group("to_char(date, 'YYYY-MM'), agency").
        select("agency, sum(to_pay_total) AS tpt, sum(commission) AS c,to_char(date, 'YYYY-MM') as dd")
    end

    def self.with_games_counts(dates_range)
      select('sales.id, sales.date, sales.agency, count(games.id) as games_count, sum(games.units) as total_game_units, sum(games.total) as total_game_amount').
        where('sales' => dates_range).
        joins('left outer join games on sales.id = games.sale_id').
        group('sales.id, sales.date, sales.agency')
    end

    def complete?
      games_count = self.attributes['games_count'] || games.count
      total_game_units = self.attributes['total_game_units'] || games.sum('units')
      total_game_amount = self.attributes['total_game_amount'] || games.sum('total')
      games_count == 12 && total_game_units > 0 && total_game_amount > 0
    end

  end

  class Game < ActiveRecord::Base

    belongs_to :sale

  end
end


text:
var bookmarks;

function initialize(tab) {
  if (tab) {
    var tabId = tab.id;
    chrome.browserAction.enable();
    chrome.browserAction.setBadgeText({'tabId':tabId, 'text':""+tabId});
    chrome.browserAction.setPopup({'tabId':tabId, 'popup':"./html/popup.html"});
  }
  chrome.bookmarks.getTree(function(tree) {
    bookmarks = tree;
  });
}

document.addEventListener("DOMContentLoaded", function(event) {
    chrome.tabs.onUpdated.addListener(
      function(tabId, changeInfo, tab) {
        if (changeInfo.status === 'complete') {
          chrome.tabs.query({currentWindow:true, active:true},
                            function(tabs) {
                              initialize(tabs[0]);
                            });
        }
      });
    chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        if (request.type == "hide") {
          chrome.sidebar.hide();
          sendResponse("OK");
        } else if (request.type == "bookmarks") {
          sendResponse(bookmarks);
        } else if (request.type == "navigate") {
          chrome.tabs.update({url: request.url});
          sendResponse("OK");
        }
      });

  });


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_agreement"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    android:clipToPadding="true"
    android:fitsSystemWindows="true"
    tools:context="tv.baokan.baokanandroid.ui.activity.AgreementActivity">

    <!--导航栏-->
    <tv.baokan.baokanandroid.widget.NavigationViewRed
        android:id="@+id/nav_agreement"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </tv.baokan.baokanandroid.widget.NavigationViewRed>

    <WebView
        android:id="@+id/wv_agreement_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/nav_agreement"
        android:overScrollMode="never">
    </WebView>

    <!--进度圈-->
    <ProgressBar
        android:id="@+id/pb_agreement_progressbar"
        style="@android:style/Widget.ProgressBar"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_marginTop="100dp"
        android:indeterminateDrawable="@anim/progressbar_rotate"/>

</RelativeLayout>


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/furniture/tatooine/shared_frn_tatt_cantina_droid_detector.iff"
	result.attribute_template_id = 6
	result.stfName("frn_n","frn_droid_detector")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
package oj.leetcode.list.merge2;

import static org.junit.Assert.*;

import org.junit.Test;

public class KSortedListMergeTest {

	private final KSortedListMerge inst = new KSortedListMerge();

	@Test
	public void test() {
	}

}


text:
<testSuite>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Print both cases">
<rule context="AAA">
<assert test="BBB">BBB element is missing.</assert>
<report test="BBB">BBB element is present.</report>

<assert test="@name">AAA misses attribute name.</assert>
<report test="@name">AAA contains attribute name.</report>
</rule>
</pattern>

<pattern name="Print positive result only">
<rule context="AAA">
<report test="BBB">BBB element is present.</report>
<report test="@name">AAA contains attribute name.</report>
</rule>
</pattern>

<pattern name="Print negative result only">
<rule context="AAA">
<assert test="BBB">BBB element is missing.</assert>
<assert test="@name">AAA misses attribute name.</assert>
</rule>
</pattern>
</schema>
</correct>
<invalid>

<AAA>
	<BBB/>
</AAA>
</invalid>
<invalid>

<AAA>
	<CCC/>
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Open model">
<rule context="AAA">
<assert test="BBB"> BBB element is not present</assert>
<assert test="CCC"> CCC element is not present</assert>
</rule>
</pattern>

<pattern name="Closed model">
<rule context="AAA">
<assert test="BBB"> BBB element is not present</assert>
<assert test="CCC"> CCC element is not present</assert>
<assert test="count(BBB|CCC) = count (*)">There is an extra element</assert>
</rule>
</pattern>

</schema></correct>
<invalid>

<AAA>
	<BBB/>
</AAA>
</invalid>
<invalid>

<AAA>
	<BBB/>
	<DDD/>
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Attribute test">
<rule context="CCC">
<assert test="@name">attribute name is not present</assert>
<report test="@name">attribute name is present</report>
</rule>
</pattern>
</schema></correct>
<invalid>

<AAA>
	<BBB>
		<CCC/>
		<CCC/>
	</BBB>
	<CCC name="c1"/>
	<CCC name="c2"/>
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Root test">
<rule context="/*">
<assert test="name()='AAA'">Root element is <name/>, not AAA</assert>
<report test="name()='AAA'">Root element is AAA</report>
</rule>
</pattern>
</schema></correct>
<invalid>

<AAA>
	<BBB>
		<CCC/>
		<CCC/>
	</BBB>
</AAA>
</invalid>
<invalid>

<XXX>
	<BBB>
		<CCC/>
		<CCC/>
	</BBB>
</XXX>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Select empty elements CCC">
<rule context="CCC">
<assert test="normalize-space(.) and *">Source contains an empty element CCC </assert>

<report test="normalize-space(.) = ''">[1]An element CCC  does not contain any text</report>
<assert test="normalize-space(.)">[2]An element CCC  does not contain any text</assert>

<report test="not(*)">[1]An element CCC  does not contain any child element</report>
<assert test="*">[2]An element CCC  does not contain any child element</assert>
</rule>
</pattern>
</schema></correct>
<invalid>

<AAA>
	<BBB>
		<CCC/>
	</BBB>
</AAA>
</invalid>
<invalid>

<AAA>
	<BBB>
		<CCC>I am CCC element</CCC>
	</BBB>
</AAA>
</invalid>
<invalid>

<AAA>
	<BBB>
		<CCC>
			<DDD/>
		</CCC>
	</BBB>
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Predefined values">
<rule context="AAA">
<report test="normalize-space(.) = 'aaa' or normalize-space(.) = 'bbb'">O.K.</report>
<assert test="normalize-space(.) = 'aaa' or normalize-space(.) = 'bbb'">The AAA value is not permitted.</assert>
</rule>
</pattern>
</schema></correct>
<invalid>

<AAA>
aaa
</AAA>
</invalid>
<invalid>

<AAA>
		bbb
</AAA>
</invalid>
<invalid>

<AAA>
  ccc
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Test integer">
<rule context="AAA">
<report test="floor(.) = number(.)">O.K.</report>
<assert test="floor(.) = number(.)">The AAA value is not an integer.</assert>
</rule>
</pattern>
</schema></correct>
<invalid>

<AAA>
aaa
</AAA>
</invalid>
<invalid>

<AAA>
 12.234
</AAA>
</invalid>
<invalid>

<AAA>
45
</AAA>
</invalid>
<invalid>

<AAA>
0
</AAA>
</invalid>
<invalid>

<AAA>
-45
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Test count">
<rule context="/*">
<report test="count(//BBB) = count(//AAA)">O.K.</report>
<assert test="count(//BBB) <= count(//AAA)">Some AAA are missing</assert>
<report test="count(//BBB) < count(//AAA)">Some BBB are missing</report>
</rule>
</pattern>
</schema></correct>
<invalid>

<XXX>
	<BBB/>
	<BBB/>
	<AAA/>
	<BBB/>
	<AAA/>
	<AAA/>
</XXX>
</invalid>
<invalid>

<XXX>
	<BBB/>
	<AAA/>
	<BBB/>
	<AAA/>
	<AAA/>
</XXX>
</invalid>
<invalid>

<XXX>
	<BBB/>
	<BBB/>
	<AAA/>
	<BBB/>
	<AAA/>
</XXX>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Test attribute">
<rule context="CCC">
<report test="parent::BBB and not(@id)">Attribute id is missing</report>
<report test="not(parent::BBB) and @id">Attribute id is used in wrong context</report>
</rule>
</pattern>
</schema></correct>
<valid>

<AAA>
	<CCC/>
	<CCC/>
	<BBB>
		<CCC id="Q1"/>
	</BBB>
</AAA>
</valid>
<invalid>

<AAA>
	<CCC id="Q2"/>
	<CCC/>
	<BBB>
		<CCC id="Q1"/>
	</BBB>
</AAA>
</invalid>
<invalid>

<AAA>
	<CCC/>
	<CCC/>
	<BBB>
		<CCC/>
	</BBB>
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Character @ forbidden">
<rule context="*">
<report test="contains(.,'@')">Text in element <name/> must not contain character @</report>
</rule>
</pattern>
</schema></correct>
<valid>

<AAA>
	<BBB>bbbb</BBB>
	<CCC>cccc</CCC>
</AAA>
</valid>
<invalid>

<AAA>
	<BBB>bbbb@bbb.com</BBB>
	<CCC>ccc@ccc.com</CCC>
</AAA>
</invalid>
<invalid>

<AAA>
	<BBB>bbbb</BBB>
	<CCC>cccc</CCC>
	aaa@aaa.net
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Attributes present">
<rule context="BBB">
<assert test="not(@aaa) or (@aaa and @bbb)">The element must not have an isolated aaa attribute</assert>
<assert test="not(@bbb) or (@aaa and @bbb)">The element must not have an isolated bbb attribute</assert>
</rule>
</pattern>
</schema></correct>
<valid>

<AAA>
	<BBB aaa="A" bbb="B"/>
</AAA>
</valid>
<invalid>

<AAA>
	<BBB bbb="B"/>
</AAA>
</invalid>
<invalid>

<AAA>
	<BBB aaa="A"/>
</AAA>
</invalid>
<valid>

<AAA>
	<BBB/>
</AAA>
</valid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Number of characters in an abbreviation">
<rule context="BBB">
<report test="string-length(@bbb) < 2">There is not enough letters in the abbreviation</report>
<report test="string-length(@bbb) > 3">There is too much letters in the abbreviation</report>
</rule>
</pattern>
</schema></correct>
<invalid>

<AAA>
	<BBB bbb="C"/>
</AAA>
</invalid>
<valid>

<AAA>
	<BBB bbb="CZ"/>
</AAA>
</valid>
<invalid>

<AAA>
	<BBB bbb="CZCZ"/>
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Sum equals 100%.">
<rule context="Total">
<assert test="sum(//Percent) = 100">The values do not sum to 100%. </assert>
</rule>
</pattern>
</schema></correct>
<invalid>

<Total>
	<Percent>20</Percent>
	<Percent>30</Percent>
	<Percent>10</Percent>
	<Percent>50</Percent>
</Total>
</invalid>
<invalid>

<Total>
	<Percent>20</Percent>
	<Percent>10</Percent>
	<Percent>50</Percent>
</Total>
</invalid>
<valid>

<Total>
	<Percent>20</Percent>
	<Percent>30</Percent>
	<Percent>50</Percent>
</Total>
</valid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="a child of selected elements">
<rule context="CCC">
<assert test="parent::*[name()='BBB' or name()='DDD']">Element CCC must not be a child of element <name path="parent::*"/> </assert>
</rule>
</pattern>
</schema></correct>
<invalid>

<AAA>
	<BBB>
		<CCC/>
	</BBB>
	<CCC/>
	<DDD>
		<CCC/>
		<EEE>
			<CCC/>
		</EEE>
	</DDD>
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="id is the only permited attribute name">
<rule context="*">
<report test="@*[not(name()='id')]">Atrribute <name path="@*[not(name()='id')]"/> is forbidden in element <name/> </report>
</rule>
</pattern>
</schema></correct>
<invalid>

<AAA name="aaa">
<BBB id="bbb"/>
<CCC color="ccc"/>
</AAA>
</invalid>
</testCase>
<testCase>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Required ID">
    <rule context="cat | dog">
        <assert test="@id">An element of type <name/> should have an id attribute that is a unique identifier for that animal.</assert>
    </rule>
</pattern>

<pattern name="Required IDREF">
	<rule context="catowner">
	   <assert test="@pet">An element of type <name/> should have a pet attribute.</assert>
	</rule>
</pattern>

<pattern name="IDREF should reference an ID used in the same document">
	<rule context="catowner[@pet]">
		<assert test="id(@pet)">An element of type <name/> should have a pet attribute that should contain a unique identifier.</assert>
	</rule>
</pattern>

<pattern name="IDREF should reference an ID of a certain element type only">
	<rule context="catowner[@pet]">
		<assert test="(name(id(@pet)) ='cat')">An element of type <name/> should have a pet attribute that should contain the unique identifier for a cat.</assert>
	</rule>
</pattern>
</schema></correct>
<invalid dtd="
<!DOCTYPE ideg
[
<!ELEMENT ideg    ( dog, cat, catowner+ )>
<!ELEMENT dog     ( #PCDATA )>
<!ELEMENT cat      ( #PCDATA )>
<!ELEMENT catowner ( #PCDATA )>
<!ATTLIST dog  id ID #REQUIRED >
<!ATTLIST cat   id ID #REQUIRED >
<!ATTLIST catowner  pet IDREF #REQUIRED>
]>">
<ideg>
        <dog  id="danny"            >Danny</dog>
        <cat   id="bede"              >Bede</cat>
        <catowner >Harold</catowner>
        <catowner pet="poochi" >Fumiaki</catowner>
        <catowner pet="danny"   >Jimmy</catowner>
        <catowner pet="bede"    >Rick</catowner>
</ideg>

</invalid>
</testCase>
<testCase>
<resource name="source1.xml">

<list>
	<author id="a1">Alice</author>
	<author id="p1">Paul</author>
	<author id="p2">Peter</author>
</list>
</resource>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Compare with the database">
    <rule context="author">
				<assert test="document('source1.xml')//author[@id=current()/@id]">The author is not in the database </assert>
    </rule>
</pattern>

</schema></correct>
<invalid>

<list>
	<author id="a1"/>
	<author id="a2"/>
	<author id="p1"/>
	<author id="p2"/>
</list>
</invalid>
</testCase>
<testCase>
<resource name="source1.xml">
<list>
	<Alice/>
	<Peter/>
	<Paul/>
</list>
</resource>
<correct>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="Start of paragraph restriction.">
    <rule context="p">
				<assert test="document('source1.xml')//*[name()=substring-before(current(),' ')]">The word at the beginning of sentence is not listed in XML 1.</assert>
    </rule>
</pattern>

</schema></correct>

<invalid>

<Document>

Alice is a nice girl.

Where is Peter.

Paul was invited.

But Paul did not come.

</Document>
</invalid>
</testCase>
<testCase>
<incorrect>
<schema xmlns="http://www.ascc.net/xml/schematron">
<pattern name="foo">
<rule context="foo bar">
  <assert test="whatever">xxx</assert>
</rule>
</pattern>
</schema>
</incorrect>
</testCase>
<testCase>
<incorrect>
<schema xmlns="http://www.ascc.net/xml/schematron">

<pattern>
<rule context="foo bar">
  <assert test="whatever">xxx</assert>
</rule>
</pattern>
</schema>
</incorrect>
</testCase>
</testSuite>


text:
using System;
namespace MessagingToolkit.QRCode.ExceptionHandler
{
	[Serializable]
	public class VersionInformationException:System.ArgumentException
	{
	}
}


text:
package service

import (
	"encoding/json"
	"fmt"

	pb "go-common/app/interface/main/broadcast/api/grpc/v1"
	"go-common/app/service/main/broadcast/model"
	"go-common/library/log"
)

const (
	_pushMsg          = "push"
	_broadcastMsg     = "broadcast"
	_broadcastRoomMsg = "broadcast_room"
)

type databusMsg struct {
	Type        string          `json:"type,omitempty"`
	Operation   int32           `json:"operation,omitempty"`
	Server      string          `json:"server,omitempty"`
	Keys        []string        `json:"keys,omitempty"`
	Room        string          `json:"room,omitempty"`
	Speed       int32           `json:"speed,omitempty"`
	Platform    string          `json:"platform,omitempty"`
	ContentType int32           `json:"content_type,omitempty"`
	Message     json.RawMessage `json:"message,omitempty"`
}

func (s *Service) pushMsg(msg []byte) (err error) {
	m := &databusMsg{}
	if err = json.Unmarshal(msg, m); err != nil {
		log.Error("json.Unmarshal(%s) error(%s)", msg, err)
		return
	}
	log.Info("push message:%s", msg)
	switch m.Type {
	case _pushMsg:
		if len(m.Keys) == 0 {
			log.Error("service push keys is invalid:%+v", m)
			return
		}
		s.pushKeys(m.Operation, m.Server, m.Keys, m.Message, m.ContentType)
	case _broadcastMsg:
		s.broadcast(m.Operation, m.Message, m.Speed, m.Platform, m.ContentType)
	case _broadcastRoomMsg:
		if m.Room == "" {
			log.Error("service broadcast room is invalid:%+v", m)
			return
		}
		if err = s.room(m.Room).Push(m.Operation, m.Message, m.ContentType); err != nil {
			log.Error("room.Push(%s) roomId:%s error(%v)", m.Message, m.Room, err)
		}
		// NOTE: 弹幕兼容老协议推送,等web播放器接完可以去掉了
		if m.Operation == 1000 {
			s.broadcastRoom(m.Room, 5, []byte(fmt.Sprintf(`{"cmd":"DM","info":%s}`, m.Message)))
		}
	default:
		log.Error("unknown message type:%s", m.Type)
	}
	return
}

// pushKeys push a message to a batch of subkeys.
func (s *Service) pushKeys(operation int32, serverID string, subKeys []string, body []byte, contentType int32) {
	p := &model.Proto{
		Ver:         1,
		Operation:   operation,
		ContentType: contentType,
		Body:        body,
	}
	var args = pb.PushMsgReq{
		Keys:    subKeys,
		ProtoOp: operation,
		Proto:   p,
	}
	if c, ok := s.cometServers[serverID]; ok {
		if err := c.Push(&args); err != nil {
			log.Error("c.Push(%v) serverId:%s error(%v)", args, serverID, err)
		}
	}
}

// broadcast broadcast a message to all.
func (s *Service) broadcast(operation int32, body []byte, speed int32, platform string, contentType int32) {
	p := &model.Proto{
		Ver:         1,
		Operation:   operation,
		ContentType: contentType,
		Body:        body,
	}
	comets := s.cometServers
	speed /= int32(len(comets))
	var args = pb.BroadcastReq{
		ProtoOp:  operation,
		Proto:    p,
		Speed:    speed,
		Platform: platform,
	}
	for serverID, c := range comets {
		if err := c.Broadcast(&args); err != nil {
			log.Error("c.Broadcast(%v) serverId:%s error(%v)", args, serverID, err)
		}
	}
}

// broadcastRoomRawBytes broadcast aggregation messages to room.
func (s *Service) broadcastRoomRawBytes(roomID string, body []byte) {
	args := pb.BroadcastRoomReq{
		RoomID: roomID,
		Proto: &model.Proto{
			Ver:       1,
			Operation: model.OpRaw,
			Body:      body,
		},
	}
	comets := s.cometServers
	for serverID, c := range comets {
		if err := c.BroadcastRoom(&args); err != nil {
			log.Error("c.BroadcastRoom(%v) roomID:%s serverId:%s  error(%v)", args, roomID, serverID, err)
		}
	}
}

// broadcastRoom broadcast messages to room.
func (s *Service) broadcastRoom(roomID string, op int32, body []byte) {
	args := pb.BroadcastRoomReq{
		RoomID: roomID,
		Proto: &model.Proto{
			Ver:       1,
			Operation: op,
			Body:      body,
		},
	}
	comets := s.cometServers
	for serverID, c := range comets {
		if err := c.BroadcastRoom(&args); err != nil {
			log.Error("c.BroadcastRoom(%v) roomID:%s serverId:%s  error(%v)", args, roomID, serverID, err)
		}
	}
}


text:
package org.willianzhao.omnitureanalysis.mapred.xplatformtxnattr.jobs;

import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.util.Tool;

/**
 * Created by weilzhao on 8/21/14.
 */
public class GeoParseJobClient extends Configured implements Tool {
    @Override
    public int run(String[] strings) throws Exception {
        return 0;
    }
}


text:
package com.google.cloud.hadoop.gcsio;

import com.google.api.client.util.DateTime;
import com.google.api.services.storage.model.Bucket;
import com.google.api.services.storage.model.StorageObject;

import java.math.BigInteger;

/**
 * Misc helpers for generating test items.
 */
public class DirectoryListCacheTestUtils {
  // TODO(user): Move the createItemInfo* methods into GoogleCloudStorageItemInfo.java.

  public static final long BUCKET_BASE_CREATE_TIME = 1234L;
  public static final long OBJECT_BASE_UPDATED_TIME = 1234L;

  /**
   * Creates a GoogleCloudStorageItemInfo for the given {@code bucketName} with all its fields set
   * to some reasonable values.
   */
  public static GoogleCloudStorageItemInfo createBucketInfo(String bucketName) {
    Bucket fakeBucket = new Bucket()
        .setName(bucketName)
        .setTimeCreated(new DateTime(BUCKET_BASE_CREATE_TIME))
        .setLocation("us")
        .setStorageClass("class-af4");
    return GoogleCloudStorageImpl.createItemInfoForBucket(
        new StorageResourceId(bucketName), fakeBucket);
  }

  /**
   * Creates a GoogleCloudStorageItemInfo for the given StorageObject denoted by {@code bucketName}
   * and {@code objectName} with all its fields set to some reasonable values.
   */
  public static GoogleCloudStorageItemInfo createObjectInfo(String bucketName, String objectName) {
    StorageObject fakeStorageObject = new StorageObject()
        .setName(objectName)
        .setBucket(bucketName)
        .setUpdated(new DateTime(OBJECT_BASE_UPDATED_TIME))
        .setSize(BigInteger.valueOf(1024L * 1024 * 1024 * 1024))
        .setGeneration(1L)
        .setMetageneration(1L);
    return GoogleCloudStorageImpl.createItemInfoForStorageObject(
        new StorageResourceId(bucketName, objectName), fakeStorageObject);
  }
}


text:
require 'omniauth/oauth'
require 'multi_json'

module OmniAuth
  module Strategies
    class Etsy < OmniAuth::Strategies::OAuth

      # Cribbed from the etsy gem.
      SANDBOX_HOST = 'sandbox.openapi.etsy.com'
      PRODUCTION_HOST = 'openapi.etsy.com'

      # Set the environment, accepts either :sandbox or :production. Defaults to :production
      # and will raise an exception when set to an unrecognized environment.
      def self.environment=(environment)
        unless [:sandbox, :production].include?(environment)
          raise(ArgumentError, "environment must be set to either :sandbox or :production")
        end
        @environment = environment
        @host = (environment == :sandbox) ? SANDBOX_HOST : PRODUCTION_HOST
      end

      # The currently configured environment.
      def self.environment
        @environment || :production
      end

      def self.host # :nodoc:
        @host || PRODUCTION_HOST
      end

      def self.callback_url
        @callback_url || 'oob'
      end

      def initialize(app, consumer_key=nil, consumer_secret=nil, options={}, &block)
        # Set environment first; this can update our host
        OmniAuth::Strategies::Etsy.environment=options[:environment] if options[:environment]
        client_options = {
          :site => "http://#{OmniAuth::Strategies::Etsy.host}",
          :request_token_path => request_token_path(options),
          :access_token_path => access_token_path,
          :http_method => :get,
          :scheme => :query_string
        }

        super(app, :etsy, consumer_key, consumer_secret, client_options, options, &block)
      end

      def request_phase
        request_token = consumer.get_request_token(:oauth_callback => callback_url)
        session['oauth'] ||= {}
        session['oauth'][name.to_s] = {'callback_confirmed' => true, 'request_token' => request_token.token, 'request_secret' => request_token.secret}
        r = Rack::Response.new
        if request_token.params[:login_url]
          # Already contains token, etc, of the form:
          # https://www.etsy.com/oauth/signin?oauth_consumer_key=wg30ji4z8kdzsymfkw9vm333&oauth_token=650a9d4a8d589bb7e6aefed1628885&service=v2_prod
          r.redirect(request_token.params[:login_url])
        end
        r.finish
      end

      def auth_hash
        OmniAuth::Utils.deep_merge(super, {
          'uid' => user_hash['user_id'],
          'user_info' => user_info,
          'extra' => { 'user_hash' => user_hash }
        })
      end

      def user_info
        return {} unless user_hash
        {
          'uid' => user_hash['user_id'],
          'nickname' => user_hash['login_name'],
          'email' => user_hash['primary_email'],
          'name' => user_hash['login_name'],
          'feedback_info' => user_hash['feedback_info']
        }
      end

      def request_token_path(options)
        # Default scope is to read a user's private profile information, including email.  Scope is specified
        # as a uri-encoded query kv pair, "scope=scope_1+scope_2+...+scope_n"
        # For a full list of scope options, see:
        # http://www.etsy.com/developers/documentation/getting_started/oauth
        "/v2/oauth/request_token?#{to_params({:scope => options.fetch(:scope, 'profile_r+email_r')})}"
      end

      def access_token_path
        "/v2/oauth/access_token"
      end

      def to_params(options)
        options.collect{|key, value| "#{key}=#{value}"}.join('&')
      end

      def user_hash
        @user_hash ||= MultiJson.decode(@access_token.get('/v2/users/__SELF__').body)['results'][0]
      rescue ::Errno::ETIMEDOUT
        raise ::Timeout::Error
      rescue ::OAuth::Error => e
        raise e.response.inspect
      end
    end
  end
end


text:
module Hippo
    module API

        module Routing
            mattr_accessor :root_view_route

            API.routes.draw do
                # WS endpoint must come first
                get Hippo.config.api_path + '/cable' do
                    API::Cable.handle_request(request)
                end

                Extensions.each(reversed: true) do | ext |
                    ext.route(self)
                end
            end

            root_view_route.call if root_view_route
        end

    end
end


text:
var pbclient = require('libprofitbricks')
var prompt = require('prompt')
var helpers = require('../helpers')
var fs = require('fs')

exports.process = processUser

function processUser(params) {
    switch (params.user) {
        case 'list':
            pbclient.listUsers(helpers.printInfo)
            break
        case 'get':
        case 'show':
            if (!params.id || params.id == true) {
                console.error("User ID is a required field. -i [env]")
                process.exit(code = 5)
            }
            pbclient.getUser(params.id, helpers.printInfo)
            break
        case 'create':
            createUser(params)
            break
        case 'update':
            updateUser(params)
            break
        case 'delete':
            if (!params.id || params.id == true) {
                console.error("User ID is a required field. -i [env]")
                process.exit(code = 5)
            }

            if (!global.force) {
                pbclient.getUser(params.id, function(error, response, body) {
                    if (response.statusCode > 299) {
                        console.log("Object you are trying to delete does not exist")

                    } else {
                        var info = JSON.parse(body)

                        console.log('You are about to delete "' + info.properties.firstname + ' ' + info.properties.lastname + '" User. Do you want to proceed? (y/n)')
                        prompt.get(['yes'], function(err, result) {
                            if (result.yes == 'yes' || result.yes == 'y' || result.yes == '')
                                pbclient.deleteUser(params.id, helpers.printInfo)
                            else
                                process.exit(code = 0)
                        })
                    }
                })
            } else
                pbclient.deleteUser(params.id, helpers.printInfo)
            break
        default:
            params.outputHelp()
            break
    }
}

function createUser(params) {
    var data = {}
    try {
        if (params.path) {
            data = JSON.parse(fs.readFileSync(params.path, 'utf8'))
        } else {
            data.properties = {}
            if (params.firstname)
                data.properties.firstname = params.firstname
            else {
                console.error("First name is a required field.")
                process.exit(code = 5)
            }
            if (params.lastname)
                data.properties.lastname = params.lastname
            else {
                console.error("Last name is a required field.")
                process.exit(code = 5)
            }
            if (params.email)
                data.properties.email = params.email
            else {
                console.error("Email is a required field.")
                process.exit(code = 5)
            }
            if (params.password)
                data.properties.password = params.password
            else {
                console.error("Password is a required field.")
                process.exit(code = 5)
            }
            if (params.admin)
                data.properties.administrator = params.admin
            if (params.forcesecauth)
                data.properties.forceSecAuth = params.forcesecauth
        }
    } finally {
        pbclient.createUser(data, helpers.printInfo)
    }
}

function updateUser(params) {
    var data = {}

    if (!params.id || params.id == true) {
        console.error("User Id is a required field.")
        process.exit(code = 5)
    }
    data.properties = {}
    if (params.firstname)
        data.properties.firstname = params.firstname
    else {
        console.error("First name is a required field.")
        process.exit(code = 5)
    }
    if (params.lastname)
        data.properties.lastname = params.lastname
    else {
        console.error("Last name is a required field.")
        process.exit(code = 5)
    }
    if (params.email)
        data.properties.email = params.email
    else {
        console.error("Email is a required field.")
        process.exit(code = 5)
    }
    if (params.admin)
        data.properties.administrator = params.admin
    if (params.forcesecauth)
        data.properties.forceSecAuth = params.forcesecauth

    pbclient.updateUser(params.id, data, helpers.printInfo)
}


text:
package com.stratio.cassandra.lucene.builder.search.sort;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * A geo spatial distance search sort.
 *
 * @author Eduardo Alonso {@literal <eduardoalonso@stratio.com>}
 */
public class GeoDistanceSortField extends SortField {

    /** The name of the geo point field mapper to use to calculate distance. */
    @JsonProperty("field")
    final String field;

    /** The latitude of the center point to sort by distance to it. */
    @JsonProperty("latitude")
    final double latitude;

    /** The longitude of the center point to sort by distance to it. */
    @JsonProperty("longitude")
    final double longitude;

    /**
     * Creates a new {@link GeoDistanceSortField} for the specified field and reverse option.
     *
     * @param field the name of the geo point field mapper to be used for sorting
     * @param latitude the latitude in degrees of the reference point
     * @param longitude the longitude in degrees of the reference point
     */
    @JsonCreator
    public GeoDistanceSortField(@JsonProperty("field") String field,
                                @JsonProperty("latitude") double latitude,
                                @JsonProperty("longitude") double longitude) {
        this.field = field;
        this.latitude = latitude;
        this.longitude = longitude;
    }
}


text:
$(function() {

	$('select[data-select=multilingual-switch-language]').change(function() {
        var action = $(this).attr('data-action').replace('%language%', $(this).val());
        window.location.href = action;
	});
});


text:
package main

type dockerPullStatus struct {
	ID             string `json:"id"`
	Progress       string `json:"progress"`
	ProgressDetail struct {
		Current int `json:"current"`
		Total   int `json:"total"`
	} `json:"progressDetail"`
	Status string `json:"status"`
}


text:
<?php
namespace Swoole\Protocol;
use Swoole;

class FlashPolicy extends Base implements Swoole\IFace\Protocol
{
    public $default_port = 843;
    public $policy_file;
    public $policy_xml = '<cross-domain-policy>
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" to-ports="1000-9999" />
</cross-domain-policy>\0';

    function setPolicyXml($filename)
    {
        $this->policy_file = $filename;
        $this->policy_xml = file_get_contents($filename);
    }

    function onReceive($server,$client_id, $from_id, $data)
    {
        echo $data;
        $this->server->send($client_id, $this->policy_xml);
        $this->server->close($client_id);
    }

    function onStart($server)
    {
        $this->log(__CLASS__." running.");
    }

    function onConnect($server, $client_id, $from_id)
    {

    }

    function onClose($server, $client_id, $from_id)
    {

    }

    function onShutdown($server)
    {

    }
}


text:
package io.datarouter.gcp.spanner.op.read;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.Options.QueryOption;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Statement;

import io.datarouter.gcp.spanner.op.SpannerBaseOp;
import io.datarouter.model.databean.Databean;
import io.datarouter.model.key.primary.PrimaryKey;
import io.datarouter.model.serialize.fielder.DatabeanFielder;
import io.datarouter.scanner.Scanner;
import io.datarouter.storage.config.Config;
import io.datarouter.storage.file.DatabaseBlob;
import io.datarouter.storage.file.DatabaseBlobKey;
import io.datarouter.storage.file.PathbeanKey;
import io.datarouter.storage.serialize.fieldcache.PhysicalDatabeanFieldInfo;
import io.datarouter.util.string.StringTool;

public class SpannerGetBlobOp<
		PK extends PrimaryKey<PK>,
		D extends Databean<PK,D>,
		F extends DatabeanFielder<PK,D>>
extends SpannerBaseOp<List<DatabaseBlob>>{

	private static final String PATH_AND_FILE = DatabaseBlobKey.FieldKeys.pathAndFile.getColumnName();
	private static final String EXPIRATION_MS = DatabaseBlob.FieldKeys.expirationMs.getColumnName();
	private static final String SIZE = DatabaseBlob.FieldKeys.size.getColumnName();
	private static final String DATA = DatabaseBlob.FieldKeys.data.getColumnName();

	private final PhysicalDatabeanFieldInfo<PK,D,F> fieldInfo;
	private final DatabaseClient client;
	private final Collection<PathbeanKey> keys;
	private final Config config;
	private final List<String> fields;

	public SpannerGetBlobOp(DatabaseClient client,
			PhysicalDatabeanFieldInfo<PK,D,F> fieldInfo,
			Collection<PathbeanKey> keys,
			Config config,
			List<String> fields){
		super("SpannerGetBlob: " + fieldInfo.getTableName());
		this.client = client;
		this.fieldInfo = fieldInfo;
		this.keys = keys;
		this.config = config;
		this.fields = fields;
	}

	@Override
	public List<DatabaseBlob> wrappedCall(){
		long nowMs = System.currentTimeMillis();
		return Scanner.of(keys)
				.map(PathbeanKey::getPathAndFile)
				.batch(config.findRequestBatchSize().orElse(100))
				.map(batch -> buildQuery(fieldInfo.getTableName(), batch, fields, nowMs))
				.map(Statement::of)
				.concatIter(this::execute)
				.list();
	}

	private List<DatabaseBlob> execute(Statement statement){
		Set<String> fieldsForQuery = new HashSet<>(fields);
		QueryOption[] options = {};
		ResultSet resultSet = client.singleUse().executeQuery(statement, options);
		List<DatabaseBlob> resultDataBlobs = new ArrayList<>();
		while(resultSet.next()){
			DatabaseBlob blob = buildDatabaseBlob(resultSet, fieldsForQuery);
			resultDataBlobs.add(blob);
		}
		return resultDataBlobs;
	}

	private static DatabaseBlob buildDatabaseBlob(ResultSet result, Set<String> fieldsForQuery){
		Long size = fieldsForQuery.contains(SIZE)
				&& !result.isNull(SIZE)
				? result.getLong(SIZE)
				: null;
		String pathAndFile = fieldsForQuery.contains(PATH_AND_FILE)
				&& !result.isNull(PATH_AND_FILE)
				? result.getString(PATH_AND_FILE)
				: null;
		byte[] data = fieldsForQuery.contains(DATA)
				&& !result.isNull(DATA)
				? result.getBytes(DATA).toByteArray()
				: null;
		Long expirationMs = fieldsForQuery.contains(EXPIRATION_MS)
				&& !result.isNull(EXPIRATION_MS)
				? result.getLong(EXPIRATION_MS)
				: null;
		return new DatabaseBlob(
				PathbeanKey.of(pathAndFile),
				data,
				size,
				expirationMs);
	}

	private static String buildQuery(String tableName, List<String> keys, List<String> fields, long nowMs){
		var query = new StringBuilder();
		query.append("select  ");
		query.append(String.join(", ", fields));
		query.append(" from " + tableName);
		query.append(" where ");
		query.append("(");
		boolean didOne = false;
		for(String key : keys){
			if(didOne){
				query.append(" or ");
			}
			query.append(PATH_AND_FILE + " = " + StringTool.escapeString(key));
			didOne = true;
		}
		query.append(")");
		query.append(" and ");
		query.append("(");
		query.append(EXPIRATION_MS + " is null ");
		query.append(" or ");
		query.append(EXPIRATION_MS + " > " + nowMs);
		query.append(")");
		return query.toString();
	}

}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DotNet.CodeFormatting.Rules
{
    // Please keep these values sorted by number, not rule name.
    internal static class SyntaxRuleOrder
    {
        public const int HasNoCustomCopyrightHeaderFormattingRule = 1;
        public const int CopyrightHeaderRule = 2;
        public const int UsingLocationFormattingRule = 3;
        public const int NewLineAboveFormattingRule = 4;
        public const int BraceNewLineRule = 6;
        public const int NonAsciiChractersAreEscapedInLiterals = 7;
    }

    // Please keep these values sorted by number, not rule name.
    internal static class LocalSemanticRuleOrder
    {
        public const int HasNoIllegalHeadersFormattingRule = 1;
        public const int ExplicitVisibilityRule = 2;
        public const int IsFormattedFormattingRule = 3;
        public const int RemoveExplicitThisRule = 4;
        public const int AssertArgumentOrderRule = 5;
    }

    // Please keep these values sorted by number, not rule name.
    internal static class GlobalSemanticRuleOrder
    {
        public const int PrivateFieldNamingRule = 1;
        public const int MarkReadonlyFieldsRule = 2;
    }
}