text:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Toggl.DataObjects;

namespace Toggl
{
    /// <summary>
    /// https://github.com/toggl/toggl_api_docs/blob/master/chapters/tasks.md#tasks
    /// </summary>
    public class Task : BaseDataObject
    {

        [JsonProperty(PropertyName = "id")]
        public int? Id { get; set; }

        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "pid")]
        public int? ProjectId { get; set; }

        [JsonProperty(PropertyName = "wid")]
        public int? WorkspaceId { get; set; }

        [JsonProperty(PropertyName = "uid")]
        public int? UserId { get; set; }

        [JsonProperty(PropertyName = "estimated_seconds")]
        public int? EstimatedSeconds { get; set; }

        [JsonProperty(PropertyName = "is_active")]
        public bool? IsActive { get; set; }

        [JsonProperty(PropertyName = "at")]
        public DateTime? UpdatedOn { get; set; }
    }
}


text:
package de.flapdoodle.mongomapper;

import com.mongodb.DBCollection;

public abstract class AbstractCompositeIdStore<K, W, R> extends AbstractStore<K, String, W, R> {

    public <M extends ObjectWriteMapper<W> & ObjectReadMapper<R>> AbstractCompositeIdStore(MongoCollection collection, M mapper) {
        super(collection, mapper);
    }

    public <M extends ObjectWriteMapper<W> & ObjectReadMapper<R>> AbstractCompositeIdStore(DBCollection collection, M mapper) {
        super(collection, mapper);
    }

    @Override
    protected abstract K toId(String id);

    @Override
    protected abstract String fromId(K id);

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\WordPress\Services;

class ContentClassLoader
{
    private static $instance;

    public static function instance()
    {
        if (!static::$instance) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    public static function register()
    {
        spl_autoload_register([static::instance(), 'load'], true, false);
    }

    public static function unregister()
    {
        if (static::$instance) {
            spl_autoload_unregister([static::$instance, 'load']);

            static::$instance = null;
        }
    }

    public static function addNamespace($path, $namespace)
    {
        if (!empty($namespace)) {
            $namespace = trim($namespace, '\\').'\\';
        } else {
            $namespace = '';
        }

        static::instance()->root_pathes[$namespace][] = $path;
    }

    protected $root_pathes = [];

    public function load($class_name)
    {
        $class_namespace = preg_replace('/[^\\\\]+$/', '', $class_name);

        // PSR-4 class loader
        foreach ($this->root_pathes as $namespace => $root_pathes) {
            foreach ($root_pathes as $root_path) {
                if ($class_namespace === $namespace) {
                    $this->loadClass($root_path, substr($class_name, strlen($namespace)));
                }
            }
        }
    }

    public function loadClass($base_path, $relative_class_name)
    {
        $path = $base_path.'/'.str_replace('\\', '/', $relative_class_name).'.php';
        debug_log('try include', $path);

        if (file_exists($path)) {
            require_once $path;
        }
    }
}


text:
<?php

	namespace apf\web\service\google{

		use apf\parser\Uri			as	Uri;
		use apf\http\Adapter			as HttpAdapter;
		use apf\validate\Str			as ValidateString;
		use apf\http\adapter\Ecurl;

		class Translate{

			private	$fromLanguage		=	NULL;
			private	$toLanguage			=	NULL;
			private	$text					=	NULL;
			private	$translatedText	=	NULL;
			private	$adapter				=	NULL;

			const		TRANSLATE_URL	=	'https://translate.google.com';

			public function __construct($fromLanguage='en',$destinationLanguage=NULL,$text=NULL){

				if(!is_null($fromLanguage)){

					$this->setFromLanguage($fromLanguage);

				}

				if(!is_null($destinationLanguage)){

					$this->setDestinationLanguage($destinationLanguage);

				}

				if(!is_null($text)){

					$this->setText($text);

				}

			}

			public function setText($text){

				$this->text	=	ValidateString::mustBeNotEmpty($text,$trim=TRUE,'Text to translate must be not empty');

				return $this;

			}

			public function getText(){

				return $this->text;

			}

			public function setDestinationLanguage($destinationLanguage){

				$msg	=	'Destination language must be 2 characters wide';
				ValidateString::mustHaveLengthEqualTo($destinationLanguage,2,$trim=TRUE);
				$this->destinationLanguage	=	trim($destinationLanguage);

				return $this;

			}

			public function getDestinationLanguage(){

				return $this->destinationLanguage;

			}

			public function setFromLanguage($fromLanguage){

				$msg	=	'From language must be 2 characters wide';
				ValidateString::mustHaveLengthEqualTo($fromLanguage,2,$trim=TRUE);
				$this->fromLanguage	=	trim($fromLanguage);

				return $fromLanguage;

			}

			public function getFromLanguage(){

				return $this->fromLanguage;

			}

			public function setAdapter(HttpAdapter $adapter){

				$this->adapter	=	$adapter;
				return $this;

			}

			public function getAdapter(){

				return $this->adapter;

			}

			private function buildDefaultAdapter(){

				$uri		=	new Uri(self::TRANSLATE_URL);
				$uri->addRequestVariable('sl',$this->fromLanguage);
				$uri->addRequestVariable('tl',$this->destinationLanguage);
				$uri->addRequestVariable('text',$this->text);

				$adapter	=	new Ecurl($uri);
				$adapter->setHttpMethod('GET');

				return $adapter;

			}

			private function parseResult($result){

				$cut		=	'TRANSLATED_TEXT=';
				$result	=	substr($result,strpos($result,$cut)+strlen($cut));
				return trim(substr($result,0,strpos($result,';')),"'");

			}

			private function __translate(){

				try{

					return $this->translate();

				}catch(\Exception $e){

					return $e->getMessage();

				}

			}

			public function translate(){

				$this->setDestinationLanguage($this->destinationLanguage);
				$this->setFromLanguage($this->fromLanguage);
				$this->setText($this->text);

				$adapter	=	is_null($this->adapter)	?	$this->buildDefaultAdapter()	:	$this->adapter;

				$this->translatedText	=	$this->parseResult($adapter->connect());

				return $this->translatedText;

			}

			public function getTranslatedText(){

				return $this->translatedText;

			}

			public function __toString(){

				return sprintf('%s',$this->__translate());

			}

		}

	}


text:
package vanadis.core.reflection;

import java.io.IOException;
import java.io.InputStream;

public final class ContextClassLoaderObjectInputStream extends CustomObjectInputStream {

    public ContextClassLoaderObjectInputStream(InputStream in)
            throws IOException {
        super(in);
    }

    @Override
    protected ClassLoader classLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ExternalComponentManagerListener (Openfire 3.10.2 Javadoc)</title>
<meta name="date" content="2015-06-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Openfire 3.10.2 Javadoc

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jivesoftware.openfire.component

Interface ExternalComponentManagerListener

All Known Implementing Classes:

ClearspaceManager

public interface ExternalComponentManagerListener

Listener that will be alerted when an external component is disabled/enabled,
 the port is changed or configuration about an external component is modified.

 All listeners of the event will be alerted. Moreover, listeners have the chance
 to deny a change from happening. If a single listener denied the operation then
 it will not be allowed.

Author:

Gaston Dombiak

Method Summary

Methods

Modifier and Type
Method and Description

void
componentAllowed(String subdomain,
                ExternalComponentConfiguration configuration)

Notification indicating that a new component was allowed to connect using a
 given configuration.

void
componentBlocked(String subdomain)

Notification indicating that a component was blocked to connect to the server.

void
componentConfigurationDeleted(String subdomain)

Notification indicating that the configuration of a component, that was either
 blocked or allowed to connect, is being deleted.

void
componentSecretUpdated(String subdomain,
                      String newSecret)

Notification indicating that the configuration of a component, that was either
 blocked or allowed to connect, is being deleted.

void
defaultSecretChanged(String newSecret)

Notification indicating that the default secret is being modified.

void
permissionPolicyChanged(ExternalComponentManager.PermissionPolicy newPolicy)

Notification indicating that the permission policy is being modified.

void
portChanged(int newPort)

Notification indicating that the port used by external components is being
 modified.

void
serviceEnabled(boolean enabled)

Notification indicating whether the service is being enabled or disabled.

Method Detail

serviceEnabled

void serviceEnabled(boolean enabled)
                    throws ModificationNotAllowedException

Notification indicating whether the service is being enabled or disabled. The
 listener may throw an exception to not allow the change from taking place.

Parameters:

enabled - true if the service is being enabled.

Throws:

ModificationNotAllowedException - if the operation was denied.

portChanged

void portChanged(int newPort)
                 throws ModificationNotAllowedException

Notification indicating that the port used by external components is being
 modified. The listener may throw an exception to not allow the change from
 taking place.

Parameters:

newPort - new default secret being set.

Throws:

ModificationNotAllowedException - if the operation was denied.

defaultSecretChanged

void defaultSecretChanged(String newSecret)
                          throws ModificationNotAllowedException

Notification indicating that the default secret is being modified. The
 listener may throw an exception to not allow the change from taking place.

Parameters:

newSecret - new default secret being set.

Throws:

ModificationNotAllowedException - if the operation was denied.

permissionPolicyChanged

void permissionPolicyChanged(ExternalComponentManager.PermissionPolicy newPolicy)
                             throws ModificationNotAllowedException

Notification indicating that the permission policy is being modified. See
 ExternalComponentManager.PermissionPolicy for more information. The
 listener may throw an exception to not allow the change from taking place.

Parameters:

newPolicy - new permission policy being set.

Throws:

ModificationNotAllowedException - if the operation was denied.

componentAllowed

void componentAllowed(String subdomain,
                    ExternalComponentConfiguration configuration)
                      throws ModificationNotAllowedException

Notification indicating that a new component was allowed to connect using a
 given configuration. The listener may throw an exception to not allow the
 change from taking place.

Parameters:

subdomain - subdomain of the added component.

configuration - configuration for the external component.

Throws:

ModificationNotAllowedException - if the operation was denied.

componentBlocked

void componentBlocked(String subdomain)
                      throws ModificationNotAllowedException

Notification indicating that a component was blocked to connect to the server.
 The listener may throw an exception to not allow the change from taking place.

Parameters:

subdomain - subdomain of the blocked component.

Throws:

ModificationNotAllowedException - if the operation was denied.

componentSecretUpdated

void componentSecretUpdated(String subdomain,
                          String newSecret)
                            throws ModificationNotAllowedException

Notification indicating that the configuration of a component, that was either
 blocked or allowed to connect, is being deleted. The listener may throw an exception
 to not allow the change from taking place.

Parameters:

subdomain - subdomain of the component.

newSecret - new secret being set for the component.

Throws:

ModificationNotAllowedException - if the operation was denied.

componentConfigurationDeleted

void componentConfigurationDeleted(String subdomain)
                                   throws ModificationNotAllowedException

Notification indicating that the configuration of a component, that was either
 blocked or allowed to connect, is being deleted. The listener may throw an
 exception to not allow the change from taking place.

Parameters:

subdomain - subdomain of the component.

Throws:

ModificationNotAllowedException - if the operation was denied.

Overview

Package

Class

Tree

Deprecated

Index

Help

Openfire 3.10.2 Javadoc

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2003-2008 Jive Software.


text:
DECLARE_LOG_CATEGORY_EXTERN(VirtusonicLog, Log, All);
DECLARE_LOG_CATEGORY_EXTERN(VirtusonicError, Log, All);


text:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>

	<diskStore path="java.io.tmpdir/hibernate/mini-service" />

	<!-- DefaultCache setting. -->
	<defaultCache maxElementsInMemory="10000" memoryStoreEvictionPolicy="LRU" eternal="false"
		timeToIdleSeconds="300" timeToLiveSeconds="300" overflowToDisk="false" diskPersistent="false" />

	<!-- Special objects setting. -->
	<cache name="org.springside.examples.miniservice.entity.account.User" maxElementsInMemory="10000"
		memoryStoreEvictionPolicy="LRU" eternal="true" diskPersistent="false" overflowToDisk="true" maxElementsOnDisk="1000000" />
	<cache name="org.springside.examples.miniservice.entity.account.User.roleList" maxElementsInMemory="10000"
		memoryStoreEvictionPolicy="LRU" eternal="true" diskPersistent="false" overflowToDisk="true" maxElementsOnDisk="1000000" />
	<cache name="org.springside.examples.miniservice.entity.account.Role" maxElementsInMemory="10000"
		memoryStoreEvictionPolicy="LRU" eternal="true" diskPersistent="false" overflowToDisk="true" maxElementsOnDisk="1000000" />
</ehcache>


text:
#ifndef AVFILTER_FRAMEPOOL_H
#define AVFILTER_FRAMEPOOL_H

#include "libavutil/buffer.h"
#include "libavutil/frame.h"

/**
 * Frame pool. This structure is opaque and not meant to be accessed
 * directly. It is allocated with ff_frame_pool_init() and freed with
 * ff_frame_pool_uninit().
 */
typedef struct FFFramePool FFFramePool;

/**
 * Allocate and initialize a video frame pool.
 *
 * @param alloc a function that will be used to allocate new frame buffers when
 * the pool is empty. May be NULL, then the default allocator will be used
 * (av_buffer_alloc()).
 * @param width width of each frame in this pool
 * @param height height of each frame in this pool
 * @param format format of each frame in this pool
 * @param align buffers alignement of each frame in this pool
 * @return newly created video frame pool on success, NULL on error.
 */
FFFramePool *ff_frame_pool_video_init(AVBufferRef* (*alloc)(int size),
                                      int width,
                                      int height,
                                      enum AVPixelFormat format,
                                      int align);

/**
 * Allocate and initialize an audio frame pool.
 *
 * @param alloc a function that will be used to allocate new frame buffers when
 * the pool is empty. May be NULL, then the default allocator will be used
 * (av_buffer_alloc()).
 * @param channels channels of each frame in this pool
 * @param nb_samples number of samples of each frame in this pool
 * @param format format of each frame in this pool
 * @param align buffers alignement of each frame in this pool
 * @return newly created audio frame pool on success, NULL on error.
 */
FFFramePool *ff_frame_pool_audio_init(AVBufferRef* (*alloc)(int size),
                                      int channels,
                                      int samples,
                                      enum AVSampleFormat format,
                                      int align);

/**
 * Deallocate the frame pool. It is safe to call this function while
 * some of the allocated frame are still in use.
 *
 * @param pool pointer to the frame pool to be freed. It will be set to NULL.
 */
void ff_frame_pool_uninit(FFFramePool **pool);

/**
 * Get the video frame pool configuration.
 *
 * @param width width of each frame in this pool
 * @param height height of each frame in this pool
 * @param format format of each frame in this pool
 * @param align buffers alignement of each frame in this pool
 * @return 0 on success, a negative AVERROR otherwise.
 */
int ff_frame_pool_get_video_config(FFFramePool *pool,
                                   int *width,
                                   int *height,
                                   enum AVPixelFormat *format,
                                   int *align);

/**
 * Get the audio frame pool configuration.
 *
 * @param channels channels of each frame in this pool
 * @param nb_samples number of samples of each frame in this pool
 * @param format format of each frame in this pool
 * @param align buffers alignement of each frame in this pool
 * @return 0 on success, a negative AVERROR otherwise.
 */
int ff_frame_pool_get_audio_config(FFFramePool *pool,
                                   int *channels,
                                   int *nb_samples,
                                   enum AVSampleFormat *format,
                                   int *align);

/**
 * Allocate a new AVFrame, reussing old buffers from the pool when available.
 * This function may be called simultaneously from multiple threads.
 *
 * @return a new AVFrame on success, NULL on error.
 */
AVFrame *ff_frame_pool_get(FFFramePool *pool);

#endif /* AVFILTER_FRAMEPOOL_H */


text:
#ifndef cmSetSourceFilesPropertiesCommand_h
#define cmSetSourceFilesPropertiesCommand_h

#include "cmCommand.h"

class cmSetSourceFilesPropertiesCommand : public cmCommand
{
public:
  virtual cmCommand* Clone()
    {
      return new cmSetSourceFilesPropertiesCommand;
    }

  /**
   * This is called when the command is first encountered in
   * the input file.
   */
  virtual bool InitialPass(std::vector<std::string> const& args,
                           cmExecutionStatus &status);

  /**
   * The name of the command as specified in CMakeList.txt.
   */
  virtual const char* GetName() { return "set_source_files_properties";}

  /**
   * Succinct documentation.
   */
  virtual const char* GetTerseDocumentation()
    {
    return "Source files can have properties that affect how they are built.";
    }

  /**
   * Longer documentation.
   */
  virtual const char* GetFullDocumentation()
    {
      return
        "  set_source_files_properties(file1 file2 ...\n"
        "                              PROPERTIES prop1 value1\n"
        "                              prop2 value2 ...)\n"
        "Set properties on a file. The syntax for the command is to list all "
        "the files you want "
        "to change, and then provide the values you want to set next.  You "
        "can make up your own properties as well.  "
        "The following are used by CMake.  "
        "The ABSTRACT flag (boolean) is used by some class wrapping "
        "commands. "
        "If WRAP_EXCLUDE (boolean) is true then many wrapping commands "
        "will ignore this file. If GENERATED (boolean) is true then it "
        "is not an error if this source file does not exist when it is "
        "added to a target.  Obviously, "
        "it must be created (presumably by a custom command) before the "
        "target is built.  "
        "If the HEADER_FILE_ONLY (boolean) property is true then the "
        "file is not compiled.  This is useful if you want to add extra "
        "non build files to an IDE. "
        "OBJECT_DEPENDS (string) adds dependencies to the object file.  "
        "COMPILE_FLAGS (string) is passed to the compiler as additional "
        "command line arguments when the source file is compiled.  "
        "LANGUAGE (string) CXX|C will change the default compiler used "
        "to compile the source file. The languages used need to be enabled "
        "in the PROJECT command. "
        "If SYMBOLIC (boolean) is set to true the build system will be "
        "informed that the source file is not actually created on disk but "
        "instead used as a symbolic name for a build rule.";

    }

  cmTypeMacro(cmSetSourceFilesPropertiesCommand, cmCommand);

  static bool RunCommand(cmMakefile *mf,
                         std::vector<std::string>::const_iterator filebeg,
                         std::vector<std::string>::const_iterator fileend,
                         std::vector<std::string>::const_iterator propbeg,
                         std::vector<std::string>::const_iterator propend,
                         std::string &errors);
};

#endif


text:
package org.pale.gorm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Villager.Profession;
import org.bukkit.material.Stairs;
import org.bukkit.material.Torch;
//SNARK import net.minecraft.server.v1_7_R3.TileEntity;
//SNARK import org.bukkit.craftbukkit.v1_7_R3.CraftWorld;
import org.pale.gorm.config.ConfigUtils;
import org.pale.gorm.config.ConfigUtils.MissingAttributeException;

/**
 * Singleton class for the whole castle.
 *
 * @author white
 *
 */
public class Castle {
	private static Castle instance;
	private World world;
	public Random r = new Random();
	private HashMap<Profession, Integer> denizenCounts = new HashMap<Profession, Integer>();

	/**
	 * Each chunk has a list of rooms which intersect it. Naturally, a room is
	 * likely to belong to more than one chunk
	 */
	private Map<Integer, Collection<Room>> roomsByChunk = new HashMap<Integer, Collection<Room>>();
	/**
	 * This is a similar map to roomsByChunk, but for buildings.
	 */
	private Map<Integer, Collection<Building>> buildingsByChunk = new HashMap<Integer, Collection<Building>>();

	/**
	 * Rooms so we can sort by number of exits.
	 */
	private ArrayList<Room> rooms = new ArrayList<Room>();

	/**
	 * Private ctor so this is a singleton
	 */
	private Castle() {
		for (Profession p : Profession.values()) {
			denizenCounts.put(p, 0);
		}
	}

	/**
	 * MUST call this before building
	 *
	 */
	public void setWorld(World w) {
		world = w;
	}

	public World getWorld() {
		return world;
	}

	public static Castle getInstance() {
		if (instance == null) {
			instance = new Castle();
		}
		return instance;
	}

	private List<Building> buildings = new ArrayList<Building>();

	public int getBuildingCount() {
		return buildings.size();
	}

	public Room getRoomAt(IntVector pos){
		for(Room r: getRooms()){
			if(r.getExtent().contains(pos)){
				return r;
			}
		}
		return null;
	}

	/**
	 * Add a building to the internal lists, along with its rooms
	 *
	 * @param r
	 */
	void addBuilding(Building b) {
		for (int c : b.getExtent().getChunks()) {
			Collection<Building> list;
			if (!buildingsByChunk.containsKey(c)) {
				list = new ArrayList<Building>();
				buildingsByChunk.put(c, list);
			} else
				list = buildingsByChunk.get(c);
			list.add(b);
		}
		buildings.add(b);
	}

	/**
	 * returns true if e intersects any room at all. This works by iterating
	 * over the rooms in the chunks for that extent
	 *
	 * @param e
	 * @return
	 */
	public boolean intersects(Extent e) {
		for (int c : e.getChunks()) {
			Collection<Building> list = buildingsByChunk.get(c);
			if (list != null) {
				for (Building b : list) {
					if (b.getExtent().intersects(e))
						return true;
				}
			}
		}
		return false;
	}

	public boolean contains(IntVector pos) {
		int c = Extent.getChunkCode(pos.x, pos.z);
		Collection<Building> list = buildingsByChunk.get(c);
		if (list != null) {
			for (Building b : list) {
				if (b.getExtent().contains(pos))
					return true;
			}
		}
		return false;
	}

	public Collection<Building> getIntersectingBuildings(Extent e) {
		Collection<Building> blist = new ArrayList<Building>();
		for (int c : e.getChunks()) {
			Collection<Building> list = buildingsByChunk.get(c);
			if (list != null) {
				for (Building b : blist) {
					if (b.getExtent().intersects(e))
						list.add(b);
				}
			}
		}
		return blist;

	}

	public double grade(IntVector v) {
		double grade = Noise.noise2Dfractal(v.x, v.z, 3, 3, 3, 0.8);
		// rebalance such that non-dungeon castles are friendlier and
		// higher-grade
		if ((GormPlugin.getInstance().getIsDungeon() == false)
				&& (grade < 0.35)) {
			grade += 0.5;
		}
		return grade;

	}

	/**
	 * Get the grade level for the given extent, in order to determine the
	 * 'level of upkeep' of this section of the castle. Use this when we do not
	 * have access to the current building.
	 *
	 * @return grade level of the given extent, from 1 to 4
	 */

	public int gradeInt(IntVector v) {
		Castle c = Castle.getInstance();
		double grade = c.grade(v);
		if (grade <= 0.35) {
			return 1;
		} else if (grade <= 0.5) {
			return 2;
		} else if (grade <= 0.65) {
			return 3;
		} else {
			return 4;
		}
	}

	/**
	 * Fill an extent with a material and data, checking we don't overwrite
	 * certain things
	 *
	 * @param e
	 * @param mat
	 * @param data
	 */

	public void checkFill(Extent e, Material mat, int data) {
		if (mat == Material.SMOOTH_BRICK && data == 0) {// if this is plain
			// brick, flash it up!
			fillBrickWithCracksAndMoss(e, true);
		} else {
			for (int x = e.minx; x <= e.maxx; x++) {
				for (int y = e.miny; y <= e.maxy; y++) {
					for (int z = e.minz; z <= e.maxz; z++) {
						Block b = world.getBlockAt(x, y, z);
						if (canOverwrite(b)) {
							b.setType(mat);
							b.setData((byte) data);
						}
					}
				}
			}
		}
	}

	public void addLightToWall(int x, int y, int z,BlockFace dir) {
		World w = Castle.getInstance().getWorld();
		Block b = w.getBlockAt(x, y, z);

		// a hack. Creating a torch will cause it
		// to drop, unless there's something under it.
		// Even when it's attached to a wall.
		// Madness.

		Block bunder = w.getBlockAt(x, y-1, z);
		if(canOverwrite(bunder) && canOverwrite(b)){
			bunder.setType(Material.DIRT);

			Torch t = new Torch(Material.TORCH);
			t.setFacingDirection(dir);
			b.setType(Material.TORCH);
			b.setData(t.getData());

			bunder.setType(Material.AIR);
		}
	}
	public void checkFill(Extent e, MaterialDataPair mp) {
		checkFill(e, mp.m, mp.d);
	}

	/**
	 * Fill a wall extent (i.e. one of the dimensions must be of zero width)
	 * with a pattern of materials. There's an assumption that it's not a floor
	 * or ceiling but I'm sure that could be fixed.
	 *
	 * @param wallExtent
	 * @param mats
	 *            array of material pairs
	 * @param n
	 *            number of elements in array (might want to use a subset)
	 */
	public void patternFill(Extent wallExtent, MaterialDataPair[] mats, int n,
			Random rnd) {
		if (rnd == null)
			rnd = r;
		// work out the zero axis
		int shortAxis = wallExtent.getShortestAxis();
		// work out the long axis
		int longAxis = wallExtent.getLongestAxis();
		int xdim, ydim; // dimensions of the 2D array we'll make the pattern in
		switch (shortAxis) {
		case Extent.Y:
			if (longAxis == Extent.X) {
				xdim = wallExtent.xsize();
				ydim = wallExtent.zsize();
			} else {
				xdim = wallExtent.zsize();
				ydim = wallExtent.xsize();
			}
			break;
		case Extent.X:
			if (longAxis == Extent.Z) {
				xdim = wallExtent.zsize();
				ydim = wallExtent.ysize();
			} else {
				xdim = wallExtent.ysize();
				ydim = wallExtent.zsize();
			}
			break;
		default:
		case Extent.Z:
			if (longAxis == Extent.X) {
				xdim = wallExtent.xsize();
				ydim = wallExtent.ysize();
			} else {
				xdim = wallExtent.ysize();
				ydim = wallExtent.xsize();
			}
			break;
		}

		// doing it like this so I can replace with other pattern generators
		// later.

		int[][] array = new int[xdim][ydim];
		if (xdim == 1 || ydim == 1) {
			// simple version without symmetry, for tall windows.
			for (int x = 0; x < xdim; x++) {
				for (int y = 0; y < ydim; y++) {
					array[x][y] = rnd.nextInt(n);
				}
			}
		} else {
			for (int x = 0; x < xdim / 2; x++) {
				for (int y = 0; y < ydim / 2; y++) {
					int m = rnd.nextInt(n);
					array[x][y] = m;
					array[(xdim - 1) - x][y] = m;
					array[x][(ydim - 1) - y] = m;
					array[(xdim - 1) - x][(ydim - 1) - y] = m;
				}
			}
		}

		// now slap it into the extent
		for (int x = 0; x < xdim; x++) {
			for (int y = 0; y < ydim; y++) {
				int wx, wz, wy;
				switch (shortAxis) {
				case Extent.Y:
					wy = wallExtent.miny;
					if (longAxis == Extent.X) {
						wx = x + wallExtent.minx;
						wz = y + wallExtent.minz;
					} else {
						wz = x + wallExtent.minz;
						wx = y + wallExtent.minx;
					}
					break;
				case Extent.X:
					wx = wallExtent.minx;
					if (longAxis == Extent.Y) {
						wy = x + wallExtent.miny;
						wz = y + wallExtent.minz;
					} else {
						wz = x + wallExtent.minz;
						wy = y + wallExtent.miny;
					}
					break;
				default:
				case Extent.Z:
					wz = wallExtent.minz;
					if (longAxis == Extent.X) {
						wx = x + wallExtent.minx;
						wy = y + wallExtent.miny;
					} else {
						wy = x + wallExtent.miny;
						wx = y + wallExtent.minx;
					}
					break;
				}
				Block b = world.getBlockAt(wx, wy, wz);
				MaterialDataPair mat = mats[array[x][y]];
				b.setType(mat.m);
				b.setData((byte) mat.d);

			}
		}

	}

	/**
	 * Replace certain blocks within an Extent
	 *
	 * @param e
	 * @param mat
	 * @param data
	 * @param matReplace
	 * @param dataReplace
	 */

	public void replace(Extent e, Material mat, int data, Material matReplace,
			int dataReplace) {
		for (int x = e.minx; x <= e.maxx; x++) {
			for (int y = e.miny; y <= e.maxy; y++) {
				for (int z = e.minz; z <= e.maxz; z++) {
					Block b = world.getBlockAt(x, y, z);
					if (b.getType() == matReplace) {
						if (b.getData() == (byte) dataReplace) {
							b.setType(mat);
							b.setData((byte) data);
						}
					}
				}
			}
		}
	}

	public void replace(Extent e, MaterialDataPair mp,
			MaterialDataPair mpReplace) {
		replace(e, mp.m, mp.d, mpReplace.m, mpReplace.d);
	}

	/**
	 * Fill an extent with a material and data DOES NOT CHECK that the stuff
	 * we're writing will overwrite anything
	 *
	 * @param e
	 * @param mat
	 * @param data
	 */
	public void fill(Extent e, Material mat, int data) {
		if (mat == Material.SMOOTH_BRICK && data == 0) // if this is plain
			// brick, flash it up!
			fillBrickWithCracksAndMoss(e, false);
		else {
			for (int x = e.minx; x <= e.maxx; x++) {
				for (int y = e.miny; y <= e.maxy; y++) {
					for (int z = e.minz; z <= e.maxz; z++) {
						Block b = world.getBlockAt(x, y, z);
						b.setType(mat);
						b.setData((byte) data);
					}
				}
			}
		}
	}

	public void fill(Extent e, MaterialDataPair mp) {
		fill(e, mp.m, mp.d);
	}

	/**
	 * We should use this when we might overwrite a blg or exit, to prevent
	 * that.
	 *
	 * @param b
	 * @param mode
	 * @return
	 */
	public static boolean canOverwrite(Block b) {
		Material m = b.getType();
		// this is going to be hideous if they remove getData().
		byte data = b.getData();

		if(m == Material.SMOOTH_BRICK || m == Material.WOOD
				|| m == Material.BRICK || m == Material.COBBLESTONE
				|| ((m == Material.SANDSTONE || m == Material.RED_SANDSTONE) && data != 0) || isStairs(m))
			return false;

		return true;
	}

	/**
	 * Fill an area with bricks, adding moss and cracks.
	 *
	 * @param e
	 * @param checkOverwrite
	 */
	private void fillBrickWithCracksAndMoss(Extent e, boolean checkFill) {
		int t = 0;
		int dataVals[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
				0, 0, 2, 2, 1, 2 };
		for (int x = e.minx; x <= e.maxx; x++) {
			for (int y = e.miny; y <= e.maxy; y++) {
				for (int z = e.minz; z <= e.maxz; z++) {
					Block b = world.getBlockAt(x, y, z);
					if (!checkFill || canOverwrite(b)) {
						b.setType(Material.SMOOTH_BRICK);
						b.setData((byte) dataVals[r.nextInt(dataVals.length)]);
					}
				}
			}
		}
		spreadMoss(e);
		// spreadMoss(e);
	}

	private void doSpreadMoss(int cx, int cy, int cz) {
		for (int x = cx - 1; x <= cx + 1; x++) {
			for (int y = cy - 1; y <= cy + 1; y++) {
				for (int z = cz - 1; z <= cz + 1; z++) {
					Block b = world.getBlockAt(x, y, z);
					if (b.getType() == Material.SMOOTH_BRICK
							&& b.getData() == 0 && r.nextInt(10) < 1) {
						b.setData((byte) 1);
					}
				}
			}
		}
	}

	public void spreadMoss(Extent e) {
		for (int x = e.minx; x <= e.maxx; x++) {
			for (int y = e.miny; y <= e.maxy; y++) {
				for (int z = e.minz; z <= e.maxz; z++) {
					Block b = world.getBlockAt(x, y, z);
					if (b.getType() == Material.SMOOTH_BRICK
							&& b.getData() == 1) {
						doSpreadMoss(x, y, z);
					}
				}
			}
		}
	}

	public Collection<Building> getBuildings() {
		return buildings;
	}

	/**
	 * Return a list of buildings within a given extent
	 *
	 * @return
	 */
	public Collection<Building> getBuildingsIntersecting(Extent e) {
		ArrayList<Building> out = new ArrayList<Building>();

		for (Building r : buildings) {
			if (r.intersects(e))
				out.add(r);
		}
		return out;
	}

	public static boolean isStairs(Material m) {
		return (m == Material.COBBLESTONE_STAIRS || m == Material.WOOD_STAIRS
				|| m == Material.BIRCH_WOOD_STAIRS
				|| m == Material.ACACIA_STAIRS
				|| m == Material.SANDSTONE_STAIRS
				|| m == Material.RED_SANDSTONE_STAIRS
				|| m == Material.SMOOTH_STAIRS || m == Material.BRICK_STAIRS
				|| m == Material.QUARTZ_STAIRS
				|| m == Material.NETHER_BRICK_STAIRS
				|| m == Material.JUNGLE_WOOD_STAIRS || m == Material.SPRUCE_WOOD_STAIRS);
	}

	public void setStairs(int x, int y, int z, BlockFace dir, Material mat) {
		Block b = world.getBlockAt(x, y, z);
		b.setType(mat);
		Stairs matStairs = new Stairs(mat);
		matStairs.setFacingDirection(dir);
		b.setData(matStairs.getData());
	}

	@SuppressWarnings("unused")
	private void replaceSolidWithAir(Extent e) {
		for (int x = e.minx; x <= e.maxx; x++) {
			for (int y = e.miny; y <= e.maxy; y++) {
				for (int z = e.minz; z <= e.maxz; z++) {
					Block b = world.getBlockAt(x, y, z);
					if (b.getType().isSolid()) {
						b.setType(Material.AIR);
						b.setData((byte) 0);
					}
				}
			}
		}
	}

	public static boolean requiresLight(int x, int y, int z) {
		Block b = Castle.getInstance().getWorld().getBlockAt(x, y, z);
		return b.getLightLevel() < 7;
	}

	public void raze() {
		for (Building r : buildings) {
			Extent e = r.getExtent().expand(4, Extent.X|Extent.Z);
			IntVector p = e.getCentre();
			MaterialManager mgr = new MaterialManager(world.getBiome(p.x, p.z));
			fill(e.growDirection(Direction.UP, 5), Material.AIR, 0);
			fill(e.getWall(Direction.DOWN), mgr.getGround().m, 0);
		}
		buildings.clear();
	}

	public Building getRandomBuilding() {
		if (buildings.size() == 0)
			return null;
		else
			return buildings.get(r.nextInt(buildings.size()));
	}

	/**
	 * add a room to both the room list and the rooms-by-chunk map
	 *
	 * @param r
	 */
	public void addRoom(Room r) {
		GormPlugin.log("Adding room " + Integer.toString(r.id)
				+ " with extent " + r.getExtent().toString());
		rooms.add(r);
		for (int c : r.getChunks()) {
			Collection<Room> list;
			if (!roomsByChunk.containsKey(c)) {
				list = new ArrayList<Room>();
				roomsByChunk.put(c, list);
			} else
				list = roomsByChunk.get(c);
			list.add(r);
		}
	}

	/**
	 * This will return null if a chunk isn't in the map yet
	 *
	 * @return
	 */
	public Collection<Room> getRoomsByChunk(int key) {
		return roomsByChunk.get(key);
	}

	public Collection<Room> getRooms() {
		return rooms;
	}

	/**
	 * make sure the rooms list is sorted by number of exits
	 */
	public void sortRooms() {
		Collections.sort(rooms);
	}

	/**
	 * Useful shortcut for getting a block in the world.
	 *
	 * @param pos
	 * @return
	 */
	public Block getBlockAt(IntVector pos) {
		return world.getBlockAt(pos.x, pos.y, pos.z);
	}

	public void roomSanityCheck() {
		for (int i = 0; i < Room.idCounter; i++) {
			// GormPlugin.log("looking for room "+Integer.toString(i));
			boolean found = false;
			for (Room r : rooms) {
				if (r.id == i) {
					found = true;
					break;
				}
			}
			if (!found)
				GormPlugin.log("ROOM NOT FOUND IN MAIN LIST: "
						+ Integer.toString(i));

			found = false;
			outer: for (Collection<Room> col : roomsByChunk.values()) {
				for (Room r : rooms) {
					if (r.id == i) {
						found = true;
						break outer;
					}
				}
			}
			if (!found)
				GormPlugin.log("ROOM NOT FOUND IN CHUNK LISTS: "
						+ Integer.toString(i));

		}
	}

	public void patternFloor(ConfigurationSection c, Extent floor, MaterialManager mgr) throws MissingAttributeException{
		ConfigurationSection pf = c.getConfigurationSection("patternfloor");
		if(pf==null)
			throw new MissingAttributeException("patternfloor", c);
		double chance = pf.getDouble("chance",1);

		if(r.nextDouble()<chance){
			int n = ConfigUtils.getRandomValueInRangeInt(pf, "count");
			List<String> matnames = pf.getStringList("mats");
			if(matnames==null)throw new MissingAttributeException("mats",pf);
			MaterialDataPair mats[] = new MaterialDataPair[n];
			for(int i=0;i<n;i++){
				mats[i] = mgr.get(matnames.get(i));
			}
			patternFill(floor, mats, n, null);
		} else {
			MaterialDataPair ground = r.nextDouble()<0.2 ? mgr.getSupSecondary() : mgr.getGround();
			fill(floor, ground);
		}
	}

	public Map<Profession, Integer> getDenizenCounts() {
		return denizenCounts;
	}

	public void incDenizenCount(Profession p) {
		denizenCounts.put(p, denizenCounts.get(p) + 1);

	}

	public boolean onWater(int x, int z) {
		// really this should be just one call.
		int y = world.getHighestBlockYAt(x, z);
		Block b = world.getBlockAt(x, y-1, z);
		GormPlugin.getInstance().getLogger().info("Cornercheck: "+x+","+z+" = "+b.getType().toString());
		return b.getType()==Material.STATIONARY_WATER;
	}

	public static void reset() {
		instance=null;
	}

}


text:
/**
 * ------------------------------------------------------------
 * Calendar  日历
 * @author   sensen(rainforest92@126.com)
 * ------------------------------------------------------------
 */

const Component = require('../../../../ui-base/component');
const template = require('./index.html');
const _ = require('../../../../ui-base/_');

const bowser = require('bowser');
const moment = require('moment');
const polyfill = require('../../../../ui-base/polyfill');

const MS_OF_DAY = 24 * 3600 * 1000;

/**
 * @class Calendar
 * @extend Component
 * @param {object}        [options.data]                  = 绑定属性
 * @param {Date|string}   [options.data.date]             <=> 当前选择的日期,默认当前日期
 * @param {Date|string}   [options.data.minDate=null]     => 最小日期,如果为空则不限制
 * @param {Date|string}   [options.data.maxDate=null]     => 最大日期,如果为空则不限制
 * @param {boolean}       [options.data.readonly=false]   => 是否只读
 * @param {boolean}       [options.data.disabled=false]   => 是否禁用
 * @param {boolean}       [options.data.visible=true]     => 是否显示
 * @param {string}        [options.data.class]            => 补充class
 */
const Calendar = Component.extend({
  name: 'calendar',
  template: _.compressHtml(template),
  /**
     * @protected
     */
  config() {
    _.extend(this.data, {
      date: null,
      minDate: null,
      maxDate: null,
      _days: [],
    });
    this.supr();

    this.$watch('date', function (newValue, oldValue) {
      // 字符类型自动转为日期类型
      if (typeof newValue === 'string') {
        if (bowser.msie && bowser.version <= 9) {
          return (this.data.date = polyfill.StringDate(newValue));
        }
        return (this.data.date = newValue ? new Date(newValue) : new Date());
      } else if (typeof newValue === 'number') {
        return (this.data.date = new Date(newValue));
      }

      // 如果newValue为空, 则自动转到今天
      if (!newValue) {
        return (this.data.date = new Date(
          /* eslint no-bitwise: 0 */
          ((new Date() / MS_OF_DAY) >> 0) * MS_OF_DAY,
        ));
      }

      if (newValue === 'Invalid Date') throw new TypeError('Invalid Date');

      // 如果超出日期范围,则设置为范围边界的日期
      const isOutOfRange = this.isOutOfRange(newValue);
      if (isOutOfRange) {
        this.data.date = isOutOfRange;

        // 防止第二次刷新同月
        this._update();
        return;
      }

      if (!oldValue || !oldValue.getFullYear) this._update();
      else if (
        newValue.getFullYear() !== oldValue.getFullYear() ||
        newValue.getMonth() !== oldValue.getMonth()
      ) {
        this._update();
      }

      /**
             * @event change 日期改变时触发
             * @property {object} sender 事件发送对象
             * @property {object} date 改变后的日期
             */
      this.$emit('change', {
        sender: this,
        date: newValue,
      });
    });

    this.$watch('minDate', function (newValue) {
      if (!newValue) return;

      if (typeof newValue === 'string') {
        if (bowser.msie && bowser.version <= 9) {
          return (this.data.date = polyfill.StringDate(newValue));
        }
        return (this.data.minDate = new Date(newValue));
      }

      if (newValue === 'Invalid Date') throw new TypeError('Invalid Date');
    });

    this.$watch('maxDate', function (newValue) {
      if (!newValue) return;

      if (typeof newValue === 'string') {
        if (bowser.msie && bowser.version <= 9) {
          return (this.data.date = polyfill.StringDate(newValue));
        }
        return (this.data.maxDate = new Date(newValue));
      }

      if (newValue === 'Invalid Date') throw new TypeError('Invalid Date');
    });

    this.$watch(['minDate', 'maxDate'], function (minDate, maxDate) {
      if (
        !(
          (minDate && minDate instanceof Date) ||
          (maxDate && maxDate instanceof Date)
        )
      ) {
        return;
      }

      if (minDate && maxDate) {
        if ((minDate / MS_OF_DAY) >> 0 > (maxDate / MS_OF_DAY) >> 0) {
          throw new Calendar.DateRangeError(minDate, maxDate);
        }
      }

      // 如果超出日期范围,则设置为范围边界的日期
      const isOutOfRange = this.isOutOfRange(this.data.date);
      if (isOutOfRange) this.data.date = isOutOfRange;
    });
  },
  /**
     * @method _update() 日期改变后更新日历
     * @private
     * @return {void}
     */
  _update() {
    this.data._days = [];
    const date = this.data.date;
    const month = date.getMonth();
    const mfirst = new Date(date);
    mfirst.setDate(1);
    const mfirstTime = +mfirst;
    const nfirst = new Date(mfirst);
    nfirst.setMonth(month + 1);
    nfirst.setDate(1);
    const nfirstTime = +nfirst;
    const lastTime = nfirstTime + ((((7 - nfirst.getDay()) % 7) - 1) * MS_OF_DAY);
    let num = -mfirst.getDay();
    let tmpTime;
    let tmp;
    do {
      tmpTime = mfirstTime + (num * MS_OF_DAY);
      num += 1;
      tmp = new Date(tmpTime);
      this.data._days.push(tmp);
    } while (tmpTime < lastTime);
  },
  /**
     * @method addYear(year) 调整年份
     * @public
     * @param  {number} [year=0] 加/减的年份
     * @return {Date} date 计算后的日期
     */
  addYear(year) {
    if (this.data.readonly || this.data.disabled || !year) return;

    if (isNaN(year)) throw new TypeError(`${year} is not a number!`);

    const date = new Date(this.data.date);
    const oldMonth = date.getMonth();
    date.setFullYear(date.getFullYear() + year);
    if (date.getMonth() !== oldMonth) date.setDate(0);

    return (this.data.date = date);
  },
  /**
     * @method addMonth(month) 调整月份
     * @public
     * @param  {number} [month=0] 加/减的月份
     * @return {Date} date 计算后的日期
     */
  addMonth(month) {
    if (this.data.readonly || this.data.disabled || !month) return;

    if (isNaN(month)) throw new TypeError(`${month} is not a number!`);

    const date = new Date(this.data.date);
    const correctMonth = date.getMonth() + month;
    date.setMonth(correctMonth);
    // 如果跳月,则置为上一个月
    if ((date.getMonth() - correctMonth) % 12) date.setDate(0);

    return (this.data.date = date);
  },
  /**
     * @method select(date) 选择一个日期
     * @public
     * @param  {Date} date 选择的日期
     * @return {void}
     */
  select(date, e) {
    e.stopPropagation();
    if (this.data.readonly || this.data.disabled || this.isOutOfRange(date)) {
      return;
    }
    this.data.date = new Date(date);

    /**
         * @event select 选择某一个日期时触发
         * @property {object} sender 事件发送对象
         * @property {object} date 当前选择的日期
         */
    this.$emit('select', {
      sender: this,
      date,
    });
  },
  /**
     * @method goToday() 回到今天
     * @public
     * @return {void}
     */
  goToday() {
    if (this.data.readonly || this.data.disabled) return;

    this.data.date = new Date(((new Date() / MS_OF_DAY) >> 0) * MS_OF_DAY);
  },
  /**
     * @method isOutOfRange(date) 是否超出规定的日期范围
     * @public
     * @param {Date} date 待测的日期
     * @return {boolean|Date} date 如果没有超出日期范围,则返回false;如果超出日期范围,则返回范围边界的日期
     */
  isOutOfRange(date) {
    const minDate = this.data.minDate;
    const maxDate = this.data.maxDate;

    // minDate && date < minDate && minDate,先判断是否为空,再判断是否超出范围,如果超出则返回范围边界的日期
    return (
      (minDate && moment(date).isBefore(minDate, 'day') && minDate) ||
      (maxDate && moment(date).isAfter(maxDate, 'day') && maxDate)
    );
  },
});

const DateRangeError = function (minDate, maxDate) {
  this.name = 'DateRangeError';
  this.message = `Wrong Date Range where \`minDate\` is ${minDate} and \`maxDate\` is ${maxDate}!`;
};
DateRangeError.prototype = Object.create(RangeError.prototype);
DateRangeError.prototype.constructor = DateRangeError;
Calendar.DateRangeError = DateRangeError.prototype.constructor;

module.exports = Calendar;


text:
<!--
Copyright (C) 2015 The Android Open Source Project

   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.
-->

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="32.0dp"
        android:height="32.0dp"
        android:viewportWidth="32.0"
        android:viewportHeight="32.0"
        android:tint="@color/decor_button_light_color"
        >
    <group android:scaleX="0.5"
            android:scaleY="0.5"
            android:translateX="8.0"
            android:translateY="8.0" >
        <path
            android:fillColor="@color/white"
            android:pathData="M2.0,4.0l0.0,16.0l28.0,0.0L30.0,4.0L2.0,4.0zM26.0,16.0L6.0,16.0L6.0,8.0l20.0,0.0L26.0,16.0z"/>
        <path
            android:fillColor="@color/white"
            android:pathData="M2.0,24.0l28.0,0.0l0.0,4.0l-28.0,0.0z"/>
    </group>
</vector>


text:
##
# This file is part of WhatWeb and may be subject to
# redistribution and commercial restrictions. Please see the WhatWeb
# web site for more information on licensing and terms of use.
# http://www.morningstarsecurity.com/research/whatweb
##
Plugin.define "LISTSERV" do
author "Brendan Coles <bcoles@gmail.com>" # 2011-04-02
version "0.1"
description "LISTSERV launched the email list management industry in 1986 and remains the industry standard. It provides the power, reliability and enterprise-level performance you need to manage all your opt-in email lists, including email newsletters, announcement lists, discussion groups and email communities."
website "http://www.lsoft.com/products/listserv.asp"

# Google results as at 2011-04-02 #
# 68 for "Server Administration" "List Management" "List Moderation" "Subscriber's Corner" "Email Lists"

# Dorks #
dorks [
'"Server Administration" "List Management" "List Moderation" "Subscriber\'s Corner" "Email Lists"'
]

# Matches #
matches [

# CSS
{ :text=>'div.catalist h2 { font-family:times;  font-size:18pt; font-weight: bold; margin-bottom: }' },
{ :text=>'_white-space:pre;   /* IE only hack to re-specify in addition to word-wrap  */' },

# Powered by logo HTML
{ :text=>'alt="Powered by the LISTSERV Email List Manager" title="Powered by the LISTSERV Email List Manager" border="0">' },

# Redirect Page # Title
{ :text=>'<TITLE>LISTSERV - Redirecting ...</TITLE>' },

# Version Detection # Title
{ :version=>/<title>Welcome to LISTSERV ([\d\.]+)<\/title>/ },

# Version Detection # Logo
{ :version=>/<\/a><\/td>/ },

]

end


text:
__version__ = "0.4.4"

"""
Publish the a python package as AWS lambdas functions.
"""

import logging
import os
import pprint
import shutil
import types
import boto3
# noinspection PyPackageRequirements
from unix_dates import UnixDate

logger = logging.getLogger(__name__)

def aws_lambda(role_arn, timeout=60, memory=128, description="", vpc_config=None):
    """
    :type role_arn: str
    :type timeout: int
    :type memory: int
    :type description: str
    :type vpc_config: dict
    """

    def decorator(func):
        """
        Decorator to help identify which of the methods in a module are AWS Lambda functions.

        Note that this IS NOT a typical decorator. The only thing it does is add a private attribute to the function to
        mark it as an AWS lambda.
        """

        func.__aws_lambda__ = True
        func.__aws_lambda_role__ = role_arn
        func.__aws_lambda_timeout__ = timeout
        func.__aws_lambda_memory__ = memory
        func.__aws_lambda_description__ = description
        func.__aws_vpc_config__ = vpc_config

        return func

    return decorator

def get_all_lambda_functions_in_module(module_name):
    """
    Given a module (fully qualified module name), will return all the functions that are identified (using the
    aws_lambda decorator) as lambda functions.

    :param module_name: Fully qualified module name
    :return: List of all lambda function identified in the module
    :rtype: list
    """

    module = __import__(module_name, fromlist="*")

    lambda_functions = []

    for a in dir(module):
        attribute = getattr(module, a)
        if not isinstance(attribute, types.FunctionType):
            continue

        if "__aws_lambda__" in dir(attribute):
            lambda_functions.append(attribute)

    return lambda_functions

def get_latest_modified_date_in_dir(root_dir):
    """
    Recursively scan a directory to get the latest changes (used to detect if we need to upload code)

    :return: The latest modified date of all files in the directory
    """
    latest_modified = None

    for root, _, filenames in os.walk(root_dir):
        for fn in filenames:
            p = os.path.join(root, fn)

            parts = p.split(os.sep)

            if len(parts) > 1:
                if parts[1].startswith("."):
                    logger.debug("Skipping {}".format(p))
                    continue

                if parts[1] in ("lib", "lambda", "bin", "dist", "include"):
                    logger.debug("Skipping {}".format(p))
                    continue

            # Only consider the 'interesting files'. We don't want to scan random files
            _, ext = os.path.splitext(p)
            if ext not in (".py", ".txt", ".sh"):
                continue

            lm = os.stat(p).st_mtime

            if lm > (latest_modified or 0):
                latest_modified = lm

    return latest_modified

def plan(root_dir, modules, force, region):
    """
    Create a plan of upgrade existing AWS lambda functions with latest for this module.

    :type root_dir: str
    :type modules: collections.Iterable[str]
    :type force: bool
    :type force: bool
    :type region: str
    """
    module_functions = {}
    aws_functions = {}

    lambda_client = boto3.client("lambda", region_name=region)

    for module_name in modules:
        module_functions.update(
            {(module_name, fn.__name__): fn for fn in get_all_lambda_functions_in_module(module_name)})

        aws_functions.update(
            {(module_name, fn["FunctionName"]):
                 fn for fn in lambda_client.list_functions()["Functions"] if fn["Handler"].startswith(module_name)})

    to_create = {k: fn for k, fn in module_functions.iteritems() if k not in aws_functions}
    to_delete = {k: fn for k, fn in aws_functions.iteritems() if k not in module_functions}

    last_modified = get_latest_modified_date_in_dir(root_dir)

    # Examine the ones to update to see if anything changed...
    to_update, unchanged = {}, set()
    for fn_key, aws_function in aws_functions.iteritems():
        module_function = module_functions.get(fn_key)
        if not module_function:
            # We are looking for the ones that are in BOTH lists (to update / unchanged)
            continue

        changed = False
        changes = set()

        if aws_function["Role"] != module_function.__aws_lambda_role__:
            changed = True
            changes.add("Role")

        if aws_function["MemorySize"] != module_function.__aws_lambda_memory__:
            changed = True
            changes.add("MemorySize")

        if aws_function["Timeout"] != module_function.__aws_lambda_timeout__:
            changed = True
            changes.add("Timeout")

        # Check last modified (need to be within reasonable delta)
        if UnixDate.to_unix_time_from_iso_format(aws_function["LastModified"]) < last_modified:
            logger.info("Detected code change in function {}".format(fn_key))

            changed = True
            changes.add("Code")

        if changed or force:
            to_update[fn_key] = (aws_function, module_function, changes)
        else:
            unchanged.add(fn_key)

    return to_create, to_update, to_delete, unchanged

def print_plan(modules, to_create, to_update, to_delete, unchanged):
    # Group updates by reason
    update_with_reason = {(k, d[2]) for k, d in to_update.iteritems()}

    logger.info(pprint.pformat("The plan is (for modules {}):".format(modules)))
    logger.info(pprint.pformat("   Create: {}".format(to_create.keys())))
    logger.info(pprint.pformat("   Delete: {}".format(to_delete.keys())))
    logger.info(pprint.pformat("   Update: {}".format(update_with_reason)))
    logger.info(pprint.pformat("   Unchanged: {}".format(unchanged)))

def package_and_upload_module(root_dir, requirements_path, module_name, bucket, region):
    """
    Installs the module + all requirements into a folder ('lambda'). Zip it ('lambda.zip') and
    upload it to the indicated bucket in S3.

    :type root_dir: str
    :type bucket: str
    :type requirements_path: str
    :type module_name: str
    :type region: str

    :return: The s3 object key, path to the local zip file
    :rtype: str
    """

    s3_client = boto3.client("s3", region_name=region)

    assert os.path.isdir(root_dir)
    assert os.path.isfile(requirements_path)

    dist_dir = os.path.join(root_dir, "dist")
    lambda_target = "lambdas"

    # Clean up first (from any previous installation)
    lambda_dir = os.path.join(dist_dir, lambda_target)
    if os.path.exists(lambda_dir):
        shutil.rmtree(lambda_dir)

    lambda_zip = os.path.join(dist_dir, "{}.zip".format(lambda_target))
    if os.path.exists(lambda_zip):
        os.remove(lambda_zip)

    os.makedirs(lambda_dir)

    # Install the required packages
    import pip
    pip.main(["install", ".", "-t", lambda_dir])

    # Install requirements
    pip.main(["install", "-r", requirements_path, "-t", lambda_dir])

    # Make sure this package is part of the requirements!
    pip.main(["install", "publish_aws_lambda", "-t", lambda_dir])
    pip.main(["install", "unix_dates", "-t", lambda_dir])

    # No need for boto3 to be packaged
    for fn in os.listdir(lambda_dir):
        p = os.path.join(lambda_dir, fn)

        if os.path.isdir(p) and fn.startswith("boto"):
            shutil.rmtree(p)

    # ZIP it up!
    lambda_zip = shutil.make_archive(lambda_target, "zip", lambda_dir)

    # And upload to S3 (use module as object key)
    s3_client.upload_file(Filename=lambda_zip,
                          Bucket=bucket,
                          Key=module_name,
                          ExtraArgs={'ACL': 'bucket-owner-full-control'})

    logger.info("Uploaded {} to S3 bucket {} as {}".format(lambda_zip, bucket, module_name))

    return module_name

def publish(root_dir, modules, bucket, region, force=False):
    """
    Perform the publish / sync of the lambda functions. This includes packaging the lambda functions in this
    module, uploading it to S3 and then setting up the lambda function configuration

    :type root_dir: str
    :type modules: collections.Iterable[str]
    :type bucket: str
    :type force: bool
    :type region: str
    """

    lambda_client = boto3.client("lambda", region_name=region)

    # Check root_dir and make sure it has a "requirements.txt" file in it
    requirements_path = os.path.join(root_dir, "requirements.txt")
    assert os.path.exists(requirements_path), "Expecting requirements.txt to be in root_dir"

    to_create, to_update, to_delete, unchanged = plan(root_dir, modules, force, region=region)

    for fn_name in to_delete.keys():
        logger.info("Deleting lambda function {}".format(fn_name))
        lambda_client.delete_function(FunctionName=fn_name)

    for fn_key, fn in to_create.iteritems():
        module_name, fn_name = fn_key

        logger.info("Creating lambda function {}".format(fn_name))

        s3_object_key = package_and_upload_module(root_dir=root_dir,
                                                  module_name=module_name,
                                                  bucket=bucket,
                                                  requirements_path=requirements_path,
                                                  region=region)

        lambda_client.create_function(FunctionName=fn_name,
                                      Runtime="python2.7",
                                      Role=fn.__aws_lambda_role__,
                                      Handler="{}.{}".format(module_name, fn_name),
                                      Code={
                                          'S3Bucket': bucket,
                                          'S3Key': s3_object_key,
                                      },
                                      Description=fn.__aws_lambda_description__,
                                      Timeout=fn.__aws_lambda_timeout__,
                                      MemorySize=fn.__aws_lambda_memory__,
                                      VpcConfig=fn.__aws_vpc_config__,
                                      Publish=True)

    for fn_key, (aws_function, module_function, changes) in to_update.iteritems():
        module_name, fn_name = fn_key

        logger.info("Updating lambda function {}".format(fn_name))

        # Check if we need to change the attributes of the function
        if {"Role", "MemorySize", "Timeout"}.intersection(changes):
            lambda_client.update_function_configuration(FunctionName=fn_name,
                                                        Role=module_function.__aws_lambda_role__,
                                                        Handler="{}.{}".format(module_name, fn_name),
                                                        Description=module_function.__aws_lambda_description__,
                                                        Timeout=module_function.__aws_lambda_timeout__,
                                                        MemorySize=module_function.__aws_lambda_memory__)

        if "Code" in changes or force:
            s3_object_key = package_and_upload_module(root_dir=root_dir,
                                                      module_name=module_name,
                                                      requirements_path=requirements_path,
                                                      bucket=bucket,
                                                      region=region)

            lambda_client.update_function_code(FunctionName=fn_name,
                                               S3Bucket=bucket,
                                               S3Key=s3_object_key,
                                               Publish=True)


text:
Imports System.ComponentModel
Imports System.Runtime.CompilerServices

Public Class MainWindowViewModel
    Implements INotifyPropertyChanged

    Private _model As Person
    Private _clickCommand As ICommand

    Public Sub New()
#If DEBUG Then
        Me.New( _
            If(DesignerProperties.GetIsInDesignMode(New DependencyObject()), _
               CType(New DataServiceInDesign(), IDataService), _
               New DataService()))
#End If
    End Sub

    Public Sub New(dataService As IDataService)
        Dim personData = dataService.GetPerson()

        _model = New Person() With { _
            .FirstName = personData.FirstName, _
            .LastName = personData.LastName _
        }

        _clickCommand = New DelegateCommand(Sub() _model.LastName = [String].Format("{0} *", _model.LastName))
    End Sub

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Public Property Model As Person
        Get
            Return _model
        End Get

        Set(value As Person)
            _model = value
            OnPropertyChanged()
        End Set
    End Property

    Public Property ClickCommand As ICommand
        Get
            Return _clickCommand
        End Get

        Set(value As ICommand)
            _clickCommand = value
            OnPropertyChanged()
        End Set
    End Property

    Protected Overridable Sub OnPropertyChanged(<CallerMemberName> Optional propertyName As [String] = Nothing)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub
End Class


text:
#pragma once

#include <CorePlatform/CPPlatform.h>
#include <CorePlatform/CPConfig.h>
#include <CorePlatform/CPTypes.h>
#include <CorePlatform/CPAnnotations.h>
#include <CorePlatform/CPCodeUtilities.h>
#include <CorePlatform/CPMath.h>
#include <CorePlatform/CPAtomic.h>
#include <CorePlatform/CPMemory.h>
#include <CorePlatform/CPDebugging.h>
#include <CorePlatform/CPObject.h>

CP_EXTERNC_BEGIN

typedef enum CPSeekOrigin_e {
    CPSeekOriginSet             = 0,
    CPSeekOriginCurrent         = 1,
    CPSeekOriginEnd             = 2,
} CPSeekOrigin;

CP_DECLARE_TYPE(CPReadStream);

struct CPReadStream_t {
    CPObject        object;

    BOOL            closed;

    void (*close)(sal_inout CPReadStreamRef stream);

    size_t (*getLength)(sal_inout CPReadStreamRef stream);
    BOOL (*isEOF)(sal_inout CPReadStreamRef stream);

    size_t (*getPosition)(sal_inout CPReadStreamRef stream);
    void (*seek)(sal_inout CPReadStreamRef stream, const size_t offset, const CPSeekOrigin origin);

    size_t (*readBuffer)(sal_inout CPReadStreamRef stream, sal_out_bcount_opt(bufferSize) byte* buffer, const size_t bufferSize);
    size_t (*readSection)(sal_inout CPReadStreamRef stream, const size_t offset, sal_out_bcount_opt(bufferSize) byte* buffer, const size_t bufferSize);
};

CP_API sal_checkReturn sal_out_opt CPReadStreamRef CPReadStreamAlloc(sal_in const CPObjectType* subclassType, const size_t size);

CP_API void CPReadStreamClose(sal_inout CPReadStreamRef stream);

CP_API size_t CPReadStreamGetLength(sal_inout CPReadStreamRef stream);
CP_API BOOL CPReadStreamIsEOF(sal_inout CPReadStreamRef stream);

CP_API size_t CPReadStreamGetPosition(sal_inout CPReadStreamRef stream);
CP_API void CPReadStreamSetPosition(sal_inout CPReadStreamRef stream, const size_t position);
CP_API void CPReadStreamSeek(sal_inout CPReadStreamRef stream, const size_t offset, const CPSeekOrigin origin);

CP_API size_t CPReadStreamReadBuffer(sal_inout CPReadStreamRef stream, sal_out_bcount_opt(bufferSize) byte* buffer, const size_t bufferSize);
CP_API size_t CPReadStreamReadSection(sal_inout CPReadStreamRef stream, const size_t offset, sal_out_bcount_opt(bufferSize) byte* buffer, const size_t bufferSize);

CP_EXTERNC_END


text:
julia
python
markdown
pandoc


text:
package edu.mayo.mprc.mascot;

import edu.mayo.mprc.MprcException;
import edu.mayo.mprc.daemon.worker.WorkPacketBase;
import edu.mayo.mprc.daemon.worker.Worker;
import edu.mayo.mprc.integration.Installer;
import edu.mayo.mprc.swift.params2.mapping.MappingContext;
import edu.mayo.mprc.swift.params2.mapping.Mappings;
import edu.mayo.mprc.swift.params2.mapping.ParamsInfo;
import edu.mayo.mprc.swift.params2.mapping.TestMappingContextBase;
import edu.mayo.mprc.utilities.FileUtilities;
import edu.mayo.mprc.utilities.log.ParentLog;
import edu.mayo.mprc.utilities.log.SimpleParentLog;
import edu.mayo.mprc.utilities.progress.ProgressInfo;
import edu.mayo.mprc.utilities.progress.ProgressReporter;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

public final class TestMascotDaemonWorker {
	private static final Logger LOGGER = Logger.getLogger(TestMascotDaemonWorker.class);
	private File mascotTemp;
	private File inputMgfFile;
	private File inputMgfFolder;
	private static final String MASCOT_URL = "http://mascot.mayo.edu";
	private static final String TEST_MASCOT_DB = "Current_SP";

	@BeforeClass
	public void setup() throws IOException {
		mascotTemp = FileUtilities.createTempFolder();
		inputMgfFolder = Installer.mgfFiles(null, Installer.Action.INSTALL);
		inputMgfFile = new File(inputMgfFolder, "test.mgf");
	}

	@AfterClass
	public void teardown() {
		Installer.mgfFiles(inputMgfFolder, Installer.Action.UNINSTALL);
		FileUtilities.cleanupTempFile(mascotTemp);
	}

	@Test
	public void shouldProvideCorrectCgiUrl() throws MalformedURLException {
		Assert.assertEquals(MascotWorker.mascotCgiUrl(
						new URL("http://mascot.mayo.edu/")),
				new URL("http://mascot.mayo.edu/" + MascotWorker.MASCOT_CGI),
				"Mascot CGI script path generated incorrectly");
		Assert.assertEquals(MascotWorker.mascotCgiUrl(
						new URL("http://crick4.mayo.edu:2080/mascot/")),
				new URL("http://crick4.mayo.edu:2080/mascot/" + MascotWorker.MASCOT_CGI),
				"Mascot CGI script path generated incorrectly");

		// CAREFUL! You always MUST provide the trailing slash
		Assert.assertEquals(MascotWorker.mascotCgiUrl(
						new URL("http://crick4.mayo.edu:2080/mascot")),
				new URL("http://crick4.mayo.edu:2080/" + MascotWorker.MASCOT_CGI),
				"Mascot CGI script path generated incorrectly");

	}

	@Test
	public void runMascotWorker() throws IOException {
		final File mascotOut = new File(mascotTemp, "mascot.dat");

		final String mascotParams = createMascotParams();
		final MascotWorker.Config config = new MascotWorker.Config();
		config.put(MascotWorker.MASCOT_URL, MASCOT_URL);
		final MascotWorker.Factory factory = new MascotWorker.Factory();

		final Worker worker = factory.create(config, null);

		final MascotWorkPacket workPacket = new MascotWorkPacket(mascotOut, mascotParams, inputMgfFile, TEST_MASCOT_DB, false, false);
		WorkPacketBase.simulateTransfer(workPacket);

		worker.processRequest(workPacket, new ProgressReporter() {
			@Override
			public void reportStart(final String hostString) {
				LOGGER.info("Started processing on " + hostString);
			}

			@Override
			public void reportProgress(final ProgressInfo progressInfo) {
				LOGGER.info(progressInfo);
			}

			@Override
			public ParentLog getLog() {
				return new SimpleParentLog();
			}

			@Override
			public void reportSuccess() {
				Assert.assertTrue(mascotOut.length() > 0, "Mascot result file is empty.");
			}

			@Override
			public void reportFailure(final Throwable t) {
				throw new MprcException("Mascot worker failed to process work packet.", t);
			}
		});
	}

	private String createMascotParams() {
		final ParamsInfo paramsInfo = TestMascotMappings.getAbstractParamsInfo();
		final MascotMappingFactory factory = new MascotMappingFactory();
		factory.setParamsInfo(paramsInfo);
		final Mappings mapping = factory.createMapping();
		final MappingContext context = new TestMappingContextBase(paramsInfo);

		mapping.read(mapping.baseSettings());
		mapping.setSequenceDatabase(context, TEST_MASCOT_DB);

		StringWriter writer = new StringWriter(100);
		mapping.write(mapping.baseSettings(), writer);

		return writer.toString();
	}
}


text:
package com.witchworks.common.core.capability.potion;

import com.witchworks.api.item.BrewEffect;
import com.witchworks.api.item.IBrew;
import net.minecraft.entity.EntityLivingBase;

import java.util.Map;
import java.util.Optional;

/**
 * This class was created by Arekkuusu on 23/04/2017.
 * It's distributed as part of Witchworks under
 * the MIT license.
 */
public final class BrewStorageHandler {

	private BrewStorageHandler() {
	}

	/**
	 * Returns the {@link IBrewStorage} interface of the brew storage.
	 * @param entity The entity
	 * @return An {@link Optional <IBrewStorage>} for correctness
	 */
	@SuppressWarnings ("ConstantConditions")
	public static Optional<IBrewStorage> getBrewStorage(EntityLivingBase entity) {
		if (entity.hasCapability(BrewStorageProvider.BREW_STORAGE_CAPABILITY, null)) {
			return Optional.of(entity.getCapability(BrewStorageProvider.BREW_STORAGE_CAPABILITY, null));
		}
		return Optional.empty();
	}

	/**
	 * Checks if a Brew is active.
	 * @param entity The entity
	 * @param brew The brew
	 * @return If it is active
	 */
	public static boolean isBrewActive(EntityLivingBase entity, IBrew brew) {
		Optional<IBrewStorage> optional = BrewStorageHandler.getBrewStorage(entity);
		return optional.isPresent() && optional.get().getBrews().containsKey(brew);
	}

	/**
	 * Add a BrewEffect to the entity.
	 * @param entity The entity
	 * @param effect The effect
	 */
	public static void addEntityBrewEffect(EntityLivingBase entity, BrewEffect effect) {
		Optional<IBrewStorage> optional = BrewStorageHandler.getBrewStorage(entity);
		if (optional.isPresent()) {
			Map<IBrew, BrewEffect> effectMap = optional.get().getBrews();
			BrewEffect out = effectMap.get(effect.getBrew());
			if (out == null || effect.getDuration() > out.getDuration()) {
				effectMap.put(effect.getBrew(), effect);
			}
			optional.get().setBrews(effectMap);
		}
	}
}


text:
These are samples for using [Node.js][nodejs] on
[Google App Engine][appengine]. Many of these samples
are referenced from the documentation on [cloud.google.com][appengine].

There are also samples [submitted by the community][community_samples].

See our other [Google Cloud Platform GitHub repositories](https://github.com/GoogleCloudPlatform)
for sample applications and scaffolding for other frameworks and use cases.

* [Run Locally](#run-locally)
* [Deploying](#deploying)
* [Official samples](#official-samples)
* [Community samples](#community-samples)

## Run Locally

Some samples have specific instructions. If there is a `README.md` file in the
sample folder, please refer to it for any additional steps required to run the
sample.

The App Engine Node.js samples typically require that you do the following:

1.  [Setup your environment for Node.js development][nodejs_dev].
1.  [Install the Google Cloud SDK][sdk].
1.  Acquire local credentials for authenticating with Google Cloud Platform APIs:

        gcloud auth application-default login

1.  Clone this repo:

        git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

1.  Choose a sample:

        cd appengine/sample-folder/

1.  Install dependencies:

        npm install

1.  Run the sample with `npm` (See the sample's `README.md` file for
    any additional setup):

        npm start

1.  Visit the application at http://localhost:8080.

## Deploying

Some samples may have special deployment instructions.
Refer to the `README.md` file in the sample folder.

Many samples in this folder can be deployed to both App Engine Node.js standard
environment and flexible environment. Those samples come with two different
App Engine configuration files: `app.flexible.yaml` for flexible environment,
and `app.standard.yaml` for standard environment.

Samples with one single configuration file, `app.yaml`, can only be deployed
to one of the two environments. See the `README.md` files for these samples
for more information.

Generally speaking, to deploy a sample application:

1.  Use the [Google Cloud Console][console] to create a Google Cloud Platform
    project.
1.  [Enable billing][billing] for your project.

1.  Use the Cloud SDK to deploy your app.

    For samples with two configuration files (`app.flexible.yaml` and
    `app.standard.yaml`), if you plan to use App Engine Node.js Standard
    Environment, run

        gcloud app deploy app.standard.yaml

    To deploy to App Engine Node.js Flexible Environment, run

        gcloud app deploy app.flexible.yaml

    For samples with one configuration file (`app.yaml`), run

        gcloud app deploy

    to deploy the app to its compatible environment.

1.  View your deployed application at `https://YOUR_PROJECT_ID.appspot.com`.

## Official samples

View the [Official App Engine Node.js samples][official_samples].

## Community samples

View the [Community-contributed App Engine Node.js samples][community_samples].

[nodejs]: https://nodejs.org/
[appengine]: https://cloud.google.com/appengine/
[nodejs_dev]: https://cloud.google.com/community/tutorials/how-to-prepare-a-nodejs-dev-environment
[sdk]: https://cloud.google.com/sdk/
[console]: https://console.cloud.google.com
[billing]: https://support.google.com/cloud/answer/6293499#enable-billing
[official_samples]: https://github.com/GoogleCloudPlatform/nodejs-docs-samples/tree/main/appengine
[community_samples]: https://cloud.google.com/community/tutorials/?q=%22Node.js%22


text:
<?php
namespace Admin\Model;

// use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Model;
class Customer extends Model{

    public function fetchAll()
    {
        $sql=$this->_tableGateway->getSql();
        $select=$sql->select()->join(array('p'=>'product'),'p.id=customer.id',['product'])->where('p.product regexp "33|22"');
        $select->where->or->equalTo('p.id', 1);
        //echo $sql->getSqlStringForSqlObject($select);
        //return $sql->prepareStatementForSqlObject($select)->execute();
       return  $this->_tableGateway->select();
    }

}


text:
void cursorPosCallback(GLFWwindow* window, double cursorX, double cursorY);
void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
void mouseScrollCallback(GLFWwindow* window, double xoffset, double yoffset);

// Keyboard Callback
void keyboardKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
void keyboardCharCallback(GLFWwindow* window, unsigned int codepoint);

// Window
void windowResizeCallback(GLFWwindow* window, int width, int height);

// Callback Setup
void setCallbacks(GLFWwindow* window);


text:
package io.mycat.server.executors;

import io.mycat.backend.BackendConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author mycat
 */
public class RollbackReleaseHandler implements ResponseHandler {
	private static final Logger logger = LoggerFactory
			.getLogger(RollbackReleaseHandler.class);

	public RollbackReleaseHandler() {
	}

	@Override
	public void connectionAcquired(BackendConnection conn) {
		logger.error("unexpected invocation: connectionAcquired from rollback-release");
	}

	@Override
	public void connectionError(Throwable e, BackendConnection conn) {

	}

	@Override
	public void errorResponse(byte[] err, BackendConnection conn) {
		conn.quit();
	}

	@Override
	public void okResponse(byte[] ok, BackendConnection conn) {
        logger.debug("autocomit is false,but no commit or rollback ,so mycat rollbacked backend conn "+conn);
		conn.release();
	}

	@Override
	public void fieldEofResponse(byte[] header, List<byte[]> fields,
			byte[] eof, BackendConnection conn) {
	}

	@Override
	public void rowResponse(byte[] row, BackendConnection conn) {
	}

	@Override
	public void rowEofResponse(byte[] eof, BackendConnection conn) {

	}

	@Override
	public void connectionClose(BackendConnection conn, String reason) {

	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for RepositoryReport
/// </summary>
public class RepositoryReport
{
    public RepositoryReport()
    {
        //
        // TODO: Add constructor logic here
        //

    }
    static DBDataContext db;
    //public static IList<TieuChiTongHopReport> GetTieuChiTongHop()
    //{
    //    using (db = new DBDataContext(MyUtility.ChuoiKetNoi))
    //    {
    //        var result = (from dv in db.DonVis
    //                      select new TieuChiTongHopReport
    //                    {
    //                        MaDV = dv.MaDV,
    //                        TenDV = dv.TenDV
    //                    }).ToList();

    //        return result;
    //    }
    //}

    public static List<ChuKyDanhGiaReport> GetChuKyDanhGiaReport(int ckid)
    {
        using (db = new DBDataContext(MyUtility.ChuoiKetNoi))
        {
            var result = (from ckdg in db.ChuKyDanhGias
                          from bmdg in db.BieuMauDanhGias
                          where ckdg.MaCK == bmdg.MaCK
                          && (ckdg.MaCK == ckid || ckid == -1) // filter by chu kỳ
                          select new ChuKyDanhGiaReport
                          {
                              TenBieuMau = bmdg.TenBM,
                              TenCK = ckdg.TenCK,
                              FromDate = ckdg.BatDau,
                              ToDate = ckdg.KetThuc,
                              TongTieuChi = (from tctbm in db.TieuChiTheoBieuMaus
                                             where tctbm.MaBM == bmdg.MaBM
                                                  select 1).Sum()

                          }).ToList();

            return result;

        }
    }

    public static List<NhanVienReport> GetThongTinNhanVien(int vaitroid, int bophanId)
    {
        using (db = new DBDataContext(MyUtility.ChuoiKetNoi))
        {
            var result = (from nv in db.NhanViens
                          from vt in db.VaiTros
                          from cm in db.ChuyenMons
                          from vtcv in db.ViTriCongViecs
                          from dv in db.DonVis
                          from bp in db.BoPhans
                          where nv.MaVT == vt.MaVT
                          && (vt.MaVT == vaitroid || vaitroid == -1) // filter by vaitro
                          && (bp.MaBP == bophanId || bophanId == -1) // filter by Bophan
                          && nv.MaCM == cm.MaCM
                          && nv.MaVTCV == vtcv.MaVTCV
                          && vt.MaDV == dv.MaDV
                          && vtcv.MaBP == bp.MaBP
                          select new NhanVienReport
                          {
                              MaNhanVien = nv.MaNV,
                              HoTen = nv.HoTen,
                              DienThoai = nv.DienThoai,
                              Email = nv.Email,
                              GioiTinh = nv.GioiTinh == true ? "Nam" : "Nữ",
                              NgaySinh = nv.NgaySinh,
                              VaiTro = vt.TenVT,
                              ChuyenMon = cm.TenCM,
                              ViTriCongViec = vtcv.TenVTCV,
                              DonVi = dv.TenDV,
                              BoPhan = bp.TenBP
                          }).ToList();

            return result;
        }
    }
}

public class ChuKyDanhGiaReport
{
    public string TenCK { get; set; }

    public DateTime FromDate { get; set; }

    public DateTime ToDate { get; set; }

    public string TenBieuMau { get; set; }

    public int? TongTieuChi { get; set; }

}

public class NhanVienReport
{
    public string MaNhanVien { get; set; }

    public string HoTen { get; set; }

    public string GioiTinh { get; set; }

    public DateTime? NgaySinh { get; set; }

    public string DienThoai { get; set; }

    public string Email { get; set; }

    public string VaiTro { get; set; }

    public string ChuyenMon { get; set; }

    public string DonVi { get; set; }

    public string ViTriCongViec { get; set; }

    public string BoPhan { get; set; }

}

public class DetailBieuMauDanhGia
{
    public int STT { get; set; }
    public string NhomTieuChi { get; set; }
    public string TenTieuChi { get; set; }
    //public int MyProperty { get; set; }
}


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20130925190707 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'.");

        $this->addSql("CREATE INDEX bgg_id ON dan_game (bgg_id)");
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'.");

        $this->addSql("DROP INDEX bgg_id ON dan_game");
    }
}


text:
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace TestStack.FluentMVCTesting
{
    public static class ControllerExtensions
    {

        public static T WithModelErrors<T>(this T controller) where T : Controller
        {
            controller.ModelState.AddModelError("Key", "Value");
            return controller;
        }

        public static ControllerResultTest<T> WithCallTo<T, TAction>(this T controller, Expression<Func<T, TAction>> actionCall)
            where T : Controller
            where TAction : ActionResult
        {
            var actionName = ((MethodCallExpression)actionCall.Body).Method.Name;

            var actionResult = actionCall.Compile().Invoke(controller);

            return new ControllerResultTest<T>(controller, actionName, actionResult);
        }

        public static ControllerResultTest<T> WithCallTo<T, TAction>(this T controller, Expression<Func<T, Task<TAction>>> actionCall)
            where T : Controller
            where TAction : ActionResult
        {
            var actionName = ((MethodCallExpression)actionCall.Body).Method.Name;

            var actionResult = actionCall.Compile().Invoke(controller).Result;

            return new ControllerResultTest<T>(controller, actionName, actionResult);
        }

        public static ControllerResultTest<T> WithCallToChild<T, TAction>(this T controller, Expression<Func<T, TAction>> actionCall)
            where T : Controller
            where TAction : ActionResult
        {
            var action = ((MethodCallExpression)actionCall.Body).Method;

            if (!action.IsDefined(typeof(ChildActionOnlyAttribute), false))
                throw new InvalidControllerActionException(string.Format("Expected action {0} of controller {1} to be a child action, but it didn't have the ChildActionOnly attribute.", action.Name, controller.GetType().Name));

            return controller.WithCallTo(actionCall);
        }

        public static ControllerResultTest<T> WithCallToChild<T, TAction>(this T controller, Expression<Func<T, Task<TAction>>> actionCall)
            where T : Controller
            where TAction : ActionResult
        {
            var action = ((MethodCallExpression)actionCall.Body).Method;

            if (!action.IsDefined(typeof(ChildActionOnlyAttribute), false))
                throw new InvalidControllerActionException(string.Format("Expected action {0} of controller {1} to be a child action, but it didn't have the ChildActionOnly attribute.", action.Name, controller.GetType().Name));

            return controller.WithCallTo(actionCall);
        }

        public static TempDataResultTest ShouldHaveTempDataProperty(this ControllerBase controller, string key, object value = null)
        {
            var actual = controller.TempData[key];

            if (actual == null)
            {
                throw new TempDataAssertionException(string.Format(
                    "Expected TempData to have a non-null value with key '{0}', but none found.", key));
            }

            if (value != null && actual.GetType() != value.GetType())
            {
                throw new TempDataAssertionException(string.Format(
                    "Expected value to be of type {0}, but instead was {1}.",
                    value.GetType().FullName,
                    actual.GetType().FullName));
            }

            if (value != null && !value.Equals(actual))
            {
                throw new TempDataAssertionException(string.Format(
                    "Expected value for key '{0}' to be '{1}', but instead found '{2}'", key, value, actual));
            }

            return new TempDataResultTest(controller);
        }

        public static TempDataResultTest ShouldHaveTempDataProperty<TValue>(this ControllerBase controller, string key, Func<TValue, bool> predicate)
        {
            var actual = controller.TempData[key];

            if (actual == null)
            {
                throw new TempDataAssertionException(string.Format(
                    "Expected TempData to have a non-null value with key '{0}', but none found.", key));
            }

            if (!predicate((TValue)actual))
            {
                throw new TempDataAssertionException("Expected view model to pass the given condition, but it failed.");
            }

            return new TempDataResultTest(controller);
        }

        public static TempDataResultTest ShouldNotHaveTempDataProperty(this ControllerBase controller, string key)
        {
            var actual = controller.TempData[key];

            if (actual != null)
            {
                throw new TempDataAssertionException(string.Format(
                    "Expected TempData to have no value with key '{0}', but found one.", key));
            }

            return new TempDataResultTest(controller);
        }

    }
}


text: nodemon server/server.js


text:
package core

import (
	"fmt"
	"io/ioutil"
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"
	"github.com/wercker/docker-check-access"
	"github.com/wercker/wercker/auth"
	"github.com/wercker/wercker/util"
)

type ConfigSuite struct {
	*util.TestSuite
}

func TestConfigSuite(t *testing.T) {
	suiteTester := &ConfigSuite{&util.TestSuite{}}
	suite.Run(t, suiteTester)
}

func (s *ConfigSuite) TestConfigBoxStrings() {
	b, err := ioutil.ReadFile("../tests/box_strings.yml")
	s.Nil(err)
	config, err := ConfigFromYaml(b)
	s.Require().Nil(err)
	s.Equal("strings_box", config.Box.ID)
	s.Equal("strings_service", config.Services[0].ID)
	//check to see if both the service and box has an auth
	assert.NotNil(s.T(), config.Box.Auth)
	assert.NotNil(s.T(), config.Services[0].Auth)
}

func (s *ConfigSuite) TestConfigBoxStructs() {
	b, err := ioutil.ReadFile("../tests/box_structs.yml")
	s.Nil(err)
	config, err := ConfigFromYaml(b)
	s.Require().Nil(err)
	s.Equal("structs_box", config.Box.ID)
	s.Equal("structs_service", config.Services[0].ID)
	assert.NotNil(s.T(), config.Box.Auth)
	assert.NotNil(s.T(), config.Services[0].Auth)

	pipeline := config.PipelinesMap["pipeline"]
	s.Equal(pipeline.Box.ID, "blue")
	s.Equal(pipeline.Steps[0].ID, "string-step")
	s.Equal(pipeline.Steps[1].ID, "script")
	s.Equal(pipeline.Steps[2].ID, "script")

	// test to see if proper authenticatables are set
	// and if those return the proper authenticators
	amzn := config.PipelinesMap["amzn"]
	assert.NotNil(s.T(), amzn.Box.Auth)
	env := util.NewEnvironment(os.Environ()...)
	amzn.Box.Auth.Interpolate(env)
	authenticator, err := dockerauth.GetRegistryAuthenticator(amzn.Box.Auth)
	s.Empty(err)
	_, ok := authenticator.(*auth.AmazonAuth)
	s.Equal(ok, true)

	docker := config.PipelinesMap["docker-v2"]
	assert.NotNil(s.T(), docker.Box.Auth)
	docker.Box.Auth.Interpolate(env)
	authenticator, err = dockerauth.GetRegistryAuthenticator(docker.Box.Auth)
	s.Empty(err)
	_, ok = authenticator.(*auth.DockerAuth)
	s.Equal(ok, true)

	dockerV1 := config.PipelinesMap["docker"]
	assert.NotNil(s.T(), dockerV1.Box.Auth)
	dockerV1.Box.Auth.Interpolate(env)
	authenticator, err = dockerauth.GetRegistryAuthenticator(dockerV1.Box.Auth)
	s.Empty(err)
	_, ok = authenticator.(auth.DockerAuthV1)
	s.Equal(ok, true)

	azure := config.PipelinesMap["azure"]
	assert.NotNil(s.T(), azure.Box.Auth)
	azure.Box.Auth.Interpolate(env)
	authenticator, err = dockerauth.GetRegistryAuthenticator(azure.Box.Auth)
	s.Empty(err)
	_, ok = authenticator.(*auth.Azure)
	s.Equal(ok, true)
}

func (s *ConfigSuite) TestIfaceToString() {
	tests := []struct {
		input    interface{}
		expected string
	}{
		{"string input", "string input"},
		{int(1234), "1234"},
		{int32(123432), "123432"},
		{int64(123464), "123464"},
		{true, "true"},
		{false, "false"},

		// The following types are not supported, so a empty string is returned
		{nil, ""},
		{float32(123.123), ""},
		{float64(123.123), ""},
	}

	for _, test := range tests {
		actual := ifaceToString(test.input)
		s.Equal(test.expected, actual, "")
	}
}

func (s *ConfigSuite) TestWorkflowValidation() {
	b, err := ioutil.ReadFile("../tests/workflow_validation.yml")
	s.Nil(err)
	config, err := ConfigFromYaml(b)
	s.Require().Nil(err)

	tests := []struct {
		workflowName        string
		expectedErrorString string
	}{
		{"seq", ""},
		{"fanin", ""},
		{"fanin2", ""},
		{"faninOne", ""},
		{"fanout1", ""},
		{"circular1", "contains cycle echoa -> echob -> echoa"},
		{"circular2", "contains cycle echoa -> echoa"},
		{"circular3", "contains cycle echob -> readfile -> echob"},
		{"circular4", "contains cycle echob -> readfile -> readfile2 -> echob"},
		{"nonUnique", "duplicate pipeline build"},
		{"doNotExist", "pipeline missingbuild is not defined"},
		{"missingRequired", "no pipeline missingbuild required by echoa"},
		{"multipleRoots", "multiple root pipelines: build, echoa"},
	}

	for _, test := range tests {
		workflow := config.GetWorkflow(test.workflowName)
		s.NotNilf(workflow, fmt.Sprintf("no workflow %s in the config", test.workflowName))

		actual := ""
		err := workflow.Validate(config)
		if err != nil {
			actual = err.Error()
		}
		s.Equal(test.expectedErrorString, actual)
	}
}


text:
package egoscale

import "errors"

// ErrNotFound represents an error indicating a non-existent resource.
var ErrNotFound = errors.New("resource not found")

// ErrTooManyFound represents an error indicating multiple results found for a single resource.
var ErrTooManyFound = errors.New("multiple resources found")


text:
<?php

use backend\assets\FormAsset;
use common\models\MenuRecord;
use yii\bootstrap\ActiveField;
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\MenuRecord */
/* @var $form yii\bootstrap\ActiveForm */

FormAsset::register($this);
?>

    <?php $form = ActiveForm::begin([
        'layout' => 'horizontal',
        'fieldClass' => ActiveField::className(),
        'fieldConfig' => Yii::$app->params['fieldConfig'],
        'options' => [
	        'id' => 'menu-form'
        ]
    ]); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'text_id')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'web_id')->dropDownList($model->getWebOptions()) ?>

	<?= /** @noinspection PhpUndefinedMethodInspection */
	$form->field($model, 'boxes')->inline()->checkboxList([
		MenuRecord::PROPERTY_MAIN => Yii::t('back', 'Main'),
		MenuRecord::PROPERTY_ACTIVE => Yii::t('back', 'Active'),
		MenuRecord::PROPERTY_PUBLIC => Yii::t('back', 'Public')
	], [
		'id' => 'modal-boxes',
		'data-main' => (MenuRecord::existsMoreMenuRecords($model->isNewRecord ? true : false) && !$model->main) == true ? 0 : 1
	]) ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('back', 'Create') : Yii::t('back', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
	    <button type="button" class="btn btn-default" data-dismiss="modal"><?= Yii::t('back', 'Close'); ?></button>

    <?php ActiveForm::end(); ?>


text:
    <md-button ui-sref="app.export.detail({id:vm.ExportService.exporter.id, name: vm.ExportService.exporter.name})" class="md-icon-button md-mini" ng-style="{'color': vm.ExportService.indicator.style.base_color || vm.ExportService.exporter.base_color}">
      <md-icon ng-style="{'color': vm.ExportService.indicator.style.base_color || vm.ExportService.exporter.base_color}">home<md-icon>
    </md-button>

 1">Chapter

 1">

			<md-button ng-click="vm.gotoChapter(key+1)" class="md-icon-button md-mini rounded" ng-repeat="(key,item) in vm.ExportService.exporter.items" ng-class="{'active': (key) == vm.ExportService.exporter.items.indexOf(vm.ExportService.chapter)}" ng-style="{'color': vm.ExportService.indicator.style.base_color || vm.ExportService.exporter.base_color}">
				{{key + 1}}
			</md-button>

		{{vm.ExportService.exporter.title}}

	<md-button ng-click="vm.showData()" class="md-raised">Data</md-button>


text:
package ru.aplana.app.jaxb_builders;

import static java.lang.ThreadLocal.withInitial;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.datatype.DatatypeFactory;

import interfaces.Builder;
import ru.aplana.app.holders.AsBsDataHolder;
import ru.aplana.jaxb.JaxbContexts;
import ru.aplana.model.xsd.jaxb.bs.GetInsuranceDocumentationRs.GetInsuranceDocumentationRs;
import ru.aplana.model.xsd.jaxb.bs.GetInsuranceDocumentationRs.ObjectFactory;
import ru.aplana.model.xsd.jaxb.bs.GetInsuranceDocumentationRs.ResultInfoType;
import ru.aplana.tools.XmlHelper;
import ru.aplana.model.xsd.jaxb.bs.GetInsuranceDocumentationRs.GetInsuranceDocumentationRs.BusinessInfo;
import ru.aplana.model.xsd.jaxb.bs.GetInsuranceDocumentationRs.GetInsuranceDocumentationRs.BusinessInfo.DocumentContent;
import ru.aplana.model.xsd.jaxb.bs.GetInsuranceDocumentationRs.MessUIDType;

public class GetInsuranceDocumentationRsBuilder implements Builder {

	private static final ThreadLocal<SimpleDateFormat> DF = withInitial(
			() -> new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
	private static final ThreadLocal<SimpleDateFormat> DF_SECOND = withInitial(
			() -> new SimpleDateFormat("yyyy-MM-dd"));
	private static JAXBContext jaxbCtx;
	private AsBsDataHolder data;
	private String messageId;

	static {
		jaxbCtx = JaxbContexts.getInstance().getJAXBContext(GetInsuranceDocumentationRs.class.getPackage().getName(),
				ObjectFactory.class.getClassLoader());
	}

	public GetInsuranceDocumentationRsBuilder(AsBsDataHolder data, String messageId) {
		this.data = data;
		this.messageId = messageId;
	}

	@Override
	public XmlHelper getXmlHelper() {
		return new XmlHelper(jaxbCtx);
	}

	@Override
	public String makeXml() throws Exception {

		Calendar cal = Calendar.getInstance();

		Date current = new Date();
		String dateTime = DF.get().format(current);
		cal.setTime(current);
		cal.add(Calendar.YEAR, 2);
		ObjectFactory of = new ObjectFactory();

		GetInsuranceDocumentationRs response = of.createGetInsuranceDocumentationRs();

		// result info
		ResultInfoType resultInfo = new ResultInfoType();
		resultInfo.setCode(0);
		resultInfo.setDescription("OK");
		response.setResultInfo(resultInfo);

		// business info
		BusinessInfo businessInfo = new BusinessInfo();
		businessInfo.setETSMID(this.data.getAppNumber());
		businessInfo.setInsuranceProgram(this.data.getInsuranceProgram());

		DocumentContent dc = new DocumentContent();
		dc.setInsuranceTerm(DF_SECOND.get().format(cal.getTime()));

		dc.setInsuranceAmount(this.data.getInsuranceAmount());
		dc.setInsuranceSettlementAmount(this.data.getInsuranceAmount());
		dc.setInsuranceSettlementAmountText("");

		dc.setInsurancePremium(this.data.getInsurancePremium());
		dc.setInsuranceSettlementPremium(this.data.getInsurancePremium());
		dc.setInsuranceSettlementPremiumText("");

		dc.setEstimatedValue("0.0");
		dc.setVSP("");
		businessInfo.setDocumentContent(dc);
		response.setBusinessInfo(businessInfo);

		// MessUID
		MessUIDType messUid = new MessUIDType();
		messUid.setMessageId(this.messageId);
		messUid.setMessageDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(dateTime));
		messUid.setFromAbonent("АС БС");
		messUid.setToAbonent("TSM");

		response.setMessUID(messUid);
		String result = getXmlHelper().marshall(response);
		return result;
	}
}


text:
package net.bither.util;

import net.bither.BitherSetting.MarketType;
import net.bither.model.Depth;

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

public class DepthUtil {
	private static List<Depth> depths = init();

	private static List<Depth> init() {
		File file = FileUtil.getDepthFile();
		@SuppressWarnings("unchecked")
		List<Depth> depths = (List<Depth>) FileUtil.deserialize(file);
		if (depths == null) {
			depths = new ArrayList<Depth>();
		}
		return depths;
	}

	public static Depth getKDepth(MarketType marketType) {
		synchronized (depths) {
			for (Depth depth : depths) {
				if (depth.getMarketType() == marketType) {
					return depth;
				}
			}
			return null;
		}
	}

	public static void addDepth(Depth depth) {
		synchronized (depths) {
			File file = FileUtil.getDepthFile();
			depths.remove(depth);
			depths.add(depth);
			FileUtil.serializeObject(file, depths);
		}
	}

}


text:
package org.ehcache.clustered.common.internal.exceptions;

/**
 * Tests {@link IllegalMessageException} functions including
 * {@link ClusterException#withClientStackTrace() withClientStackTrace}.
 */
public class IllegalMessageExceptionTest extends BaseClusteredEhcacheExceptionTest<IllegalMessageException> {

  public IllegalMessageExceptionTest() {
    super(IllegalMessageException.class);
  }
}