text:
"""Tests for query MR job."""

import datetime

from core.domain import exp_services
from core.domain import user_query_jobs_one_off
from core.domain import user_query_services
from core.domain import user_services
from core.platform import models
from core.tests import test_utils

(user_models,) = models.Registry.import_models([models.NAMES.user])
taskqueue_services = models.Registry.import_taskqueue_services()

class UserQueryJobOneOffTests(test_utils.GenericTestBase):
    EXP_ID_1 = 'exp_id_1'
    EXP_ID_2 = 'exp_id_2'
    EXP_ID_3 = 'exp_id_3'
    USER_A_EMAIL = 'a@example.com'
    USER_A_USERNAME = 'a'
    USER_B_EMAIL = 'b@example.com'
    USER_B_USERNAME = 'b'
    USER_C_EMAIL = 'c@example.com'
    USER_C_USERNAME = 'c'
    USER_D_EMAIL = 'd@example.com'
    USER_D_USERNAME = 'd'
    USER_E_EMAIL = 'e@example.com'
    USER_E_USERNAME = 'e'
    USER_SUBMITTER_EMAIL = 'submit@example.com'
    USER_SUBMITTER_USERNAME = 'submit'

    def _run_one_off_job(self, query_id):
        """Runs the one-off MapReduce job."""
        job_id = user_query_jobs_one_off.UserQueryOneOffJob.create_new()
        params = {
            'query_id': query_id
        }
        user_query_jobs_one_off.UserQueryOneOffJob.enqueue(
            job_id, additional_job_params=params)
        self.assertEqual(
            self.count_jobs_in_taskqueue(
                queue_name=taskqueue_services.QUEUE_NAME_DEFAULT), 1)
        self.process_and_flush_pending_tasks()

    def setUp(self):
        super(UserQueryJobOneOffTests, self).setUp()
        # User A has no created or edited explorations
        # User B has one created exploration
        # User C has one edited exploration
        # User D has created an exploration and then edited it.
        # User E has created an exploration 10 days before.
        # Submitter is the user who submits the query.
        self.signup(self.USER_A_EMAIL, self.USER_A_USERNAME)
        self.user_a_id = self.get_user_id_from_email(self.USER_A_EMAIL)
        self.signup(self.USER_B_EMAIL, self.USER_B_USERNAME)
        self.user_b_id = self.get_user_id_from_email(self.USER_B_EMAIL)
        self.signup(self.USER_C_EMAIL, self.USER_C_USERNAME)
        self.user_c_id = self.get_user_id_from_email(self.USER_C_EMAIL)
        self.signup(self.USER_D_EMAIL, self.USER_D_USERNAME)
        self.user_d_id = self.get_user_id_from_email(self.USER_D_EMAIL)
        self.signup(self.USER_E_EMAIL, self.USER_E_USERNAME)
        self.user_e_id = self.get_user_id_from_email(self.USER_E_EMAIL)
        self.signup(self.USER_SUBMITTER_EMAIL, self.USER_SUBMITTER_USERNAME)
        self.submitter_id = self.get_user_id_from_email(
            self.USER_SUBMITTER_EMAIL)

        self.save_new_valid_exploration(
            self.EXP_ID_1, self.user_b_id, end_state_name='End')

        exp_services.update_exploration(self.user_c_id, self.EXP_ID_1, [{
            'cmd': 'edit_exploration_property',
            'property_name': 'objective',
            'new_value': 'the objective'
        }], 'Test edit')

        self.save_new_valid_exploration(
            self.EXP_ID_2, self.user_d_id, end_state_name='End')

        exp_services.update_exploration(self.user_d_id, self.EXP_ID_2, [{
            'cmd': 'edit_exploration_property',
            'property_name': 'objective',
            'new_value': 'the objective'
        }], 'Test edit')

        self.save_new_valid_exploration(
            self.EXP_ID_3, self.user_e_id, end_state_name='End')
        user_e_settings = user_services.get_user_settings(self.user_e_id)
        user_e_settings.last_created_an_exploration = (
            user_e_settings.last_created_an_exploration -
            datetime.timedelta(days=10))
        # Last edited time also changes when user creates an explorationan.
        user_e_settings.last_edited_an_exploration = (
            datetime.datetime.utcnow() - datetime.timedelta(days=10))
        user_e_settings.last_logged_in = (
            user_e_settings.last_logged_in - datetime.timedelta(days=10))
        user_services._save_user_settings(user_e_settings) # pylint: disable=protected-access

        user_a_settings = user_services.get_user_settings(self.user_a_id)
        user_a_settings.last_logged_in = (
            user_a_settings.last_logged_in - datetime.timedelta(days=3))
        user_services._save_user_settings(user_a_settings) # pylint: disable=protected-access

        # Set tmpsuperadm1n as admin in ADMIN_USERNAMES config property.
        self.set_admins(['tmpsuperadm1n'])

    def test_user_has_not_logged_in_last_n_days(self):
        query_id = user_query_services.save_new_query_model(
            self.submitter_id, has_not_logged_in_for_n_days=6)
        self._run_one_off_job(query_id)

        query = user_models.UserQueryModel.get(query_id)

        # List of users who has not logged_in in last 6 days.
        qualifying_user_ids = [self.user_e_id]
        self.assertEqual(len(query.user_ids), 1)
        self.assertEqual(sorted(query.user_ids), sorted(qualifying_user_ids))

        query_id = user_query_services.save_new_query_model(
            self.submitter_id, has_not_logged_in_for_n_days=2)
        self._run_one_off_job(query_id)

        query = user_models.UserQueryModel.get(query_id)

        # List of users logged_in in last 2 days.
        qualifying_user_ids = (
            [self.user_a_id, self.user_e_id])
        self.assertEqual(len(query.user_ids), 2)
        self.assertEqual(sorted(query.user_ids), sorted(qualifying_user_ids))

        # Test for legacy user.
        user_settings = user_services.get_user_settings(self.user_a_id)
        user_settings.last_logged_in = None
        user_services._save_user_settings(user_settings) # pylint: disable=protected-access

        query_id = user_query_services.save_new_query_model(
            self.submitter_id, has_not_logged_in_for_n_days=6)
        self._run_one_off_job(query_id)

        query = user_models.UserQueryModel.get(query_id)
        qualifying_user_ids = ([self.user_a_id, self.user_e_id])

        # Make sure that legacy user is included in qualified user's list.
        self.assertEqual(len(query.user_ids), 2)
        self.assertEqual(sorted(query.user_ids), sorted(qualifying_user_ids))

    def test_user_is_inactive_in_last_n_days(self):
        query_id = user_query_services.save_new_query_model(
            self.submitter_id, inactive_in_last_n_days=3)
        self._run_one_off_job(query_id)

        query = user_models.UserQueryModel.get(query_id)

        # List of users who were not active in last 3 days.
        qualifying_user_ids = [self.user_e_id]
        self.assertEqual(len(query.user_ids), 1)
        self.assertEqual(sorted(query.user_ids), sorted(qualifying_user_ids))

    def test_user_has_created_at_least_n_exps(self):
        query_id = user_query_services.save_new_query_model(
            self.submitter_id, created_at_least_n_exps=1)
        self._run_one_off_job(query_id)

        query = user_models.UserQueryModel.get(query_id)
        qualifying_user_ids = [self.user_b_id, self.user_d_id, self.user_e_id]
        self.assertEqual(len(query.user_ids), 3)
        self.assertEqual(sorted(query.user_ids), sorted(qualifying_user_ids))

    def test_user_has_created_fewer_than_n_exps(self):
        query_id = user_query_services.save_new_query_model(
            self.submitter_id, created_fewer_than_n_exps=1)
        self._run_one_off_job(query_id)

        query = user_models.UserQueryModel.get(query_id)
        qualifying_user_ids = [self.user_a_id, self.user_c_id]
        self.assertEqual(len(query.user_ids), 2)
        self.assertEqual(sorted(query.user_ids), sorted(qualifying_user_ids))

    def test_user_has_edited_at_least_n_exps(self):
        query_id = user_query_services.save_new_query_model(
            self.submitter_id, edited_at_least_n_exps=1)
        self._run_one_off_job(query_id)

        query = user_models.UserQueryModel.get(query_id)
        qualifying_user_ids = (
            [self.user_b_id, self.user_c_id, self.user_d_id, self.user_e_id])
        self.assertEqual(len(query.user_ids), 4)
        self.assertEqual(sorted(query.user_ids), sorted(qualifying_user_ids))

    def test_user_has_edited_fewer_than_n_exps(self):
        query_id = user_query_services.save_new_query_model(
            self.submitter_id, edited_fewer_than_n_exps=1)
        self._run_one_off_job(query_id)

        query = user_models.UserQueryModel.get(query_id)
        qualifying_user_ids = [self.user_a_id]
        self.assertEqual(len(query.user_ids), 1)
        self.assertEqual(query.user_ids, qualifying_user_ids)

    def test_combination_of_query_params(self):
        query_a_id = user_query_services.save_new_query_model(
            self.submitter_id, created_at_least_n_exps=1)
        self._run_one_off_job(query_a_id)

        query_b_id = user_query_services.save_new_query_model(
            self.submitter_id, edited_at_least_n_exps=1)
        self._run_one_off_job(query_b_id)

        query_combined_id = user_query_services.save_new_query_model(
            self.submitter_id, created_at_least_n_exps=1,
            edited_at_least_n_exps=1)
        self._run_one_off_job(query_combined_id)

        qualifying_user_ids_a = [self.user_b_id, self.user_d_id, self.user_e_id]
        qualifying_user_ids_b = (
            [self.user_b_id, self.user_c_id, self.user_d_id, self.user_e_id])
        qualifying_user_ids_combined = (
            [self.user_b_id, self.user_d_id, self.user_e_id])

        query_a = user_models.UserQueryModel.get(query_a_id)
        query_b = user_models.UserQueryModel.get(query_b_id)
        query_combined = user_models.UserQueryModel.get(query_combined_id)

        self.assertEqual(len(query_a.user_ids), 3)
        self.assertEqual(
            sorted(query_a.user_ids), sorted(qualifying_user_ids_a))

        self.assertEqual(len(query_b.user_ids), 4)
        self.assertEqual(
            sorted(query_b.user_ids), sorted(qualifying_user_ids_b))

        self.assertEqual(len(query_combined.user_ids), 3)
        self.assertEqual(
            sorted(query_combined.user_ids),
            sorted(qualifying_user_ids_combined))


text:
layout: announcement
version: v1.6.5
title: Monkey v1.6.5
intro: Release notes
---

### Introduction

[Monkey Server](http://monkey-project.com) is a fast and lightweight HTTP server for Linux, OSX and BSD. It has been designed to be very scalable with low memory and CPU consumption, the perfect solution for High Demand Production Servers and Embedded Devices. Made for ARM, x86 and x86_64.

We are proud to announce the availability of __Monkey v1.6.5__, which fixes a few  issues found recently in some plugins:

### Changes

Below there is a list of the most relevant changes on this version:

- Core: when hanging a connection that is being handled by a plugin, validate the stage30_hangup callback.
- Auth: implement missing stage30_hangup callback.
- FastCGI: invalidate handler if the connection failed, avoid a crash if FastCGI server is down.

### Contributors

We would like to thanks to the following people who have been involved doing coding, bug fixes, troubleshooting and general contributions on this release:

- [Eduardo Silva](http://twitter.com/edsiper)
- Phil Blackburn

### Join us!

We want to hear about you, our community is growing and you can be part of it!, you can contact us at:

 Slack: http://slack.monkey-project.com

     Mailing list: http://lists.monkey-project.com

 Github: http://github.com/monkey/monkey

 Google Plus: https://plus.google.com/communities/109231235096868947735

 IRC: irc.freenode.net #monkey

 Twitter: @monkeywebserver

 LinkedIn: https://www.linkedin.com/grp/home?gid=3211216

redpajama_set_name: RedPajamaGithub


text:
<?php namespace application\models;

class Role extends \system\utilities\Model {

    public $table = 'roles';

    //use \application\models\decorators\RoleDecorator;

    public function relationships()
    {

        $this->hasMany(['role_permissions'=>'role_id','roles'=>'id']);

    }

}


text: package fake_command_runner // import "code.cloudfoundry.org/commandrunner/fake_command_runner"


text:
Rails.application.routes.draw do
  get '/movies' => 'movies#index'
  get '/movies/:id' => 'movies#show', as: :movie
end


text:
package com.gearservice.config.converter;

import org.springframework.core.convert.converter.Converter;

import java.time.OffsetDateTime;

/**
 * Class OffsetDateTimeToStringConverter is configuration for converter OffsetDateTime to String
 * Used for converting Java 8 OffsetDateTime to JSON String
 * Only for MongoBD
 *
 * @version 1.1
 * @author Dmitry
 * @since 22.01.2016
 */

public class OffsetDateTimeToStringConverter implements Converter<OffsetDateTime, String> {

    @Override
    public String convert(OffsetDateTime entityValue) {
        return entityValue != null ? entityValue.toString() : null;

    }
}


text:
class Newsletter < ActiveRecord::Base
    file_column :file
end


text:
<?php
namespace Faker\Components\Engine\DB\Builder;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use PHPStats\Generator\GeneratorInterface;
use Doctrine\DBAL\Connection;

use Faker\Locale\LocaleInterface;
use Faker\Components\Engine\EngineException;
use Faker\Components\Engine\Common\Composite\CompositeInterface;
use Faker\Components\Engine\Common\Utilities;
use Faker\Components\Engine\Common\TypeRepository;
use Faker\Components\Templating\Loader;
use Faker\Components\Engine\Common\Builder\NodeCollection;
use Faker\Components\Engine\Common\Datasource\DatasourceRepository;
use Faker\Components\Engine\Common\Datasource\PHPDatasource;

/**
  *  Factory for Datasources
  *
  *  @author Lewis Dyer <getintouch@icomefromthenet.com>
  *  @since 1.0.5
  */
class DatasourceBuilder extends NodeCollection
{
    /**
      *  @var Faker\Components\Engine\Common\Datasource\DatasourceRepository
      */
    protected $repo;

     /**
      *  Class Constructor
      *
      *  @access public
      *  @return void
      */
    public function __construct($name,
                                EventDispatcherInterface $event,
                                TypeRepository $repo,
                                Utilities $util,
                                GeneratorInterface $generator,
                                LocaleInterface $locale,
                                Connection $conn,
                                Loader $loader,
                                DatasourceRepository $datasourceRepo)
    {
        parent::__construct($name,$event,$repo,$util,$generator,$locale,$conn,$loader);

        $this->repo = $datasourceRepo;

    }

    public function getNode()
    {
        return null;
    }

    public function end()
    {
        $parent   = $this->getParent();
        $children = $this->children();

        foreach($children as $formatter) {
            $parent->append($formatter);
        }

        return $parent;
    }

    //------------------------------------------------------------------
    # Builders

    /**
      *  Returns a datasource definition
      *
      *  @return Faker\Components\Engine\Common\Datasource\AbstractDefinition
      *  @access public
      */
    public function customDatasource($alias)
    {
        if(($resolvedAlias = $this->repo->find($alias)) === null) {
            throw new EngineException("$alias not found in datasource definition repository unable to create definition");
        }

        $field = new $resolvedAlias();

        # set the basic fields need by each type
        $field->generator($this->generator);
        $field->utilities($this->utilities);
        $field->database($this->database);
        $field->locale($this->locale);
        $field->eventDispatcher($this->eventDispatcher);
        //$field->templateLoader($this->templateLoader);
        $field->setParent($this);

        # return the definition for configuration by user
        return $field;
    }

    /**
      *  Returns a file datasource definition
      *
      *  @return Faker\Components\Engine\Common\Datasource\AbstractDefinition
      *  @access public
      */
    public function createFileSource()
    {
        return $this->customDatasource('filesource');
    }

    /**
      *  Returns a sql datasource definition
      *
      *  @return Faker\Components\Engine\Common\Datasource\AbstractDefinition
      *  @access public
      */
    public function createSQLSource()
    {
        return $this->customDatasource('sqlsource');
    }

    /**
      *  Returns a php datasource definition
      *
      *  @return Faker\Components\Engine\Common\Datasource\PHPDatasource
      *  @access public
      */
    public function createPHPSource()
    {
        return $this->customDatasource('phpsource');
    }

}
/* End of File */


text:
@section('content')

                     Restaurant Details

                {{ Form::model($model,['url' => route('update-my-restaurant'),'class'=>"form-horizontal",'role'=>"form",'method'=>'post']) }}

has('name') ? 'has-error' : '' }}">
                        Restaurant name

                            {{ Form::text('name', null, array('class' => 'form-control','placeholder'=>"Restaurant name")) }}
                            {{ $errors->first('name', ':message') }}

has('address') ? 'has-error' : '' }}">
                        Address

                            {{ Form::textarea('address', null, array('class' => 'form-control','placeholder'=>"Address",'rows'=>3)) }}
                            {{ $errors->first('address', ':message') }}

has('latitude') ? 'has-error' : '' }}">
                        Latitude

                            {{ Form::text('latitude', null, array('class' => 'form-control','placeholder'=>"Latitude")) }}
                            {{ $errors->first('latitude', ':message') }}

has('longitude') ? 'has-error' : '' }}">
                        Longitude

                            {{ Form::text('longitude', null, array('class' => 'form-control','placeholder'=>"Longitude")) }}
                            {{ $errors->first('longitude', ':message') }}

has('phone') ? 'has-error' : '' }}">
                        Phone

                            {{ Form::text('phone', null, array('class' => 'form-control','placeholder'=>"Phone")) }}
                            {{ $errors->first('phone', ':message') }}

has('backup_phone') ? 'has-error' : '' }}">
                        Backup Phone

                            {{ Form::text('backup_phone', null, array('class' => 'form-control','placeholder'=>"Backup Phone")) }}
                            {{ $errors->first('backup_phone', ':message') }}

has('taxes') ? 'has-error' : '' }}">
                        Taxes(%)

                            {{ Form::text('taxes', null, array('class' => 'form-control','placeholder'=>"Taxes")) }}
                            {{ $errors->first('taxes', ':message') }}

has('facebook') ? 'has-error' : '' }}">
                        Facebook Page Url

                            {{ Form::text('facebook', null, array('class' => 'form-control','placeholder'=>"Facebook Page Url")) }}
                            {{ $errors->first('facebook', ':message') }}

has('twitter') ? 'has-error' : '' }}">
                        Twitter Page Url

                            {{ Form::text('twitter', null, array('class' => 'form-control','placeholder'=>"Twitter Page Url")) }}
                            {{ $errors->first('twitter', ':message') }}

has('google_plus') ? 'has-error' : '' }}">
                        Google+ Page Url

                            {{ Form::text('google_plus', null, array('class' => 'form-control','placeholder'=>"Google+ Page Url")) }}
                            {{ $errors->first('google_plus', ':message') }}

                                <button type="submit" class="btn {{$_theme['save_btn_colour']}}">Save</button>
                                Cancel

                {{ Form::close() }}

@stop


text:
@interface MXPageController : UIViewController <MXPageControllerProtocal>

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *topView;

@end


text:
/**
 * Executes searching.
 */
function Search() {}

var searchTable, mapTable;

/**
 * Executes requests to db with search text written by the user.
 * Search requests include selected facet values.
 */
Search.execute = function(searchText) {
	console.log(searchText);

	//check selected facet value @see exhibitOutputFunctions.js
    var selectedTopics = getTopicSelection();
    var selectedDatatypes = getDatatypeSelection();
    var selectedOrganizations = getOrganizationSelection();
    var selectedScenarios = getScenarioSelection();
    var selectedHierarchylevelnames = getHierarchylevelnameSelection();
    var selectedBoundingboxes = getBoundingboxSelection();

    //push all selections into one array
    var selectionCluster = [];
    selectionCluster.push(selectedHierarchylevelnames);
    selectionCluster.push(selectedScenarios);
    selectionCluster.push(selectedTopics);
    selectionCluster.push(selectedDatatypes);
    selectionCluster.push(selectedOrganizations);
    selectionCluster.push(selectedBoundingboxes);

    if ("/" + selectedHierarchylevelnames + "/" + selectedTopics + "/" + selectedDatatypes + "/" + selectedOrganizations + "/" + selectedScenarios == "/-/-/-/-/-"){
    	//get results without consideration of user facet selection
        var resultWSEntries = httpGet(findSimilarLimited + "/" + searchText + "/-/-/-/-/-");
        var resultWSScenarios = httpGet(findSimilarScenarioValues + "/" + searchText + "/-/-/-/-");
        var resultWSHvls = httpGet(findSimilarHierarchylevelnameValues + "/" + searchText + "/-/-/-/-");
        var resultWSTopics = httpGet(findSimilarTopiccategoryValues + "/" + searchText + "/-/-/-/-");
        var resultWSDatatypes = httpGet(findSimilarDatatypeValues + "/" + searchText + "/-/-/-/-");
        var resultWSOrganizations = httpGet(findSimilarOrganizationValues + "/" + searchText + "/-/-/-/-");
    } else {
    	 //get results in consideration of user facet selection
        var resultEntries = httpGet(findSimilarLimited + "/" + searchText + "/" + selectedHierarchylevelnames + "/" + selectedTopics + "/" + selectedDatatypes + "/" + selectedOrganizations + "/" + selectedScenarios);
        var resultScenarios = httpGet(findSimilarScenarioValues + "/" + searchText + "/" + selectedHierarchylevelnames + "/" + selectedTopics + "/" + selectedDatatypes + "/" + selectedOrganizations);
        var resultHvls = httpGet(findSimilarHierarchylevelnameValues + "/" + searchText + "/" + selectedScenarios + "/" + selectedTopics + "/" + selectedDatatypes + "/" + selectedOrganizations);
        var resultTopics = httpGet(findSimilarTopiccategoryValues + "/" + searchText + "/" + selectedScenarios + "/" + selectedHierarchylevelnames + "/" + selectedDatatypes + "/" + selectedOrganizations);
        var resultDatatypes = httpGet(findSimilarDatatypeValues + "/" + searchText + "/" + selectedScenarios + "/" + selectedHierarchylevelnames + "/" + selectedTopics + "/" + selectedOrganizations);
        var resultOrganizations = httpGet(findSimilarOrganizationValues + "/" + searchText + "/" + selectedScenarios + "/" + selectedHierarchylevelnames + "/" + selectedTopics + "/" + selectedDatatypes);
    }

    //push all results into one array
    var resultCluster = [];
    resultCluster.push(resultHvls);
    resultCluster.push(resultScenarios);
    resultCluster.push(resultTopics);
    resultCluster.push(resultDatatypes);
    resultCluster.push(resultOrganizations);
    resultCluster.push(resultEntries);

    //push all results into one array
    var resultWSCluster = [];
    resultWSCluster.push(resultWSHvls);
    resultWSCluster.push(resultWSScenarios);
    resultWSCluster.push(resultWSTopics);
    resultWSCluster.push(resultWSDatatypes);
    resultWSCluster.push(resultWSOrganizations);
    resultWSCluster.push(resultWSEntries);

    //display results
    displayResultOverview(resultCluster, resultWSCluster, selectionCluster, searchText);
};

function displayResultOverview(data, dataWS, selectionCluster, searchText) {
	require(["dojo/dom-construct", "dijit/form/Button", "dijit/layout/TabContainer", "dijit/layout/ContentPane", "dojo/domReady!"], function(domConstruct, Button, TabContainer, ContentPane) {

		//Body + Header ---------------------------------------------------------------------
		var globalBody = domConstruct.create("div", {
			id: "Dialog_body",
			style: "width: 100%;"
		});

		domConstruct.create("div", {
			innerHTML: "Choose the preferred result",
			style: "width: 100%; margin-bottom: 20px;font-size: 14px; color: #007C95; text-align: center;"
		}, globalBody);

		var bodyWS = domConstruct.create("div", {
			id: "innerBodyWS",
			style: "width: 100%;"
		}, globalBody);

	    //-----------------------------------------------------------------------------------
//	    createTable(data, selectionCluster, body, domConstruct, Button, searchText);
	    createTable(dataWS, null, bodyWS, domConstruct, Button, searchText);

		darkDarkerDarkest(globalBody);
	});
}

function createTable(data, selectionCluster, body, domConstruct, Button, searchText) {
    //Table with results ----------------------------------------------------------------
	var widget = domConstruct.create("table", {
		id: "SearchResults",
		style: "width: 100%;"
	}, body);

	searchTable = widget;

	//Fill table with results -----------------------------------------------------------
	for (var i = 0; i < data.length; i++) {
		if (i == 0) facetName = hierarchylevelnameFacet;
		else if (i == 1) facetName = scenarioFacet;
		else if (i == 2) facetName = topicFacet;
		else if (i == 3) facetName = datatypeFacet;
		else if (i == 4) facetName = organizationFacet;
		else facetName = "";

		if (data[i] && data[i].length > 0) {
			createRow(facetName, data[i], selectionCluster, domConstruct, widget, searchText);
		}
	}

	var mapResults = GeoNames.body;
	mapTable = mapResults.childNodes[0];
	body.appendChild(mapResults);

	//Buttons ---------------------------------------------------------------------------
	var okBTN = domConstruct.create("div", {
		style: "width: 100%; height: 30px;"
	}, body);

	var cancelBTN = domConstruct.create("div", {
		style: "width: 100%; height: 30px;"
	}, body);

	new Button({
		label: "OK",
		onClick: function() {
			//Facet and details results
			for (var i = 0; i < widget.rows.length; i++) {
				var row = widget.rows[i];
				if (row.style.backgroundColor === "rgba(0, 124, 149, 0.2)") {
					updateFacetsAndResultlist(row, selectionCluster);
				}
			}
			//GeoNames results
			for (var i = 0; i < mapTable.rows.length; i++) {
				var row = mapTable.rows[i];
				if (row.style.backgroundColor === "rgba(0, 124, 149, 0.2)") {

					var LatLongFcode = row.cells[0].id.split(":");
					map2.getView().setCenter(transform(Number(LatLongFcode[1]), Number(LatLongFcode[0])));
					map2.getView().setZoom(manageLevelOfZoom(LatLongFcode[2]));

				}
			}

			require(["dijit/registry"], function(registry) {
				var dialog = registry.byId("SearchResultOverview");
				dialog.hide();
			});
		}
	}, okBTN);

	new Button({
		label: "Cancel",
		onClick: function() {
			require(["dijit/registry"], function(registry) {
				var dialog = registry.byId("SearchResultOverview");
				dialog.hide();
			});
		}
	}, cancelBTN);
}

/**
 * Create a row for each facet and each result belonging to this facet.
 *
 * Method is called for each facet (entry in selectionCluster) - one call creates
 * all rows for one facet.
 *
 * @param facetName - facetName
 * @param data - result list (entries that match the query)
 * @param selectionCluster - summarizes all selected facet values ordered by facet
 * @param domConstruct - to create new dom elements, e.g. table/row
 * @param widget - to add the rows
 */
function createRow(facetName, data, selectionCluster, domConstruct, widget, searchText) {
	var trHead = domConstruct.create("tr", {
		style: "background-color: #FFFFFF;",
	}, widget);

	var singleResults = false;
	if (facetName == "") {
		singleResults = true;
	}

	for (var i = 0; i < data.length; i++) {
		if (singleResults) facetName = data[i].id;

		var tr = domConstruct.create("tr", {
			id : facetName,
			style: "background-color: #FFFFFF;border-top:1px solid gray;",
			ondblclick: function() {  //dbl click to select
				for (var i = 0; i < widget.rows.length; i++) {
					var row = widget.rows[i];
					if (row.style.backgroundColor === "rgba(0, 124, 149, 0.2)") {
						updateFacetsAndResultlist(row, selectionCluster);
					}
				}

				require(["dijit/registry"], function(registry) {
					var dialog = registry.byId("SearchResultOverview");
					dialog.hide();
				});
			},

			onclick: function() {
				for (var i = 0; i < widget.rows.length; i++) {
					row = widget.rows[i];
					row.style.backgroundColor = "#fff";
				}

				//map results - resetting colors
				for (var i = 0; i < mapTable.rows.length; i++) {
					row = mapTable.rows[i];
					row.style.backgroundColor = "#fff";
				}

				this.style.backgroundColor = "rgba(0,124,149,0.2)";
			}
		}, widget);

		tr.style.backgroundColor = "#fff";

		//fill the list with results
		if (facetName == scenarioFacet || facetName == hierarchylevelnameFacet || facetName == topicFacet || facetName == datatypeFacet || facetName == organizationFacet) {
			//search for more keywords if a space sign is detected to highlight all keywords properly
			//if more than 1 keyword - and show keywords properly with lower and upper case etc
			if (searchText.split(" ").length > 1){
				var keywords = searchText.split(" ");
				var highlighted = data[i];
				for (var x=0;  x<keywords.length; x++){
					var re = new RegExp(keywords[x],'ig');
					var result= highlighted.match(re);
					highlighted = highlighted.replace(re, "" + result + "");

				}
				domConstruct.create("td", { id: data[i], innerHTML: highlighted + "
Facet: " + facetName, style: { cursor: "pointer" }  }, tr);
			}else {
				var re = new RegExp(searchText, 'ig');
				var result= data[i].match(re);
				var highlighted = data[i].replace(re, "" + result + "");
				domConstruct.create("td", { id: data[i], innerHTML: highlighted + "
Facet: " + facetName, style: { cursor: "pointer" }  }, tr);
			}

		} else {

			//if more than 1 keyword - and show keywords properly with lower and upper case etc
			if (searchText.split(" ").length > 1){
				var keywords = searchText.split(" ");
				var highlighted = data[i].label;
				for (var x=0;  x<keywords.length; x++){
					var re = new RegExp(keywords[x],'ig');
					var result= highlighted.match(re);
					highlighted = highlighted.replace(re, "" + result + "");

				}
				domConstruct.create("td", { id: data[i], innerHTML: highlighted + "
Data type: " + data[i].datatype + "
" + data[i].description, style: { cursor: "pointer" } }, tr);
			} else {
				var re = new RegExp(searchText,'ig');
				var result= data[i].label.match(re);
				var highlighted = data[i].label.replace(re, "" + result + "");
				domConstruct.create("td", { id: data[i], innerHTML: highlighted + "
Data type: " + data[i].datatype + "
" + data[i].description, style: { cursor: "pointer" } }, tr);
			}

		}
	}
}

/**
 * After the user has chosen a result, this method is called.
 * It updates all facets and the result list.
 *
 * @param row - the selected row
 */
function updateFacetsAndResultlist(row, selectionCluster) {
	if (row.id == topicFacet) {
		selectedValue = row.cells[0].id;

		var selected = new Object();
		selected[selectedValue] = true;

		exhibit._registry._registry.facet.f3._valueSet._count = 1;
		exhibit._registry._registry.facet.f3._valueSet._hash = selected;
		exhibit._registry._registry.facet.f3._notifyCollection();

	} else if (row.id == datatypeFacet) {
		selectedValue = row.cells[0].id;

		var selected = new Object();
		selected[selectedValue] = true;

		exhibit._registry._registry.facet.f2._valueSet._count = 1;
		exhibit._registry._registry.facet.f2._valueSet._hash = selected;
		exhibit._registry._registry.facet.f2._notifyCollection();

	} else if (row.id == organizationFacet) {
		selectedValue = row.cells[0].id;

		var selected = new Object();
		selected[selectedValue] = true;

		exhibit._registry._registry.facet.f4._valueSet._count = 1;
		exhibit._registry._registry.facet.f4._valueSet._hash = selected;
		exhibit._registry._registry.facet.f4._notifyCollection();

	} else if (row.id == scenarioFacet) {
		selectedValue = row.cells[0].id;

		var selected = new Object();
		selected["value"] = selectedValue;

		exhibit._registry._registry.facet.f1._selections = [selected];
		exhibit._registry._registry.facet.f1._notifyCollection();

	} else if (row.id == hierarchylevelnameFacet) {
		selectedValue = row.cells[0].id;

		var selected = new Object();
		selected["value"] = selectedValue;

		exhibit._registry._registry.facet.f0._selections = [selected];
		exhibit._registry._registry.facet.f0._notifyCollection();

	} else {
		//single entry selected

		//clear facet selection
		if (!selectionCluster) {
			exhibit._registry._registry.facet.f0._selections = {};
			exhibit._registry._registry.facet.f0._notifyCollection();

			exhibit._registry._registry.facet.f1._selections = {};
			exhibit._registry._registry.facet.f1._notifyCollection();

			exhibit._registry._registry.facet.f2._valueSet._count = 0;
			exhibit._registry._registry.facet.f2._valueSet._hash = {};
			exhibit._registry._registry.facet.f2._notifyCollection();

			exhibit._registry._registry.facet.f3._valueSet._count = 0;
			exhibit._registry._registry.facet.f3._valueSet._hash = {};
			exhibit._registry._registry.facet.f3._notifyCollection();

			exhibit._registry._registry.facet.f4._valueSet._count = 0;
			exhibit._registry._registry.facet.f4._valueSet._hash = {};
			exhibit._registry._registry.facet.f4._notifyCollection();

			exhibit._registry._registry.facet.f5._valueSet._count = 0;
			exhibit._registry._registry.facet.f5._valueSet._hash = {};
			exhibit._registry._registry.facet.f5._notifyCollection();
		}

		//fill detailed view -> general metadata and tree
		selectedValue = row.cells[0].id;
		guiFunctions.setItemDetails(row.id);

	}
}

/**
*\details	this method pops up a dijit dialog which display the search results in a table
*\author		Hannes Tressel
*\param		widget	content element
*/
function darkDarkerDarkest(widget) {
	require(["dijit/Dialog", "dojo/window", "dijit/registry", "dojo/on", "dojo/keys"], function(dialog, window, registry, on, keys){
		var browserSize = window.getBox();

		if (registry.byId("SearchResultOverview")) {
			registry.byId("SearchResultOverview").destroyRecursive();
		}

		var dialogWidget = new dialog({
			id: "SearchResultOverview",
			title: "Results",
			autofocus: false,
			style: "width:"+(browserSize.w*80)/100+"px; height:"+(browserSize.h*60)/100+"px;",
			content: widget
		});
		dialogWidget.show();

		if (heatmap) {
			searchMode = true;
			dialogWidget.connect(dialogWidget, "hide", function(e){
			    searchMode = false;
			});
		}
	});
}


text:
class Consul < FPM::Cookery::Recipe
  name 'consul'
  version '1.0.5'
  source "https://releases.hashicorp.com/consul/#{version}/consul_#{version}_linux_amd64.zip"
  homepage 'https://consul.io/'

  depends %w[
    systemd
  ]

  config_files '/etc/sysconfig/consul'

  post_install 'post_install'
  pre_uninstall 'pre_uninstall'

  def build
    safesystem "strip -s #{name}"
  end

  def install
    etc(name).mkdir
    etc("#{name}/bootstrap").mkdir
    etc("#{name}/server").mkdir
    etc("#{name}/client").mkdir
    etc('sysconfig').install workdir("config"), name
    sbin.install Dir[name]
    prefix("lib/systemd/system").install workdir("#{name}.service")
    var('lib/consul').mkdir
  end
end


text: I am raised when the text is accepted in the view


text:
package org.ccnx.ccn.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.security.keystore.AESKeyStoreSpi;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;

/**
 * Command line utility to write and read a symmetric keystore file for testing
 **/
 public class ccnkeystoretool extends CommonOutput implements Usage {
	 static final int KEYSIZE = 256/8;
	 static ccnkeystoretool createkeystore = new ccnkeystoretool();
	 static String[] okArgs = {"-log", "-v"};

	/**
	 * @param args
	 */
	public void keytool(String[] args) {
		Log.setDefaultLevel(Level.WARNING);
		boolean readMode = false;
		String data = null;
		String password = null;
		String digest = null;

		for (int i = 0; i < args.length; i++) {
			if (CommonArguments.parseArguments(args, i, createkeystore, okArgs)) {
				i = CommonParameters.startArg;
				continue;
			}
			if (args[i].equals("-data")) {
				data = args[i + 1];
				CommonParameters.startArg = ++i;
			} else if (args[i].equals("-password")) {
				password = args[i + 1];
				CommonParameters.startArg = ++i;
			} else if (args[i].equals("-read")) {
				readMode = true;
			} else if (args[i].equals("-digest")) {
				digest = args[i + 1];
				CommonParameters.startArg = ++i;
			} else
				usage(CommonArguments.getExtraUsage());
		}

		if (args.length < CommonParameters.startArg) {
			usage(CommonArguments.getExtraUsage());
		}

		KeyManager km = KeyManager.getDefaultKeyManager();
		if (readMode) {
			if (null == digest)
				usage(CommonArguments.getExtraUsage());
			try {
				PublisherPublicKeyDigest ppkd = KeyManager.keyStoreToDigest(SystemConfiguration.KEYSTORE_NAMING_VERSION, digest);
				Key key = km.getVerificationKey(ppkd, null, AESKeyStoreSpi.TYPE, null, password,
						SystemConfiguration.NO_TIMEOUT);
				if (null == key)
					System.out.println("Couldn't get the key for: " + digest);
				else {
					System.out.println("Retrieved key: 0x" +  DataUtils.printHexBytes(((SecretKey)key).getEncoded()));
				}
			} catch (FileNotFoundException fnfe) {
				System.out.println("Can't find key file for digest: " + digest);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			try {
				SecretKey sk = null;
				if (null == data) {
					KeyGenerator kg = KeyGenerator.getInstance("HMAC-SHA256", KeyManager.PROVIDER);
					sk = kg.generateKey();
				} else {
					byte[] dbytes = data.getBytes();
					byte[] keyBytes = new byte[KEYSIZE];
					int len = dbytes.length > KEYSIZE ? KEYSIZE : dbytes.length;
					System.arraycopy(dbytes, 0, keyBytes, 0, len);
					if (len < KEYSIZE)
						for (int i = len; i < KEYSIZE; i++)
							keyBytes[i] = 0;
					sk = new SecretKeySpec(keyBytes, "HMAC-SHA256");
				}
				km.saveVerificationKey(sk, null, null, null, password);
				System.out.println("Stored key successfully");
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		System.exit(1);

	}

	@Override
	public void usage(String extraUsage) {
		System.out.println("usage: ccncreatekeystore " + extraUsage + "[-v (verbose)] [-log level] [-data <dataforkey>]"
					+ "\n\t\t [-password <password>] [-read -digest <digest>]");
		System.exit(1);
	}

	public static void main(String[] args) {
		createkeystore.keytool(args);
	}
}


text:
Shader::Shader(const std::string& fileName, const std::vector<std::string>& uniforms)
{
	m_Program = glCreateProgram();
	m_Shaders[VERTEX_SHADER] = Shader::CreateShader(Shader::LoadShader(fileName + ".vs"), GL_VERTEX_SHADER);
	m_Shaders[FRAGMENT_SHADER] = Shader::CreateShader(Shader::LoadShader(fileName + ".fs"), GL_FRAGMENT_SHADER);

	for (auto i : {0U, 1U}) {
		glAttachShader(m_Program, m_Shaders[i]);
	}

	glLinkProgram(m_Program);
	GLint status;
	glGetProgramiv(m_Program, GL_LINK_STATUS, &status);
	if (status != GL_TRUE) {
		GLint infoLogLength;
		glGetProgramiv(m_Program, GL_INFO_LOG_LENGTH, &infoLogLength);

		// Intentional memory leak, this will end the program execution anyway
		GLchar* buffer = new GLchar[infoLogLength];

		GLsizei bufferSize;
		glGetProgramInfoLog(m_Program, infoLogLength, &bufferSize, buffer);
		throw Error("Shader linking failed: " + std::string(buffer));
	}

	glValidateProgram(m_Program);
	glGetProgramiv(m_Program, GL_VALIDATE_STATUS, &status);
	if (status != GL_TRUE) {
		GLint infoLogLength;
		glGetProgramiv(m_Program, GL_INFO_LOG_LENGTH, &infoLogLength);

		// Intentional memory leak, this will end the program execution anyway
		GLchar* buffer = new GLchar[infoLogLength];

		GLsizei bufferSize;
		glGetProgramInfoLog(m_Program, infoLogLength, &bufferSize, buffer);
		throw Error("Shader linking failed: " + std::string(buffer));
	}

	for (auto& uniform : uniforms) {
		m_Uniforms.push_back(glGetUniformLocation(m_Program, uniform.c_str()));
	}
}

Shader::~Shader()
{
	for (auto i : { 0U, 1U }) {
		glDetachShader(m_Program, m_Shaders[i]);
		glDeleteShader(m_Shaders[i]);
	}
	glDeleteProgram(m_Program);
}

void Shader::Start()
{
	glUseProgram(m_Program);
}

void Shader::Stop()
{
	glUseProgram(0);
}

void Shader::SendUniform(const int uniformID, const glm::mat4& matrix)
{
	glUniformMatrix4fv(m_Uniforms[uniformID], 1, GL_FALSE, &matrix[0][0]);
}

void Shader::SendUniform(const int uniformID, const glm::vec4& vector)
{
	glUniform4fv(m_Uniforms[uniformID], 1, &vector[0]);
}

void Shader::SendUniform(const int uniformID, const float number)
{
	glUniform1f(uniformID, number);
}

std::string Shader::LoadShader(const std::string& fileName)
{
	std::ifstream file;
	file.open(fileName.c_str());

	std::string output;
	std::string line;

	if (!file.is_open()) {
		throw Error("Unable to load shader: " + fileName);
	}

	while (file.good()) {
		std::getline(file, line);
		output += (line + '\n');
	}

	return output;
}

GLuint Shader::CreateShader(const std::string& text, const GLenum shaderType)
{
	GLuint shader = glCreateShader(shaderType);
	if (shader == 0)
		throw Error("Shader creating failed!");

	const GLchar* shaderSourceStrings[1];
	GLint shaderSourceStringLengths[1];

	shaderSourceStrings[0] = text.c_str();
	shaderSourceStringLengths[0] = text.length();

	glShaderSource(shader, 1, shaderSourceStrings, shaderSourceStringLengths);
	glCompileShader(shader);

	GLint status;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
	if (status != GL_TRUE) {
		GLint infoLogLength;
		glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);

		// Intentional memory leak, this will end the program execution anyway
		GLchar* buffer = new GLchar[infoLogLength];

		GLsizei bufferSize;
		glGetShaderInfoLog(shader, infoLogLength, &bufferSize, buffer);
		throw Error("Shader compilation failed: " + std::string(buffer));
	}
	return shader;
}


text:
<?php namespace Pixel\Repositories\User;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Pixel\Contracts\User\RepositoryContract;
use Pixel\Exceptions\User\UserNotFoundException;
use Pixel\Repositories\Repository;
use Pixel\User as UserModel;

class DbRepository extends Repository implements RepositoryContract {

    use Permissions;

    /**
     * The attributes excluded from the repositories JSON form
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token', 'activation_token', 'activation_code'];

    /**
     * Create a new user
     *
     * @param array $attributes
     *
     * @return $this
     */
    public function create(array $attributes)
    {
        // Create the user and return a fresh repository instance
        $user = UserModel::create($attributes);
        $this->fill( $user->toArray() );

        return $this;
    }

    /**
     * Activate a users account
     */
    public function activate()
    {
        // Update our activation columns
        $this->setAttribute('active', 1);
        $this->hiddenAttributes[$this->getActivationTokenName()] = null;
        $this->hiddenAttributes[$this->getActivationCodeName()]  = null;

        $this->save();
    }

    /**
     * Terminate the specified user
     */
    public function destroy()
    {
        UserModel::destroy($this->getAuthIdentifier());
    }

    /**
     * Update a users attributes
     */
    public function save()
    {
        UserModel::where('id', '=', $this->getAuthIdentifier())
            ->update($this->getAllAttributes());
    }

    /**
     * Retrieve a user by their unique identifier
     *
     * @param int $id
     *
     * @return $this
     * @throws UserNotFoundException
     */
    public function getById($id)
    {
        try {
            $user = UserModel::findOrFail($id)->toArray();
        } catch (ModelNotFoundException $e) {
            throw new UserNotFoundException($e->getMessage(), $e->getCode());
        }
        $this->fill($user);

        return $this;
    }

    /**
     * Retrieve a user by their OAuth credentials
     *
     * @param string $driver
     * @param int    $id
     *
     * @return $this
     * @throws UserNotFoundException
     */
    public function getByOAuthId($driver, $id)
    {
        try {
            $user = UserModel::where('oauth_id', '=', $id)
                ->where('oauth_driver', '=', $driver)
                ->firstOrFail()
                ->toArray();
        } catch (ModelNotFoundException $e) {
            throw new UserNotFoundException($e->getMessage(), $e->getCode());
        }
        $this->fill($user);

        return $this;
    }

    /**
     * Retrieve a user by by their unique identifier and "remember me" token
     *
     * @param int     $id
     * @param string  $token
     *
     * @return $this
     * @throws UserNotFoundException
     */
    public function getByToken($id, $token)
    {
        $model = new UserModel;

        try {
            $user = $model->newQuery()
                         ->where($model->getKeyName(), $id)
                         ->where($model->getRememberTokenName(), $token)
                         ->firstOrFail()
                         ->toArray();
        } catch (ModelNotFoundException $e) {
            throw new UserNotFoundException($e->getMessage(), $e->getCode());
        }
        $this->fill($user);

        return $this;
    }

    /**
     * Retrieve a user by the given credentials
     *
     * @param array $credentials
     *
     * @return $this
     * @throws UserNotFoundException
     */
    public function getByCredentials(array $credentials)
    {
        // First we will add each credential element to the query as a where clause.
        // Then we can execute the query and, if we found a user, return it in a
        // Eloquent User "model" that will be utilized by the Guard instances.
        $model = new UserModel;
        $query = $model->newQuery();

        foreach ($credentials as $key => $value)
        {
            if ( ! str_contains($key, 'password')) $query->where($key, $value);
        }

        try {
            $this->fill( $query->firstOrFail()->toArray() );
        } catch (ModelNotFoundException $e) {
            throw new UserNotFoundException('No user with the provided credentials found');
        }

        return $this;
    }

    /**
     * Get the unique identifier for the user
     *
     * @return int
     */
    public function getAuthIdentifier()
    {
        return $this->attributes['id'];
    }

    /**
     * Get the password for the user
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->hiddenAttributes['password'];
    }

    /**
     * Get the token value for the "remember me" session
     *
     * @return string
     */
    public function getRememberToken()
    {
        return $this->hiddenAttributes[$this->getRememberTokenName()];
    }

    /**
     * Get the token value for the activation session
     *
     * @return string
     */
    public function getActivationToken()
    {
        return $this->hiddenAttributes[$this->getActivationTokenName()];
    }

    /**
     * Get the activation code for the users account
     *
     * @return string
     */
    public function getActivationCode()
    {
        return $this->hiddenAttributes[$this->getActivationCodeName()];
    }

    /**
     * Set the token value for the "remember me" session
     *
     * @param string $value
     */
    public function setRememberToken($value)
    {
        UserModel::where('id', '=', $this->getAuthIdentifier())
            ->update([$this->getRememberTokenName() => $value]);
    }

    /**
     * Set the token value for the activation session
     *
     * @param string $value
     */
    public function setActivationToken($value)
    {
        $this->hiddenAttributes[$this->getActivationTokenName()] = $value;

        UserModel::where('id', '=', $this->getAuthIdentifier())
                 ->update([$this->getActivationTokenName() => $value]);
    }

    /**
     * Make sure the supplied activation code is valid
     *
     * @param string $code
     *
     * @return bool
     */
    public function validateActivationCode($code)
    {
        // Make sure we are actually an inactive user
        if ( $this->attributes['active'] || empty($this->hiddenAttributes[$this->getActivationTokenName()]) )
            return false;

        return ($this->hiddenAttributes[$this->getActivationCodeName()] == $code);
    }

    /**
     * Make sure the supplied activation token is valid
     *
     * @param string $token
     *
     * @return bool
     */
    public function validateActivationToken($token)
    {
        // Make sure we are actually an inactive user
        if ( $this->attributes['active'] || empty($this->hiddenAttributes[$this->getActivationTokenName()]) )
            return false;

        return ($this->hiddenAttributes[$this->getActivationTokenName()] == $token);
    }

    /**
     * Get the column name for the "remember me" token
     *
     * @return string
     */
    public function getRememberTokenName()
    {
        return 'remember_token';
    }

    /**
     * Get the column name for the activation token
     *
     * @return string
     */
    public function getActivationTokenName()
    {
        return 'activation_token';
    }

    /**
     * Get the column name for the activation code
     *
     * @return string
     */
    public function getActivationCodeName()
    {
        return 'activation_code';
    }

    /**
     * Get the e-mail address where password reset links are sent.
     *
     * @return string
     */
    public function getEmailForPasswordReset()
    {
        return $this->getAttribute('email');
    }

}


text:
def mapper(book):
    return [1, book.pages]

reducer=double_sum


text:
using System;
using System.Linq;
using Microsoft.WindowsAzure.WebSitesExtensions.Models;

namespace Microsoft.WindowsAzure.WebSitesExtensions.Models
{
    public abstract partial class WebJobBase
    {
        private string _error;

        /// <summary>
        /// Optional. The error if there was one.
        /// </summary>
        public string Error
        {
            get { return this._error; }
            set { this._error = value; }
        }

        private string _extraInfoUrl;

        /// <summary>
        /// Optional. The extra information url.
        /// </summary>
        public string ExtraInfoUrl
        {
            get { return this._extraInfoUrl; }
            set { this._extraInfoUrl = value; }
        }

        private string _name;

        /// <summary>
        /// Optional. The name.
        /// </summary>
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }

        private string _runCommand;

        /// <summary>
        /// Optional. The run command.
        /// </summary>
        public string RunCommand
        {
            get { return this._runCommand; }
            set { this._runCommand = value; }
        }

        private WebJobType _type;

        /// <summary>
        /// Optional. The type.
        /// </summary>
        public WebJobType Type
        {
            get { return this._type; }
            set { this._type = value; }
        }

        private Uri _url;

        /// <summary>
        /// Optional. The url.
        /// </summary>
        public Uri Url
        {
            get { return this._url; }
            set { this._url = value; }
        }

        private bool _usingSdk;

        /// <summary>
        /// Optional. True if the job is using the WebJobs SDK otherwise false.
        /// </summary>
        public bool UsingSdk
        {
            get { return this._usingSdk; }
            set { this._usingSdk = value; }
        }

        /// <summary>
        /// Initializes a new instance of the WebJobBase class.
        /// </summary>
        public WebJobBase()
        {
        }
    }
}


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

import org.sleuthkit.autopsy.discovery.search.AbstractFilter;
import static java.awt.BorderLayout.CENTER;
import java.awt.Color;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.apache.commons.lang.StringUtils;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoException;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepository;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.ThreadConfined;
import org.sleuthkit.autopsy.discovery.search.DiscoveryAttributes;
import org.sleuthkit.autopsy.discovery.search.DiscoveryEventUtils;
import org.sleuthkit.autopsy.discovery.search.Group;
import org.sleuthkit.autopsy.discovery.search.Group.GroupSortingAlgorithm;
import org.sleuthkit.autopsy.discovery.search.DiscoveryAttributes.GroupingAttributeType;
import org.sleuthkit.autopsy.discovery.search.ResultsSorter;
import org.sleuthkit.autopsy.discovery.search.ResultsSorter.SortingMethod;
import org.sleuthkit.autopsy.discovery.search.SearchData;
import org.sleuthkit.autopsy.ingest.IngestManager;
import org.sleuthkit.autopsy.ingest.ModuleDataEvent;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.TskCoreException;

/**
 * Dialog for displaying the controls and filters for configuration of a
 * Discovery search.
 */
final class DiscoveryDialog extends javax.swing.JDialog {

    private static final Set<Case.Events> CASE_EVENTS_OF_INTEREST = EnumSet.of(Case.Events.CURRENT_CASE,
            Case.Events.DATA_SOURCE_ADDED, Case.Events.DATA_SOURCE_DELETED);
    private static final Set<IngestManager.IngestModuleEvent> INGEST_MODULE_EVENTS_OF_INTEREST = EnumSet.of(IngestManager.IngestModuleEvent.DATA_ADDED);
    private static final long serialVersionUID = 1L;
    private final static Logger logger = Logger.getLogger(DiscoveryDialog.class.getName());
    private ImageFilterPanel imageFilterPanel = null;
    private VideoFilterPanel videoFilterPanel = null;
    private DocumentFilterPanel documentFilterPanel = null;
    private DomainFilterPanel domainFilterPanel = null;
    private static final Color SELECTED_COLOR = new Color(216, 230, 242);
    private static final Color UNSELECTED_COLOR = new Color(240, 240, 240);
    private SearchWorker searchWorker = null;
    private static DiscoveryDialog discDialog;
    private static volatile boolean shouldUpdate = false;
    private SearchData.Type type = SearchData.Type.IMAGE;
    private final PropertyChangeListener listener;
    private final Set<BlackboardAttribute> objectsDetected = new HashSet<>();
    private final Set<BlackboardAttribute> interestingItems = new HashSet<>();
    private final Set<BlackboardAttribute> hashSets = new HashSet<>();

    /**
     * Get the Discovery dialog instance.
     *
     * @return The instance of the Discovery Dialog.
     */
    static synchronized DiscoveryDialog getDiscoveryDialogInstance() {
        if (discDialog == null) {
            discDialog = new DiscoveryDialog();
        }
        if (shouldUpdate) {
            discDialog.updateSearchSettings();
            shouldUpdate = false;
        }
        return discDialog;
    }

    /**
     * Private constructor to construct a new DiscoveryDialog
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    @Messages("DiscoveryDialog.name.text=Discovery")
    private DiscoveryDialog() {
        super(WindowManager.getDefault().getMainWindow(), Bundle.DiscoveryDialog_name_text(), true);
        initComponents();
        listener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("FilterError") && evt.getNewValue() != null) {
                    setValid(evt.getNewValue().toString());
                }
            }
        };
        updateSearchSettings();
        groupByCombobox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    getSelectedFilterPanel().setLastGroupingAttributeType(groupByCombobox.getItemAt(groupByCombobox.getSelectedIndex()));
                }
            }
        });
        orderByCombobox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    getSelectedFilterPanel().setLastSortingMethod(orderByCombobox.getItemAt(orderByCombobox.getSelectedIndex()));
                }
            }
        });
        groupSortingComboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    getSelectedFilterPanel().setLastGroupSortingAlg(groupSortingComboBox.getItemAt(groupSortingComboBox.getSelectedIndex()));
                }
            }
        });
        Case.addEventTypeSubscriber(CASE_EVENTS_OF_INTEREST, this.new CasePropertyChangeListener());
        IngestManager.getInstance().addIngestModuleEventListener(INGEST_MODULE_EVENTS_OF_INTEREST, this.new ModuleChangeListener());
        setPreferredSize(new java.awt.Dimension(1000, 800));
    }

    /**
     * Update the search settings to a default state.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    void updateSearchSettings() {
        removeAllPanels();
        imageFilterPanel = null;
        videoFilterPanel = null;
        documentFilterPanel = null;
        imageFilterPanel = new ImageFilterPanel();
        videoFilterPanel = new VideoFilterPanel();
        documentFilterPanel = new DocumentFilterPanel();
        domainFilterPanel = new DomainFilterPanel();
        unselectAllButtons();
        imagesButton.setSelected(true);
        imagesButton.setEnabled(false);
        imagesButton.setBackground(SELECTED_COLOR);
        imagesButton.setForeground(Color.BLACK);
        type = SearchData.Type.IMAGE;
        add(imageFilterPanel, CENTER);
        imageFilterPanel.addPropertyChangeListener(listener);
        updateComboBoxes();
        pack();
        repaint();
    }

    /**
     * Set the type buttons to a default state where none are selected.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    private void unselectAllButtons() {
        imagesButton.setSelected(false);
        imagesButton.setEnabled(true);
        imagesButton.setBackground(UNSELECTED_COLOR);
        videosButton.setSelected(false);
        videosButton.setEnabled(true);
        videosButton.setBackground(UNSELECTED_COLOR);
        documentsButton.setSelected(false);
        documentsButton.setEnabled(true);
        documentsButton.setBackground(UNSELECTED_COLOR);
        domainsButton.setSelected(false);
        domainsButton.setEnabled(true);
        domainsButton.setBackground(UNSELECTED_COLOR);
    }

    /**
     * Private helper method to perform update of comboboxes update.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    private void updateComboBoxes() {
        // Set up the grouping attributes
        List<GroupingAttributeType> groupingAttrs = new ArrayList<>();
        List<SortingMethod> sortingMethods = new ArrayList<>();
        groupByCombobox.removeAllItems();
        if (type == SearchData.Type.DOMAIN) {
            groupingAttrs.addAll(GroupingAttributeType.getOptionsForGroupingForDomains());
            sortingMethods.addAll(SortingMethod.getOptionsForOrderingDomains());
        } else {
            groupingAttrs.addAll(GroupingAttributeType.getOptionsForGroupingForFiles());
            sortingMethods.addAll(SortingMethod.getOptionsForOrderingFiles());
        }
        for (GroupingAttributeType groupingType : groupingAttrs) {
            addTypeToGroupByComboBox(groupingType);
        }
        groupByCombobox.setSelectedItem(getSelectedFilterPanel().getLastGroupingAttributeType());
        orderByCombobox.removeAllItems();
        // Set up the file order list
        for (SortingMethod method : sortingMethods) {
            if (method != SortingMethod.BY_FREQUENCY || CentralRepository.isEnabled()) {
                orderByCombobox.addItem(method);
            }
        }
        orderByCombobox.setSelectedItem(getSelectedFilterPanel().getLastSortingMethod());
        groupSortingComboBox.removeAllItems();
        for (GroupSortingAlgorithm groupSortAlgorithm : GroupSortingAlgorithm.values()) {
            groupSortingComboBox.addItem(groupSortAlgorithm);
        }
        groupSortingComboBox.setSelectedItem(getSelectedFilterPanel().getLastGroupSortingAlg());
    }

    /**
     * Private helper method to get the correct panel for the selected type.
     *
     * @return The panel that corresponds to the currently selected type.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    private AbstractFiltersPanel getSelectedFilterPanel() {
        switch (type) {
            case IMAGE:
                return imageFilterPanel;
            case VIDEO:
                return videoFilterPanel;
            case DOCUMENT:
                return documentFilterPanel;
            case DOMAIN:
                return domainFilterPanel;
            default:
                return imageFilterPanel;
        }
    }

    /**
     * Private helper method to add GroupingAttributeType to the
     * groupByCombobox.
     *
     * @param type The Type of GroupingAttribute to add.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    private void addTypeToGroupByComboBox(GroupingAttributeType type) {
        switch (type) {
            case FREQUENCY:
                if (!CentralRepository.isEnabled()) {
                    return;
                }
                break;
            case OBJECT_DETECTED:
                if (!imageFilterPanel.isObjectsFilterSupported()) {
                    return;
                }
                break;
            case INTERESTING_ITEM_SET:
                if (!imageFilterPanel.isInterestingItemsFilterSupported()) {
                    return;
                }
                break;
            case HASH_LIST_NAME:
                if (!imageFilterPanel.isHashSetFilterSupported()) {
                    return;
                }
                break;
            default:
                break;
        }
        groupByCombobox.addItem(type);
    }

    /**
     * Validate the filter settings for File type filters.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    void validateDialog() {
        AbstractFiltersPanel panel = getSelectedFilterPanel();
        if (panel != null) {
            panel.validateFields();
        }
    }

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

        javax.swing.JPanel toolBarPanel = new javax.swing.JPanel();
        imagesButton = new javax.swing.JButton();
        videosButton = new javax.swing.JButton();
        documentsButton = new javax.swing.JButton();
        javax.swing.JLabel step1Label = new javax.swing.JLabel();
        javax.swing.Box.Filler filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(104, 0), new java.awt.Dimension(104, 0), new java.awt.Dimension(104, 32767));
        domainsButton = new javax.swing.JButton();
        javax.swing.JPanel displaySettingsPanel = new javax.swing.JPanel();
        searchButton = new javax.swing.JButton();
        errorLabel = new javax.swing.JLabel();
        javax.swing.JPanel sortingPanel = new javax.swing.JPanel();
        groupByCombobox = new javax.swing.JComboBox<>();
        orderByCombobox = new javax.swing.JComboBox<>();
        javax.swing.JLabel orderGroupsByLabel = new javax.swing.JLabel();
        javax.swing.JLabel orderByLabel = new javax.swing.JLabel();
        javax.swing.JLabel groupByLabel = new javax.swing.JLabel();
        groupSortingComboBox = new javax.swing.JComboBox<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(600, 300));
        setPreferredSize(new java.awt.Dimension(1000, 800));

        imagesButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/pictures-icon.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(imagesButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.imagesButton.text")); // NOI18N
        imagesButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/pictures-icon.png"))); // NOI18N
        imagesButton.setFocusable(false);
        imagesButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        imagesButton.setMaximumSize(new java.awt.Dimension(90, 43));
        imagesButton.setMinimumSize(new java.awt.Dimension(90, 43));
        imagesButton.setPreferredSize(new java.awt.Dimension(90, 43));
        imagesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                imagesButtonActionPerformed(evt);
            }
        });

        videosButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/video-icon.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(videosButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.videosButton.text")); // NOI18N
        videosButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/video-icon.png"))); // NOI18N
        videosButton.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/video-icon.png"))); // NOI18N
        videosButton.setFocusable(false);
        videosButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        videosButton.setMaximumSize(new java.awt.Dimension(90, 43));
        videosButton.setMinimumSize(new java.awt.Dimension(90, 43));
        videosButton.setPreferredSize(new java.awt.Dimension(90, 43));
        videosButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                videosButtonActionPerformed(evt);
            }
        });

        documentsButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/documents-icon.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(documentsButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.documentsButton.text")); // NOI18N
        documentsButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/documents-icon.png"))); // NOI18N
        documentsButton.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/documents-icon.png"))); // NOI18N
        documentsButton.setFocusable(false);
        documentsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                documentsButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(step1Label, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.step1Label.text")); // NOI18N

        domainsButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/domain-32.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(domainsButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.domainsButton.text")); // NOI18N
        domainsButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/domain-32.png"))); // NOI18N
        domainsButton.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/domain-32.png"))); // NOI18N
        domainsButton.setFocusable(false);
        domainsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                domainsButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout toolBarPanelLayout = new javax.swing.GroupLayout(toolBarPanel);
        toolBarPanel.setLayout(toolBarPanelLayout);
        toolBarPanelLayout.setHorizontalGroup(
            toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(toolBarPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(toolBarPanelLayout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(imagesButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(videosButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(documentsButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(domainsButton)
                        .addContainerGap(190, Short.MAX_VALUE))
                    .addGroup(toolBarPanelLayout.createSequentialGroup()
                        .addComponent(step1Label, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(391, Short.MAX_VALUE))))
        );

        toolBarPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {documentsButton, domainsButton, imagesButton, videosButton});

        toolBarPanelLayout.setVerticalGroup(
            toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(toolBarPanelLayout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(step1Label))
                .addGap(6, 6, 6)
                .addGroup(toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(videosButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(imagesButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(documentsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(domainsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6))
        );

        getContentPane().add(toolBarPanel, java.awt.BorderLayout.PAGE_START);

        org.openide.awt.Mnemonics.setLocalizedText(searchButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.searchButton.text")); // NOI18N
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        errorLabel.setForeground(new java.awt.Color(255, 0, 0));

        sortingPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.sortingPanel.border.title"))); // NOI18N
        sortingPanel.setPreferredSize(new java.awt.Dimension(345, 112));

        org.openide.awt.Mnemonics.setLocalizedText(orderGroupsByLabel, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.orderGroupsByLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(orderByLabel, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.orderByLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(groupByLabel, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.groupByLabel.text")); // NOI18N

        javax.swing.GroupLayout sortingPanelLayout = new javax.swing.GroupLayout(sortingPanel);
        sortingPanel.setLayout(sortingPanelLayout);
        sortingPanelLayout.setHorizontalGroup(
            sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(sortingPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(orderGroupsByLabel)
                    .addComponent(groupByLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(groupSortingComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(groupByCombobox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(orderByLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(orderByCombobox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        sortingPanelLayout.setVerticalGroup(
            sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(sortingPanelLayout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(groupByCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(groupByLabel)
                    .addComponent(orderByCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(orderByLabel))
                .addGap(6, 6, 6)
                .addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(groupSortingComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(orderGroupsByLabel))
                .addGap(6, 6, 6))
        );

        javax.swing.GroupLayout displaySettingsPanelLayout = new javax.swing.GroupLayout(displaySettingsPanel);
        displaySettingsPanel.setLayout(displaySettingsPanelLayout);
        displaySettingsPanelLayout.setHorizontalGroup(
            displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, displaySettingsPanelLayout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(sortingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 741, Short.MAX_VALUE)
                    .addGroup(displaySettingsPanelLayout.createSequentialGroup()
                        .addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE)
                        .addGap(65, 65, 65)
                        .addComponent(searchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(8, 8, 8))
        );
        displaySettingsPanelLayout.setVerticalGroup(
            displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, displaySettingsPanelLayout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(sortingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addGroup(displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(errorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton))
                .addGap(6, 6, 6))
        );

        getContentPane().add(displaySettingsPanel, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void imagesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_imagesButtonActionPerformed
        removeAllPanels();
        add(imageFilterPanel, CENTER);
        unselectAllButtons();
        imagesButton.setSelected(true);
        imagesButton.setEnabled(false);
        imagesButton.setBackground(SELECTED_COLOR);
        imagesButton.setForeground(Color.BLACK);
        type = SearchData.Type.IMAGE;
        imageFilterPanel.addPropertyChangeListener(listener);
        updateComboBoxes();
        validateDialog();
        pack();
        repaint();
    }//GEN-LAST:event_imagesButtonActionPerformed

    private void videosButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_videosButtonActionPerformed
        removeAllPanels();
        add(videoFilterPanel, CENTER);
        unselectAllButtons();
        videosButton.setSelected(true);
        videosButton.setEnabled(false);
        videosButton.setBackground(SELECTED_COLOR);
        videosButton.setForeground(Color.BLACK);
        videoFilterPanel.addPropertyChangeListener(listener);
        type = SearchData.Type.VIDEO;
        updateComboBoxes();
        validateDialog();
        pack();
        repaint();
    }//GEN-LAST:event_videosButtonActionPerformed

    private void documentsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_documentsButtonActionPerformed
        removeAllPanels();
        add(documentFilterPanel, CENTER);
        unselectAllButtons();
        documentsButton.setSelected(true);
        documentsButton.setEnabled(false);
        documentsButton.setBackground(SELECTED_COLOR);
        documentsButton.setForeground(Color.BLACK);
        type = SearchData.Type.DOCUMENT;
        documentFilterPanel.addPropertyChangeListener(listener);
        updateComboBoxes();
        validateDialog();
        pack();
        repaint();
    }//GEN-LAST:event_documentsButtonActionPerformed

    /**
     * Helper method to remove all filter panels and their listeners
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    private void removeAllPanels() {
        if (imageFilterPanel != null) {
            remove(imageFilterPanel);
            imageFilterPanel.removePropertyChangeListener(listener);
        }
        if (domainFilterPanel != null) {
            remove(domainFilterPanel);
            domainFilterPanel.removePropertyChangeListener(listener);
        }
        if (documentFilterPanel != null) {
            remove(documentFilterPanel);
            documentFilterPanel.removePropertyChangeListener(listener);
        }
        if (videoFilterPanel != null) {
            remove(videoFilterPanel);
            videoFilterPanel.removePropertyChangeListener(listener);
        }
    }

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        setVisible(false); //set visible used here instead of dispose incase dispose code changes
        final DiscoveryTopComponent tc = DiscoveryTopComponent.getTopComponent();
        if (tc == null) {
            setValid("No Top Component Found");
            return;
        }
        if (tc.isOpened() == false) {
            tc.open();
        }
        tc.resetTopComponent();
        // Get the selected filters
        List<AbstractFilter> filters;
        if (videosButton.isSelected()) {
            filters = videoFilterPanel.getFilters();
        } else if (documentsButton.isSelected()) {
            filters = documentFilterPanel.getFilters();
        } else if (imagesButton.isSelected()) {
            filters = imageFilterPanel.getFilters();
        } else if (domainsButton.isSelected()) {
            filters = domainFilterPanel.getFilters();
        } else {
            logger.log(Level.SEVERE, "No filter type selected");
            filters = new ArrayList<>();
        }

        DiscoveryEventUtils.getDiscoveryEventBus().post(new DiscoveryEventUtils.SearchStartedEvent(type));

        // Get the grouping attribute and group sorting method
        DiscoveryAttributes.AttributeType groupingAttr = groupByCombobox.getItemAt(groupByCombobox.getSelectedIndex()).getAttributeType();
        Group.GroupSortingAlgorithm groupSortAlgorithm = groupSortingComboBox.getItemAt(groupSortingComboBox.getSelectedIndex());

        // Get the file sorting method
        ResultsSorter.SortingMethod fileSort = (ResultsSorter.SortingMethod) orderByCombobox.getSelectedItem();
        CentralRepository centralRepoDb = null;
        if (CentralRepository.isEnabled()) {
            try {
                centralRepoDb = CentralRepository.getInstance();
            } catch (CentralRepoException ex) {
                centralRepoDb = null;
                logger.log(Level.SEVERE, "Error loading central repository database, no central repository options will be available for Discovery", ex);
            }
        }
        searchWorker = new SearchWorker(centralRepoDb, type, filters, groupingAttr, groupSortAlgorithm, fileSort);
        searchWorker.execute();
        tc.toFront();
        tc.requestActive();
    }//GEN-LAST:event_searchButtonActionPerformed

    private void domainsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_domainsButtonActionPerformed
        removeAllPanels();
        add(domainFilterPanel, CENTER);
        unselectAllButtons();
        domainsButton.setSelected(true);
        domainsButton.setEnabled(false);
        domainsButton.setBackground(SELECTED_COLOR);
        domainsButton.setForeground(Color.BLACK);
        type = SearchData.Type.DOMAIN;
        domainFilterPanel.addPropertyChangeListener(listener);
        updateComboBoxes();
        validateDialog();
        pack();
        repaint();
    }//GEN-LAST:event_domainsButtonActionPerformed

    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    @Override
    public void dispose() {
        setVisible(false);
    }

    /**
     * Cancel the searchWorker if it exists.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    void cancelSearch() {
        if (searchWorker != null) {
            searchWorker.cancel(true);
            searchWorker = null;
        }
    }

    /**
     * The adjust the controls to reflect whether the settings are valid based
     * on the error.
     *
     * @param error The error message to display, empty string if there is no
     *              error.
     */
    @ThreadConfined(type = ThreadConfined.ThreadType.AWT)
    private void setValid(String error) {
        if (StringUtils.isBlank(error)) {
            errorLabel.setText("");
            searchButton.setEnabled(true);
        } else {
            errorLabel.setText(error);
            searchButton.setEnabled(false);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton documentsButton;
    private javax.swing.JButton domainsButton;
    private javax.swing.JLabel errorLabel;
    private javax.swing.JComboBox<GroupingAttributeType> groupByCombobox;
    private javax.swing.JComboBox<GroupSortingAlgorithm> groupSortingComboBox;
    private javax.swing.JButton imagesButton;
    private javax.swing.JComboBox<SortingMethod> orderByCombobox;
    private javax.swing.JButton searchButton;
    private javax.swing.JButton videosButton;
    // End of variables declaration//GEN-END:variables

    /**
     * PropertyChangeListener to listen to case level events that may modify the
     * filters available.
     */
    private class CasePropertyChangeListener implements PropertyChangeListener {

        @Override
        @SuppressWarnings("fallthrough")
        public void propertyChange(PropertyChangeEvent evt) {
            switch (Case.Events.valueOf(evt.getPropertyName())) {
                case CURRENT_CASE: {
                    if (evt.getNewValue() == null) {
                        //do not refresh when a case is closed only when it is opened.
                        break;
                    }
                    //else fallthrough
                }
                case DATA_SOURCE_ADDED:
                //fallthrough
                case DATA_SOURCE_DELETED:
                    shouldUpdate = true;
                    break;
                default:
                    //do nothing if the event is not one of the above events.
                    break;
            }
        }
    }

    /**
     * PropertyChangeListener to listen to ingest module events that may modify
     * the filters available.
     */
    private class ModuleChangeListener implements PropertyChangeListener {

        /**
         * @SuppressWarnings("deprecation") - we need to support already
         * existing interesting file and artifact hits.
         */
        @SuppressWarnings("deprecation")
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (!shouldUpdate) {
                String eventType = evt.getPropertyName();
                if (eventType.equals(IngestManager.IngestModuleEvent.DATA_ADDED.toString())) {
                    /**
                     * Checking for a current case is a stop gap measure until a
                     * different way of handling the closing of cases is worked
                     * out. Currently, remote events may be received for a case
                     * that is already closed.
                     */
                    try {
                        Case.getCurrentCaseThrows();
                        /**
                         * Even with the check above, it is still possible that
                         * the case will be closed in a different thread before
                         * this code executes. If that happens, it is possible
                         * for the event to have a null oldValue.
                         */
                        ModuleDataEvent eventData = (ModuleDataEvent) evt.getOldValue();
                        if (null != eventData) {
                            if (eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_OBJECT_DETECTED.getTypeID() && eventData.getArtifacts() != null) {
                                shouldUpdate = shouldUpdateFilters(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DESCRIPTION.getTypeID(), eventData, objectsDetected);
                            } else if (eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID()) {
                                shouldUpdate = shouldUpdateFilters(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID(), eventData, hashSets);
                            } else if (eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_ITEM.getTypeID()
                                    || eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT.getTypeID()
                                    || eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_ARTIFACT_HIT.getTypeID()) {
                                shouldUpdate = shouldUpdateFilters(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID(), eventData, interestingItems);
                            }
                        }
                    } catch (NoCurrentCaseException notUsed) {
                        // Case is closed, do nothing.
                    } catch (TskCoreException ex) {
                        logger.log(Level.WARNING, "Unable to determine if discovery UI should be updated", ex);
                    }
                }
            }
        }

        /**
         * Helper method to determine if the artifact in the eventData
         * represents a new value for the filter.
         *
         * @param attributeTypeId  The attribute id of the attribute which
         *                         contains the value for the filter.
         * @param eventData        The event which contains the artifacts.
         * @param filterSetToCheck The set of current values for the relevant
         *                         filter.
         *
         * @return True if the value is a new value for the filter, false
         *         otherwise.
         *
         * @throws TskCoreException Thrown because the attributes were unable to
         *                          be retrieved for one of the artifacts in the
         *                          eventData.
         */
        private boolean shouldUpdateFilters(int attributeTypeId, ModuleDataEvent eventData, Set<BlackboardAttribute> filterSetToCheck) throws TskCoreException {
            for (BlackboardArtifact artifact : eventData.getArtifacts()) {
                if (artifact.getAttributes() != null) {
                    for (BlackboardAttribute attr : artifact.getAttributes()) {
                        if (attr.getAttributeType().getTypeID() == attributeTypeId && !filterSetToCheck.contains(attr)) {
                            filterSetToCheck.add(attr);
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Stud. Mycol. 27: 61 (1985)

#### Original name
null

### Remarks
null


text:
def longest_string(list_of_words)
  if list_of_words == []
    p nil
  else
    words_and_lengths = {}
    list_of_words.each do |word|
      words_and_lengths[word.length] = word
    end
    p words_and_lengths
    longest_length = list_of_words[0].length
    words_and_lengths.each do|length, word|
      if length > longest_length
        longest_length = length
      end
    end
    p words_and_lengths[longest_length]
  end
end

#refactored version
# def longest_string(list_of_words)
  # if list_of_words == []
    # nil
  # else

    # longest = list_of_words[0]
#
    # list_of_words.each do |word|
      # longest = word if longest.length < word.length
    # end

    # p longest

# def longest_string(list_of_words)
  # if list_of_words == []
    # nil
  # else
#
#
    # longest = list_of_words[0]
    # i=0
    # for word in list_of_words
    # while i < list_of_words.length
      # longest = word if longest.length < word.length
      # i += 1
    # end
#
    # p longest

# def longest_string(list_of_words)
  # if list_of_words == []
    # nil
  # else
#

    # longest = list_of_words[0]
    # for word in list_of_words
    # list_of_words.length.times do |i|
      # longest = list_of_words[i] if longest.length < list_of_words[i].length
    # end

# def longest_string(list_of_words)
#   if list_of_words == []
#     nil
#   else

# #     if list_of_words.length == 1
# #       return length_of_words[0]
# #     else
#     longest = list_of_words[0]
#     i = 1
#     while i < list_of_words.length
#       longest = list_of_words[i] if longest.length < list_of_words[i].length
#       i += 1
#     end

#     p longest