text:
This interractive graph allows you to draw points, lines and curves on it while keeping track point coordinates.

It might be extended in future to calculate results from input, because it is a matrix of points that detect which one was clicked and what value it is supposed to represent given the range of min and max for the graph.

It can also be used to display certain charts and data.

## To find out "why" scroll to the bottom where it is explained

## To test it either run it on server and view demo links in the index.html

or view screenshots.

Interactive Graph Example:
![alt text](https://github.com/k-gintaras/interactive-graph/blob/master/public_html/screenshots/interactive%20test.JPG "Interactive Graph Example")
***
antagonists Example:
![alt text](https://github.com/k-gintaras/interactive-graph/blob/master/public_html/screenshots/antagonists2.JPG "Interactive Graph Example")
***
binding assay Example:
![alt text](https://github.com/k-gintaras/interactive-graph/blob/master/public_html/screenshots/binding%20assay%20%202.JPG "Interactive Graph Example")
***
## To install you need:
 to take the folder of this soft (with or without git) and put it in the server
 to create database from given sql or modify (studentDBM and lecturerDBM to store and retrieve data in other way)

 current database connection settings in lecturerDBM.php and studentDBM.php:
```sql
$GLOBALS["myErrors"] = "\n";
$GLOBALS["dbhost"] = "localhost";
$GLOBALS["dbname"] = "organbathsimulation";
$GLOBALS["dbuser"] = "root";
$GLOBALS["dbpass"] = "";
```
## Lecturer's page is at
public_html/lecturer.html

lecturers password, currently can only be changed by interacting with database directly, due to required system for password recovery if that was indirect:
111

current exercise password, can be changed in the lecturer's page:
111

## Student's page is at
index.html

## How it works:
html page sends AJAX request to lecturerDBM or studentDBM, these then communicate with database

## How students submit:
As singular or group of students they can enter their IDs separated by space or comma and enter EXERCISE password given by the lecturer
lecturer can change EXERCISE password any time, so then students cannot submit anymore and therefore have a time constraint for lecturer to decide, whenever lecturer changes password
currently lecturer can only review answers and manually has to check for correct or wrong answers with the assistance of images from submitted graphs.

## The Why's:

## Why it is a mess:
First page was agonists, with the idea that there will be no more pages, then wild new requirements popped up and the need to separate concerns arose.
That lead to other pages having different designs and separate graph instance redesigned for reuse along with separate file for description of user inputs and outputs.
Requirements kept changing on the go with the quick prototypes on to which things had to be built on top to save time.
Very slow feedbacks for requirement analysis, mostly individual work through experimentation and determination to simply practice solving problems from scratch without using external help.

## Why no libraries:
Part of final year project, to learn solving problems from scratch and practice programming, also to reduce the need for referencing other's work.
ufunctions is small alternative to basic jQuery. its main functions are called like H.el.div(id,where); for example to create new div.
ugraph is custom interactive graph library written completely from scratch and can be reused for future exercises
helpfulFunctions is small set of functions to create elements, but not for every exercise as for reason (why it is a mess).
other functions are old versions of these and mostly used in the agonist, which was left as is, because of the "why it is a mess".

## Why no MVC:
Just graduated, after graduation first time heard about it was in job specification.

## Why no relational database:
This was prototyping based design starting from very vague requirements with no overall description of the whole system. Things got extremely oversimplified there and overcomplicated elsewhere.


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TextView
            style="@style/Header"
            android:id="@+id/loanInstallmentDetails_header"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/loanInstallmentDetails_header"
            />

        <HorizontalScrollView
            android:layout_below="@id/loanInstallmentDetails_header"
            android:fillViewport="true"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <TableLayout
                android:id="@+id/loanInstallmentDetails_table"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:stretchColumns="1"
                android:padding="3dp">

                <TableRow>
                    <TextView
                        style="@style/TableColumnHeader"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_currentInstallment_columnLabel"
                        />
                    <TextView
                        style="@style/TableColumnHeader"
                        android:layout_column="2"
                        android:text="@string/loanInstallmentDetails_amount_columnLabel"
                        />
                </TableRow>

                <View
                    style="@style/BigTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/TableItem"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_principal_columnLabel"
                        />
                    <TextView
                        style="@style/TableItem"
                        android:id="@+id/loanInstallmentDetails_currentPrincipal"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

                <View
                    style="@style/SmallTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/TableItem"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_interest_columnLabel"
                        />
                    <TextView
                        style="@style/TableItem"
                        android:id="@+id/loanInstallmentDetails_currentInterest"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

                <View
                    style="@style/SmallTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/TableItem"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_fees_columnLabel"
                        />
                    <TextView
                        style="@style/TableItem"
                        android:id="@+id/loanInstallmentDetails_currentFees"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

                <View
                    style="@style/SmallTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/TableItem"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_penalty_columnLabel"
                        />
                    <TextView
                        style="@style/TableItem"
                        android:id="@+id/loanInstallmentDetails_currentPenalty"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

                <View
                    style="@style/SmallTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/ItalicizedTableItem"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_subTotal_columnLabel"
                        />
                    <TextView
                        style="@style/ItalicizedTableItem"
                        android:id="@+id/loanInstallmentDetails_currentSubTotal"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

                <View
                    style="@style/BigTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/TableColumnHeader"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_overdueAmount_columnLabel"
                        />
                    <TextView
                        style="@style/TableColumnHeader"
                        android:layout_column="2"
                        android:text="@string/loanInstallmentDetails_amount_columnLabel"
                        />
                </TableRow>

                <View
                    style="@style/BigTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/TableItem"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_principal_columnLabel"
                        />
                    <TextView
                        style="@style/TableItem"
                        android:id="@+id/loanInstallmentDetails_overduePrincipal"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

                <View
                    style="@style/SmallTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/TableItem"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_interest_columnLabel"
                        />
                    <TextView
                        style="@style/TableItem"
                        android:id="@+id/loanInstallmentDetails_overdueInterest"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

                <View
                    style="@style/SmallTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/TableItem"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_fees_columnLabel"
                        />
                    <TextView
                        style="@style/TableItem"
                        android:id="@+id/loanInstallmentDetails_overdueFees"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

                <View
                    style="@style/SmallTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/TableItem"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_penalty_columnLabel"
                        />
                    <TextView
                        style="@style/TableItem"
                        android:id="@+id/loanInstallmentDetails_overduePenalty"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

                <View
                    style="@style/SmallTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/ItalicizedTableItem"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_subTotal_columnLabel"
                        />
                    <TextView
                        style="@style/ItalicizedTableItem"
                        android:id="@+id/loanInstallmentDetails_overdueSubTotal"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

                <View
                    style="@style/BigTableSeparator"
                    />

                <TableRow>
                    <TextView
                        style="@style/BoldItalicizedTableItem"
                        android:id="@+id/loanInstallmentDetails_totalAmountDue_columnLabel"
                        android:layout_column="1"
                        android:text="@string/loanInstallmentDetails_totalAmountDue_columnLabel"
                        />
                    <TextView
                        style="@style/BoldItalicizedTableItem"
                        android:id="@+id/loanInstallmentDetails_totalAmountDue"
                        android:layout_column="2"
                        android:text="@string/not_available"
                        />
                </TableRow>

            </TableLayout>

        </HorizontalScrollView>

    </RelativeLayout>

</ScrollView>

redpajama_set_name: RedPajamaGithub


text:
package com.gildaswise.horizontalcounterdemo;

public class Values {

    Double value;
    Double step;
    Double max;
    Double min;

    public Values(Double value, Double step, Double max, Double min) {
        this.value = value;
        this.step = step;
        this.max = max;
        this.min = min;
    }

    public Double getValue() {
        return value;
    }

    public void setValue(Double value) {
        this.value = value;
    }

    public Double getStep() {
        return step;
    }

    public void setStep(Double step) {
        this.step = step;
    }

    public Double getMax() {
        return max;
    }

    public void setMax(Double max) {
        this.max = max;
    }

    public Double getMin() {
        return min;
    }

    public void setMin(Double min) {
        this.min = min;
    }
}


text:
Experiment in distributing webpack loaders with a library

## The Problem

Webpack is very useful as a way to bundle files for single-page web
applications, while providing node-style `require()` and `import` statements
with specialized semantics via Webpack loaders. Along with code-splitting
capabilities, this allows a client to download and execute slices of the final
bundle as needed, providing a nice balance between download times for the client
and lessened burden of code-structuring for the developer.

However, Webpack is not as good at bundling libraries for use in a different
project. The problem comes mainly because Webpack creates a large bundle, which
is not a problem for a single-page application, but may be for a library that
will in turn be *included* in a single-page application.

# The Easy Solution (Which Doesn't Work)

The solution of simply distributing the library source files for selective
inclusion via Webpack in the client project doesn't quite work because the
library developer may want to use Webpack to provide different semantics for
`require()` and `import` statements (taking advantages of one of Webpack's major
value-add features).

# The Harder Solution (Which Might Work)

The **experimental solution** in this repository is to include a file,
[`webpack-module.js`](https://github.com/ronichoudhury-work/borges/blob/master/webpack-module.js),
in the distribution which takes a Webpack configuration object and returns a new
one with added loaders (and possibly other configs) to selectively apply the
library writer's desired semantics to just the distribution files as they reside
in the client project's *node_modules* directory.

The loader declarations look almost identical to what would appear in an
ordinary Webpack configuration, but the `test` property references the
*node_modules* directory specifically, to avoid "leaking" the loader rules onto
other files in a client project. In other words, `webpack-module.js` provides a
sort of encapsulation of the library files that can now move with the library.

## How It Works

This repository provides a dummy library with one function written in ES6, and
an HTML template function written in Jade. Any client project would need to use
Babel to translate the function to ES5, and Jade to compile the template to a
function. These capabilities are in fact crucial for such a library to function
as intended.

Webpack loaders for Babel and Jade are listed as production dependencies of the
project, meaning that any client project that install *this* project as a
dependency will gain those loaders as well.

Finally, the `webpack-module.js` file provides, essentially, instructions to the
client project on how to invoke those loaders on the appropriate files (meaning,
the files of the appropriate type *inside the node_modules/borges directory*).
The result is that the client project can import individual files from the
library and its own Webpack process will correctly interpret the files as
intended.

# Questions and Possible Pitfalls

1. *What happens if the client project already uses the same loaders as the
   library?*

   This is generally speaking not a problem. If the client project lists a
   loader as a dependency, and the library does too, NPM is smart enough to
   download the dependency once and make use of it everywhere as needed.

2. *What if a loader is the same between client and library, except for its
   version number?*

   This is a harder question, but also more general, in the sense that it is
   already a problem for any dependency that lists its own production dependencies.
   Solutions to the problem are unsavory at best, along the lines of updating one
   or the other project so that it can use the same version of the disputed
   dependency.

   But whatever a (or the) general solution is to this problem will also solve it
   for purposes of this question.

3. *What if the client project doesn't use Webpack at all?*

   The library project can include a Webpack configuration of its own that
   builds a bundled library (i.e., following the same steps a single-page
   application project would, outputting a single bundle file containing all the
   library code) which can then be distributed along with the source files. Since
   Webpack conveniently gives the option of producing a UMD module, any client
   project that doesn't take advantage of Webpack and the library's loader
   distribution file can simply use the UMD module instead.

# Try It Out!

This experiment has a sister repository,
[Horace](https://github.com/ronichoudhury-work/horace), which models a Node
project making use of this library. Hop over there to learn how to download,
install, and test it.

If you have questions, suggestions, or bug fixes, please open an issue or pull
request!

# Why "Borges"?

Jorge Luis Borges wrote about [The Library of
Babel](https://en.wikipedia.org/wiki/The_Library_of_Babel), an unimaginably
large complex of hexagonal rooms consisting of every possible 410-page book
using a particular set of characters.

You might have some trouble using Webpack to bundle up this whole library for
use in a client project.

(There is a [digital version](https://libraryofbabel.info/) of the Library that
you can explore.)


text:
volUpdateTime = 50 -- ms of volume update timer when slider gets changed
soundsoff = false

local theResourcesName = {--Change names of the resources here if they are changed.
    ["announcer"] = "race_voicepack",
    ["horn"] = "gcshop",
    ["musicplayer"] = "sc-musicplayer",
}

theResources = {}

Volumes = {
	["map"] = 1,
	["horn"] = 1,
	["announcer"] = 1,
	["musicplayer"] = 1,
	["miscellaneous"] = 1,
}

-- Reapply settings when one of these resources (re)starts
local SND_reApplyTimer = false
-- Add resource name here when used
local resetResource = {"race_voicepack","gcshop","sc-musicplayer","race"}
addEventHandler("onClientResourceStart",root,
    function(res)
        local resName = getResourceName(res)
        for _,rn in ipairs(resetResource) do
            if rn == resName then
                -- Timer system so no settings spam
                refreshResourcePointers()
                if isTimer(SND_reApplyTimer) then killTimer(SND_reApplyTimer) end
                SND_reApplyTimer = setTimer(function() getSoundSettings() end,5000,1)
                break
            end
        end
    end
)

function refreshResourcePointers()
    for name,resname in pairs(theResourcesName) do
        theResources[name] = getResourceRootElement( getResourceFromName(resname) )
    end
end
addEventHandler("onClientResourceStart", root, refreshResourcePointers)

function getSoundSettings()

	soundXML = xmlLoadFile( "/settings/soundsettings.xml" )
	if not soundXML then
		soundXML = xmlCreateFile( "/settings/soundsettings.xml", "settings" )
		for f, u in pairs(Volumes) do
			local theChild = xmlCreateChild( soundXML, f )
			xmlNodeSetValue( theChild, tostring(u) )
		end
		xmlSaveFile( soundXML )
	end

    -- Second Check if player has all settings
    for f, u in pairs(Volumes) do
        local doIexist = xmlFindChild( soundXML, f, 0 )
        if not doIexist then
            local theChild = xmlCreateChild( soundXML, f )
            xmlNodeSetValue(theChild, tostring(u))
        end
    end

	-- Load settings into table --
	local _soundSettingsTable = {
		["map"] = xmlNodeGetValue( xmlFindChild(soundXML, "map", 0) ),
		["horn"] = xmlNodeGetValue( xmlFindChild(soundXML, "horn", 0) ),
		["announcer"] = xmlNodeGetValue( xmlFindChild(soundXML, "announcer", 0) ),
		["musicplayer"] = xmlNodeGetValue( xmlFindChild(soundXML, "musicplayer", 0) ),
		["miscellaneous"] = xmlNodeGetValue( xmlFindChild(soundXML, "miscellaneous", 0) ),
}
	Volumes = _soundSettingsTable

	xmlUnloadFile( soundXML )

	setScrollBars()
end
addEventHandler("onClientResourceStart", resourceRoot, getSoundSettings)

currentMap = false
MapSound = {}
function detectMap(theRes)
    local MaporNot = isMap(getResourceRootElement( theRes ) )

    if MaporNot == true then

        currentMap = source
        MapSound = {}
        MapSound = getElementsByType( "sound", source )
        for f, u in pairs(MapSound) do
            setElementData( u, "soundSource", "map", false )
        end
        setVol("map")
      end
end
addEventHandler("onClientResourceStart", root, detectMap)

function soundHandling(reason)

    local theSound = source
    local theResource = getElementResource(source)

    if theResource == currentMap then -- If the sound comes from the map --
        table.insert(MapSound, source) -- Insert the sound in the MapSound table --
		setSoundVolume(theSound, tonumber(Volumes["map"]))
        -- setVol("map")
        setElementData( theSound, "soundSource", "map", false ) -- Mark sound for source

    elseif theResource == theResources["announcer"] then
        setElementData( theSound, "soundSource", "announcer", false ) -- Mark sound for source
    	setVol("announcer", source)

    elseif theResource == theResources["horn"] then
        setElementData( theSound, "soundSource", "horn", false ) -- Mark sound for source
    	setVol("horn", source)

    elseif theResource == theResources["musicplayer"] then
        setElementData( theSound, "soundSource", "musicplayer", false ) -- Mark sound for source
    	setVol("musicplayer", source)

    else
        setVol("miscellaneous", source)
    end

end
addEventHandler("onClientSoundStarted", root, soundHandling)

function setVol(reason,theSound)
    if MapSound and reason == "map" then
        for f, u in pairs(MapSound) do

        	setSoundVolume(u, tonumber(Volumes["map"]))
        	setTimer(function()
                if isElement(u) then
                    setSoundVolume(u, tonumber(Volumes["map"]))
                    if Volumes["map"] == 0 then
                        setSoundPaused( u, true )
                    end
                else u = nil
                end
        	 end, 50, 2) -- timer to set volume after map script has set volume --

        end
        -- outputDebugString("Set volume for "..reason.." "..Volumes["map"])
    elseif reason == "announcer" then

    	setSoundVolume( theSound, tonumber(Volumes["announcer"] ))
        setTimer(setSoundVolume,50,2,theSound, tonumber(Volumes["announcer"]))
    	-- outputDebugString("Set volume for "..reason)
    elseif reason == "horn" then

    	setSoundVolume( theSound, tonumber(Volumes["horn"] ))
        setTimer(setSoundVolume,50,2,theSound, tonumber(Volumes["horn"]))
    	-- outputDebugString("Set volume for "..reason)
    elseif reason == "musicplayer" then

    	setSoundVolume( theSound, tonumber(Volumes["musicplayer"] ))
        setTimer(setSoundVolume,50,2,theSound, tonumber(Volumes["musicplayer"]))
    	-- outputDebugString("Set volume for "..reason)

    elseif reason == "miscellaneous" then

    	setSoundVolume( theSound, tonumber(Volumes["miscellaneous"] ))
        setTimer(setSoundVolume,50,2,theSound, tonumber(Volumes["miscellaneous"]))
    	-- outputDebugString("Set volume for "..reason)

    end
end

function updateVolume(givenSource)
    local allSounds = getElementsByType( "sound" )
    for f, u in pairs(allSounds) do
        local theSource = getElementData( u, "soundSource" )
        if not theSource then
            theSource = "miscellaneous"
        end

        if tostring(theSource) == givenSource then
            setSoundVolume( u, tonumber(Volumes[tostring(theSource)]) )
            if tostring(theSource) == "map" then
                if isSoundPaused( u ) and Volumes["map"] ~= 0 then
                    setSoundPaused( u, false )
                end
            end
        end

        if givenSource == "soundsoff" then
            setSoundVolume( u, 0)
        elseif givenSource == "soundson" then
            setSoundVolume( u, tonumber(Volumes[tostring(theSource)]) )
        end
    end
end

function saveSoundVolumes()
    local soundXML = xmlLoadFile( "/settings/soundsettings.xml" )
    for f, u in pairs(Volumes) do
        local theChild = xmlFindChild(soundXML, f, 0)
        if theChild then
            xmlNodeSetValue( theChild, u )
        else
            local theNewChild = xmlCreateChild( soundXML, f )
            xmlNodeSetValue( theNewChild, u )
        end
    end
    xmlSaveFile( soundXML )
    xmlUnloadFile( soundXML )
    outputConsole("Sound Settings Saved!")
end

-- utils --
function isMap(resourceElement)
    if #getElementsByType('spawnpoint', resourceElement) > 0 then return true
        else return false end
end

function getElementResource (element)
        local parent = element
        repeat
                parent = getElementParent ( parent )
        until not parent or getElementType(parent) == 'resource'
        if getElementType(parent) == 'resource' then return parent
        else
        -- for _, resource in ipairs(getResources()) do
                -- if getResourceRootElement(resource) == parent then
                --         return resource
                -- end
        -- end
        return false
    end
end

-- GUI HANDLERS --
function sounds_scrollbarhandler()
    if not isTimer(IgnoreScrollOnStartup) then
        if source == GUIEditor.scrollbar[1] then
            local procent = guiScrollBarGetScrollPosition(source)
            guiSetText(GUIEditor.label[10], procent.."%")
            Volumes["map"] = guiScrollBarGetScrollPosition( source )/100
            if isTimer( soundSaveTimer ) then
                killTimer( soundSaveTimer )
                soundSaveTimer = nil
            end
            soundSaveTimer = setTimer( saveSoundVolumes, 5000, 1 )

            if isTimer(updateMapVolumeTimer) then -- Update Volumes Dynamically
                killTimer(updateMapVolumeTimer)
                updateMapVolumeTimer = nil
            end
            updateMapVolumeTimer = setTimer(updateVolume, volUpdateTime, 1, "map")

        elseif source == GUIEditor.scrollbar[2] then
            local procent = guiScrollBarGetScrollPosition(source)
            guiSetText(GUIEditor.label[12], procent.."%")
            Volumes["horn"] = guiScrollBarGetScrollPosition( source )/100
            if isTimer( soundSaveTimer ) then
                killTimer( soundSaveTimer )
                soundSaveTimer = nil
            end
            soundSaveTimer = setTimer( saveSoundVolumes, 5000, 1 )

            if isTimer(updateHornVolumeTimer) then -- Update Volumes Dynamically
                killTimer(updateHornVolumeTimer)
                updateHornVolumeTimer = nil
            end
            updateHornVolumeTimer = setTimer(updateVolume, volUpdateTime, 1, "horn")

        elseif source == GUIEditor.scrollbar[3] then
            local procent = guiScrollBarGetScrollPosition(source)
            guiSetText(GUIEditor.label[14], procent.."%")
            Volumes["announcer"] = guiScrollBarGetScrollPosition( source )/100
            if isTimer( soundSaveTimer ) then
                killTimer( soundSaveTimer )
                soundSaveTimer = nil
            end
            soundSaveTimer = setTimer( saveSoundVolumes, 5000, 1 )

            if isTimer(updateAnnouncerVolumeTimer) then -- Update Volumes Dynamically
                killTimer(updateAnnouncerVolumeTimer)
                updateAnnouncerVolumeTimer = nil
            end
            updateAnnouncerVolumeTimer = setTimer(updateVolume, volUpdateTime, 1, "announcer")

        elseif source == GUIEditor.scrollbar[4] then
            local procent = guiScrollBarGetScrollPosition(source)
            guiSetText(GUIEditor.label[16], procent.."%")
            Volumes["musicplayer"] = guiScrollBarGetScrollPosition( source )/100
            if isTimer( soundSaveTimer ) then
                killTimer( soundSaveTimer )
                soundSaveTimer = nil
            end
            soundSaveTimer = setTimer( saveSoundVolumes, 5000, 1 )

            if isTimer(updateMusicplayerVolumeTimer) then -- Update Volumes Dynamically
                killTimer(updateMusicplayerVolumeTimer)
                updateMusicplayerVolumeTimer = nil
            end
            updateMusicplayerVolumeTimer = setTimer(updateVolume, volUpdateTime, 1, "musicplayer")

        elseif source == GUIEditor.scrollbar[5] then
            local procent = guiScrollBarGetScrollPosition(source)
            guiSetText(GUIEditor.label[19], procent.."%")
            Volumes["miscellaneous"] = guiScrollBarGetScrollPosition( source )/100
            if isTimer( soundSaveTimer ) then
                killTimer( soundSaveTimer )
                soundSaveTimer = nil
            end
            soundSaveTimer = setTimer( saveSoundVolumes, 5000, 1 )

            if isTimer(updateMiscellaneousVolumeTimer) then -- Update Volumes Dynamically
                killTimer(updateMiscellaneousVolumeTimer)
                updateMiscellaneousVolumeTimer = nil
            end
            updateMiscellaneousVolumeTimer = setTimer(updateVolume, volUpdateTime, 1, "miscellaneous")

        end
    end
end
addEventHandler("onClientGUIScroll", resourceRoot, sounds_scrollbarhandler)

function setScrollBars()

    local map = tonumber(Volumes["map"])*100
    local horn = tonumber(Volumes["horn"])*100
    local announcer = tonumber(Volumes["announcer"])*100
    local musicplayer = tonumber(Volumes["musicplayer"])*100
    local misc = tonumber(Volumes["miscellaneous"])*100
    IgnoreScrollOnStartup = setTimer(function() end, 1000, 1)
	guiScrollBarSetScrollPosition( GUIEditor.scrollbar[1], map )
	guiScrollBarSetScrollPosition( GUIEditor.scrollbar[2], horn )
	guiScrollBarSetScrollPosition( GUIEditor.scrollbar[3], announcer )
	guiScrollBarSetScrollPosition( GUIEditor.scrollbar[4], musicplayer )
	guiScrollBarSetScrollPosition( GUIEditor.scrollbar[5], misc )

	guiSetText(GUIEditor.label[10], tostring(map).."%")
    guiSetText(GUIEditor.label[12], tostring(horn).."%")
    guiSetText(GUIEditor.label[14], tostring(announcer).."%")
    guiSetText(GUIEditor.label[16], tostring(musicplayer).."%")
    guiSetText(GUIEditor.label[19], tostring(misc).."%")
end

function soundsCommandHandler(cmd)
    if cmd == "soundson" then
        if not soundsoff then return end
        soundsoff = false
        soundson()
    elseif cmd == "soundsoff" then
        soundsoff = not soundsoff
        soundson()

    end
end
addCommandHandler( "soundsoff", soundsCommandHandler )
addCommandHandler("soundson", soundsCommandHandler)

function soundson()
    if soundsoff then
        outputChatBox("Custom Sounds disabled. (You can set individual sound volumes in the /settings menu, this command is not saved on reconnect.)",255,0,0)

        guiSetText( SoundsOffLabel, "/soundsoff is enabled." )
        guiLabelSetColor(SoundsOffLabel, 255, 0, 0)
        guiLabelSetColor( GUIEditor.label[9], 255, 0, 0 )
        guiLabelSetColor( GUIEditor.label[10], 255, 0, 0 )
        guiLabelSetColor( GUIEditor.label[11], 255, 0, 0 )
        guiLabelSetColor( GUIEditor.label[12], 255, 0, 0 )
        guiLabelSetColor( GUIEditor.label[13], 255, 0, 0 )
        guiLabelSetColor( GUIEditor.label[14], 255, 0, 0 )
        guiLabelSetColor( GUIEditor.label[15], 255, 0, 0 )
        guiLabelSetColor( GUIEditor.label[16], 255, 0, 0 )
        guiLabelSetColor( GUIEditor.label[18], 255, 0, 0 )
        guiLabelSetColor( GUIEditor.label[19], 255, 0, 0 )

        VolumesJson = toJSON( Volumes )

        for f,u in pairs(Volumes) do
            Volumes[f] = 0
        end

        updateVolume("soundsoff")

    elseif not soundsoff then
        outputChatBox("Custom Sounds enabled again. (You can set individual sound volumes in the /settings menu, this command is not saved on reconnect.)",0,255,0)

        guiSetText( SoundsOffLabel, "/soundsoff is disabled." )
        guiLabelSetColor(SoundsOffLabel, 255, 255, 255)
        guiLabelSetColor( GUIEditor.label[9], 255, 255, 255 )
        guiLabelSetColor( GUIEditor.label[10], 255, 255, 255 )
        guiLabelSetColor( GUIEditor.label[11], 255, 255, 255 )
        guiLabelSetColor( GUIEditor.label[12], 255, 255, 255 )
        guiLabelSetColor( GUIEditor.label[13], 255, 255, 255 )
        guiLabelSetColor( GUIEditor.label[14], 255, 255, 255 )
        guiLabelSetColor( GUIEditor.label[15], 255, 255, 255 )
        guiLabelSetColor( GUIEditor.label[16], 255, 255, 255 )
        guiLabelSetColor( GUIEditor.label[18], 255, 255, 255 )
        guiLabelSetColor( GUIEditor.label[19], 255, 255, 255 )

        local old_Volumes = fromJSON( VolumesJson )
        for f, u in pairs(old_Volumes) do
            Volumes[f] = u
        end

        updateVolume("soundson")
    end
end


text:
package fr.javatronic.damapping.test.mappermethod.sub;

/**
 * C -
 *
 * @author Sébastien Lesaint
 */
public class C {
}


text:
<!doctype html>

  <meta charset="utf-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <title>About me</title>
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="shortcut icon" href="/favicon.ico" />

  <meta name="viewport" content="width=device-width,initial-scale=1">

  <link rel="stylesheet" href="css/style.css">
  <link rel="stylesheet" href="css/style2.css">

	Gaston Paul Gouron

	born 06/03/1988 in Paris

	live and work in Bruxelles

	STUDIES

	2010 — now

	Master classes E.N.S.A.V La Cambre

	Visual communication

	Graphic design department

	2007 — 2010

	Bachelor classes E.S.B.A.Toulouse

	Visual communication

	Graphic design department

	2004 — 2007

	La Merci

	Economics and social sciences

	EXPERIENCES

	01.2011 — 04.2013

	Innership BASE Design

	Bruxelles

	10.2012 — 12.2012

	Innership S.I.G.N advertising agency

	Bruxelles

	12.2011 — 03.2012

	Innership Doodle web agency

	Bruxelles

	11.2009 — 12.2009

	Innership Lamazière printing house

	Lyon

	10.2009 — 11.2009

	Innership Ponceblanc book binding

	Lyon


text:
#pragma once

#include <modules/webbrowser/webbrowsermoduledefine.h>  // for IVW_MODULE_WEBBROWSER_API

#include <inviwo/core/processors/progressbar.h>  // for ProgressBarObserver

#include <string>  // for string

#include <warn/push>
#include <warn/ignore/all>
#include <include/cef_base.h>   // for CefRefPtr
#include <include/cef_frame.h>  // for CefFrame

#include <warn/pop>
namespace inviwo {

/**
 * \brief Observes progress bar changes and notifies supplied javascript functions on change.
 */
class IVW_MODULE_WEBBROWSER_API ProgressBarObserverCEF : public ProgressBarObserver {
public:
    ProgressBarObserverCEF(CefRefPtr<CefFrame> frame = nullptr, std::string onProgressChange = "",
                           std::string onVisibleChange = "");
    virtual ~ProgressBarObserverCEF(){};

    /**
     * Execute currently set onProgressChange javascript function
     * @param progress New progress between [0 1]
     */
    virtual void progressChanged(float progress) override;

    /**
     * Execute currently set OnProgressVisibleChange javascript function
     * @param visible state that ProgressBar changed into
     */
    virtual void progressBarVisibilityChanged(bool visible) override;
    /*
     * Name of javascript function to call when progress changes
     */
    void setOnProgressChange(std::string onChange) { onProgressChange_ = onChange; }
    const std::string& getOnProgressChange() const { return onProgressChange_; }
    /*
     * Name of javascript function to call when progress bar visibility changes
     */
    void setOnProgressVisibleChange(std::string onChange) { onProgressVisibleChange_ = onChange; }
    const std::string& getOnProgressVisibleChange() const { return onProgressVisibleChange_; }

    /*
     * Set frame containing html item.
     */
    void setFrame(CefRefPtr<CefFrame> frame);

private:
    std::string onProgressChange_;         /// Callback to execute when progress changes
    std::string onProgressVisibleChange_;  /// Callback to execute when visibility changes
    CefRefPtr<CefFrame> frame_;            /// Browser frame containing corresponding callbacks
};

}  // namespace inviwo


text:
<!DOCTYPE html>
<script src="../../resources/js-test.js"></script>
<script src="resources/shared.js"></script>
<script>

description("Regression test to ensure that IndexedDB connections don't leak");

setDBNameFromPath();
waitForRequests([
    indexedDB.deleteDatabase(dbname)
], doFirstOpen);

function doFirstOpen()
{
    preamble();

    evalAndLog("request = indexedDB.open(dbname, 1)");
    evalAndLog("sawUpgradeNeeded1 = false");
    request.onerror = unexpectedErrorCallback;
    request.onblocked = unexpectedBlockedCallback;
    request.onupgradeneeded = function onUpgradeNeeded1() {
        preamble();
        evalAndLog("sawUpgradeNeeded1 = true");
    };
    request.onsuccess = function onOpenSuccess1() {
        preamble();
        shouldBeTrue("sawUpgradeNeeded1");
        evalAndLog("db = request.result");
        evalAndLog("db.close()");

        doSecondOpen();
    };
}

function doSecondOpen()
{
    preamble();

    evalAndLog("request = indexedDB.open(dbname, 1)");
    request.onerror = unexpectedErrorCallback;
    request.onblocked = unexpectedBlockedCallback;
    request.onupgradeneeded = unexpectedUpgradeNeededCallback;
    request.onsuccess = function onOpenSuccess2() {
        preamble();
        evalAndLog("db = request.result");

        evalAndLog("db = null");
        evalAndLog("request = null");

        debug("Run GC outside of request's callback via setTimeout()");
        setTimeout( function() {
            evalAndLog("window.gc()");
            doThirdOpen();
        }, 0);
    };
}

function doThirdOpen()
{
    preamble();

    evalAndLog("request = indexedDB.open(dbname, 2)");
    evalAndLog("sawUpgradeNeeded3 = false");
    request.onerror = unexpectedErrorCallback;
    request.onblocked = unexpectedBlockedCallback;
    request.onupgradeneeded = function onUpgradeNeeded2() {
        preamble();
        evalAndLog("sawUpgradeNeeded3 = true");
    };
    request.onsuccess = function onOpenSuccess3() {
        preamble();
        shouldBeTrue("sawUpgradeNeeded3");
        evalAndLog("db = request.result");
        evalAndLog("db.close()");

        finishJSTest();
    };
}

</script>


text:
<?php
/**
 * Description of ScoreQuestionsQueries
 *
 * @author ben.dokter
 */
class ScoreQuestionsQueries {

    static function getScoreQuestions($active_only = false) {

        $filter = ($active_only == true) ? ' AND active = 1 ' : '';

        $sql = 'SELECT
                    ID_MQ,
                    active,
                    question
                FROM
                    _customers_misc_questions
                WHERE
                    customer_id = ' . CUSTOMER_ID .
                    $filter . '
                ORDER BY
                    seq_num';

        $sql_result = BaseQueries::performQuery($sql);
        return $sql_result;
    }

    static function getScoreAnswers($i_employee_id)
    {
        $sql = 'SELECT
                    *
                FROM
                    employees_misc_answers ema
                    INNER JOIN _customers_misc_questions cmq
                        ON ema.ID_MQ = cmq.ID_MQ
                WHERE
                    cmq.customer_id = ' . CUSTOMER_ID . '
                    AND cmq.active = 1
                    AND ema.ID_E = ' . $i_employee_id . '
                ORDER BY
                    seq_num';

        $sql_result = BaseQueries::performQuery($sql);
        return $sql_result;
    }

    static function getQuestionsAndAnswers($i_employee_id)
    {
        $sql = 'SELECT
                    cmq.*,
                    ema.ID_MA,
                    ema.answer
                FROM
                    _customers_misc_questions cmq
                    LEFT JOIN employees_misc_answers ema
                        ON ema.ID_MQ = cmq.ID_MQ
                            AND ema.ID_E = ' . $i_employee_id . '
                WHERE
                    cmq.customer_id = ' . CUSTOMER_ID . '
                    AND cmq.active = 1
                ORDER BY
                    seq_num';

        $sql_result = BaseQueries::performQuery($sql);
        return $sql_result;
    }

    static function getQuestionAnswer($i_employee_id,
                                      $i_question_id)
    {
        $sql = 'SELECT
                    *
                FROM
                    employees_misc_answers
                WHERE
                    customer_id = ' . CUSTOMER_ID . '
                    AND ID_E    = ' . $i_employee_id . '
                    AND ID_MQ   = ' . $i_question_id;

        $sql_result = BaseQueries::performQuery($sql);
        return $sql_result;
    }

    static function insertQuestionAnswer($i_employee_id,
                                         $i_question_id,
                                         $s_answer)
    {
        $sql = 'INSERT INTO
                    employees_misc_answers
                    ( customer_id,
                      ID_E,
                      ID_MQ,
                      answer
                    ) VALUES (
                       ' . CUSTOMER_ID . ',
                       ' . $i_employee_id . ',
                       ' . $i_question_id . ',
                      "' . mysql_real_escape_string($s_answer) . '"
                    )';

        BaseQueries::performQuery($sql);
        return @mysql_insert_id();

    }

    static function updateQuestionAnswer($i_employee_id,
                                         $i_question_id,
                                         $i_answer_id,
                                         $s_answer)
    {
        $sql = 'UPDATE
                    employees_misc_answers
                SET
                    answer = "' . mysql_real_escape_string($s_answer) . '"
                WHERE
                    customer_id = ' . CUSTOMER_ID . '
                    AND ID_E   = ' . $i_employee_id . '
                    AND ID_MQ  = ' . $i_question_id . '
                    AND ID_MA  = ' . $i_answer_id;

        $sql_result = BaseQueries::performQuery($sql);
        return @mysql_affected_rows($sql_result);
    }
}

?>


text:
/**
 */
package de.uka.ipd.sdq.dsexplore.qml.profile.tests;

import de.uka.ipd.sdq.dsexplore.qml.profile.ProfileFactory;
import de.uka.ipd.sdq.dsexplore.qml.profile.RefinedQMLProfile;

import junit.textui.TestRunner;

/**
 *
 * A test case for the model object 'Refined QML Profile'.
 *
 *

 * The following operations are tested:
 *

 *
{@link de.uka.ipd.sdq.dsexplore.qml.profile.RefinedQMLProfile#profile_cannot_refine_itself(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) Profile cannot refine itself}

 *

 *

 * @generated
 */
public class RefinedQMLProfileTest extends GenericQMLProfileTest {

	/**
	 *
	 *
	 * @generated
	 */
	public static void main(String[] args) {
		TestRunner.run(RefinedQMLProfileTest.class);
	}

	/**
	 * Constructs a new Refined QML Profile test case with the given name.
	 *
	 *
	 * @generated
	 */
	public RefinedQMLProfileTest(String name) {
		super(name);
	}

	/**
	 * Returns the fixture for this Refined QML Profile test case.
	 *
	 *
	 * @generated
	 */
	@Override
	protected RefinedQMLProfile getFixture() {
		return (RefinedQMLProfile)fixture;
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#setUp()
	 * @generated
	 */
	@Override
	protected void setUp() throws Exception {
		setFixture(ProfileFactory.eINSTANCE.createRefinedQMLProfile());
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#tearDown()
	 * @generated
	 */
	@Override
	protected void tearDown() throws Exception {
		setFixture(null);
	}

	/**
	 * Tests the '{@link de.uka.ipd.sdq.dsexplore.qml.profile.RefinedQMLProfile#profile_cannot_refine_itself(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) Profile cannot refine itself}' operation.
	 *
	 *
	 * @see de.uka.ipd.sdq.dsexplore.qml.profile.RefinedQMLProfile#profile_cannot_refine_itself(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map)
	 * @generated
	 */
	public void testProfile_cannot_refine_itself__DiagnosticChain_Map() {
		// TODO: implement this operation test method
		// Ensure that you remove @generated or mark it @generated NOT
		fail();
	}

} //RefinedQMLProfileTest


text:
#https://help.preyproject.com/article/188-prey-unattended-install-for-computers

$ErrorActionPreference = 'Stop'

$toolsPath = Split-Path -parent $MyInvocation.MyCommand.Definition

$packageArgs = @{
  packageName    = $env:ChocolateyPackageName
  fileType       = 'msi'
  file           = "$toolsPath\prey-windows-1.9.5-x86.msi"
  file64         = "$toolsPath\prey-windows-1.9.5-x64.msi"
  softwareName   = 'prey*'
  silentArgs     = "/qn /norestart /l*v `"$($env:TEMP)\$($env:chocolateyPackageName).$($env:chocolateyPackageVersion).MsiInstall.log`""
  validExitCodes = @(0, 2010, 1641)
}

Install-ChocolateyInstallPackage @packageArgs

Get-ChildItem $toolsPath\*.msi | ForEach-Object { Remove-Item $_ -ea 0; if (Test-Path $_) { Set-Content "$_.ignore" } }


text:
package alluxio.hub.agent.process;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import alluxio.conf.AlluxioConfiguration;
import alluxio.hub.agent.util.process.ProcessLauncher;
import alluxio.hub.common.RpcClient;
import alluxio.hub.proto.AlluxioNodeType;
import alluxio.hub.proto.ManagerAgentServiceGrpc;

import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class TestAgentProcessContextFactory {

  public static AgentProcessContext newContext(Set<AlluxioNodeType> procs,
      ProcessLauncher launcher, AlluxioConfiguration conf) throws Exception {
    RpcClient<ManagerAgentServiceGrpc.ManagerAgentServiceBlockingStub> rpcClient =
        mock(RpcClient.class);
    ManagerAgentServiceGrpc.ManagerAgentServiceBlockingStub stub =
        mock(ManagerAgentServiceGrpc.ManagerAgentServiceBlockingStub.class);
    when(rpcClient.get()).thenReturn(stub);
    Map<AlluxioNodeType, Object> p = procs.stream()
        .collect(Collectors.toMap(s -> s, s -> new Object()));
    AgentProcessContext apc = new AgentProcessContext(conf, rpcClient, p, launcher);
    return apc;
  }

  public static AgentProcessContext simpleContext(AlluxioConfiguration conf) throws Exception {
    return newContext(Collections.singleton(AlluxioNodeType.MASTER), mock(ProcessLauncher.class),
        conf);
  }
}


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ("ddcz", "0104_runes_and_userrating_table"),
    ]

    operations = [
        migrations.RenameModel(
            old_name="UzivateleCekajici",
            new_name="AwaitingRegistration",
        ),
        migrations.RenameModel(
            old_name="Letters",
            new_name="Letter",
        ),
        migrations.RenameModel(
            old_name="Runes",
            new_name="Rune",
        ),
        migrations.RenameModel(
            old_name="UserRatings",
            new_name="UserRating",
        ),
        migrations.AlterUniqueTogether(
            name="awaitingregistration",
            unique_together=set(),
        ),
    ]


text:
class ApplicationController

  # This method call child method execute, each "controller" needs call method
  # return array | response headers
  #
  def self.call(env)
    response = self.new(env)
    if response.valid_key?
      return response.execute
    end

    S3Proxy::Logger.error("Header key doesn't match with S3Proxy key")
    response.render "Access Denied", status: 403
  end

  attr_reader :request

  def initialize(env)
    @request = Rack::Request.new(env)
  end

  # This method validate key sended by header: 'Access-Token: S3Proxy'
  # return bool
  #
  def valid_key?
    request.env['HTTP_ACCESS_TOKEN'] == S3Proxy.config.application['token']
  end

  # This method is used to simplificate Rack response
  # return array | [status_code, content_type, [body_response]]
  #
  def render(body, options = {})
    status = options.delete(:status) || 200
    headers = {'Content-Type' => 'text/plain'}.merge(options)
    S3Proxy::Logger.error("event=application status=#{status}")

    [status, headers, [body]]
  end

end


text:
require 'spec_helper'

describe Github::Client do
  let(:object) { described_class }

  subject(:client) { object.new }

  after { reset_authentication_for client }

  it { expect(client.activity).to be_a Github::Client::Activity }

  it { expect(client.oauth).to be_a Github::Client::Authorizations }

  it { expect(client.gists).to be_a Github::Client::Gists }

  it { expect(client.git_data).to be_a Github::Client::GitData }

  it { expect(client.issues).to be_a Github::Client::Issues }

  it { expect(client.markdown).to be_a Github::Client::Markdown }

  it { expect(client.meta).to be_a Github::Client::Meta }

  it { expect(client.orgs).to be_a Github::Client::Orgs }

  it { expect(client.pull_requests).to be_a Github::Client::PullRequests }

  it { expect(client.repos).to be_a Github::Client::Repos }

  it { expect(client.users).to be_a Github::Client::Users }
end


text:
module Bitmap (bmp) where

import Color

import System.IO
import Data.Binary.Put
import Data.Word
import Control.Monad
import qualified Data.ByteString.Char8 as C

bytesPerPlane = 3
bitsPerPlane = bytesPerPlane*8

bmp :: [[Color]] -> Put
bmp colors = do
    bmpFileHeader (54 + ((height colors) * (paddedWidthInBytes colors)))
    bmpInfoHeader (width colors) (height colors)
    bmpColors colors

bmpFileHeader :: Word32 -> Put
bmpFileHeader s = do
    putByteString (C.pack "BM")
    putWord32le s
    putWord32le 0
    putWord32le 54 -- sizeof(bmpFileHeader) + sizeof(BitmapInfoHeader)

bmpInfoHeader :: Word32 -> Word32 -> Put
bmpInfoHeader w h = do
    putWord32le 40 -- sizeof(BitmapInfoHeader)
    putWord32le w
    putWord32le h
    putWord16le 1
    putWord16le bitsPerPlane
    putWord32le 0
    putWord32le 0
    putWord32le 0
    putWord32le 0
    putWord32le 0
    putWord32le 0

bmpColors :: [[Color]] -> Put
bmpColors [] = return()
bmpColors colors =
    let
        rowWidthInBytes = (width colors) * fromIntegral(bytesPerPlane) :: Word32
        pad = (paddedWidthInBytes colors) - rowWidthInBytes
    in do
        bmpRow (last colors) pad
        bmpColors (init colors)

bmpRow :: [Color] -> Word32 -> Put
bmpRow (c:clrs) pad = do
    putWord8 (b c)
    putWord8 (g c)
    putWord8 (r c)
    bmpRow clrs pad
bmpRow [] 0 = return()
bmpRow [] n = do
    putWord8 0
    bmpRow [] (n-1)

width :: [[Color]] -> Word32
width colors = fromIntegral(length (head colors)) :: Word32

height :: [[Color]] -> Word32
height colors = fromIntegral(length colors) :: Word32

paddedWidthInBytes :: [[Color]] -> Word32
paddedWidthInBytes colors =
    let
        colorsWidth = (width colors)
    in
        3*colorsWidth + (mod (3*colorsWidth) 4)


text:
#pragma once
#include <aws/kms/KMS_EXPORTS.h>
#include <aws/kms/KMSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace KMS
{
namespace Model
{

  /**
   */
  class AWS_KMS_API UpdateAliasRequest : public KMSRequest
  {
  public:
    UpdateAliasRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateAlias"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
Identifies the alias that is changing its KMS key. This value must begin with
     * alias/ followed by the alias name, such as
     * alias/ExampleAlias. You cannot use UpdateAlias to change the alias
     * name.

     */
    inline const Aws::String& GetAliasName() const{ return m_aliasName; }

    /**
     *
Identifies the alias that is changing its KMS key. This value must begin with
     * alias/ followed by the alias name, such as
     * alias/ExampleAlias. You cannot use UpdateAlias to change the alias
     * name.

     */
    inline bool AliasNameHasBeenSet() const { return m_aliasNameHasBeenSet; }

    /**
     *
Identifies the alias that is changing its KMS key. This value must begin with
     * alias/ followed by the alias name, such as
     * alias/ExampleAlias. You cannot use UpdateAlias to change the alias
     * name.

     */
    inline void SetAliasName(const Aws::String& value) { m_aliasNameHasBeenSet = true; m_aliasName = value; }

    /**
     *
Identifies the alias that is changing its KMS key. This value must begin with
     * alias/ followed by the alias name, such as
     * alias/ExampleAlias. You cannot use UpdateAlias to change the alias
     * name.

     */
    inline void SetAliasName(Aws::String&& value) { m_aliasNameHasBeenSet = true; m_aliasName = std::move(value); }

    /**
     *
Identifies the alias that is changing its KMS key. This value must begin with
     * alias/ followed by the alias name, such as
     * alias/ExampleAlias. You cannot use UpdateAlias to change the alias
     * name.

     */
    inline void SetAliasName(const char* value) { m_aliasNameHasBeenSet = true; m_aliasName.assign(value); }

    /**
     *
Identifies the alias that is changing its KMS key. This value must begin with
     * alias/ followed by the alias name, such as
     * alias/ExampleAlias. You cannot use UpdateAlias to change the alias
     * name.

     */
    inline UpdateAliasRequest& WithAliasName(const Aws::String& value) { SetAliasName(value); return *this;}

    /**
     *
Identifies the alias that is changing its KMS key. This value must begin with
     * alias/ followed by the alias name, such as
     * alias/ExampleAlias. You cannot use UpdateAlias to change the alias
     * name.

     */
    inline UpdateAliasRequest& WithAliasName(Aws::String&& value) { SetAliasName(std::move(value)); return *this;}

    /**
     *
Identifies the alias that is changing its KMS key. This value must begin with
     * alias/ followed by the alias name, such as
     * alias/ExampleAlias. You cannot use UpdateAlias to change the alias
     * name.

     */
    inline UpdateAliasRequest& WithAliasName(const char* value) { SetAliasName(value); return *this;}

    /**
     *
Identifies the customer
     * managed key to associate with the alias. You don't have permission to
     * associate an alias with an Amazon
     * Web Services managed key.

The KMS key must be in the same Amazon Web
     * Services account and Region as the alias. Also, the new target KMS key must be
     * the same type as the current target KMS key (both symmetric or both asymmetric)
     * and they must have the same key usage.

Specify the key ID or key ARN of
     * the KMS key.

For example:

Key ID:
     * 1234abcd-12ab-34cd-56ef-1234567890ab

Key ARN:
     * arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
     *

To get the key ID and key ARN for a KMS key, use
     * ListKeys or DescribeKey.

To verify that the alias is mapped
     * to the correct KMS key, use ListAliases.

     */
    inline const Aws::String& GetTargetKeyId() const{ return m_targetKeyId; }

    /**
     *
Identifies the customer
     * managed key to associate with the alias. You don't have permission to
     * associate an alias with an Amazon
     * Web Services managed key.

The KMS key must be in the same Amazon Web
     * Services account and Region as the alias. Also, the new target KMS key must be
     * the same type as the current target KMS key (both symmetric or both asymmetric)
     * and they must have the same key usage.

Specify the key ID or key ARN of
     * the KMS key.

For example:

Key ID:
     * 1234abcd-12ab-34cd-56ef-1234567890ab

Key ARN:
     * arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
     *

To get the key ID and key ARN for a KMS key, use
     * ListKeys or DescribeKey.

To verify that the alias is mapped
     * to the correct KMS key, use ListAliases.

     */
    inline bool TargetKeyIdHasBeenSet() const { return m_targetKeyIdHasBeenSet; }

    /**
     *
Identifies the customer
     * managed key to associate with the alias. You don't have permission to
     * associate an alias with an Amazon
     * Web Services managed key.

The KMS key must be in the same Amazon Web
     * Services account and Region as the alias. Also, the new target KMS key must be
     * the same type as the current target KMS key (both symmetric or both asymmetric)
     * and they must have the same key usage.

Specify the key ID or key ARN of
     * the KMS key.

For example:

Key ID:
     * 1234abcd-12ab-34cd-56ef-1234567890ab

Key ARN:
     * arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
     *

To get the key ID and key ARN for a KMS key, use
     * ListKeys or DescribeKey.

To verify that the alias is mapped
     * to the correct KMS key, use ListAliases.

     */
    inline void SetTargetKeyId(const Aws::String& value) { m_targetKeyIdHasBeenSet = true; m_targetKeyId = value; }

    /**
     *
Identifies the customer
     * managed key to associate with the alias. You don't have permission to
     * associate an alias with an Amazon
     * Web Services managed key.

The KMS key must be in the same Amazon Web
     * Services account and Region as the alias. Also, the new target KMS key must be
     * the same type as the current target KMS key (both symmetric or both asymmetric)
     * and they must have the same key usage.

Specify the key ID or key ARN of
     * the KMS key.

For example:

Key ID:
     * 1234abcd-12ab-34cd-56ef-1234567890ab

Key ARN:
     * arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
     *

To get the key ID and key ARN for a KMS key, use
     * ListKeys or DescribeKey.

To verify that the alias is mapped
     * to the correct KMS key, use ListAliases.

     */
    inline void SetTargetKeyId(Aws::String&& value) { m_targetKeyIdHasBeenSet = true; m_targetKeyId = std::move(value); }

    /**
     *
Identifies the customer
     * managed key to associate with the alias. You don't have permission to
     * associate an alias with an Amazon
     * Web Services managed key.

The KMS key must be in the same Amazon Web
     * Services account and Region as the alias. Also, the new target KMS key must be
     * the same type as the current target KMS key (both symmetric or both asymmetric)
     * and they must have the same key usage.

Specify the key ID or key ARN of
     * the KMS key.

For example:

Key ID:
     * 1234abcd-12ab-34cd-56ef-1234567890ab

Key ARN:
     * arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
     *

To get the key ID and key ARN for a KMS key, use
     * ListKeys or DescribeKey.

To verify that the alias is mapped
     * to the correct KMS key, use ListAliases.

     */
    inline void SetTargetKeyId(const char* value) { m_targetKeyIdHasBeenSet = true; m_targetKeyId.assign(value); }

    /**
     *
Identifies the customer
     * managed key to associate with the alias. You don't have permission to
     * associate an alias with an Amazon
     * Web Services managed key.

The KMS key must be in the same Amazon Web
     * Services account and Region as the alias. Also, the new target KMS key must be
     * the same type as the current target KMS key (both symmetric or both asymmetric)
     * and they must have the same key usage.

Specify the key ID or key ARN of
     * the KMS key.

For example:

Key ID:
     * 1234abcd-12ab-34cd-56ef-1234567890ab

Key ARN:
     * arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
     *

To get the key ID and key ARN for a KMS key, use
     * ListKeys or DescribeKey.

To verify that the alias is mapped
     * to the correct KMS key, use ListAliases.

     */
    inline UpdateAliasRequest& WithTargetKeyId(const Aws::String& value) { SetTargetKeyId(value); return *this;}

    /**
     *
Identifies the customer
     * managed key to associate with the alias. You don't have permission to
     * associate an alias with an Amazon
     * Web Services managed key.

The KMS key must be in the same Amazon Web
     * Services account and Region as the alias. Also, the new target KMS key must be
     * the same type as the current target KMS key (both symmetric or both asymmetric)
     * and they must have the same key usage.

Specify the key ID or key ARN of
     * the KMS key.

For example:

Key ID:
     * 1234abcd-12ab-34cd-56ef-1234567890ab

Key ARN:
     * arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
     *

To get the key ID and key ARN for a KMS key, use
     * ListKeys or DescribeKey.

To verify that the alias is mapped
     * to the correct KMS key, use ListAliases.

     */
    inline UpdateAliasRequest& WithTargetKeyId(Aws::String&& value) { SetTargetKeyId(std::move(value)); return *this;}

    /**
     *
Identifies the customer
     * managed key to associate with the alias. You don't have permission to
     * associate an alias with an Amazon
     * Web Services managed key.

The KMS key must be in the same Amazon Web
     * Services account and Region as the alias. Also, the new target KMS key must be
     * the same type as the current target KMS key (both symmetric or both asymmetric)
     * and they must have the same key usage.

Specify the key ID or key ARN of
     * the KMS key.

For example:

Key ID:
     * 1234abcd-12ab-34cd-56ef-1234567890ab

Key ARN:
     * arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
     *

To get the key ID and key ARN for a KMS key, use
     * ListKeys or DescribeKey.

To verify that the alias is mapped
     * to the correct KMS key, use ListAliases.

     */
    inline UpdateAliasRequest& WithTargetKeyId(const char* value) { SetTargetKeyId(value); return *this;}

  private:

    Aws::String m_aliasName;
    bool m_aliasNameHasBeenSet;

    Aws::String m_targetKeyId;
    bool m_targetKeyIdHasBeenSet;
  };

} // namespace Model
} // namespace KMS
} // namespace Aws


text:
start_test Image rewrite with flush.
HOST_NAME="http://image-rewrite-with-flush.example.com"
URL="http://image-rewrite-with-flush.example.com/mod_pagespeed_test/image_rewrite_with_flush/image_rewrite_with_flush.php"
http_proxy=$SECONDARY_HOSTNAME fetch_until -save "$URL" 'fgrep -c .pagespeed.ic' 2


text:
<?php

namespace Oscaballer\Pcgallery\Facades;

use Illuminate\Support\Facades\Facade;

class Pcgallery extends Facade {

  /**
   * Get the registered name of the component.
   *
   * @return string
   */
  protected static function getFacadeAccessor() { return 'pcgallery'; }

}


text:
@echo off
rem Assign current time and date to a file without modifying the file.
rem
rem author:  Olivier Wenger <https://github.com/ouly>
rem version: 1.0.0, 2014-11-06
rem see:     http://technet.microsoft.com/en-us/library/bb490886.aspx

IF "%~1"=="" (
    echo Missing argument.
    goto error
)

IF "%~1"=="/?" (
    echo Assign current time and date to a file without modifying the file.
    echo.
    echo TOUCH file
    echo.
    echo   file         File to touch.
    goto end
)

copy /b /y "%~1"+,,

:end
exit /B 0
:error
exit /B 1

rem END OF FILE


text:
package ru.scalalaz.gen

import java.nio.file.Paths

object Main extends App {

  val markdownDir = Paths.get("src/main/resources/md")
  val targetPath  = Paths.get("target/site")

  val siteSettings = SiteSettings()

  val gen  = new Generator(siteSettings, markdownDir, targetPath)
  val pgen = new SpecialPagesGenerator(markdownDir, targetPath)

  gen.generate() match {
    case Left(error) =>
      println("Main Pages generation failed, error:")
      println(error)
      sys.exit(1)
    case _ =>
      println("Main Pages generation - Done")
  }

  pgen.generate() match {
    case Left(error) =>
      println("Special Pages generation failed, error:")
      println(error)
      sys.exit(1)
    case _ =>
      println("Special Pages generation - Done")
  }

}


text:
@implementation WXSVGPolygon

@end


text:
<?php
return [
    'mail_config' => [

        /**
         * Default email sender
         */
        'from_name'  => 'Hardie Boeve',
        'from_email' => 'hdboeve@boevewebdevelopment.nl',

        /**
         * Default email receiver(s)
         */
        'to' => [
            [
                'name'  => 'Hardie Boeve',
                'email' => 'hdboeve@boevewebdevelopment.nl'
            ]
        ],

        /**
         * Transport type
         *
         * Available options: mail, smtp, file (see transport config)
         *
         */
        'transport_type' => 'mail',

        /**
         *  Transport config
         *
         *  mail:
         *   - uses  : Zend\Mail\Transport\Sendmail
         *   - config: emty array, no further configuration needed
         *
         *  smtp:
         *   - uses  : Zend\Mail\Transport\Smtp
         *   - config: array, for available configuration options go to http://zf2.readthedocs.org/en/latest/modules/zend.mail.smtp.options.html
         *
         *  file:
         *   - uses  : Zend\Mail\Transport\FileOptions
         *   - config: array, for available configuration options go to http://zf2.readthedocs.org/en/latest/modules/zend.mail.file.options.html
         */
        'transport_config' => [],

        /**
         * Default template
         */
        'template' => 'default.phtml',

        /**
         * Template paths
         *
         * For custom templates, copy the folowing lines to the module.config.php of the appropriate module
         *
         * 'mail_module' => [
         *     'template_paths' => [
         *         __DIR__ . '/../view/mail/templates/'
         *     ]
         * ]
        */
    ]
];


text:
'use strict';

import fs = require('fs');

import gracefulFs = require('graceful-fs');
gracefulFs.gracefulify(fs);

import arrays = require('vs/base/common/arrays');
import { compareByScore } from 'vs/base/common/comparers';
import objects = require('vs/base/common/objects');
import paths = require('vs/base/common/paths');
import scorer = require('vs/base/common/scorer');
import strings = require('vs/base/common/strings');
import { PPromise, TPromise } from 'vs/base/common/winjs.base';
import { MAX_FILE_SIZE } from 'vs/platform/files/common/files';
import { FileWalker, Engine as FileSearchEngine } from 'vs/workbench/services/search/node/fileSearch';
import { Engine as TextSearchEngine } from 'vs/workbench/services/search/node/textSearch';
import { TextSearchWorkerProvider } from 'vs/workbench/services/search/node/textSearchWorkerProvider';
import { IRawSearchService, IRawSearch, IRawFileMatch, ISerializedFileMatch, ISerializedSearchProgressItem, ISerializedSearchComplete, ISearchEngine } from './search';
import { ICachedSearchStats, IProgress } from 'vs/platform/search/common/search';

export type IRawProgressItem<T> = T | T[] | IProgress;

export class SearchService implements IRawSearchService {

	private static BATCH_SIZE = 512;

	private caches: { [cacheKey: string]: Cache; } = Object.create(null);

	private textSearchWorkerProvider: TextSearchWorkerProvider;

	public fileSearch(config: IRawSearch): PPromise<ISerializedSearchComplete, ISerializedSearchProgressItem> {
		return this.doFileSearch(FileSearchEngine, config, SearchService.BATCH_SIZE);
	}

	public textSearch(config: IRawSearch): PPromise<ISerializedSearchComplete, ISerializedSearchProgressItem> {
		if (!this.textSearchWorkerProvider) {
			this.textSearchWorkerProvider = new TextSearchWorkerProvider();
		}

		let engine = new TextSearchEngine(
			config,
			new FileWalker({
				rootFolders: config.rootFolders,
				extraFiles: config.extraFiles,
				includePattern: config.includePattern,
				excludePattern: config.excludePattern,
				filePattern: config.filePattern,
				maxFilesize: MAX_FILE_SIZE
			}),
			this.textSearchWorkerProvider);

		return this.doTextSearch(engine, SearchService.BATCH_SIZE);
	}

	public doFileSearch(EngineClass: { new (config: IRawSearch): ISearchEngine<IRawFileMatch>; }, config: IRawSearch, batchSize?: number): PPromise<ISerializedSearchComplete, ISerializedSearchProgressItem> {

		if (config.sortByScore) {
			let sortedSearch = this.trySortedSearchFromCache(config);
			if (!sortedSearch) {
				const walkerConfig = config.maxResults ? objects.assign({}, config, { maxResults: null }) : config;
				const engine = new EngineClass(walkerConfig);
				sortedSearch = this.doSortedSearch(engine, config);
			}

			return new PPromise<ISerializedSearchComplete, ISerializedSearchProgressItem>((c, e, p) => {
				process.nextTick(() => { // allow caller to register progress callback first
					sortedSearch.then(([result, rawMatches]) => {
						const serializedMatches = rawMatches.map(rawMatch => this.rawMatchToSearchItem(rawMatch));
						this.sendProgress(serializedMatches, p, batchSize);
						c(result);
					}, e, p);
				});
			}, () => {
				sortedSearch.cancel();
			});
		}

		let searchPromise: PPromise<void, IRawProgressItem<IRawFileMatch>>;
		return new PPromise<ISerializedSearchComplete, ISerializedSearchProgressItem>((c, e, p) => {
			const engine = new EngineClass(config);
			searchPromise = this.doSearch(engine, batchSize)
				.then(c, e, progress => {
					if (Array.isArray(progress)) {
						p(progress.map(m => this.rawMatchToSearchItem(m)));
					} else if ((<IRawFileMatch>progress).relativePath) {
						p(this.rawMatchToSearchItem(<IRawFileMatch>progress));
					} else {
						p(progress);
					}
				});
		}, () => {
			searchPromise.cancel();
		});
	}

	private rawMatchToSearchItem(match: IRawFileMatch): ISerializedFileMatch {
		return { path: match.base ? [match.base, match.relativePath].join(paths.nativeSep) : match.relativePath };
	}

	private doSortedSearch(engine: ISearchEngine<IRawFileMatch>, config: IRawSearch): PPromise<[ISerializedSearchComplete, IRawFileMatch[]], IProgress> {
		let searchPromise: PPromise<void, IRawProgressItem<IRawFileMatch>>;
		let allResultsPromise = new PPromise<[ISerializedSearchComplete, IRawFileMatch[]], IProgress>((c, e, p) => {
			let results: IRawFileMatch[] = [];
			searchPromise = this.doSearch(engine, -1)
				.then(result => {
					c([result, results]);
				}, e, progress => {
					if (Array.isArray(progress)) {
						results = progress;
					} else {
						p(progress);
					}
				});
		}, () => {
			searchPromise.cancel();
		});

		let cache: Cache;
		if (config.cacheKey) {
			cache = this.getOrCreateCache(config.cacheKey);
			cache.resultsToSearchCache[config.filePattern] = allResultsPromise;
			allResultsPromise.then(null, err => {
				delete cache.resultsToSearchCache[config.filePattern];
			});
			allResultsPromise = this.preventCancellation(allResultsPromise);
		}

		return new PPromise<[ISerializedSearchComplete, IRawFileMatch[]], IProgress>((c, e, p) => {
			allResultsPromise.then(([result, results]) => {
				const scorerCache: ScorerCache = cache ? cache.scorerCache : Object.create(null);
				const unsortedResultTime = Date.now();
				const sortedResults = this.sortResults(config, results, scorerCache);
				const sortedResultTime = Date.now();

				c([{
					stats: objects.assign({}, result.stats, {
						unsortedResultTime,
						sortedResultTime
					}),
					limitHit: result.limitHit || typeof config.maxResults === 'number' && results.length > config.maxResults
				}, sortedResults]);
			}, e, p);
		}, () => {
			allResultsPromise.cancel();
		});
	}

	private getOrCreateCache(cacheKey: string): Cache {
		const existing = this.caches[cacheKey];
		if (existing) {
			return existing;
		}
		return this.caches[cacheKey] = new Cache();
	}

	private trySortedSearchFromCache(config: IRawSearch): PPromise<[ISerializedSearchComplete, IRawFileMatch[]], IProgress> {
		const cache = config.cacheKey && this.caches[config.cacheKey];
		if (!cache) {
			return;
		}

		const cacheLookupStartTime = Date.now();
		const cached = this.getResultsFromCache(cache, config.filePattern);
		if (cached) {
			return new PPromise<[ISerializedSearchComplete, IRawFileMatch[]], IProgress>((c, e, p) => {
				cached.then(([result, results, cacheStats]) => {
					const cacheLookupResultTime = Date.now();
					const sortedResults = this.sortResults(config, results, cache.scorerCache);
					const sortedResultTime = Date.now();

					const stats: ICachedSearchStats = {
						fromCache: true,
						cacheLookupStartTime: cacheLookupStartTime,
						cacheFilterStartTime: cacheStats.cacheFilterStartTime,
						cacheLookupResultTime: cacheLookupResultTime,
						cacheEntryCount: cacheStats.cacheFilterResultCount,
						resultCount: results.length
					};
					if (config.sortByScore) {
						stats.unsortedResultTime = cacheLookupResultTime;
						stats.sortedResultTime = sortedResultTime;
					}
					if (!cacheStats.cacheWasResolved) {
						stats.joined = result.stats;
					}
					c([
						{
							limitHit: result.limitHit || typeof config.maxResults === 'number' && results.length > config.maxResults,
							stats: stats
						},
						sortedResults
					]);
				}, e, p);
			}, () => {
				cached.cancel();
			});
		}
	}

	private sortResults(config: IRawSearch, results: IRawFileMatch[], scorerCache: ScorerCache): IRawFileMatch[] {
		const filePattern = config.filePattern;
		const normalizedSearchValue = strings.stripWildcards(filePattern).toLowerCase();
		const compare = (elementA: IRawFileMatch, elementB: IRawFileMatch) => compareByScore(elementA, elementB, FileMatchAccessor, filePattern, normalizedSearchValue, scorerCache);
		return arrays.top(results, compare, config.maxResults);
	}

	private sendProgress(results: ISerializedFileMatch[], progressCb: (batch: ISerializedFileMatch[]) => void, batchSize: number) {
		if (batchSize && batchSize > 0) {
			for (let i = 0; i < results.length; i += batchSize) {
				progressCb(results.slice(i, i + batchSize));
			}
		} else {
			progressCb(results);
		}
	}

	private getResultsFromCache(cache: Cache, searchValue: string): PPromise<[ISerializedSearchComplete, IRawFileMatch[], CacheStats], IProgress> {
		if (paths.isAbsolute(searchValue)) {
			return null; // bypass cache if user looks up an absolute path where matching goes directly on disk
		}

		// Find cache entries by prefix of search value
		const hasPathSep = searchValue.indexOf(paths.nativeSep) >= 0;
		let cached: PPromise<[ISerializedSearchComplete, IRawFileMatch[]], IProgress>;
		let wasResolved: boolean;
		for (let previousSearch in cache.resultsToSearchCache) {

			// If we narrow down, we might be able to reuse the cached results
			if (strings.startsWith(searchValue, previousSearch)) {
				if (hasPathSep && previousSearch.indexOf(paths.nativeSep) < 0) {
					continue; // since a path character widens the search for potential more matches, require it in previous search too
				}

				const c = cache.resultsToSearchCache[previousSearch];
				c.then(() => { wasResolved = false; });
				wasResolved = true;
				cached = this.preventCancellation(c);
				break;
			}
		}

		if (!cached) {
			return null;
		}

		return new PPromise<[ISerializedSearchComplete, IRawFileMatch[], CacheStats], IProgress>((c, e, p) => {
			cached.then(([complete, cachedEntries]) => {
				const cacheFilterStartTime = Date.now();

				// Pattern match on results
				let results: IRawFileMatch[] = [];
				const normalizedSearchValueLowercase = strings.stripWildcards(searchValue).toLowerCase();
				for (let i = 0; i < cachedEntries.length; i++) {
					let entry = cachedEntries[i];

					// Check if this entry is a match for the search value
					if (!scorer.matches(entry.relativePath, normalizedSearchValueLowercase)) {
						continue;
					}

					results.push(entry);
				}

				c([complete, results, {
					cacheWasResolved: wasResolved,
					cacheFilterStartTime: cacheFilterStartTime,
					cacheFilterResultCount: cachedEntries.length
				}]);
			}, e, p);
		}, () => {
			cached.cancel();
		});
	}

	private doTextSearch(engine: TextSearchEngine, batchSize: number): PPromise<ISerializedSearchComplete, IRawProgressItem<ISerializedFileMatch>> {
		return new PPromise<ISerializedSearchComplete, IRawProgressItem<ISerializedFileMatch>>((c, e, p) => {
			// Use BatchedCollector to get new results to the frontend every 2s at least, until 50 results have been returned
			const collector = new BatchedCollector<ISerializedFileMatch>(batchSize, p);
			engine.search((matches) => {
				const totalMatches = matches.reduce((acc, m) => acc + m.numMatches, 0);
				collector.addItems(matches, totalMatches);
			}, (progress) => {
				p(progress);
			}, (error, stats) => {
				collector.flush();

				if (error) {
					e(error);
				} else {
					c(stats);
				}
			});
		}, () => {
			engine.cancel();
		});
	}

	private doSearch<T>(engine: ISearchEngine<T>, batchSize?: number): PPromise<ISerializedSearchComplete, IRawProgressItem<T>> {
		return new PPromise<ISerializedSearchComplete, IRawProgressItem<T>>((c, e, p) => {
			let batch: T[] = [];
			engine.search((match) => {
				if (match) {
					if (batchSize) {
						batch.push(match);
						if (batchSize > 0 && batch.length >= batchSize) {
							p(batch);
							batch = [];
						}
					} else {
						p(match);
					}
				}
			}, (progress) => {
				p(progress);
			}, (error, stats) => {
				if (batch.length) {
					p(batch);
				}
				if (error) {
					e(error);
				} else {
					c(stats);
				}
			});
		}, () => {
			engine.cancel();
		});
	}

	public clearCache(cacheKey: string): TPromise<void> {
		delete this.caches[cacheKey];
		return TPromise.as(undefined);
	}

	private preventCancellation<C, P>(promise: PPromise<C, P>): PPromise<C, P> {
		return new PPromise<C, P>((c, e, p) => {
			// Allow for piled up cancellations to come through first.
			process.nextTick(() => {
				promise.then(c, e, p);
			});
		}, () => {
			// Do not propagate.
		});
	}
}

class Cache {

	public resultsToSearchCache: { [searchValue: string]: PPromise<[ISerializedSearchComplete, IRawFileMatch[]], IProgress>; } = Object.create(null);

	public scorerCache: ScorerCache = Object.create(null);
}

interface ScorerCache {
	[key: string]: number;
}

class FileMatchAccessor {

	public static getLabel(match: IRawFileMatch): string {
		return match.basename;
	}

	public static getResourcePath(match: IRawFileMatch): string {
		return match.relativePath;
	}
}

interface CacheStats {
	cacheWasResolved: boolean;
	cacheFilterStartTime: number;
	cacheFilterResultCount: number;
}

/**
 * Collects items that have a size - before the cumulative size of collected items reaches START_BATCH_AFTER_COUNT, the callback is called for every
 * set of items collected.
 * But after that point, the callback is called with batches of maxBatchSize.
 * If the batch isn't filled within some time, the callback is also called.
 */
class BatchedCollector<T> {
	private static TIMEOUT = 4000;

	// After RUN_TIMEOUT_UNTIL_COUNT items have been collected, stop flushing on timeout
	private static START_BATCH_AFTER_COUNT = 50;

	private totalNumberCompleted = 0;
	private batch: T[] = [];
	private batchSize = 0;
	private timeoutHandle: number;

	constructor(private maxBatchSize: number, private cb: (items: T | T[]) => void) {
	}

	addItems(items: T[], size: number): void {
		if (!items) {
			return;
		}

		if (this.maxBatchSize > 0) {
			this.addItemsToBatch(items, size);
		} else {
			this.cb(items);
		}
	}

	private addItemsToBatch(items: T[], size: number): void {
		this.batch = this.batch.concat(items);
		this.batchSize += size;
		if (this.totalNumberCompleted < BatchedCollector.START_BATCH_AFTER_COUNT) {
			// Flush because we aren't batching yet
			this.flush();
		} else if (this.batchSize >= this.maxBatchSize) {
			// Flush because the batch is full
			this.flush();
		} else if (!this.timeoutHandle) {
			// No timeout running, start a timeout to flush
			this.timeoutHandle = setTimeout(() => {
				this.flush();
			}, BatchedCollector.TIMEOUT);
		}
	}

	flush(): void {
		if (this.batchSize) {
			this.totalNumberCompleted += this.batchSize;
			this.cb(this.batch);
			this.batch = [];
			this.batchSize = 0;

			if (this.timeoutHandle) {
				clearTimeout(this.timeoutHandle);
				this.timeoutHandle = 0;
			}
		}
	}
}


text:
var links = [];
var casper = require('casper').create();

function getLinks() {
  var links = document.querySelectorAll('h3.r a');
  return Array.prototype.map.call(links, function(e) {
    return e.getAttribute('href');
  });
}

casper.start('http://google.dk/', function() {
  // search for 'casperjs' from google form
  this.fill('form[action="/search"]', { q: 'Inzite Media & Marketing' }, true);
});

casper.then(function() {
  // aggregate results for the 'phantomjs' search
  links = links.concat(this.evaluate(getLinks));
});

casper.run(function() {
  // echo results in some pretty fashion
  this.echo(links.length + ' links found:');
  this.echo(' - ' + links.join('\n - ')).exit();
});


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../../">
  <title data-ice="title">src/policy/PEP.js | Service Framework API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

  Home

  Reference
  Source
  Test

    <input class="search-input">

allocation
CAddressAllocation

bus
CBus

CMessageBus

CMiniBus

CPipeline

discovery
CCoreDiscovery

graphconnector
CBloomFilter

CGlobalRegistryRecord

CGraphConnector

CGraphConnectorContactData

identity
CCrypto

CGuiFake

CIdentity

CIdentityModule

COpenIdLib

policy
CActionsService

CCombiningAlgorithm

COperators

CPDP

CPEP

CPolicy

CReThinkCtx

CRule

policy/combiningAlgorithms
CAllowOverrides

CBlockOverrides

CFirstApplicable

policy/conditions
CAdvancedCondition

CCondition

CSubscriptionCondition

policy/context
CRuntimeCoreCtx

protostub
CIdpProxyStub

Factivate

registry
CHypertyInstance

CRegistry

CRegistryDataModel

runtime
CDescriptors

CLoader

CRuntimeUA

VruntimeConfiguration

VruntimeUtils

sandbox
CSandbox

CSandboxRegistry

VSandboxType

store-objects
CDataObjectsStorage

syncher
CObserverObject

CReporterObject

CSubscription

CSyncherManager

utils
CEventEmitter

FschemaValidation

Fassign

FbuildURL

FcheckAttribute

FconvertToUserURL

FdeepClone

FdivideEmail

FdivideURL

FemptyObject

FgenerateGUID

FgetConfigurationResources

FgetUserEmailFromURL

FgetUserIdentityDomain

FgetUserURLFromEmail

FisBackendServiceURL

FisDataObjectURL

FisHypertyURL

FisLegacy

FisURL

FisUserURL

FparseAttributes

FremovePathFromURL

FsplitObjectURL

Vtv4

TdivideURL

src/policy/PEP.js

import ActionsService from './ActionsService';
import PDP from './PDP';
import Policy from './Policy';
import {isHypertyURL} from '../utils/utils';

class PEP {

  /**
  * Creates a Policy Enforcement Point (PEP) instance
  * @param    {Object}    context
  */
  constructor(context) {
    let _this = this;

    _this.pdp = new PDP(context);
    _this.actionsService = new ActionsService(context);
    _this.context = context;
    context.pep = _this;

    //TODO should be added a trigger to verify when the loadConfigurations is successfully completed
    context.loadConfigurations();
  }

  /**
  * return the messageBus in this Registry
  * @param {MessageBus}           messageBus
  */
  get messageBus() {
    let _this = this;
    return _this.context.messageBus;
  }

  /**
  * Set the messageBus in this Registry
  * @param {MessageBus}           messageBus
  */
  set messageBus(messageBus) {
    let _this = this;
    _this.context.messageBus = messageBus;
    _this.addGUIListeners();
  }

  addGUIListeners() {
    let _this = this;

    _this.context.messageBus.addListener(_this.context.pepURL, (msg) => {
      let funcName = msg.body.method;

      let returnedValue;
      if (funcName === 'addToGroup') {
        let groupName = msg.body.params.groupName;
        let userEmail = msg.body.params.userEmail;
        returnedValue = _this.context.addToGroup(groupName, userEmail);
      } else if (funcName === 'createGroup') {
        let groupName = msg.body.params.groupName;
        returnedValue = _this.context.createGroup(groupName);
      } else if (funcName === 'addPolicy') {
        let source = msg.body.params.source;
        let key = msg.body.params.key;
        let policy = msg.body.params.policy;
        let combiningAlgorithm = msg.body.params.combiningAlgorithm;
        returnedValue = _this.addPolicy(source, key, policy, combiningAlgorithm);
      } else if(funcName === 'deleteGroup') {
        let groupName = msg.body.params.groupName;
        returnedValue = _this.context.deleteGroup(groupName);
      } else if(funcName === 'removePolicy') {
        let source = msg.body.params.source;
        let key = msg.body.params.key;
        returnedValue = _this.removePolicy(source, key);
      } else if(funcName === 'savePolicies') {
        let source = msg.body.params.source;
        returnedValue = _this.context.savePolicies(source);
      } else if(funcName === 'userPolicies') {
        returnedValue = _this.context.userPolicies;
      } else if(funcName === 'activeUserPolicy') {
        let userPolicy = msg.body.params.userPolicy;
        if (userPolicy) { _this.context.activeUserPolicy = userPolicy; }
        returnedValue = _this.context.activeUserPolicy;
      } else if(funcName === 'userPolicy') {
        let key = msg.body.params.key;
        returnedValue = _this.context.userPolicies[key];
      } else if(funcName === 'saveActivePolicy') {
        returnedValue = _this.context.saveActivePolicy();
      } else if(funcName === 'getMyEmails') {
        returnedValue = _this.context.getMyEmails();
      } else if(funcName === 'getMyHyperties') {
        returnedValue = _this.context.getMyHyperties();
      } else if(funcName === 'groups') {
        returnedValue = _this.context.groups;
      } else if(funcName === 'getGroupsNames') {
        returnedValue = _this.context.getGroupsNames();
      } if (funcName === 'removeFromGroup') {
        let groupName = msg.body.params.groupName;
        let userEmail = msg.body.params.userEmail;
        returnedValue = _this.context.removeFromGroup(groupName, userEmail);
      }

      let value = {type: 'execute', value: returnedValue, code: 200};
      let replyMsg = {id: msg.id, type: 'response', to: msg.from, from: msg.to, body: value};
      _this.context.messageBus.postMessage(replyMsg);
    });
  }

  /**
  * Adds a policy to the Policy Enforcement Point (PEP). The policy can be created by the service
  * provider or by the user.
  * @param    {String}    source
  * @param    {String}    key
  * @param    {Object}    policy
  */
  addPolicy(source, key, policy, combiningAlgorithm) {
    if (!source) throw new Error('source is not defined');
    if (!key) throw new Error('key is not defined');

    if (policy === undefined) {
      policy = new Policy(key, [], [], combiningAlgorithm);
    } else {
      if (!(policy instanceof Policy)) {
        policy = new Policy(policy.key, policy.rules, policy.actions, policy.combiningAlgorithm);
      }
    }

    switch (source) {
      case 'SERVICE_PROVIDER':
        this.context.savePolicies(source, policy, key);
        break;
      case 'USER':
        this.context.userPolicies[key] = policy;
        this.context.savePolicies(source);
        break;
      default:
        throw Error('Unknown policy source: ' + source);
    }
  }

  authorise(message) {
    console.log('[Policy.PEP Authorise] ', message);
    console.log(message);
    if (!message) throw new Error('message is not defined');
    if (!message.from) throw new Error('message.from is not defined');
    if (!message.to) throw new Error('message.to is not defined');
    if (!message.type) throw new Error('message.type is not defined');
    message.body = message.body || {};

    return new Promise((resolve, reject) => {

      message.body = message.body || {};
      let _this = this;
      let result;
      if (_this._isToVerify(message)) {
        let isIncoming = _this._isIncomingMessage(message);
        _this.context.prepareForEvaluation(message, isIncoming).then(message => {
          result = _this.pdp.evaluatePolicies(message, isIncoming);
          if (result === 'Not Applicable') {
            result = _this.context.defaultBehaviour;
            message.body.auth = false;
          }
          _this.actionsService.enforcePolicies(message, isIncoming).then(messages => {
            for (let i in messages) {
              message = messages[i];
              _this.context.prepareToForward(message, isIncoming, result).then(message => {
                if (result) {
                  message.body.auth = (message.body.auth === undefined) ? true : message.body.auth;
                  resolve(message);
                } else {
                  let errorMessage = { body: { code: 403, description: 'Blocked by policy' }, from: message.to, to: message.from, type: 'response' };
                  reject(errorMessage);
                }
              }, (error) => {
                reject(error);
              });
            }
          }, (error) => {
            reject(error);
          });
        }, (error) => {
          reject(error);
        });
      } else {
        result = _this.context.defaultBehaviour;
        if (result) {
          message.body.auth = false;
          resolve(message);
        } else {
          let errorMessage = { body: { code: 403, description: 'Blocked by policy' }, from: message.to, to: message.from, type: 'response' };
          reject(errorMessage);
        }
      }
    });
  }

  authoriseSync(message) {
    let result;
    message.body = message.body || {};
    if (this._isToVerify(message)) {
      let isIncoming = this._isIncomingMessage(message);
      message = this.context.prepareForEvaluation(message, isIncoming);
      result = this.pdp.evaluatePolicies(message, isIncoming);
      if (result === 'Not Applicable') {
        result = this.context.defaultBehaviour;
        message.body.auth = false;
      }
      this.actionsService.enforcePolicies(message, isIncoming);
      message = this.context.prepareToForward(message, isIncoming, result);
      if (result) {
        message.body.auth = (message.body.auth === undefined) ? true : message.body.auth;
        return true;
      } else {
        return false;
      }
    } else {
      result = this.context.defaultBehaviour;
      if (result) {
        message.body.auth = false;
        return true;
      } else {
        return false;
      }
    }
  }

  _isIncomingMessage(message) {
    let from;

    if (message.type === 'forward') {
      console.info('[PEP - isIncomingMessage] - message.type: ', message.type);
      from = message.body.from;
    } else if (message.body.hasOwnProperty('source') && message.body.source) {
      console.info('[PEP - isIncomingMessage] - message.body.source: ', message.body.source);
      from = message.body.source;
    } else if (message.body.hasOwnProperty('subscriber') && message.body.subscriber) {
      //TODO: this subscriber validation should not exist, because is outdated
      //TODO: the syncher and syncher manager not following the correct spec;
      console.info('[PEP - isIncomingMessage] - message.body.subscriber: ', message.body.subscriber);
      from = message.body.subscriber;
    }  else if (message.body.hasOwnProperty('reporter') && message.body.reporter) {
      //TODO: this subscriber validation should not exist, because is outdated
      //TODO: the syncher and syncher manager not following the correct spec;
      console.info('[PEP - isIncomingMessage] - message.body.reporter: ', message.body.reporter);
      from = message.body.reporter;
    } else {
      console.info('[PEP - isIncomingMessage] - message.from ', message.from);
      from = message.from;
    }

    console.info('[PEP - isIncomingMessage] - check if isLocal: ', from);
    return !this.context.isLocal(from);
  }

  /**
  * Identifies the messages to be verified by the Policy Engine
  * @param    {Message}   message
  * @returns  {boolean}   returns true if the message requires encryption/decryption
  *                       or if its type equals 'handshake'; false otherwise
  */
  _isToVerify(message) {
    let schemasToIgnore = ['domain', 'domain-idp', 'global', 'hyperty-runtime', 'runtime'];
    let splitFrom = (message.from).split('://');
    let fromSchema = splitFrom[0];
    let splitTo = (message.to).split('://');
    let toSchema =  splitTo[0];
    let from = message.from;
    let to = message.to;

    // Signalling messages between P2P Stubs don't have to be verified. FFS

    if (message.body && message.body.source) {
      from = message.body.source;
    }

    if (message.body && message.body.subscriber) {
      from = message.body.subscriber;
    }

    if (from.indexOf('/p2phandler/') !== -1 || from.indexOf('/p2prequester/') !== -1 || to.indexOf('/p2phandler/') !== -1 || to.indexOf('/p2prequester/') !== -1) {
      return false;
    }

    // hack to disable Identity verification for messages coming from legacy domains while solution is not implemented

    if (this.context.isInterworkingProtoStub(from)) {
      return false;
    }

    if (message.from === fromSchema || message.to === toSchema || message.type === 'read' || message.type === 'response' || (isHypertyURL(message.from) && message.type === 'delete')) {
      return false;
    } else {
      return schemasToIgnore.indexOf(fromSchema) === -1 || schemasToIgnore.indexOf(toSchema) === -1;
    }
  }

  removePolicy(source, key) {
    if (!source) throw new Error('source is not defined');
    if (source !== '*' && !key) throw new Error('key is not defined');

    switch (source) {
      case '*':
        this.context.serviceProviderPolicy = {};
        this.context.userPolicies = {};
        this.context.activeUserPolicy = undefined;
        this.context.savePolicies('USER');
        this.context.savePolicies('SERVICE_PROVIDER');
        this.context.saveActivePolicy();
        break;
      case 'SERVICE_PROVIDER':
        delete this.context.serviceProviderPolicy[key];
        this.context.savePolicies();
        break;
      case 'USER':
        delete this.context.userPolicies[key];
        if (key === this.context.activeUserPolicy) {
          this.context.activeUserPolicy = undefined;
          this.context.saveActivePolicy();
        }
        this.context.savePolicies('USER');
        break;
      default:
        throw Error('Unknown policy source: ' + source);
    }
  }

}

export default PEP;

  Generated by ESDoc(0.5.2)