text:
package workers

import (
	"fmt"
	"github.com/APTrust/exchange/constants"
	"github.com/APTrust/exchange/context"
	"github.com/APTrust/exchange/models"
	"github.com/APTrust/exchange/network"
	"github.com/APTrust/exchange/stats"
	"github.com/APTrust/exchange/util"
	"github.com/aws/aws-sdk-go/service/s3"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"
)

// If Config.BucketReaderCacheHours isn't set to something
// sensible, cache Ingest WorkItems up to this many hours old.
const DEFAULT_CACHE_HOURS = 24

// How many S3 keys should we fetch in each batch when
// we're getting the contents of a bucket?
const MAX_KEYS = 1000

// APTBucketReader scans APTrust receiving buckets for items
// that need to be ingested. It creates a WorkItem record and
// an NSQ entry for each qualifying bag, and is responsible for
// knowing whether items in the receiving buckets actually need
// to be queued.
type APTBucketReader struct {
	Context           *context.Context
	Institutions      map[string]*models.Institution
	RecentIngestItems map[string]*models.WorkItem
	stats             *stats.APTBucketReaderStats
	statsEnabled      bool
}

// Creates a new bucket reader with the given context.
// Param enableStats is generally used for integration tests.
// Enabling stats in production can cause high memory usage,
// so keep that off unless you're trying to diagnose specific problems.
func NewAPTBucketReader(context *context.Context, enableStats bool) *APTBucketReader {
	reader := &APTBucketReader{
		Context:           context,
		Institutions:      make(map[string]*models.Institution),
		RecentIngestItems: make(map[string]*models.WorkItem),
		statsEnabled:      enableStats,
	}

	// Patch for https://trello.com/c/Ep4pKzZB
	err := CacheBucketNames(context)
	if err != nil {
		panic(fmt.Sprintf("Cannot cache bucket names from Pharos: %v", err))
	}

	if enableStats {
		reader.stats = stats.NewAPTBucketReaderStats()
	}
	return reader
}

func (reader *APTBucketReader) Run() error {
	err := reader.cacheInstitutions()
	if err != nil {
		return err
	}
	err = reader.cacheRecentIngestItems()
	if err != nil {
		return err
	}
	reader.readAllBuckets()
	return nil
}

// Cache a list of all institutions. There are < 20.
// Exit on failure.
func (reader *APTBucketReader) cacheInstitutions() error {
	params := url.Values{}
	params.Add("page", "1")
	params.Add("per_page", "100")
	resp := reader.Context.PharosClient.InstitutionList(params)
	if resp.Error != nil {
		if reader.stats != nil {
			reader.stats.AddError(resp.Error.Error())
			reader.Context.MessageLog.Error(resp.Error.Error())
		}
		return resp.Error
	}
	if resp.Response.StatusCode != 200 {
		return reader.processPharosError(resp)
	}
	for _, inst := range resp.Institutions() {
		reader.Institutions[inst.Identifier] = inst
		if reader.stats != nil {
			reader.stats.AddToInstitutionsCached(inst)
		}
	}
	reader.Context.MessageLog.Info("Loaded %d institutions", len(reader.Institutions))
	return nil
}

// Cache a list of Ingest items that have been added to
// the list of WorkItems in the past X hours, so we won't
// have to do 1000 lookups. (X is usually around 24, but
// check Config.BucketReaderCacheHours for the exact value.
// This function exits on failure.
func (reader *APTBucketReader) cacheRecentIngestItems() error {
	hours := reader.Context.Config.BucketReaderCacheHours
	if hours < 1 {
		hours = DEFAULT_CACHE_HOURS
	}
	createdAfter := time.Now().Add(time.Duration(-1*hours) * time.Hour).UTC()
	params := url.Values{}
	params.Add("page", "1")
	params.Add("per_page", "100") // change to 4 to test hasMoreResults loop
	params.Add("item_action", constants.ActionIngest)
	params.Add("created_after", createdAfter.Format(time.RFC3339))
	hasMoreResults := true
	for hasMoreResults {
		resp := reader.Context.PharosClient.WorkItemList(params)
		if resp.Error != nil {
			if reader.stats != nil {
				reader.stats.AddError(resp.Error.Error())
			}
			return resp.Error
		}
		if resp.Response.StatusCode != 200 {
			return reader.processPharosError(resp)
		}
		reader.Context.MessageLog.Debug("%s", resp.Request.URL.String())
		for _, workItem := range resp.WorkItems() {
			hashKey := reader.makeHashKey(workItem.Name, workItem.ETag)
			reader.RecentIngestItems[hashKey] = workItem
			if reader.stats != nil {
				reader.stats.AddWorkItem("WorkItemsCached", workItem)
			}
		}
		if resp.Next != nil {
			pageNum, err := strconv.Atoi(params.Get("page"))
			if err != nil {
				msg := fmt.Sprintf("Page number '%s' doesn't look like a number!", params.Get("page"))
				if reader.stats != nil {
					reader.stats.AddError(msg)
				}
				return fmt.Errorf(msg)
			}
			params.Set("page", strconv.Itoa(pageNum+1))
		} else {
			hasMoreResults = false
		}
	}
	reader.Context.MessageLog.Info("Loaded %d recent ingest WorkItems", len(reader.RecentIngestItems))
	return nil
}

func (reader *APTBucketReader) makeHashKey(key, etag string) string {
	return fmt.Sprintf("%s|%s", key, strings.Replace(etag, "\"", "", -1))
}

func (reader *APTBucketReader) readAllBuckets() {
	// A.D. 2021-02-04: Get bucket from Pharos, not from the config files.
	// Ideally, we should check buckets for active institutions only, but
	// Pharos isn't giving us institution state info right now, and it's
	// too brittle to mess with.
	bucketNames := make([]string, 0)
	// This sucks, but the integration tests rely on reading bucket
	// names from config files. I'm hacking this rather than going
	// through a painful fix, because we'll be retiring Exchange soon.
	if strings.HasSuffix(reader.Context.Config.ActiveConfig, "integration.json") {
		reader.Context.MessageLog.Info("Using bucket names from config file for integration tests.")
		bucketNames = reader.Context.Config.ReceivingBuckets
	} else {
		reader.Context.MessageLog.Info("Using bucket names from Pharos institution records.")
		for _, inst := range reader.Institutions {
			bucketNames = append(bucketNames, inst.ReceivingBucket)
		}
	}
	for _, bucketName := range bucketNames {
		reader.processBucket(bucketName)
	}
}

func (reader *APTBucketReader) processBucket(bucketName string) {
	reader.Context.MessageLog.Debug("Checking bucket %s", bucketName)
	s3ObjList := network.NewS3ObjectList(
		os.Getenv("AWS_ACCESS_KEY_ID"),
		os.Getenv("AWS_SECRET_ACCESS_KEY"),
		reader.Context.Config.APTrustS3Region,
		bucketName, MAX_KEYS)
	keepFetching := true
	for keepFetching {
		s3ObjList.GetList("")
		if s3ObjList.ErrorMessage != "" {
			if reader.stats != nil {
				reader.stats.AddError(s3ObjList.ErrorMessage)
			}
			reader.Context.MessageLog.Error(s3ObjList.ErrorMessage)
			break
		}
		for _, s3Object := range s3ObjList.Response.Contents {
			// Skip items in nested directories. Unfortunately, the prefix
			// filter for s3.ListObjectsInput does not allow you to specify
			// patterns or things you want to exclude.
			if strings.Contains(*s3Object.Key, "/") {
				msg := fmt.Sprintf("Ignoring %s (subdirectory)", *s3Object.Key)
				reader.Context.MessageLog.Info(msg)
				if reader.stats != nil {
					reader.stats.AddWarning(msg)
				}
				continue
			}
			// Skip non-tar files
			if !strings.HasSuffix(*s3Object.Key, ".tar") {
				msg := fmt.Sprintf("Ignoring non-tar file %s", *s3Object.Key)
				reader.Context.MessageLog.Info(msg)
				if reader.stats != nil {
					reader.stats.AddWarning(msg)
				}
				continue
			}
			// Ok, it's not in a nested directory, so let's process it.
			if reader.stats != nil {
				reader.stats.AddS3Item(fmt.Sprintf("%s/%s", bucketName, *s3Object.Key))
			}
			reader.processS3Object(s3Object, bucketName)
		}
		keepFetching = *s3ObjList.Response.IsTruncated
	}
}

func (reader *APTBucketReader) processS3Object(s3Object *s3.Object, bucketName string) {
	if reader.Context.Config.MaxFileSize > int64(0) && *s3Object.Size > reader.Context.Config.MaxFileSize {
		msg := fmt.Sprintf("Skipping %s/%s because size %d is greater than "+
			"current max file size %d", bucketName, *s3Object.Key, *s3Object.Size,
			reader.Context.Config.MaxFileSize)
		if reader.stats != nil {
			reader.stats.AddWarning(msg)
		}
		reader.Context.MessageLog.Debug(msg)
		return
	}
	workItem, err := reader.findWorkItem(*s3Object.Key, *s3Object.ETag)
	if err != nil {
		// Don't create a work item, because one may already exist.
		// Error will be logged and added to stats at source.
		msg := fmt.Sprintf("Not creating WorkItem for %s/%s because "+
			"we can't tell if one already exists.", bucketName, *s3Object.Key)
		reader.Context.MessageLog.Warning(msg)
		if reader.stats != nil {
			reader.stats.AddWarning(msg)
		}
		return
	}
	// A.D. added 2019-09-23: Requeue ingest if prior WorkItem was cancelled.
	if workItem == nil || workItem.Status == constants.StatusCancelled {
		workItem = reader.createWorkItem(bucketName, s3Object)
		if workItem == nil {
			// Error logged and statted at source.
			return
		}
	}
	// Queue the item in NSQ if necessary. This will go into the fetch
	// queue for ingest, so be sure we don't accidentally pick up any
	// unqueued items for delete, or restore.
	if (workItem.QueuedAt == nil || workItem.QueuedAt.IsZero()) &&
		workItem.Action == constants.ActionIngest &&
		workItem.Stage == constants.StageReceive {
		reader.addToNSQ(workItem)
		reader.markAsQueued(workItem)
	}
}

func (reader *APTBucketReader) findWorkItem(key, etag string) (*models.WorkItem, error) {
	etag = strings.Replace(etag, "\"", "", -1)
	hashKey := reader.makeHashKey(key, etag)
	if workItem, ok := reader.RecentIngestItems[hashKey]; ok {
		reader.Context.MessageLog.Debug("Found hash key '%s' in cache", hashKey)
		return workItem, nil
	}
	reader.Context.MessageLog.Debug("Looking up hash key '%s' in Pharos", hashKey)
	params := url.Values{}
	params.Add("page", "1")
	params.Add("per_page", "1")
	params.Add("item_action", constants.ActionIngest)
	params.Add("name", key)
	params.Add("etag", etag)
	//params.Add("bag_date", lastModified.Format(time.RFC3339))
	resp := reader.Context.PharosClient.WorkItemList(params)
	if resp.Error != nil {
		errMsg := fmt.Sprintf("Error getting WorkItem for name '%s', etag '%s': %v",
			params.Get("name"), params.Get("etag"), resp.Error)
		reader.Context.MessageLog.Debug("%s", resp.Request.URL.String())
		reader.Context.MessageLog.Error(errMsg)
		if reader.stats != nil {
			reader.stats.AddError(errMsg)
		}
		return nil, fmt.Errorf(errMsg)
	}
	if resp.Response.StatusCode != 200 {
		err := reader.processPharosError(resp)
		return nil, err
	}
	workItem := resp.WorkItem()
	if workItem != nil {
		reader.Context.MessageLog.Debug("Found WorkItem for hash key '%s' in Pharos", hashKey)
		if reader.stats != nil {
			reader.stats.AddWorkItem("WorkItemsFetched", workItem)
		}
	} else {
		reader.Context.MessageLog.Debug("Did not find WorkItem for hash key '%s' in Pharos", hashKey)
	}
	return workItem, nil
}

func (reader *APTBucketReader) createWorkItem(bucket string, s3Object *s3.Object) *models.WorkItem {
	// Create a WorkItem in Pharos
	institution := reader.Institutions[util.OwnerOf(bucket)]
	if institution == nil {
		errMsg := fmt.Sprintf("Cannot find institution record for item %s/%s. "+
			"Owner computes to '%s'", bucket, *s3Object.Key, util.OwnerOf(bucket))
		reader.Context.MessageLog.Error(errMsg)
		if reader.stats != nil {
			reader.stats.AddError(errMsg)
		}
		return nil
	}
	workItem := &models.WorkItem{}
	workItem.Id = 0
	workItem.Name = *s3Object.Key
	workItem.Bucket = bucket
	workItem.ETag = strings.Replace(*s3Object.ETag, "\"", "", -1)
	workItem.Size = *s3Object.Size
	workItem.BagDate = *s3Object.LastModified
	workItem.InstitutionId = institution.Id
	workItem.User = constants.APTrustSystemUser
	workItem.Date = time.Now().UTC()
	workItem.Note = "Bag is in receiving bucket"
	workItem.Action = constants.ActionIngest
	workItem.Stage = constants.StageReceive
	workItem.Status = constants.StatusPending
	workItem.Outcome = "Item is pending ingest"
	workItem.Retry = true
	resp := reader.Context.PharosClient.WorkItemSave(workItem)

	if resp.Error != nil {
		errMsg := fmt.Sprintf("Error creating WorkItem for name '%s', etag '%s', time '%s': %v",
			workItem.Name, workItem.ETag, workItem.BagDate, resp.Error)
		reader.Context.MessageLog.Debug("%s", resp.Request.URL.String())
		reader.Context.MessageLog.Error(errMsg)
		if reader.stats != nil {
			reader.stats.AddError(errMsg)
		}
		return nil
	}
	if resp.Response.StatusCode != 201 {
		reader.processPharosError(resp)
		return nil
	}

	savedWorkItem := resp.WorkItem()
	reader.Context.MessageLog.Debug("Created WorkItem with id %d for %s/%s in Pharos",
		savedWorkItem.Id, bucket, *s3Object.Key)
	if reader.stats != nil {
		reader.stats.AddWorkItem("WorkItemsCreated", savedWorkItem)
	}
	return savedWorkItem
}

func (reader *APTBucketReader) addToNSQ(workItem *models.WorkItem) {
	client := network.NewNSQClient(reader.Context.Config.NsqdHttpAddress)
	err := client.Enqueue(reader.Context.Config.FetchWorker.NsqTopic, workItem.Id)
	if err != nil {
		msg := fmt.Sprintf("Error sending WorkItem %d to NSQ: %v", workItem.Id, err)
		if reader.stats != nil {
			reader.stats.AddError(msg)
		}
		reader.Context.MessageLog.Error(msg)
		return
	}
	reader.Context.MessageLog.Info("Added WorkItem id %d to NSQ (%s/%s)",
		workItem.Id, workItem.Bucket, workItem.Name)
	if reader.stats != nil {
		reader.stats.AddWorkItem("WorkItemsQueued", workItem)
	}
	return
}

func (reader *APTBucketReader) markAsQueued(workItem *models.WorkItem) *models.WorkItem {
	utcNow := time.Now().UTC()
	workItem.QueuedAt = &utcNow
	resp := reader.Context.PharosClient.WorkItemSave(workItem)
	if resp.Error != nil {
		errMsg := fmt.Sprintf("Error setting QueuedAt for WorkItem with id %d: %v",
			workItem.Id, resp.Error)
		reader.Context.MessageLog.Debug("%s", resp.Request.URL.String())
		reader.Context.MessageLog.Error(errMsg)
		if reader.stats != nil {
			reader.stats.AddError(errMsg)
		}
		return nil
	}
	if resp.Response.StatusCode != 200 {
		reader.processPharosError(resp)
		return nil
	}
	if reader.stats != nil {
		reader.stats.AddWorkItem("WorkItemsMarkedAsQueued", workItem)
	}
	return resp.WorkItem()
}

func (reader *APTBucketReader) processPharosError(resp *network.PharosResponse) error {
	respBody := ""
	bytesRead, readErr := resp.RawResponseData()
	if readErr == nil {
		respBody = string(bytesRead)
	} else {
		respBody = fmt.Sprintf("[Could not read response body: %v]", readErr)
	}
	msg := fmt.Sprintf("%s %s returned status code %d. Response body: %s",
		resp.Request.Method, resp.Request.URL, resp.Response.StatusCode, respBody)
	reader.Context.MessageLog.Error(msg)
	if reader.stats != nil {
		reader.stats.AddError(msg)
	}
	return fmt.Errorf(msg)
}

func (reader *APTBucketReader) GetStats() *stats.APTBucketReaderStats {
	return reader.stats
}


text:
#include "util/u_inlines.h"
#include "pipe/p_defines.h"
#include "util/u_format.h"
#include "util/u_math.h"
#include "util/u_bitmask.h"
#include "translate/translate.h"

#include "svga_context.h"
#include "svga_state.h"
#include "svga_cmd.h"
#include "svga_tgsi.h"

#include "svga_hw_reg.h"

/***********************************************************************
 */

static INLINE int compare_vs_keys( const struct svga_vs_compile_key *a,
                                   const struct svga_vs_compile_key *b )
{
   unsigned keysize = svga_vs_key_size( a );
   return memcmp( a, b, keysize );
}

static struct svga_shader_result *search_vs_key( struct svga_vertex_shader *vs,
                                                 const struct svga_vs_compile_key *key )
{
   struct svga_shader_result *result = vs->base.results;

   assert(key);

   for ( ; result; result = result->next) {
      if (compare_vs_keys( key, &result->key.vkey ) == 0)
         return result;
   }

   return NULL;
}

static enum pipe_error compile_vs( struct svga_context *svga,
                                   struct svga_vertex_shader *vs,
                                   const struct svga_vs_compile_key *key,
                                   struct svga_shader_result **out_result )
{
   struct svga_shader_result *result;
   enum pipe_error ret = PIPE_ERROR;

   result = svga_translate_vertex_program( vs, key );
   if (result == NULL) {
      ret = PIPE_ERROR_OUT_OF_MEMORY;
      goto fail;
   }

   result->id = util_bitmask_add(svga->vs_bm);
   if(result->id == UTIL_BITMASK_INVALID_INDEX) {
      ret = PIPE_ERROR_OUT_OF_MEMORY;
      goto fail;
   }

   ret = SVGA3D_DefineShader(svga->swc,
                             result->id,
                             SVGA3D_SHADERTYPE_VS,
                             result->tokens,
                             result->nr_tokens * sizeof result->tokens[0]);
   if (ret != PIPE_OK)
      goto fail;

   *out_result = result;
   result->next = vs->base.results;
   vs->base.results = result;
   return PIPE_OK;

fail:
   if (result) {
      if (result->id != UTIL_BITMASK_INVALID_INDEX)
         util_bitmask_clear( svga->vs_bm, result->id );
      svga_destroy_shader_result( result );
   }
   return ret;
}

/* SVGA_NEW_PRESCALE, SVGA_NEW_RAST, SVGA_NEW_ZERO_STRIDE, SVGA_NEW_FS
 */
static void
make_vs_key(struct svga_context *svga, struct svga_vs_compile_key *key)
{
   memset(key, 0, sizeof *key);
   key->need_prescale = svga->state.hw_clear.prescale.enabled;
   key->allow_psiz = svga->curr.rast->templ.point_size_per_vertex;
   key->zero_stride_vertex_elements =
      svga->curr.zero_stride_vertex_elements;
   key->num_zero_stride_vertex_elements =
      svga->curr.num_zero_stride_vertex_elements;

   /* SVGA_NEW_FS */
   key->fs_generic_inputs = svga->curr.fs->generic_inputs;
}

static enum pipe_error
emit_hw_vs(struct svga_context *svga, unsigned dirty)
{
   struct svga_shader_result *result = NULL;
   unsigned id = SVGA3D_INVALID_ID;
   enum pipe_error ret = PIPE_OK;

   /* SVGA_NEW_NEED_SWTNL */
   if (!svga->state.sw.need_swtnl) {
      struct svga_vertex_shader *vs = svga->curr.vs;
      struct svga_vs_compile_key key;

      make_vs_key( svga, &key );

      result = search_vs_key( vs, &key );
      if (!result) {
         ret = compile_vs( svga, vs, &key, &result );
         if (ret != PIPE_OK)
            return ret;
      }

      assert (result);
      id = result->id;
   }

   if (result != svga->state.hw_draw.vs) {
      ret = SVGA3D_SetShader(svga->swc,
                             SVGA3D_SHADERTYPE_VS,
                             id );
      if (ret != PIPE_OK)
         return ret;

      svga->dirty |= SVGA_NEW_VS_RESULT;
      svga->state.hw_draw.vs = result;
   }

   return PIPE_OK;
}

struct svga_tracked_state svga_hw_vs =
{
   "vertex shader (hwtnl)",
   (SVGA_NEW_VS |
    SVGA_NEW_FS |
    SVGA_NEW_PRESCALE |
    SVGA_NEW_NEED_SWTNL |
    SVGA_NEW_ZERO_STRIDE),
   emit_hw_vs
};

/***********************************************************************
 */
static enum pipe_error
update_zero_stride( struct svga_context *svga,
                    unsigned dirty )
{
   unsigned i;

   svga->curr.zero_stride_vertex_elements = 0;
   svga->curr.num_zero_stride_vertex_elements = 0;

   for (i = 0; i < svga->curr.velems->count; i++) {
      const struct pipe_vertex_element *vel = &svga->curr.velems->velem[i];
      const struct pipe_vertex_buffer *vbuffer = &svga->curr.vb[
         vel->vertex_buffer_index];

      if (vbuffer->stride == 0) {
         unsigned const_idx =
            svga->curr.num_zero_stride_vertex_elements;
	 struct pipe_transfer *transfer;
         struct translate *translate;
         struct translate_key key;
         void *mapped_buffer;

         svga->curr.zero_stride_vertex_elements |= (1 << i);
         ++svga->curr.num_zero_stride_vertex_elements;

         key.output_stride = 4 * sizeof(float);
         key.nr_elements = 1;
         key.element[0].type = TRANSLATE_ELEMENT_NORMAL;
         key.element[0].input_format = vel->src_format;
         key.element[0].output_format = PIPE_FORMAT_R32G32B32A32_FLOAT;
         key.element[0].input_buffer = vel->vertex_buffer_index;
         key.element[0].input_offset = vel->src_offset;
         key.element[0].instance_divisor = vel->instance_divisor;
         key.element[0].output_offset = const_idx * 4 * sizeof(float);

         translate_key_sanitize(&key);
         /* translate_generic_create is technically private but
          * we don't want to code-generate, just want generic
          * translation */
         translate = translate_generic_create(&key);

         assert(vel->src_offset == 0);

         mapped_buffer = pipe_buffer_map_range(&svga->pipe,
                                               vbuffer->buffer,
                                               vel->src_offset,
                                               util_format_get_blocksize(vel->src_format),
                                               PIPE_TRANSFER_READ,
					       &transfer);
         mapped_buffer = (uint8_t*)mapped_buffer - vel->src_offset;

         translate->set_buffer(translate, vel->vertex_buffer_index,
                               mapped_buffer,
                               vbuffer->stride, ~0);
         translate->run(translate, 0, 1, 0,
                        svga->curr.zero_stride_constants);

         pipe_buffer_unmap(&svga->pipe, transfer);

         translate->release(translate);
      }
   }

   if (svga->curr.num_zero_stride_vertex_elements)
      svga->dirty |= SVGA_NEW_ZERO_STRIDE;

   return 0;
}

struct svga_tracked_state svga_hw_update_zero_stride =
{
   "update zero_stride",
   ( SVGA_NEW_VELEMENT |
     SVGA_NEW_VBUFFER ),
   update_zero_stride
};

redpajama_set_name: RedPajamaGithub


text:
"""Test config validators."""
from datetime import timedelta, datetime, date
import enum
import os
from socket import _GLOBAL_DEFAULT_TIMEOUT
from unittest.mock import Mock, patch

import pytest
import voluptuous as vol

import homeassistant.helpers.config_validation as cv

from tests.common import get_test_home_assistant

def test_boolean():
    """Test boolean validation."""
    schema = vol.Schema(cv.boolean)

    for value in ('T', 'negative', 'lock'):
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    for value in ('true', 'On', '1', 'YES', 'enable', 1, True):
        assert schema(value)

    for value in ('false', 'Off', '0', 'NO', 'disable', 0, False):
        assert not schema(value)

def test_latitude():
    """Test latitude validation."""
    schema = vol.Schema(cv.latitude)

    for value in ('invalid', None, -91, 91, '-91', '91', '123.01A'):
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    for value in ('-89', 89, '12.34'):
        schema(value)

def test_longitude():
    """Test longitude validation."""
    schema = vol.Schema(cv.longitude)

    for value in ('invalid', None, -181, 181, '-181', '181', '123.01A'):
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    for value in ('-179', 179, '12.34'):
        schema(value)

def test_port():
    """Test TCP/UDP network port."""
    schema = vol.Schema(cv.port)

    for value in ('invalid', None, -1, 0, 80000, '81000'):
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    for value in ('1000', 21, 24574):
        schema(value)

def test_isfile():
    """Validate that the value is an existing file."""
    schema = vol.Schema(cv.isfile)

    fake_file = 'this-file-does-not.exist'
    assert not os.path.isfile(fake_file)

    for value in ('invalid', None, -1, 0, 80000, fake_file):
        with pytest.raises(vol.Invalid):
            schema(value)

    # patching methods that allow us to fake a file existing
    # with write access
    with patch('os.path.isfile', Mock(return_value=True)), \
            patch('os.access', Mock(return_value=True)):
        schema('test.txt')

def test_url():
    """Test URL."""
    schema = vol.Schema(cv.url)

    for value in ('invalid', None, 100, 'htp://ha.io', 'http//ha.io',
                  'http://??,**', 'https://??,**'):
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    for value in ('http://localhost', 'https://localhost/test/index.html',
                  'http://home-assistant.io', 'http://home-assistant.io/test/',
                  'https://community.home-assistant.io/'):
        assert schema(value)

def test_platform_config():
    """Test platform config validation."""
    options = (
        {},
        {'hello': 'world'},
    )
    for value in options:
        with pytest.raises(vol.MultipleInvalid):
            cv.PLATFORM_SCHEMA(value)

    options = (
        {'platform': 'mqtt'},
        {'platform': 'mqtt', 'beer': 'yes'},
    )
    for value in options:
        cv.PLATFORM_SCHEMA(value)

def test_ensure_list():
    """Test ensure_list."""
    schema = vol.Schema(cv.ensure_list)
    assert [] == schema(None)
    assert [1] == schema(1)
    assert [1] == schema([1])
    assert ['1'] == schema('1')
    assert ['1'] == schema(['1'])
    assert [{'1': '2'}] == schema({'1': '2'})

def test_entity_id():
    """Test entity ID validation."""
    schema = vol.Schema(cv.entity_id)

    with pytest.raises(vol.MultipleInvalid):
        schema('invalid_entity')

    assert schema('sensor.LIGHT') == 'sensor.light'

def test_entity_ids():
    """Test entity ID validation."""
    schema = vol.Schema(cv.entity_ids)

    options = (
        'invalid_entity',
        'sensor.light,sensor_invalid',
        ['invalid_entity'],
        ['sensor.light', 'sensor_invalid'],
        ['sensor.light,sensor_invalid'],
    )
    for value in options:
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    options = (
        [],
        ['sensor.light'],
        'sensor.light'
    )
    for value in options:
        schema(value)

    assert schema('sensor.LIGHT, light.kitchen ') == [
        'sensor.light', 'light.kitchen'
    ]

def test_ensure_list_csv():
    """Test ensure_list_csv."""
    schema = vol.Schema(cv.ensure_list_csv)

    options = (
        None,
        12,
        [],
        ['string'],
        'string1,string2'
    )
    for value in options:
        schema(value)

    assert schema('string1, string2 ') == [
        'string1', 'string2'
    ]

def test_event_schema():
    """Test event_schema validation."""
    options = (
        {}, None,
        {
            'event_data': {},
        },
        {
            'event': 'state_changed',
            'event_data': 1,
        },
    )
    for value in options:
        with pytest.raises(vol.MultipleInvalid):
            cv.EVENT_SCHEMA(value)

    options = (
        {'event': 'state_changed'},
        {'event': 'state_changed', 'event_data': {'hello': 'world'}},
    )
    for value in options:
        cv.EVENT_SCHEMA(value)

def test_platform_validator():
    """Test platform validation."""
    hass = None

    try:
        hass = get_test_home_assistant()

        schema = vol.Schema(cv.platform_validator('light'))

        with pytest.raises(vol.MultipleInvalid):
            schema('platform_that_does_not_exist')

        schema('hue')
    finally:
        if hass is not None:
            hass.stop()

def test_icon():
    """Test icon validation."""
    schema = vol.Schema(cv.icon)

    for value in (False, 'work', 'icon:work'):
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    schema('mdi:work')

def test_time_period():
    """Test time_period validation."""
    schema = vol.Schema(cv.time_period)

    options = (
        None, '', 'hello:world', '12:', '12:34:56:78',
        {}, {'wrong_key': -10}
    )
    for value in options:

        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    options = (
        '8:20', '23:59', '-8:20', '-23:59:59', '-48:00', {'minutes': 5}, 1, '5'
    )
    for value in options:
        schema(value)

    assert timedelta(seconds=180) == schema('180')
    assert timedelta(hours=23, minutes=59) == schema('23:59')
    assert -1 * timedelta(hours=1, minutes=15) == schema('-1:15')

def test_service():
    """Test service validation."""
    schema = vol.Schema(cv.service)

    with pytest.raises(vol.MultipleInvalid):
        schema('invalid_turn_on')

    schema('homeassistant.turn_on')

def test_service_schema():
    """Test service_schema validation."""
    options = (
        {}, None,
        {
            'service': 'homeassistant.turn_on',
            'service_template': 'homeassistant.turn_on'
        },
        {
            'data': {'entity_id': 'light.kitchen'},
        },
        {
            'service': 'homeassistant.turn_on',
            'data': None
        },
        {
            'service': 'homeassistant.turn_on',
            'data_template': {
                'brightness': '{{ no_end'
            }
        },
    )
    for value in options:
        with pytest.raises(vol.MultipleInvalid):
            cv.SERVICE_SCHEMA(value)

    options = (
        {'service': 'homeassistant.turn_on'},
        {
            'service': 'homeassistant.turn_on',
            'entity_id': 'light.kitchen',
        },
        {
            'service': 'homeassistant.turn_on',
            'entity_id': ['light.kitchen', 'light.ceiling'],
        },
    )
    for value in options:
        cv.SERVICE_SCHEMA(value)

def test_slug():
    """Test slug validation."""
    schema = vol.Schema(cv.slug)

    for value in (None, 'hello world'):
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    for value in (12345, 'hello'):
        schema(value)

def test_string():
    """Test string validation."""
    schema = vol.Schema(cv.string)

    with pytest.raises(vol.MultipleInvalid):
        schema(None)

    for value in (True, 1, 'hello'):
        schema(value)

def test_temperature_unit():
    """Test temperature unit validation."""
    schema = vol.Schema(cv.temperature_unit)

    with pytest.raises(vol.MultipleInvalid):
        schema('K')

    schema('C')
    schema('F')

def test_x10_address():
    """Test x10 addr validator."""
    schema = vol.Schema(cv.x10_address)
    with pytest.raises(vol.Invalid):
        schema('Q1')
        schema('q55')
        schema('garbage_addr')

    schema('a1')
    schema('C11')

def test_template():
    """Test template validator."""
    schema = vol.Schema(cv.template)

    for value in (None, '{{ partial_print }', '{% if True %}Hello', ['test']):
        with pytest.raises(vol.Invalid,
                           message='{} not considered invalid'.format(value)):
            schema(value)

    options = (
        1, 'Hello',
        '{{ beer }}',
        '{% if 1 == 1 %}Hello{% else %}World{% endif %}',
    )
    for value in options:
        schema(value)

def test_template_complex():
    """Test template_complex validator."""
    schema = vol.Schema(cv.template_complex)

    for value in (None, '{{ partial_print }', '{% if True %}Hello'):
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    options = (
        1, 'Hello',
        '{{ beer }}',
        '{% if 1 == 1 %}Hello{% else %}World{% endif %}',
        {'test': 1, 'test2': '{{ beer }}'},
        ['{{ beer }}', 1]
    )
    for value in options:
        schema(value)

def test_time_zone():
    """Test time zone validation."""
    schema = vol.Schema(cv.time_zone)

    with pytest.raises(vol.MultipleInvalid):
        schema('America/Do_Not_Exist')

    schema('America/Los_Angeles')
    schema('UTC')

def test_datetime():
    """Test date time validation."""
    schema = vol.Schema(cv.datetime)
    for value in [date.today(), 'Wrong DateTime', '2016-11-23']:
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    schema(datetime.now())
    schema('2016-11-23T18:59:08')

def test_key_dependency():
    """Test key_dependency validator."""
    schema = vol.Schema(cv.key_dependency('beer', 'soda'))

    options = (
        {'beer': None}
    )
    for value in options:
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    options = (
        {'beer': None, 'soda': None},
        {'soda': None}, {}
    )
    for value in options:
        schema(value)

def test_has_at_least_one_key():
    """Test has_at_least_one_key validator."""
    schema = vol.Schema(cv.has_at_least_one_key('beer', 'soda'))

    for value in (None, [], {}, {'wine': None}):
        with pytest.raises(vol.MultipleInvalid):
            schema(value)

    for value in ({'beer': None}, {'soda': None}):
        schema(value)

def test_enum():
    """Test enum validator."""
    class TestEnum(enum.Enum):
        """Test enum."""

        value1 = "Value 1"
        value2 = "Value 2"

    schema = vol.Schema(cv.enum(TestEnum))

    with pytest.raises(vol.Invalid):
        schema('value3')

def test_socket_timeout():  # pylint: disable=invalid-name
    """Test socket timeout validator."""
    TEST_CONF_TIMEOUT = 'timeout'  # pylint: disable=invalid-name

    schema = vol.Schema(
        {vol.Required(TEST_CONF_TIMEOUT, default=None): cv.socket_timeout})

    with pytest.raises(vol.Invalid):
        schema({TEST_CONF_TIMEOUT: 0.0})

    with pytest.raises(vol.Invalid):
        schema({TEST_CONF_TIMEOUT: -1})

    assert _GLOBAL_DEFAULT_TIMEOUT == schema({TEST_CONF_TIMEOUT:
                                              None})[TEST_CONF_TIMEOUT]

    assert schema({TEST_CONF_TIMEOUT: 1})[TEST_CONF_TIMEOUT] == 1.0


text:
"use strict" ;

var url = require( 'url' ) ;
var WebSocket = require( 'ws' ) ;
var Ngev = require( 'nextgen-events' ) ;

var log = require( 'logfella' ).global.use( 'spellcast' ) ;

function WsClient( url_ ) {
	this.url = url_ ;
	this.ws = null ;
	this.proxy = null ;
	this.user = null ;
}

module.exports = WsClient ;

// For backward compatibility
WsClient.create = ( ... args ) => new WsClient( ... args ) ;

WsClient.prototype.run = function run( callback ) {
	this.proxy = new Ngev.Proxy() ;

	var parsed = url.parse( this.url ) ;

	// Set the default port
	if ( ! parsed.port ) { parsed.port = 57311 ; }

	// rebuild the url
	this.url = url.format( parsed ) ;

	this.ws = new WebSocket( this.url ) ;

	this.ws.on( 'open' , () => {

		// Add the remote services
		this.proxy.addRemoteService( 'bus' ) ;

		// Send 'ready' to server?
		// No, let the UI send it.
		//this.proxy.remoteServices.bookInput.emit( 'ready' ) ;

		log.debug( 'Connected to server!' ) ;

		if ( typeof callback === 'function' ) { callback() ; }
	} ) ;

	this.ws.on( 'message' , ( message ) => {
		try {
			message = JSON.parse( message ) ;
		}
		catch ( error ) {
			console.error( 'Parse error (server data): ' + error ) ;
			return ;
		}

		log.debug( 'Received message: %I' , message ) ;
		this.proxy.receive( message ) ;
	} ) ;

	// Define the send method
	this.proxy.send = ( message ) => {
		this.ws.send( JSON.stringify( message ) ) ;
	} ;

	// Clean up after everything is done
	this.ws.on( 'close' , () => {
		this.proxy.destroy() ;
		log.debug( 'Websocket closed!' ) ;
	} ) ;

	this.ws.on( 'error' , ( error ) => {
		log.info( 'Websocket error: %E' , error ) ;
		// What should be done here?
	} ) ;
} ;

WsClient.prototype.authenticate = function authenticate( data ) {
	if ( ! data || typeof data !== 'object' || Array.isArray( data ) ) { return ; }
	this.proxy.remoteServices.bus.emit( 'authenticate' , data ) ;
} ;


text:
using Bjd.Memory;
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

namespace Bjd.Threading
{
    public class SimpleAsyncAwaiter : IDisposable, IPoolBuffer
    {
        const int USE = 1;
        const int NOTUSE = 0;
        const int LOCKED = 1;
        const int UNLOCKED = 0;

        static LazyCancelTimer timer = LazyCancelTimer.Instance;
        private static Action<Task> _ActionEmpty = _ => { };
        private static Func<Task, bool> _FuncCancelFalse = _ => (_.IsCanceled ? false : true);
        private static Action<object> CancelRegister = _ =>
        {
            try { ((CancellationTokenSource)_).Cancel(); } catch { }
        };
        private static Action<Task, object> CancelDispose = (t, o) =>
        {
            try { ((CancellationTokenSource)o).Dispose(); }
            catch { }
        };

        private int lockState = 0;
        private SimpleAsyncAwaiterPool _pool;
        private Task waitTask;
        private SimpleAwait waitAwaiterAsync;
        private static Action nullAction = () => { };
        private int usewaitTask = NOTUSE;
        private int usewaitAwait = NOTUSE;

        public SimpleAsyncAwaiter(SimpleAsyncAwaiterPool pool)
        {
            _pool = pool;
            waitTask = new Task(nullAction, TaskCreationOptions.RunContinuationsAsynchronously | TaskCreationOptions.LongRunning);
            waitTask.ConfigureAwait(false);
            waitAwaiterAsync = new SimpleAwait();
            Reset();
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Set()
        {
            if (Interlocked.Exchange(ref lockState, UNLOCKED) == LOCKED)
            {
                if (Interlocked.CompareExchange(ref usewaitTask, NOTUSE, USE) == USE)
                {
                    var t = new Task(nullAction, TaskCreationOptions.RunContinuationsAsynchronously | TaskCreationOptions.LongRunning);
                    t.ConfigureAwait(false);
                    var nowT = Interlocked.Exchange(ref waitTask, t);
                    nowT.RunSynchronously(TaskScheduler.Default);
                }
                if (Interlocked.CompareExchange(ref usewaitAwait, NOTUSE, USE) == USE)
                {
                    //var a = new SimpleAwait();
                    //var nowA = Interlocked.Exchange(ref waitAwaiter, a);
                    //nowA.Complete();
                    waitAwaiterAsync.Complete();
                }

            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Reset()
        {
            if (Interlocked.Exchange(ref lockState, LOCKED) == UNLOCKED)
            {
                waitAwaiterAsync.Reset();
            }
        }

        public bool IsLocked
        {
            get
            {
                return (Interlocked.CompareExchange(ref lockState, UNLOCKED, UNLOCKED) == LOCKED);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public Task WaitAsync()
        {
            var t = waitTask;
            Interlocked.CompareExchange(ref usewaitTask, USE, NOTUSE);
            if (Interlocked.CompareExchange(ref lockState, UNLOCKED, UNLOCKED) == LOCKED)
            {
                return t;
            }
            return Task.CompletedTask;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async ValueTask<bool> WaitAsyncValueTask()
        {
            //var t = waitTask;
            var a = waitAwaiterAsync;
            Interlocked.CompareExchange(ref usewaitAwait, USE, NOTUSE);
            if (Interlocked.CompareExchange(ref lockState, LOCKED, LOCKED) == UNLOCKED)
            {
                return true;
            }
            return await a;
        }

        public async ValueTask<bool> WaitAsyncValueTask(int millisecondsTimeout)
        {
            var a = waitAwaiterAsync;

            Interlocked.CompareExchange(ref usewaitAwait, USE, NOTUSE);
            if (Interlocked.CompareExchange(ref lockState, LOCKED, LOCKED) == UNLOCKED)
            {
                return true;
            }

            return await a.GetLimited(millisecondsTimeout);

        }

        public async ValueTask<bool> WaitAsyncValueTask(int millisecondsTimeout, CancellationToken cancellationToken)
        {
            var t1 = waitTask;
            Interlocked.CompareExchange(ref usewaitTask, USE, NOTUSE);
            if (Interlocked.CompareExchange(ref lockState, LOCKED, LOCKED) == UNLOCKED)
            {
                return true;
            }

            var timerToken = timer.Get(millisecondsTimeout);
            var cancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            timerToken.Register(CancelRegister, cancel);
            var t2 = t1.ContinueWith(_ActionEmpty, cancel.Token, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
            var t3_1 = t2.ContinueWith(CancelDispose, cancel, TaskContinuationOptions.ExecuteSynchronously);
            var t3_2 = t2.ContinueWith(_FuncCancelFalse, TaskContinuationOptions.ExecuteSynchronously);
            return await t3_2;
        }

        public async ValueTask<bool> WaitAsyncValueTask(CancellationToken cancellationToken)
        {
            var t1 = waitTask;
            Interlocked.CompareExchange(ref usewaitTask, USE, NOTUSE);
            if (Interlocked.CompareExchange(ref lockState, LOCKED, LOCKED) == UNLOCKED)
            {
                return true;
            }
            var t2 = t1.ContinueWith(_ActionEmpty, cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
            var t3 = t2.ContinueWith(_FuncCancelFalse, TaskContinuationOptions.ExecuteSynchronously);
            return await t3;
        }

        #region IDisposable Support

        private bool disposedValue = false; // 重複する呼び出しを検出するには

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                }

                Set();

                _pool = null;

                disposedValue = true;
            }
        }

        ~SimpleAsyncAwaiter()
        {
            Dispose(true);
        }

        public void Dispose()
        {
            if (disposedValue) return;
            Set();
            _pool.PoolInternal(this);
        }

        public void Initialize()
        {
            //Interlocked.Exchange(ref usewaitTask, NOTUSE);
            Reset();
        }

        public void DisposeInternal()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

    }

}


text:
Color-logs works as console.log logger on Node.js but with extra data and colors to make easier find the lines on your log files.

## Installation

  npm install color-logs

## Usage
You can use all of them as console.log(), send just a string, multiple strings or mix strings and objects.

    var log = require('color-logs.js')(isLogEnabled, isDebugEnabled, __filename);

    log.debug(...);
    log.info(...);
    log.warning(...);
    log.error(...);

## Sample

- 06 Jun 15:40:36.045 - **[file_name.js]** DEBUG: message {object to value also} *-> BLUE*
- 06 Jun 15:40:36.045 - **[file_name.js]** INFO: message {object to value also} *-> GREEN*
- 06 Jun 15:40:36.045 - **[file_name.js]** WARNING: message {object to value also} *-> YELLOW*
- 06 Jun 15:40:36.045 - **[file_name.js]** ERROR: message {object to value also} *-> RED*

![Color-logs](http://i59.tinypic.com/15mb9y9.png)

### Update jan-2015
by [PauloVelho](https://github.com/paulovelho)
You can set the color of the output on the fly.
So, if you want to highlit any specific debug, it's possible using the function `log.colors()`

Colors available:
black, red, green, yellow, blue, cyan, magenta, white

#### Sample

```javascript
	log.colors("cyan").error("some error message") // outputs *some error message* in cyan
	log.colors("black", "red").debug("some debug") // outputs *some debug* in black with a red background
```

## Testing

	npm i
 	npm test

## Release History

* 0.6.0 Added colorize function by [PauloVelho](https://github.com/paulovelho)

* 0.5.3 Fixed path file on log for windows

* 0.5.0 Added support for lowercase funcions name

* 0.2.3 Simply update readme image

* 0.2.2 Enabled again test

* 0.2.1 Disabled test

* 0.2.0 Fixed test and enabled and disable bug and log

* 0.1.0 Initial release


text:
package com.hazelcast.map.impl.operation;

import com.hazelcast.map.impl.MapDataSerializerHook;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.spi.impl.operationservice.MutatingOperation;

import static com.hazelcast.core.EntryEventType.ADDED;
import static com.hazelcast.core.EntryEventType.UPDATED;
import static com.hazelcast.map.impl.record.Record.UNSET;

public class SetOperation extends BasePutOperation implements MutatingOperation {

    private transient boolean newRecord;

    public SetOperation() {
    }

    public SetOperation(String name, Data dataKey, Data value) {
        super(name, dataKey, value);
    }

    @Override
    protected void runInternal() {
        oldValue = recordStore.set(dataKey, dataValue, getTtl(), getMaxIdle());
        newRecord = oldValue == null;
    }

    protected long getTtl() {
        return UNSET;
    }

    protected long getMaxIdle() {
        return UNSET;
    }

    @Override
    protected void afterRunInternal() {
        eventType = newRecord ? ADDED : UPDATED;

        super.afterRunInternal();
    }

    @Override
    public int getClassId() {
        return MapDataSerializerHook.SET;
    }
}


text:
// -----------------------------------------------------------------------
//  <copyright file="LoggingController.cs" company="OSharp开源团队">
//      Copyright (c) 2014-2015 OSharp. All rights reserved.
//  </copyright>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2015-06-30 3:51</last-date>
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using OSharp.Core.Logging;
using OSharp.Demo.Contracts;
using OSharp.Utility;
using OSharp.Utility.Data;
using OSharp.Utility.Filter;
using OSharp.Web.Mvc.Binders;
using OSharp.Web.Mvc.Security;
using OSharp.Web.UI;
using OSharp.Utility.Logging;

namespace OSharp.Demo.Web.Areas.Admin.Controllers
{
    [Description("管理-日志")]
    public class LoggingController : AdminBaseController
    {
        /// <summary>
        /// 获取或设置 日志业务对象
        /// </summary>
        public ILoggingContract LoggingContract { get; set; }

        #region Ajax功能

        #region 获取数据

        [AjaxOnly]
        [Description("操作日志-列表数据")]
        public ActionResult OperateLogGridData()
        {
            int total;
            GridRequest request = new GridRequest(Request);
            if (request.PageCondition.SortConditions.Length == 0)
            {
                request.PageCondition.SortConditions = new[] { new SortCondition("CreatedTime", ListSortDirection.Descending) };
            }
            var datas = GetQueryData<OperateLog, int>(LoggingContract.OperateLogs, out total, request).Select(m => new
            {
                m.Id,
                m.FunctionName,
                m.Operator.UserId,
                m.Operator.NickName,
                m.Operator.Ip,
                m.CreatedTime,
                DataLogs = new { m.Id, m.DataLogs.Count }
            }).ToList();
            return Json(new GridData<object>(datas, total), JsonRequestBehavior.AllowGet);
        }

        [AjaxOnly]
        [Description("数据日志-列表数据")]
        public ActionResult DataLogGridData(int id)
        {
            GridRequest request = new GridRequest(Request);
            if (id > 0)
            {
                request.FilterGroup.Rules.Add(new FilterRule("OperateLog.Id", id));
            }
            int total;
            var datas = GetQueryData<DataLog, int>(LoggingContract.DataLogs, out total, request).Select(m => new
            {
                m.Id,
                m.EntityKey,
                m.Name,
                m.EntityName,
                m.OperateType,
                LogItems = m.LogItems.Select(n => new
                {
                    n.Field,
                    n.FieldName,
                    n.OriginalValue,
                    n.NewValue,
                    n.DataType
                })
            }).ToList();
            return Json(new GridData<object>(datas, total), JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 功能方法

        [AjaxOnly]
        [Description("操作日志-删除")]
        public ActionResult DeleteOperateLogs([ModelBinder(typeof(JsonBinder<int>))] ICollection<int> ids)
        {
            ids.CheckNotNull("ids");
            OperationResult result = LoggingContract.DeleteOperateLogs(ids.ToArray());
            return Json(result.ToAjaxResult(), JsonRequestBehavior.AllowGet);
        }

        #endregion

        #endregion

        #region 视图功能

        [Description("日志模块-首页")]
        public override ActionResult Index()
        {
            return RedirectToAction("OperateLogs");
        }

        [Description("操作日志-列表")]
        public ActionResult OperateLogs()
        {
            return View();
        }

        [Description("系统日志-列表")]
        public ActionResult SystemLogs()
        {
            return Content("数据日志");
           // return View();
        }

        #endregion
    }
}


text:
docker run -d -p 8443:443 --name openvas9 openvas9

echo "Waiting for startup to complete..."
until docker logs openvas9 | grep -E 'It seems like your OpenVAS-9 installation is'; do
  echo .
  sleep 5
done

if $(curl -k https://localhost:8443/login/login.html | grep -q "Greenbone Security Assistant"); then
  echo "Greenbone started successfully!"
else
  echo "Greenbone couldn't be found. There's probably something wrong"
  exit 1
fi


text:
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;

namespace SJP.Schematic.PostgreSql.Tests.Integration.Versions.V11
{
    internal partial class PostgreSqlRelationalDatabaseTableProviderTests : PostgreSql11Test
    {
        [Test]
        public async Task Indexes_WhenGivenTableWithNoIndexes_ReturnsEmptyCollection()
        {
            var table = await GetTableAsync("v11_table_test_table_1").ConfigureAwait(false);

            Assert.That(table.Indexes, Is.Empty);
        }

        [Test]
        public async Task Indexes_WhenGivenTableWithSingleColumnIndex_ReturnsIndexWithColumnOnly()
        {
            var table = await GetTableAsync("v11_table_test_table_8").ConfigureAwait(false);
            var index = table.Indexes.Single();
            var indexColumns = index.Columns
                .Select(c => c.DependentColumns.Single())
                .ToList();

            Assert.Multiple(() =>
            {
                Assert.That(indexColumns, Has.Exactly(1).Items);
                Assert.That(indexColumns.Single().Name.LocalName, Is.EqualTo("test_column"));
            });
        }

        [Test]
        public async Task Indexes_WhenGivenTableWithSingleColumnIndex_ReturnsIndexWithCorrectName()
        {
            var table = await GetTableAsync("v11_table_test_table_8").ConfigureAwait(false);
            var index = table.Indexes.Single();

            Assert.That(index.Name.LocalName, Is.EqualTo("ix_test_table_8"));
        }

        [Test]
        public async Task Indexes_WhenGivenTableWithMultiColumnIndex_ReturnsIndexWithColumnsInCorrectOrder()
        {
            var expectedColumnNames = new[] { "first_name", "last_name", "middle_name" };

            var table = await GetTableAsync("v11_table_test_table_9").ConfigureAwait(false);
            var index = table.Indexes.Single();
            var indexColumns = index.Columns
                .Select(c => c.DependentColumns.Single())
                .Select(c => c.Name.LocalName)
                .ToList();

            Assert.Multiple(() =>
            {
                Assert.That(indexColumns, Has.Exactly(3).Items);
                Assert.That(indexColumns, Is.EqualTo(expectedColumnNames));
            });
        }

        [Test]
        public async Task Indexes_WhenGivenTableWithMultiColumnIndex_ReturnsIndexWithCorrectName()
        {
            var table = await GetTableAsync("v11_table_test_table_9").ConfigureAwait(false);
            var index = table.Indexes.Single();

            Assert.That(index.Name.LocalName, Is.EqualTo("ix_test_table_9"));
        }

        [Test]
        public async Task Indexes_WhenGivenTableWithIndexContainingNoIncludedColumns_ReturnsIndexWithoutIncludedColumns()
        {
            var table = await GetTableAsync("v11_table_test_table_9").ConfigureAwait(false);
            var index = table.Indexes.Single();
            var includedColumns = index.IncludedColumns
                .Select(c => c.Name.LocalName)
                .ToList();

            Assert.That(includedColumns, Is.Empty);
        }

        [Test]
        public async Task Indexes_WhenGivenTableWithEnabledIndex_ReturnsIndexWithIsEnabledTrue()
        {
            var table = await GetTableAsync("v11_table_test_table_11").ConfigureAwait(false);
            var index = table.Indexes.Single();

            Assert.That(index.IsEnabled, Is.True);
        }

        [Test]
        public async Task Indexes_WhenGivenTableWithNonUniqueIndex_ReturnsIndexWithIsUniqueFalse()
        {
            var table = await GetTableAsync("v11_table_test_table_9").ConfigureAwait(false);
            var index = table.Indexes.Single();

            Assert.That(index.IsUnique, Is.False);
        }

        [Test]
        public async Task Indexes_WhenGivenTableWithUniqueIndex_ReturnsIndexWithIsUniqueTrue()
        {
            var table = await GetTableAsync("v11_table_test_table_13").ConfigureAwait(false);
            var index = table.Indexes.Single();

            Assert.That(index.IsUnique, Is.True);
        }

        [Test]
        public async Task Indexes_WhenGivenTableWithIncludedColumnIndex_ReturnsIndexWithIncludedColumn()
        {
            var expectedColumnNames = new[] { "last_name_parent" };
            var expectedIncludedColumnNames = new[] { "first_name_parent" };

            var table = await GetTableAsync("v11_table_test_table_15").ConfigureAwait(false);
            var index = table.Indexes.Single(ix => !ix.IsUnique);
            var indexColumns = index.Columns
                .Select(c => c.DependentColumns.Single())
                .Select(c => c.Name.LocalName)
                .ToList();
            var includedColumns = index.IncludedColumns
                .Select(c => c.Name.LocalName)
                .ToList();

            Assert.Multiple(() =>
            {
                Assert.That(indexColumns, Has.Exactly(1).Items);
                Assert.That(indexColumns, Is.EqualTo(expectedColumnNames));

                Assert.That(includedColumns, Has.Exactly(1).Items);
                Assert.That(includedColumns, Is.EqualTo(expectedIncludedColumnNames));
            });
        }

        [Test]
        public async Task Indexes_WhenGivenTableWithMultipleIncludedColumnIndex_ReturnsIndexWithIncludedColumnsInCorrectOrder()
        {
            var expectedColumnNames = new[] { "last_name" };
            var expectedIncludedColumnNames = new[] { "middle_name", "first_name_child" };

            var table = await GetTableAsync("v11_table_test_table_16").ConfigureAwait(false);
            var index = table.Indexes.Single();
            var indexColumns = index.Columns
                .Select(c => c.DependentColumns.Single())
                .Select(c => c.Name.LocalName)
                .ToList();
            var includedColumns = index.IncludedColumns
                .Select(c => c.Name.LocalName)
                .ToList();

            Assert.Multiple(() =>
            {
                Assert.That(indexColumns, Has.Exactly(1).Items);
                Assert.That(indexColumns, Is.EqualTo(expectedColumnNames));

                Assert.That(includedColumns, Has.Exactly(2).Items);
                Assert.That(includedColumns, Is.EqualTo(expectedIncludedColumnNames));
            });
        }
    }
}


text:
limit = 4000000
sum = 0
previousTerm = 1
currentTerm = 2

loop do
	if currentTerm % 2 ==0
		sum += currentTerm
	end
	nextTerm = previousTerm + currentTerm
	previousTerm = currentTerm
	currentTerm = nextTerm

	break if currentTerm >= limit
end

puts sum


text:
require_dependency 'db_officer/utils'
module DbOfficer
  class TableColumn
    include ActiveModel::Model
    include ActiveModel::Validations

    attr_accessor :name,:field_type, :_destroy

    validates :name, presence: true
    validates :field_type, presence: true
  end
end


text:
package io.restassured.itest.java.objects;

import org.junit.Ignore;

@Ignore
public class ScalatraObject {
    private String hello;

    public String getHello() {
        return hello;
    }

    public void setHello(String hello) {
        this.hello = hello;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ScalatraObject that = (ScalatraObject) o;

        if (hello != null ? !hello.equals(that.hello) : that.hello != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return hello != null ? hello.hashCode() : 0;
    }
}


text:
require "json"
require "open-uri"

require_relative "yossarian_plugin"

class ExchangeRates < YossarianPlugin
  include Cinch::Plugin
  use_blacklist

  KEY = ENV["OEX_API_KEY"]
  URL = "https://openexchangerates.org/api/latest.json?app_id=%{key}"

  def usage
    "!rate <code [code2...]> - Get the currency exchange rate between USD and one or more currencies."
  end

  def match?(cmd)
    cmd =~ /^(!)?rate$/
  end

  match /rate (.+)/, method: :exchange_rate, strip_colors: true

  def exchange_rate(m, code)
    if KEY
      url = URL % { key: KEY }
      codes = code.upcase.split

      begin
        hash = JSON.parse(open(url).read)
        hash["rates"].default = "?"

        rates = codes.map do |curr|
          "USD/#{curr}: #{hash['rates'][curr]}"
        end.join(", ")

        m.reply rates, true
      rescue Exception => e
        m.reply e.to_s, true
      end
    else
      m.reply "#{self.class.name}: Internal error (missing API key)."
    end
  end
end


text:
package com.hw.addressbook.tests;

import com.hw.addressbook.model.AddressBookEntry;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.stream.Collectors;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Created by evg on 08.11.16.
 */
public class ContactVisibleTests extends TestBase {
    @Test
    public void testContactVisible(){
        app.goTo().homePage();
        AddressBookEntry contact = app.contact().all().iterator().next();
        AddressBookEntry contactInfoFromEditForm = app.contact().infoFromEditForm(contact);
        assertThat(contact.getAllPhones(), equalTo(mergePhones(contactInfoFromEditForm)));
        assertThat(contact.getAllEmails(), equalTo(mergeEmails(contactInfoFromEditForm)));
        assertThat(contact.getAddress(), equalTo(contactInfoFromEditForm.getAllPostAddress()));
    }

    @Test
    public void testDetailsVisible() {
        app.goTo().homePage();
        AddressBookEntry contact = app.contact().all().iterator().next();
        AddressBookEntry contactInfoFromDetailsForm = app.contact().infoFromDetails(contact);
        assertThat(contact.getFirstname(), equalTo(contactInfoFromDetailsForm.getFirstname()));
        assertThat(contact.getLastname(), equalTo(contactInfoFromDetailsForm.getLastname()));
        assertThat(contact.getAllPhones(), equalTo(mergePhones(contactInfoFromDetailsForm)));
        assertThat(contact.getAllEmails(), equalTo(mergeEmails(contactInfoFromDetailsForm)));
    }

    private String mergePhones(AddressBookEntry contact) {
        return Arrays.asList(contact.getPhoneHome(), contact.getMobile(), contact.getPhoneWork())
                .stream().filter( (s) -> ! s.equals(""))
                .map(ContactVisibleTests::cleaned)
                .collect(Collectors.joining("\n"));
    }
    private String mergeEmails(AddressBookEntry contact) {
        return Arrays.asList(contact.getEmail(), contact.getEmail2(), contact.getEmail3())
                .stream().filter( (s) -> ! s.equals(""))
                .map(ContactVisibleTests::cleaned)
                .collect(Collectors.joining("\n"));
    }

    public static String cleaned(String str){
        return str.replaceAll("\\s", "").replaceAll("[-()]", "");
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Patrick's thoughts: Blog Archive</title>
  <meta name="author" content="Patrick O'Doherty">

  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="canonical" href="http://patrickodoherty.com/blog/blog/archives/index.html"/>
  <link href="/blog/favicon.png" rel="shortcut icon" />
  <link href="/blog/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">

  <link href="/blog/atom.xml" rel="alternate" title="Patrick's thoughts" type="application/atom+xml"/>

<link href='http://fonts.googleapis.com/css?family=PT+Serif:regular,italic,bold,bolditalic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic' rel='stylesheet' type='text/css'>

  <hgroup>

Patrick's thoughts

From code to music via insanity and back again

</hgroup>

RSS

<form action="http://google.com/search" method="get">
  <fieldset role="site-search">
    <input type="hidden" name="q" value="site:patrickodoherty.com/blog" />
    <input class="search" type="text" name="q" results="0" placeholder="Search"/>
  </fieldset>
</form>

Blog

Archives

Blog Archive

2012

SSH in Amazon’s VPC

<time datetime="2012-04-07 16:40:00 -0700" pubdate>Apr 07 2012</time>

Complying With PEP8

<time datetime="2012-01-07 16:14:00 -0800" pubdate>Jan 07 2012</time>

  posted in code,, python,, vim

2011

Dealing With ‘Bluetooth Not Available’ on Mac OS X

<time datetime="2011-09-08 21:45:00 -0700" pubdate>Sep 08 2011</time>

  posted in bug,, mac

About Me

I’m a nineteen year old Irish developer trying my hand at making things people want in Silicon Valley.

Included file ‘asides.twitter.html’ not found in _includes directory

  Copyright © 2012 - Patrick O'Doherty -
  Powered by Octopress


text:
package EDU.purdue.cs.bloat.editor;

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

import EDU.purdue.cs.bloat.reflect.Constant;
import EDU.purdue.cs.bloat.util.Assert;
import EDU.purdue.cs.bloat.util.ResizeableArrayList;

/**
 * ConstantPool models constants in the constant pool. Recall that the
 * reflection mechanism represents constants as a tag and a value. ConstantPool
 * consists of an array of <tt>reflect.Constant</tt>s that are resolved into
 * their appropriate value (e.g. Type, NameAndType, MemberRef, etc.) as they are
 * needed.
 *
 * @see EDU.purdue.cs.bloat.reflect.Constant
 *
 * @author Nate Nystrom (nystrom@cs.purdue.edu)
 */
public class ConstantPool {
	/**
	 * ConstantPool maintains some information about the constants in the
	 * constant pool to make its life easier.
	 *
	 * constantIndices A mapping between constants and their indices in the
	 * constant pool. Knowing this information makes adding constants to the
	 * constant pool easier.
	 *
	 * constants A list of the reflect.Constant objects that are used to create
	 * the ConstantPool.
	 *
	 * resolved A list of the constants in their resolved form (such as
	 * NameAndType or String)
	 */
	private Map constantIndices;

	ResizeableArrayList constants;

	ResizeableArrayList resolved;

	/**
	 * Constructor. Resolve the constants in the constant pool, converting from
	 * the index-based representation of the class file to a more amenable
	 * external representation.
	 *
	 * @param c
	 *            An array of Constant.
	 */
	public ConstantPool(final Constant[] c) {
		constantIndices = new HashMap();
		constants = new ResizeableArrayList(c.length);
		resolved = new ResizeableArrayList(c.length);

		/*
		 * constants = new ResizeableArrayList(c.length, 256); resolved = new
		 * ResizeableArrayList(c.length, 256);
		 */
		for (int i = 0; i < c.length; i++) {
			constants.add(c[i]);
			resolved.add(null);
			if (c[i] != null) {
				constantIndices.put(c[i], new Integer(i));
			}
		}
	}

	/**
	 * Creates a new, empty ConstantPool
	 */
	public ConstantPool() {
		this.constantIndices = new HashMap();
		this.constants = new ResizeableArrayList();
		this.resolved = new ResizeableArrayList();
	}

	/**
	 * Obtain the resolved value of a constant at given index in the constant
	 * pool.
	 *
	 * @param idx
	 *            Index into the constant pool.
	 * @return The value of the constant at index.
	 */
	public Object constantAt(final int idx) {
		if (idx == 0) {
			return null;
		}

		Object value = resolved.get(idx);

		if (value != null) {
			return value;
		}

		final Constant c = (Constant) constants.get(idx);

		if (c == null) {
			return null;
		}

		value = c.value();

		if (value == null) {
			return null;
		}

		// Okay, we have to resolve the Constant.

		switch (c.tag()) {
		case Constant.CLASS: {
			// Lookup the UTF8 at the index and use the class name
			// to create a Type.
			Assert.isTrue(value instanceof Integer, "Invalid constant: " + c);

			final int index = ((Integer) value).intValue();
			Assert.isTrue(constantTag(index) == Constant.UTF8,
					"Invalid constant: " + c);

			final String className = (String) constantAt(index);

			value = Type.getType(Type.classDescriptor(className));
			break;
		}
		case Constant.STRING: {
			// Lookup the UTF8 at the index and store the String directly.
			Assert.isTrue(value instanceof Integer, "Invalid constant: " + c);

			final int index = ((Integer) value).intValue();
			Assert.isTrue(constantTag(index) == Constant.UTF8,
					"Invalid constant: " + c);

			value = constantAt(index);
			break;
		}
		case Constant.FIELD_REF:
		case Constant.METHOD_REF:
		case Constant.INTERFACE_METHOD_REF: {
			// The constant at the first index should be a CLASS.
			//
			// The constant at the second should be a NAME_AND_TYPE.
			//
			// Resolve the two constants and then create a MemberRef
			// for this constant.
			//
			Assert.isTrue(value instanceof int[], "Invalid constant: " + c);

			final int[] v = (int[]) value;

			Assert.isTrue(constantTag(v[0]) == Constant.CLASS,
					"Invalid constant: " + c);
			Assert.isTrue(constantTag(v[1]) == Constant.NAME_AND_TYPE,
					"Invalid constant: " + c);

			final Type clazz = (Type) constantAt(v[0]);
			final NameAndType nameAndType = (NameAndType) constantAt(v[1]);

			value = new MemberRef(clazz, nameAndType);
			break;
		}
		case Constant.NAME_AND_TYPE: {
			// The constant at the first index should be a UTF8 with the
			// name of the field.
			//
			// The constant at the second should be a UTF8 with the type
			// of the field.
			//
			// Resolve the two constants as a String and a Type and then
			// create a NameAndType for this constant.
			//
			Assert.isTrue(value instanceof int[], "Invalid constant: " + c);

			final int[] v = (int[]) value;

			Assert.isTrue(constantTag(v[0]) == Constant.UTF8,
					"Invalid constant: " + c);
			Assert.isTrue(constantTag(v[1]) == Constant.UTF8,
					"Invalid constant: " + c);

			final String name = (String) constantAt(v[0]);
			final String type = (String) constantAt(v[1]);

			value = new NameAndType(name, Type.getType(type));
			break;
		}
		default:
			break;
		}

		resolved.ensureSize(idx + 1);
		resolved.set(idx, value);

		return value;
	}

	public int numConstants() {
		return constants.size();
	}

	/**
	 * Get the tag of a constant.
	 *
	 * @param index
	 *            Index into the constant pool.
	 * @return The tag of the constant at index, or Constant.UTF8.
	 */
	public int constantTag(final int index) {
		if ((0 < index) && (index < constants.size())) {
			final Constant c = (Constant) constants.get(index);

			if (c != null) {
				return c.tag();
			}
		}

		return Constant.UTF8;
	}

	/**
	 * Get the index of the constant with the given tag and value.
	 *
	 * @param tag
	 *            The constant's tag (for example, <tt>Constant.UTF8</tt>).
	 * @param value
	 *            The constant's value (for example, a <tt>String</tt>).
	 * @return The index of the constant.
	 */
	public int constantIndex(final int tag, final Object value) {
		return addConstant(tag, value);
	}

	/**
	 * Returns the index of the constant pool entry for the given class
	 */
	public int getClassIndex(final Class c) {
		return (addConstant(Constant.CLASS, Type.getType(c)));
	}

	/**
	 * Returns the index of the constant pool entry for the given integer
	 */
	public int getIntegerIndex(final Integer i) {
		return (addConstant(Constant.INTEGER, i));
	}

	/**
	 * Returns the index of the constant pool entry for the given float
	 */
	public int getFloatIndex(final Float f) {
		return (addConstant(Constant.FLOAT, f));
	}

	/**
	 * Returns the index of the constant pool entry for the given long
	 */
	public int getLongIndex(final Long l) {
		return (addConstant(Constant.LONG, l));
	}

	/**
	 * Returns the index of the constant pool entry for the given double
	 */
	public int getDoubleIndex(final Double d) {
		return (addConstant(Constant.DOUBLE, d));
	}

	/**
	 * Returns the index of the constant pool entry for the given class.
	 */
	public int getClassIndex(final Type type) {
		Assert
				.isTrue(type.isObject(), "Type " + type
						+ " is not an class type");
		// Make sure that the descriptor constant is also there
		getTypeIndex(type);
		return (addConstant(Constant.CLASS, type));
	}

	/**
	 * Returns the index of the constant pool entry for the given
	 * Type
	 */
	public int getTypeIndex(final Type type) {
		return (addConstant(Constant.UTF8, type.descriptor()));
	}

	/**
	 * Returns the index of the constant pool entry for the given String
	 */
	public int getStringIndex(final String s) {
		return (addConstant(Constant.STRING, s));
	}

	/**
	 * Returns the index of the constant pool entry for the given
	 * MemberRef
	 */
	public int getMemberRefIndex(final MemberRef ref) {
		return (addConstant(Constant.FIELD_REF, ref));
	}

	/**
	 * Returns the index of the constant pool entry for the given
	 * NameAndType
	 */
	public int getNameAndTypeIndex(final NameAndType nat) {
		return (addConstant(Constant.NAME_AND_TYPE, nat));
	}

	/**
	 * Returns the index of the constant pool entry for the given UTF8 string
	 */
	public int getUTF8Index(final String s) {
		return (addConstant(Constant.UTF8, s));
	}

	/**
	 * Add a constant to the constant pool. Will not add the same constant
	 * twice.
	 *
	 * @param tag
	 *            The constant's tag (for example, <tt>Constant.UTF8</tt>).
	 * @param value
	 *            The constant's value (for example, a <tt>String</tt>).
	 * @return The index of the constant.
	 */
	public int addConstant(final int tag, final Object value) {
		if (value == null) {
			return 0;
		}

		Constant c;

		switch (tag) {
		case Constant.CLASS: {
			Assert.isTrue(value instanceof Type, "Invalid value: " + value);
			final int index = addConstant(Constant.UTF8, ((Type) value)
					.className());
			c = new Constant(Constant.CLASS, new Integer(index));
			break;
		}
		case Constant.STRING: {
			Assert.isTrue(value instanceof String, "Invalid value: " + value);
			final int index = addConstant(Constant.UTF8, value);
			c = new Constant(Constant.STRING, new Integer(index));
			break;
		}
		case Constant.FIELD_REF:
		case Constant.METHOD_REF:
		case Constant.INTERFACE_METHOD_REF: {
			// The constant at the first index should be a CLASS.
			//
			// The constant at the second should be a NAME_AND_TYPE.
			//
			// Resolve the two constants and then create a MemberRef
			// for this constant.
			//
			Assert
					.isTrue(value instanceof MemberRef, "Invalid value: "
							+ value);

			final int[] v = new int[2];

			v[0] = addConstant(Constant.CLASS, ((MemberRef) value)
					.declaringClass());
			v[1] = addConstant(Constant.NAME_AND_TYPE, ((MemberRef) value)
					.nameAndType());

			c = new Constant(tag, v);
			break;
		}
		case Constant.NAME_AND_TYPE: {
			// The constant at the first index should be a UTF8 with the
			// name of the field.
			//
			// The constant at the second should be a UTF8 with the type
			// of the field.
			//
			// Resolve the two constants as a String and a Type and then
			// create a NameAndType for this constant.
			//
			Assert.isTrue(value instanceof NameAndType, "Invalid value: "
					+ value);

			final int[] v = new int[2];

			v[0] = addConstant(Constant.UTF8, ((NameAndType) value).name());
			v[1] = addConstant(Constant.UTF8, ((NameAndType) value).type()
					.descriptor());

			c = new Constant(tag, v);
			break;
		}
		case Constant.UTF8: {
			final String s = (String) value;
			c = new Constant(tag, s.intern());
			break;
		}
		default: {
			c = new Constant(tag, value);
			break;
		}
		}

		Integer index = (Integer) constantIndices.get(c);

		if (index == null) {
			index = new Integer(constants.size());
			constantIndices.put(c, index);
			constants.add(c);
			resolved.add(value);

			if ((tag == Constant.LONG) || (tag == Constant.DOUBLE)) {
				constants.add(null);
				resolved.add(null);
			}
		}

		return index.intValue();
	}

	/**
	 * Get an array of the constants in the pool.
	 *
	 * @return An array of the constants in the pool.
	 */
	public Constant[] constants() {
		final Object[] a = constants.toArray();
		final Constant[] array = new Constant[a.length];
		System.arraycopy(a, 0, array, 0, a.length);
		return array;
	}

	/**
	 * Returns an unmodifiable List of constants in this constant pool.
	 */
	public List getConstantsList() {
		return Collections.unmodifiableList(this.constants);
	}
}


text:
<OutOfBrowserSettings ShortName="Caliburn.Micro.Coroutines Application" EnableGPUAcceleration="False" ShowInstallMenuItem="True">
  <OutOfBrowserSettings.Blurb>Caliburn.Micro.Coroutines Application on your desktop; at home, at work or on the go.</OutOfBrowserSettings.Blurb>
  <OutOfBrowserSettings.WindowSettings>
    <WindowSettings Title="Caliburn.Micro.Coroutines Application" />
  </OutOfBrowserSettings.WindowSettings>
  <OutOfBrowserSettings.Icons />
</OutOfBrowserSettings>


text:
class AddAttachmentAvatarToCartoons < ActiveRecord::Migration
  def self.up
    change_table :cartoons do |t|
      t.attachment :avatar
    end
  end

  def self.down
    remove_attachment :cartoons, :avatar
  end
end


text:
package org.apereo.portal.portlet.registry;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import javax.portlet.PortletMode;
import javax.portlet.WindowState;
import org.apache.commons.lang.Validate;
import org.apereo.portal.portlet.PortletUtils;
import org.apereo.portal.portlet.om.IPortletEntityId;
import org.apereo.portal.portlet.om.IPortletWindowDescriptor;
import org.apereo.portal.portlet.om.IPortletWindowId;

/**
 * Serializable persistent portlet window data. This class MUST be thread safe.
 *
 */
class PortletWindowData implements IPortletWindowDescriptor, Serializable {
    private static final long serialVersionUID = 1L;

    private final IPortletEntityId portletEntityId;
    private final IPortletWindowId portletWindowId;
    private final IPortletWindowId delegationParentId;
    private volatile Map<String, String[]> renderParameters = Collections.emptyMap();
    private volatile Map<String, String[]> publicRenderParameters = Collections.emptyMap();
    private transient volatile PortletMode portletMode = PortletMode.VIEW;
    private transient volatile WindowState windowState = WindowState.NORMAL;
    private volatile Integer expirationCache = null;

    /**
     * @param portletWindowId The unique identifier for this PortletWindow
     * @param portletEntityId The unique identifier of the parent IPortletEntity
     * @param delegationParentId The delegation parent of this portlet, null allowed
     * @throws IllegalArgumentException if portletWindowId, or portletEntityId are null
     */
    public PortletWindowData(
            IPortletWindowId portletWindowId,
            IPortletEntityId portletEntityId,
            IPortletWindowId delegationParentId) {
        Validate.notNull(portletWindowId, "portletWindowId can not be null");
        Validate.notNull(portletEntityId, "portletEntityId can not be null");

        this.portletWindowId = portletWindowId;
        this.portletEntityId = portletEntityId;
        this.delegationParentId = delegationParentId;
    }

    /**
     * @param portletWindowId The unique identifier for this PortletWindow
     * @param portletEntityId The unique identifier of the parent IPortletEntity
     * @throws IllegalArgumentException if portletWindowId, or portletEntityId are null
     */
    public PortletWindowData(IPortletWindowId portletWindowId, IPortletEntityId portletEntityId) {
        this(portletWindowId, portletEntityId, null);
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#getRenderParameters()
     */
    public Map<String, String[]> getRenderParameters() {
        return this.renderParameters;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#setRenderParameters(java.util.Map)
     */
    public void setRenderParameters(Map<String, String[]> renderParameters) {
        Validate.notNull(renderParameters, "renderParameters can not be null");
        this.renderParameters = renderParameters;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#getPublicRenderParameters()
     */
    public Map<String, String[]> getPublicRenderParameters() {
        return this.publicRenderParameters;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#setPublicRenderParameters(java.util.Map)
     */
    public void setPublicRenderParameters(Map<String, String[]> publicRenderParameters) {
        Validate.notNull(publicRenderParameters, "publicRenderParameters can not be null");
        this.publicRenderParameters = publicRenderParameters;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#getPortletMode()
     */
    public PortletMode getPortletMode() {
        return this.portletMode;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#setPortletMode(javax.portlet.PortletMode)
     */
    public void setPortletMode(PortletMode portletMode) {
        Validate.notNull(portletMode, "PortletMode can not be null");
        this.portletMode = portletMode;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#getWindowState()
     */
    public WindowState getWindowState() {
        return this.windowState;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#setWindowState(javax.portlet.WindowState)
     */
    public void setWindowState(WindowState windowState) {
        Validate.notNull(windowState, "WindowState can not be null");
        this.windowState = windowState;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#getExpirationCache()
     */
    public Integer getExpirationCache() {
        return this.expirationCache;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#setExpirationCache(java.lang.Integer)
     */
    public void setExpirationCache(Integer expirationCache) {
        this.expirationCache = expirationCache;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#getPortletEntityId()
     */
    @Override
    public IPortletEntityId getPortletEntityId() {
        return this.portletEntityId;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#getPortletWindowId()
     */
    @Override
    public IPortletWindowId getPortletWindowId() {
        return this.portletWindowId;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.portlet.om.IPortletWindowData#getDelegationParentId()
     */
    public IPortletWindowId getDelegationParentId() {
        return this.delegationParentId;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result =
                prime * result
                        + ((this.delegationParentId == null)
                                ? 0
                                : this.delegationParentId.hashCode());
        result =
                prime * result
                        + ((this.portletEntityId == null) ? 0 : this.portletEntityId.hashCode());
        result =
                prime * result
                        + ((this.portletWindowId == null) ? 0 : this.portletWindowId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        PortletWindowData other = (PortletWindowData) obj;
        if (this.delegationParentId == null) {
            if (other.delegationParentId != null) return false;
        } else if (!this.delegationParentId.equals(other.delegationParentId)) return false;
        if (this.portletEntityId == null) {
            if (other.portletEntityId != null) return false;
        } else if (!this.portletEntityId.equals(other.portletEntityId)) return false;
        if (this.portletWindowId == null) {
            if (other.portletWindowId != null) return false;
        } else if (!this.portletWindowId.equals(other.portletWindowId)) return false;
        return true;
    }

    @Override
    public String toString() {
        return "PortletWindow ["
                + "portletWindowId="
                + this.portletWindowId
                + ", "
                + "delegationParentId="
                + this.delegationParentId
                + ", "
                + "portletMode="
                + this.portletMode
                + ", "
                + "windowState="
                + this.windowState
                + ", "
                + "expirationCache="
                + this.expirationCache
                + ", "
                + "renderParameters="
                + this.renderParameters
                + ", "
                + "publicRenderParameters="
                + this.publicRenderParameters
                + ", "
                + "portletEntityId="
                + this.portletEntityId
                + "]";
    }

    private void writeObject(ObjectOutputStream oos) throws IOException {
        oos.defaultWriteObject();
        oos.writeObject(this.portletMode.toString());
        oos.writeObject(this.windowState.toString());
    }

    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        //Read & validate non-transient fields
        ois.defaultReadObject();

        if (this.portletWindowId == null) {
            throw new InvalidObjectException("portletWindowId can not be null");
        }
        if (this.portletEntityId == null) {
            throw new InvalidObjectException("portletEntityId can not be null");
        }

        //Read & validate transient fields
        final String portletModeStr = (String) ois.readObject();
        if (portletModeStr == null) {
            throw new InvalidObjectException("portletMode can not be null");
        }
        this.portletMode = PortletUtils.getPortletMode(portletModeStr);

        final String windowStateStr = (String) ois.readObject();
        if (windowStateStr == null) {
            throw new InvalidObjectException("windowState can not be null");
        }
        this.windowState = PortletUtils.getWindowState(windowStateStr);
    }
}


text:
/**
 * Create a Multilevel Menu from JSON String.
 * Unordered list and Select (Combobox)
 * @autor David Ticona Saravia <david.ticona.saravia@gmail.com>
 * @version 0.9.0
 * @param {jQuery} $
 */
(function ($) {
    $.fn.setClass = function(classes) {
        this.attr('class', classes);
        return this;
    };
    $.fn.renderizeMenu = function (data, options) {
        var settings = $.extend({
            active: window.location.href,
            activeClass: 'active',
            rootClass: '',
            itemClass: null,
            linkClass: null,
            itemHasMenuClass: null,
            linkHasMenuClass: null,
            menuClass: null,
            menuItemClass: null,
            menuLinkClass: null,
            menuItemHasSubmenuClass: null,
            menuLinkHasSubmenuClass: null,
            submenuClass: null,
            dropdownIcon: null
        }, options);
        var arrJson = data;
        if (this.prop('tagName') !== 'UL') {
            return null;
        }
        if (typeof data === 'string') {
            try {
                arrJson = JSON.parse(data);
            } catch (e) {
                return null;
            }
        }
        this.setClass(settings.rootClass);
        var _settings = {
            menuClass: settings.menuClass,
            itemClass: settings.itemClass,
            linkClass: settings.linkClass,
            itemHasMenuClass: settings.itemHasMenuClass,
            linkHasMenuClass: settings.linkHasMenuClass
        };
        buildList(this, arrJson, settings.active, 0);
        return this;

        function buildList($container, arrayItem, active, depth) {
            var level = (typeof (depth) === 'undefined') ? 0 : depth;
            var $elem;
            if (level === 0) {
                $elem = $container;
            } else {
                $elem = $('<ul>').setClass(options.menuClass);
            }
            $.each(arrayItem, function (k, v) {
                var isParent = (typeof (v.children) !== "undefined") && ($.isArray(v.children));
                _settings = {
                    menuClass: settings.menuClass,
                    itemClass: settings.itemClass,
                    linkClass: settings.linkClass,
                    itemHasMenuClass: settings.itemHasMenuClass,
                    linkHasMenuClass: settings.linkHasMenuClass
                };
                if (level>=1) {
                    _settings = {
                        menuClass: settings.submenuClass,
                        itemClass: settings.menuItemClass,
                        linkClass: settings.menuLinkClass,
                        itemHasMenuClass: settings.menuItemHasSubmenuClass,
                        linkHasMenuClass: settings.menuLinkHasSubmenuClass
                    };
                }
                var $li = $('<li>').setClass(_settings.itemClass);
                if ((v.href === '#') || (isParent)) {
                    v.href = 'javascript:void(0)';
                }
                var $a = $('<a>').attr('href', v.href).setClass(_settings.linkClass);
                if (v.hasOwnProperty('target'))
                    $a.attr('target', v.target);
                if (v.hasOwnProperty('title'))
                    $a.attr('title', v.title);
                if (active === v.href) {
                    $a.addClass(settings.activeClass);
                }
                var $i = $('<i>').addClass(v.icon);
                $a.append($i).append(" ").append(v.text);
                if ((isParent) && (settings.dropdownIcon !== null)) {
                    $a.append(' ').append(settings.dropdownIcon);
                }
                if (isParent) {
                    $li.setClass(_settings.itemHasMenuClass);
                    $a.setClass(_settings.linkHasMenuClass);
                }
                $li.append($a);
                if (isParent) {
                    $li.append(buildList($container, v.children, active, level + 1));
                }
                $elem.append($li);
            });
            return $elem;
        }
    };

    function str_repeat(input, multiplier) {
        var y = '';
        while (true) {
            if (multiplier & 1) {
                y += input;
            }
            multiplier >>= 1;
            if (multiplier) {
                input += input;
            } else {
                break;
            }
        }
        return y;
    }

    $.fn.nestedSelect = function (data, options) {
        var settings = $.extend({
            active: window.location.href,
            title: '',
            group: false,
            bullet: '- ',
            propertyValue: 'value'
        }, options);
        if (this.prop('tagName') !== 'SELECT') {
            return null;
        }
        var arrJson = data;
        if (typeof data === 'string') {
            try {
                arrJson = JSON.parse(data);
            } catch (e) {
                return null;
            }
        }
        if (settings.title !== '') {
            this.append($('<option>').append(settings.title).val(""));
        }
        populateSelect(this, arrJson, settings.active);
        return this;
        function populateSelect(jqContainer, arrayItem, active, level) {
            var $element = jqContainer;
            level = (typeof (level) === 'undefined') ? 0 : level;
            $.each(arrayItem, function (k, v) {
                var isParent = ((typeof (v.children) !== "undefined") && ($.isArray(v.children)));
                var $opt = $('<option>');
                var value = v[settings.propertyValue];
                if (active === value) {
                    $opt.addClass('active').prop('selected', true);
                }
                var bullet = (level === 0) ? '' : settings.bullet;
                if ((!settings.group) || ((level === 0) && (!isParent))) {
                    $opt.val(value).append(str_repeat(' ', level)).append(bullet + v.text);
                    $element.append($opt);
                }
                if (isParent) {
                    if ((settings.group)) {
                        createGroup($element, v.text, v.children);
                    } else {
                        populateSelect(jqContainer, v.children, active, level + 2);
                    }
                }
            });
        }
        function createGroup(jqContainer, title, items) {
            var $group = $('<optgroup>').attr('label', title);
            for (var i=0, len=items.length; i<len; i++){
                var $opt = $('<option>').val(items[i].value).append(settings.bullet + items[i].text);
                $group.append($opt);
            }
            jqContainer.append($group);
        }
    };
}(jQuery));


text:
"""view controller for user login route"""
from django.template import RequestContext
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

def user_login(request):
    """Log in view"""
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)

        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('Home'))
            else:
                return render(
                    request,
                    'login.html',
                    {'login_msg': 'user is inactive, please talk to an admin.'}
                )
        else:
            return render(
                request,
                'login.html',
                {'login_msg': 'invalid credentials!'}
            )
    else:
        return render(
            request,
            'login.html',
            {'login_msg': 'please log in:'}
        )


text: hello message


text:
/**
 * Defines the view model for the application shell.
 */
define([
    'plugins/router',
    'durandal/app',
    'authentication',
    'infrastructure/moduleRouter',
    'infrastructure/moduleRegistry',
    'ko'
],
function (router, app, authentication, moduleRouter, moduleRegistry, ko) {
    'use strict';

    return {
        router: router,
        authentication: authentication,

        activate: function () {
            //configure routing
            router.map([
                    { route: '', moduleId: 'viewmodels/welcome', title: 'Willkommen', nav: false },
                    { route: 'login', moduleId: 'viewmodels/login', title: 'Anmelden', nav: false },
                    { route: 'forbidden', moduleId: 'viewmodels/forbidden', title: 'Nicht erlaubt', nav: false },
                    { route: 'profile', moduleId: 'viewmodels/profile', title: 'Profildaten', nav: false, hash: '#profile' },
                    { route: 'website', moduleId: 'viewmodels/websites', title: 'Website', nav: false },
                    { route: 'templates/:websiteId/create', moduleId: 'viewmodels/templateEditor', title: 'Vorlage erstellen', nav: false },
                    { route: 'templates/:websiteId/edit/:id', moduleId: 'viewmodels/templateEditor', title: 'Vorlage bearbeiten', nav: false }
            ]);
            return moduleRouter.mapModuleRoutes(router)
                .buildNavigationModel()
                .activate();
        },

        navigationItemTemplate: function (item) {
            return (item.isModuleRoute && item.isModuleRoute === true) ? 'module-tile' : 'default-tile';
        },

        navigationItems: ko.computed(function () {
            return ko.utils.arrayFilter(router.navigationModel(), function (item) {
                return authentication.isAuthenticated() && (!item.roles || authentication.user().isInAnyRole(item.roles));
            });
        }),

        showModule: function (item) {
            require([item.moduleId], function (module) {
                module.router.navigateToModule();
            });
        },

        logOff: function () {
            if (authentication.isAuthenticated() === true)
                authentication.logoff().then(router.navigate('login', { trigger: true, replace: true }));
        }
    };
});