text:
package org.apache.commons.lang3.text;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

/**
 *
Operations on Strings that contain words.

 *
 *
This class tries to handle {@code null} input gracefully.
 * An exception will not be thrown for a {@code null} input.
 * Each method documents its behavior in more detail.

 *
 * @since 2.0
 * @deprecated as of 3.6, use commons-text
 *
 * WordUtils instead
 */
@Deprecated
public class WordUtils {

    /**
     *
{@code WordUtils} instances should NOT be constructed in
     * standard programming. Instead, the class should be used as
     * {@code WordUtils.wrap("foo bar", 20);}.

     *
     *
This constructor is public to permit tools that require a JavaBean
     * instance to operate.

     */
    public WordUtils() {
      super();
    }

    // Wrapping
    //--------------------------------------------------------------------------
    /**
     *
Wraps a single line of text, identifying words by {@code ' '}.

     *
     *
New lines will be separated by the system property line separator.
     * Very long words, such as URLs will not be wrapped.

     *
     *
Leading spaces on a new line are stripped.
     * Trailing spaces are not stripped.

     *
     *

     *
Examples

     *

     *   input
     *   wrapLength
     *   result
     *

     *

     *   null
     *   *
     *   null
     *

     *

     *   ""
     *   *
     *   ""
     *

     *

     *   "Here is one line of text that is going to be wrapped after 20 columns."
     *   20
     *   "Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
     *

     *

     *   "Click here to jump to the commons website - https://commons.apache.org"
     *   20
     *   "Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"
     *

     *

     *   "Click here, https://commons.apache.org, to jump to the commons website"
     *   20
     *   "Click here,\nhttps://commons.apache.org,\nto jump to the\ncommons website"
     *

     *

     *
     * (assuming that '\n' is the systems line separator)
     *
     * @param str  the String to be word wrapped, may be null
     * @param wrapLength  the column to wrap the words at, less than 1 is treated as 1
     * @return a line with newlines inserted, {@code null} if null input
     */
    public static String wrap(final String str, final int wrapLength) {
        return wrap(str, wrapLength, null, false);
    }

    /**
     *
Wraps a single line of text, identifying words by {@code ' '}.

     *
     *
Leading spaces on a new line are stripped.
     * Trailing spaces are not stripped.

     *
     *

     *
Examples

     *

     *   input
     *   wrapLength
     *   newLineString
     *   wrapLongWords
     *   result
     *

     *

     *   null
     *   *
     *   *
     *   true/false
     *   null
     *

     *

     *   ""
     *   *
     *   *
     *   true/false
     *   ""
     *

     *

     *   "Here is one line of text that is going to be wrapped after 20 columns."
     *   20
     *   "\n"
     *   true/false
     *   "Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
     *

     *

     *   "Here is one line of text that is going to be wrapped after 20 columns."
     *   20
     *   "<br />"
     *   true/false
     *   "Here is one line of<br />text that is going<br />to be wrapped after<br />20 columns."
     *

     *

     *   "Here is one line of text that is going to be wrapped after 20 columns."
     *   20
     *   null
     *   true/false
     *   "Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."
     *

     *

     *   "Click here to jump to the commons website - https://commons.apache.org"
     *   20
     *   "\n"
     *   false
     *   "Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"
     *

     *

     *   "Click here to jump to the commons website - https://commons.apache.org"
     *   20
     *   "\n"
     *   true
     *   "Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"
     *

     *

     *
     * @param str  the String to be word wrapped, may be null
     * @param wrapLength  the column to wrap the words at, less than 1 is treated as 1
     * @param newLineStr  the string to insert for a new line,
     *  {@code null} uses the system property line separator
     * @param wrapLongWords  true if long words (such as URLs) should be wrapped
     * @return a line with newlines inserted, {@code null} if null input
     */
    public static String wrap(final String str, final int wrapLength, final String newLineStr, final boolean wrapLongWords) {
        return wrap(str, wrapLength, newLineStr, wrapLongWords, " ");
    }

    /**
     *
Wraps a single line of text, identifying words by {@code wrapOn}.

     *
     *
Leading spaces on a new line are stripped.
     * Trailing spaces are not stripped.

     *
     *

     *
Examples

     *

     *   input
     *   wrapLength
     *   newLineString
     *   wrapLongWords
     *   wrapOn
     *   result
     *

     *

     *   null
     *   *
     *   *
     *   true/false
     *   *
     *   null
     *

     *

     *   ""
     *   *
     *   *
     *   true/false
     *   *
     *   ""
     *

     *

     *   "Here is one line of text that is going to be wrapped after 20 columns."
     *   20
     *   "\n"
     *   true/false
     *   " "
     *   "Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
     *

     *

     *   "Here is one line of text that is going to be wrapped after 20 columns."
     *   20
     *   "<br />"
     *   true/false
     *   " "
     *   "Here is one line of<br />text that is going<br />to be wrapped after<br />20 columns."
     *

     *

     *   "Here is one line of text that is going to be wrapped after 20 columns."
     *   20
     *   null
     *   true/false
     *   " "
     *   "Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."
     *

     *

     *   "Click here to jump to the commons website - https://commons.apache.org"
     *   20
     *   "\n"
     *   false
     *   " "
     *   "Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"
     *

     *

     *   "Click here to jump to the commons website - https://commons.apache.org"
     *   20
     *   "\n"
     *   true
     *   " "
     *   "Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"
     *

     *

     *   "flammable/inflammable"
     *   20
     *   "\n"
     *   true
     *   "/"
     *   "flammable\ninflammable"
     *

     *

     * @param str  the String to be word wrapped, may be null
     * @param wrapLength  the column to wrap the words at, less than 1 is treated as 1
     * @param newLineStr  the string to insert for a new line,
     *  {@code null} uses the system property line separator
     * @param wrapLongWords  true if long words (such as URLs) should be wrapped
     * @param wrapOn regex expression to be used as a breakable characters,
     *               if blank string is provided a space character will be used
     * @return a line with newlines inserted, {@code null} if null input
     */
    public static String wrap(final String str, int wrapLength, String newLineStr, final boolean wrapLongWords, String wrapOn) {
        if (str == null) {
            return null;
        }
        if (newLineStr == null) {
            newLineStr = System.lineSeparator();
        }
        if (wrapLength < 1) {
            wrapLength = 1;
        }
        if (StringUtils.isBlank(wrapOn)) {
            wrapOn = " ";
        }
        final Pattern patternToWrapOn = Pattern.compile(wrapOn);
        final int inputLineLength = str.length();
        int offset = 0;
        final StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32);

        while (offset < inputLineLength) {
            int spaceToWrapAt = -1;
            Matcher matcher = patternToWrapOn.matcher(
                str.substring(offset, Math.min((int) Math.min(Integer.MAX_VALUE, offset + wrapLength + 1L), inputLineLength)));
            if (matcher.find()) {
                if (matcher.start() == 0) {
                    offset += matcher.end();
                    continue;
                }
                spaceToWrapAt = matcher.start() + offset;
            }

            // only last line without leading spaces is left
            if (inputLineLength - offset <= wrapLength) {
                break;
            }

            while (matcher.find()) {
                spaceToWrapAt = matcher.start() + offset;
            }

            if (spaceToWrapAt >= offset) {
                // normal case
                wrappedLine.append(str, offset, spaceToWrapAt);
                wrappedLine.append(newLineStr);
                offset = spaceToWrapAt + 1;

            } else {
                // really long word or URL
                if (wrapLongWords) {
                    // wrap really long word one line at a time
                    wrappedLine.append(str, offset, wrapLength + offset);
                    wrappedLine.append(newLineStr);
                    offset += wrapLength;
                } else {
                    // do not wrap really long word, just extend beyond limit
                    matcher = patternToWrapOn.matcher(str.substring(offset + wrapLength));
                    if (matcher.find()) {
                        spaceToWrapAt = matcher.start() + offset + wrapLength;
                    }

                    if (spaceToWrapAt >= 0) {
                        wrappedLine.append(str, offset, spaceToWrapAt);
                        wrappedLine.append(newLineStr);
                        offset = spaceToWrapAt + 1;
                    } else {
                        wrappedLine.append(str, offset, str.length());
                        offset = inputLineLength;
                    }
                }
            }
        }

        // Whatever is left in line is short enough to just pass through
        wrappedLine.append(str, offset, str.length());

        return wrappedLine.toString();
    }

    // Capitalizing
    //-----------------------------------------------------------------------
    /**
     *
Capitalizes all the whitespace separated words in a String.
     * Only the first character of each word is changed. To convert the
     * rest of each word to lowercase at the same time,
     * use {@link #capitalizeFully(String)}.

     *
     *
Whitespace is defined by {@link Character#isWhitespace(char)}.
     * A {@code null} input String returns {@code null}.
     * Capitalization uses the Unicode title case, normally equivalent to
     * upper case.

     *
     *

     * WordUtils.capitalize(null)        = null
     * WordUtils.capitalize("")          = ""
     * WordUtils.capitalize("i am FINE") = "I Am FINE"
     *

     *
     * @param str  the String to capitalize, may be null
     * @return capitalized String, {@code null} if null String input
     * @see #uncapitalize(String)
     * @see #capitalizeFully(String)
     */
    public static String capitalize(final String str) {
        return capitalize(str, null);
    }

    /**
     *
Capitalizes all the delimiter separated words in a String.
     * Only the first character of each word is changed. To convert the
     * rest of each word to lowercase at the same time,
     * use {@link #capitalizeFully(String, char[])}.

     *
     *
The delimiters represent a set of characters understood to separate words.
     * The first string character and the first non-delimiter character after a
     * delimiter will be capitalized.

     *
     *
A {@code null} input String returns {@code null}.
     * Capitalization uses the Unicode title case, normally equivalent to
     * upper case.

     *
     *

     * WordUtils.capitalize(null, *)            = null
     * WordUtils.capitalize("", *)              = ""
     * WordUtils.capitalize(*, new char[0])     = *
     * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
     * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
     *

     *
     * @param str  the String to capitalize, may be null
     * @param delimiters  set of characters to determine capitalization, null means whitespace
     * @return capitalized String, {@code null} if null String input
     * @see #uncapitalize(String)
     * @see #capitalizeFully(String)
     * @since 2.1
     */
    public static String capitalize(final String str, final char... delimiters) {
        final int delimLen = delimiters == null ? -1 : delimiters.length;
        if (StringUtils.isEmpty(str) || delimLen == 0) {
            return str;
        }
        final char[] buffer = str.toCharArray();
        boolean capitalizeNext = true;
        for (int i = 0; i < buffer.length; i++) {
            final char ch = buffer[i];
            if (isDelimiter(ch, delimiters)) {
                capitalizeNext = true;
            } else if (capitalizeNext) {
                buffer[i] = Character.toTitleCase(ch);
                capitalizeNext = false;
            }
        }
        return new String(buffer);
    }

    //-----------------------------------------------------------------------
    /**
     *
Converts all the whitespace separated words in a String into capitalized words,
     * that is each word is made up of a titlecase character and then a series of
     * lowercase characters.

     *
     *
Whitespace is defined by {@link Character#isWhitespace(char)}.
     * A {@code null} input String returns {@code null}.
     * Capitalization uses the Unicode title case, normally equivalent to
     * upper case.

     *
     *

     * WordUtils.capitalizeFully(null)        = null
     * WordUtils.capitalizeFully("")          = ""
     * WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
     *

     *
     * @param str  the String to capitalize, may be null
     * @return capitalized String, {@code null} if null String input
     */
    public static String capitalizeFully(final String str) {
        return capitalizeFully(str, null);
    }

    /**
     *
Converts all the delimiter separated words in a String into capitalized words,
     * that is each word is made up of a titlecase character and then a series of
     * lowercase characters.

     *
     *
The delimiters represent a set of characters understood to separate words.
     * The first string character and the first non-delimiter character after a
     * delimiter will be capitalized.

     *
     *
A {@code null} input String returns {@code null}.
     * Capitalization uses the Unicode title case, normally equivalent to
     * upper case.

     *
     *

     * WordUtils.capitalizeFully(null, *)            = null
     * WordUtils.capitalizeFully("", *)              = ""
     * WordUtils.capitalizeFully(*, null)            = *
     * WordUtils.capitalizeFully(*, new char[0])     = *
     * WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
     *

     *
     * @param str  the String to capitalize, may be null
     * @param delimiters  set of characters to determine capitalization, null means whitespace
     * @return capitalized String, {@code null} if null String input
     * @since 2.1
     */
    public static String capitalizeFully(String str, final char... delimiters) {
        final int delimLen = delimiters == null ? -1 : delimiters.length;
        if (StringUtils.isEmpty(str) || delimLen == 0) {
            return str;
        }
        str = str.toLowerCase();
        return capitalize(str, delimiters);
    }

    //-----------------------------------------------------------------------
    /**
     *
Uncapitalizes all the whitespace separated words in a String.
     * Only the first character of each word is changed.

     *
     *
Whitespace is defined by {@link Character#isWhitespace(char)}.
     * A {@code null} input String returns {@code null}.

     *
     *

     * WordUtils.uncapitalize(null)        = null
     * WordUtils.uncapitalize("")          = ""
     * WordUtils.uncapitalize("I Am FINE") = "i am fINE"
     *

     *
     * @param str  the String to uncapitalize, may be null
     * @return uncapitalized String, {@code null} if null String input
     * @see #capitalize(String)
     */
    public static String uncapitalize(final String str) {
        return uncapitalize(str, null);
    }

    /**
     *
Uncapitalizes all the whitespace separated words in a String.
     * Only the first character of each word is changed.

     *
     *
The delimiters represent a set of characters understood to separate words.
     * The first string character and the first non-delimiter character after a
     * delimiter will be uncapitalized.

     *
     *
Whitespace is defined by {@link Character#isWhitespace(char)}.
     * A {@code null} input String returns {@code null}.

     *
     *

     * WordUtils.uncapitalize(null, *)            = null
     * WordUtils.uncapitalize("", *)              = ""
     * WordUtils.uncapitalize(*, null)            = *
     * WordUtils.uncapitalize(*, new char[0])     = *
     * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
     *

     *
     * @param str  the String to uncapitalize, may be null
     * @param delimiters  set of characters to determine uncapitalization, null means whitespace
     * @return uncapitalized String, {@code null} if null String input
     * @see #capitalize(String)
     * @since 2.1
     */
    public static String uncapitalize(final String str, final char... delimiters) {
        final int delimLen = delimiters == null ? -1 : delimiters.length;
        if (StringUtils.isEmpty(str) || delimLen == 0) {
            return str;
        }
        final char[] buffer = str.toCharArray();
        boolean uncapitalizeNext = true;
        for (int i = 0; i < buffer.length; i++) {
            final char ch = buffer[i];
            if (isDelimiter(ch, delimiters)) {
                uncapitalizeNext = true;
            } else if (uncapitalizeNext) {
                buffer[i] = Character.toLowerCase(ch);
                uncapitalizeNext = false;
            }
        }
        return new String(buffer);
    }

    //-----------------------------------------------------------------------
    /**
     *
Swaps the case of a String using a word based algorithm.

     *
     *

     *
Upper case character converts to Lower case

     *
Title case character converts to Lower case

     *
Lower case character after Whitespace or at start converts to Title case

     *
Other Lower case character converts to Upper case

     *

     *
     *
Whitespace is defined by {@link Character#isWhitespace(char)}.
     * A {@code null} input String returns {@code null}.

     *
     *

     * StringUtils.swapCase(null)                 = null
     * StringUtils.swapCase("")                   = ""
     * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
     *

     *
     * @param str  the String to swap case, may be null
     * @return the changed String, {@code null} if null String input
     */
    public static String swapCase(final String str) {
        if (StringUtils.isEmpty(str)) {
            return str;
        }
        final char[] buffer = str.toCharArray();

        boolean whitespace = true;

        for (int i = 0; i < buffer.length; i++) {
            final char ch = buffer[i];
            if (Character.isUpperCase(ch) || Character.isTitleCase(ch)) {
                buffer[i] = Character.toLowerCase(ch);
                whitespace = false;
            } else if (Character.isLowerCase(ch)) {
                if (whitespace) {
                    buffer[i] = Character.toTitleCase(ch);
                    whitespace = false;
                } else {
                    buffer[i] = Character.toUpperCase(ch);
                }
            } else {
                whitespace = Character.isWhitespace(ch);
            }
        }
        return new String(buffer);
    }

    //-----------------------------------------------------------------------
    /**
     *
Extracts the initial characters from each word in the String.

     *
     *
All first characters after whitespace are returned as a new string.
     * Their case is not changed.

     *
     *
Whitespace is defined by {@link Character#isWhitespace(char)}.
     * A {@code null} input String returns {@code null}.

     *
     *

     * WordUtils.initials(null)             = null
     * WordUtils.initials("")               = ""
     * WordUtils.initials("Ben John Lee")   = "BJL"
     * WordUtils.initials("Ben J.Lee")      = "BJ"
     *

     *
     * @param str  the String to get initials from, may be null
     * @return String of initial letters, {@code null} if null String input
     * @see #initials(String,char[])
     * @since 2.2
     */
    public static String initials(final String str) {
        return initials(str, null);
    }

    /**
     *
Extracts the initial characters from each word in the String.

     *
     *
All first characters after the defined delimiters are returned as a new string.
     * Their case is not changed.

     *
     *
If the delimiters array is null, then Whitespace is used.
     * Whitespace is defined by {@link Character#isWhitespace(char)}.
     * A {@code null} input String returns {@code null}.
     * An empty delimiter array returns an empty String.

     *
     *

     * WordUtils.initials(null, *)                = null
     * WordUtils.initials("", *)                  = ""
     * WordUtils.initials("Ben John Lee", null)   = "BJL"
     * WordUtils.initials("Ben J.Lee", null)      = "BJ"
     * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
     * WordUtils.initials(*, new char[0])         = ""
     *

     *
     * @param str  the String to get initials from, may be null
     * @param delimiters  set of characters to determine words, null means whitespace
     * @return String of initial characters, {@code null} if null String input
     * @see #initials(String)
     * @since 2.2
     */
    public static String initials(final String str, final char... delimiters) {
        if (StringUtils.isEmpty(str)) {
            return str;
        }
        if (delimiters != null && delimiters.length == 0) {
            return StringUtils.EMPTY;
        }
        final int strLen = str.length();
        final char[] buf = new char[strLen / 2 + 1];
        int count = 0;
        boolean lastWasGap = true;
        for (int i = 0; i < strLen; i++) {
            final char ch = str.charAt(i);

            if (isDelimiter(ch, delimiters)) {
                lastWasGap = true;
            } else if (lastWasGap) {
                buf[count++] = ch;
                lastWasGap = false;
            } else {
                continue; // ignore ch
            }
        }
        return new String(buf, 0, count);
    }

    //-----------------------------------------------------------------------
    /**
     *
Checks if the String contains all words in the given array.

     *
     *

     * A {@code null} String will return {@code false}. A {@code null}, zero
     * length search array or if one element of array is null will return {@code false}.
     *

     *
     *

     * WordUtils.containsAllWords(null, *)            = false
     * WordUtils.containsAllWords("", *)              = false
     * WordUtils.containsAllWords(*, null)            = false
     * WordUtils.containsAllWords(*, [])              = false
     * WordUtils.containsAllWords("abcd", "ab", "cd") = false
     * WordUtils.containsAllWords("abc def", "def", "abc") = true
     *

     *
     *
     * @param word The CharSequence to check, may be null
     * @param words The array of String words to search for, may be null
     * @return {@code true} if all search words are found, {@code false} otherwise
     * @since 3.5
     */
    public static boolean containsAllWords(final CharSequence word, final CharSequence... words) {
        if (StringUtils.isEmpty(word) || ArrayUtils.isEmpty(words)) {
            return false;
        }
        for (final CharSequence w : words) {
            if (StringUtils.isBlank(w)) {
                return false;
            }
            final Pattern p = Pattern.compile(".*\\b" + w + "\\b.*");
            if (!p.matcher(word).matches()) {
                return false;
            }
        }
        return true;
    }

    //-----------------------------------------------------------------------
    /**
     * Is the character a delimiter.
     *
     * @param ch  the character to check
     * @param delimiters  the delimiters
     * @return true if it is a delimiter
     */
    private static boolean isDelimiter(final char ch, final char[] delimiters) {
        if (delimiters == null) {
            return Character.isWhitespace(ch);
        }
        for (final char delimiter : delimiters) {
            if (ch == delimiter) {
                return true;
            }
        }
        return false;
    }

}


text:
namespace Gu.State
{
    internal abstract class PathItem
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
var http = require('http');
var express = require('express');

var printer = require('./printer');
shelljs = require('shelljs/global');
var nodeApp = express();
var settings = null;
var collection;
var api = [];

function Start() {
	nodeApp.listen(settings.port);
	printer.PrintOk('Server started on port: ' + settings.port);
	exec('midori -e Fullscreen --app=http://127.0.0.1:' + settings.port + '/', {silent: true, async:true});
}

function Stop() {

}

function Init(dataCollection, config) {
	settings = config;
	collection = dataCollection;
	registerParams();
	nodeApp.use(express.static(settings.staticPath));
	nodeApp.use('/data', express.static(settings.dataPath + '/www'));
	nodeApp.use('/img', express.static(settings.dataPath + '/img'));

	MapRoutes(nodeApp, initRoutes());
	nodeApp.get('/api', function(req, res) {
		res.send(api);
	});
}

module.exports = {
	createServer: Init,
	start: Start
};

function registerParams() {
	nodeApp.param('key', function(req, res, next, raw) {
		var pure = decodeURIComponent(raw.replace(/\+/g, ' '));
		req.loc = pure;
		next();
	});
	nodeApp.param('value', function(req, res, next, raw) {
		var pure = decodeURIComponent(raw.replace(/\+/g, ' '));
		req.loc = pure;
		next();
	});
	nodeApp.param('pid', function(req, res, next, pId) {
		var id;
		if (pId >= 0) {
			id = pId
		}
		req.pid = id;
		next();
	});
}

function initRoutes() {
	var programmes = {
		list: function(req, res) {
			res.send(collection.getAll());
		},
		getById: function(req, res) {
			res.send(collection.getAtKey(req.params.pid));
		},
		update: function(req, res) {
			res.send('Update programme ID: ' + req.pid);
		},
		delete: function(req, res) {
			res.send('Delete programme ID: ' + req.pid);
		},
		getByParam: function(req, res) {
			res.send(collection.getBy(req.params.key, req.loc));
		},
		getCats: function(req, res) {
			res.send(collection.getCategoryList());
		}
	};

	var routeMap = {
		'/programmes': {
			get: programmes.list,
			'/:pid': {
				get: programmes.getById,
				post: programmes.update,
				delete: programmes.delete
			},
			'/:key/:value': {
				get: programmes.getByParam
			}
		},
		'/categories': {
			get: programmes.getCats
		}
	};
	return routeMap;
}

function MapRoutes(app, a, route) {
	var key;
	route = route || '';
	for (key in a) {
		switch(typeof a[key]) {
			case 'object':
				MapRoutes(app, a[key], route + key);
				break;
			case 'function':
				api.push(key + ' ' + route);
				app[key](route, a[key]);
				break;
		}
	}
}


text:
> Thanks for your pull request, we really appreciate contributions!
>
> Please understand that it may take some time to be reviewed.
>
> Also, make sure to follow the [Contribution Guide](https://taskfile.dev/contributing/).


text:
namespace arrow {
namespace json {
namespace internal {

namespace rj = arrow::rapidjson;

class ObjectParser::Impl {
 public:
  Status Parse(arrow::util::string_view json) {
    document_.Parse(reinterpret_cast<const rj::Document::Ch*>(json.data()),
                    static_cast<size_t>(json.size()));

    if (document_.HasParseError()) {
      return Status::Invalid("Json parse error (offset ", document_.GetErrorOffset(),
                             "): ", document_.GetParseError());
    }
    if (!document_.IsObject()) {
      return Status::TypeError("Not a json object");
    }
    return Status::OK();
  }

  Result<std::string> GetString(const char* key) const {
    if (!document_.HasMember(key)) {
      return Status::KeyError("Key '", key, "' does not exist");
    }
    if (!document_[key].IsString()) {
      return Status::TypeError("Key '", key, "' is not a string");
    }
    return document_[key].GetString();
  }

  Result<bool> GetBool(const char* key) const {
    if (!document_.HasMember(key)) {
      return Status::KeyError("Key '", key, "' does not exist");
    }
    if (!document_[key].IsBool()) {
      return Status::TypeError("Key '", key, "' is not a boolean");
    }
    return document_[key].GetBool();
  }

 private:
  rj::Document document_;
};

ObjectParser::ObjectParser() : impl_(new ObjectParser::Impl()) {}

ObjectParser::~ObjectParser() = default;

Status ObjectParser::Parse(arrow::util::string_view json) { return impl_->Parse(json); }

Result<std::string> ObjectParser::GetString(const char* key) const {
  return impl_->GetString(key);
}

Result<bool> ObjectParser::GetBool(const char* key) const { return impl_->GetBool(key); }

}  // namespace internal
}  // namespace json
}  // namespace arrow


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['feedbackmoodlemessaging'] = 'Moodle boodskapdiens';
$string['feedbacknone'] = 'Niks';
$string['feedbackwebpage'] = 'Webblad';
$string['navigation'] = 'Navigasie';
$string['navigation_embed'] = 'Ingeboude webblad';
$string['navigation_frame'] = 'Moodle navigasie raamwerk';
$string['navigation_none'] = 'Niks';
$string['securityhdr'] = 'Sekuriteit beperkinge';


text:
package org.zaproxy.zap.extension.fuzz;

import javax.swing.JPanel;
import org.zaproxy.zap.extension.httppanel.Message;

public interface FuzzerMessageProcessorUIPanel<
        T1 extends Message,
        T2 extends FuzzerMessageProcessor<T1>,
        T3 extends FuzzerMessageProcessorUI<T1, T2>> {

    void init(T1 message);

    JPanel getComponent();

    void setFuzzerMessageProcessorUI(T3 payloadProcessorUI);

    T3 getFuzzerMessageProcessorUI();

    boolean validate();

    void clear();

    /**
     * Gets the 'target' to the help page of this payload generator panel. The 'target' must be
     * defined in the {@code map}'s help file. If there's no help available this method should
     * return {@code null}.
     *
     * <p>A help button is shown when the help is available.
     *
     * @return the 'target' to the help page of this payload generator panel, or {@code null} if no
     *     help page is available
     */
    String getHelpTarget();
}


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

/**
 * @fileoverview Controller for the conversation skin.
 */

// Note: This file should be assumed to be in an IIFE, and the constants below
// should only be used within this file.
var TIME_FADEOUT_MSEC = 100;
var TIME_HEIGHT_CHANGE_MSEC = 500;
var TIME_FADEIN_MSEC = 100;
var TIME_NUM_CARDS_CHANGE_MSEC = 500;

oppia.animation('.conversation-skin-responses-animate-slide', function() {
  return {
    removeClass: function(element, className, done) {
      if (className !== 'ng-hide') {
        done();
        return;
      }
      element.hide().slideDown(400, done);
    },
    addClass: function(element, className, done) {
      if (className !== 'ng-hide') {
        done();
        return;
      }
      element.slideUp(400, done);
    }
  };
});

oppia.animation('.conversation-skin-animate-tutor-card-on-narrow', function() {
  var tutorCardLeft, tutorCardWidth, tutorCardHeight, oppiaAvatarLeft;
  var tutorCardAnimatedLeft, tutorCardAnimatedWidth;

  var beforeAddClass = function(element, className, done) {
    if (className !== 'ng-hide') {
      done();
      return;
    }
    var tutorCard = element;
    var supplementalCard = $('.conversation-skin-supplemental-card-container');
    var oppiaAvatar = $('.conversation-skin-oppia-avatar.show-tutor-card');
    oppiaAvatarLeft = supplementalCard.position().left +
                      supplementalCard.width() - oppiaAvatar.width();
    tutorCardLeft = tutorCard.position().left;
    tutorCardWidth = tutorCard.width();
    tutorCardHeight = tutorCard.height();

    if (tutorCard.offset().left + tutorCardWidth > oppiaAvatar.offset().left) {
      var animationLength = Math.min(oppiaAvatarLeft - tutorCard.offset().left,
                                     tutorCardWidth);
      tutorCardAnimatedLeft = tutorCardLeft + animationLength;
      tutorCardAnimatedWidth = tutorCardWidth - animationLength;
    } else {
      tutorCardAnimatedLeft = oppiaAvatarLeft;
      tutorCardAnimatedWidth = 0;
    }

    oppiaAvatar.hide();
    tutorCard.css({
      'min-width': 0
    });
    tutorCard.animate({
      left: tutorCardAnimatedLeft,
      width: tutorCardAnimatedWidth,
      height: 0,
      opacity: 1
    }, 500, function() {
      oppiaAvatar.show();
      tutorCard.css({
        left: '',
        width: '',
        height: '',
        opacity: '',
        'min-width': ''
      });
      done();
    });
  };

  var removeClass = function(element, className, done) {
    if (className !== 'ng-hide') {
      done();
      return;
    }
    var tutorCard = element;
    $('.conversation-skin-oppia-avatar.show-tutor-card').hide(0, function() {
      tutorCard.css({
        left: tutorCardAnimatedLeft,
        width: tutorCardAnimatedWidth,
        height: 0,
        opacity: 0,
        'min-width': 0
      });
      tutorCard.animate({
        left: tutorCardLeft,
        width: tutorCardWidth,
        height: tutorCardHeight,
        opacity: 1
      }, 500, function() {
        tutorCard.css({
          left: '',
          width: '',
          height: '',
          opacity: '',
          'min-width': ''
        });
        done();
      });
    });
  };

  return {
    beforeAddClass: beforeAddClass,
    removeClass: removeClass
  };
});

oppia.animation('.conversation-skin-animate-cards', function() {
  // This removes the newly-added class once the animation is finished.
  var animateCards = function(element, className, done) {
    var tutorCardElt = jQuery(element).find(
      '.conversation-skin-main-tutor-card');
    var supplementalCardElt = jQuery(element).find(
      '.conversation-skin-supplemental-card-container');

    if (className === 'animate-to-two-cards') {
      var supplementalWidth = supplementalCardElt.width();
      supplementalCardElt.css({
        width: 0,
        'min-width': '0',
        opacity: '0'
      });
      supplementalCardElt.animate({
        width: supplementalWidth
      }, TIME_NUM_CARDS_CHANGE_MSEC, function() {
        supplementalCardElt.animate({
          opacity: '1'
        }, TIME_FADEIN_MSEC, function() {
          supplementalCardElt.css({
            width: '',
            'min-width': '',
            opacity: ''
          });
          jQuery(element).removeClass('animate-to-two-cards');
          done();
        });
      });

      return function(cancel) {
        if (cancel) {
          supplementalCardElt.css({
            width: '',
            'min-width': '',
            opacity: ''
          });
          supplementalCardElt.stop();
          jQuery(element).removeClass('animate-to-two-cards');
        }
      };
    } else if (className === 'animate-to-one-card') {
      supplementalCardElt.css({
        opacity: 0,
        'min-width': 0
      });
      supplementalCardElt.animate({
        width: 0
      }, TIME_NUM_CARDS_CHANGE_MSEC, function() {
        jQuery(element).removeClass('animate-to-one-card');
        done();
      });

      return function(cancel) {
        if (cancel) {
          supplementalCardElt.css({
            opacity: '',
            'min-width': '',
            width: ''
          });
          supplementalCardElt.stop();

          jQuery(element).removeClass('animate-to-one-card');
        }
      };
    } else {
      return;
    }
  };

  return {
    addClass: animateCards
  };
});

oppia.animation('.conversation-skin-animate-card-contents', function() {
  var animateCardChange = function(element, className, done) {
    if (className !== 'animate-card-change') {
      return;
    }

    var currentHeight = element.height();
    var expectedNextHeight = $(
      '.conversation-skin-future-tutor-card ' +
      '.conversation-skin-tutor-card-content'
    ).height();

    // Fix the current card height, so that it does not change during the
    // animation, even though its contents might.
    element.css('height', currentHeight);

    jQuery(element).animate({
      opacity: 0
    }, TIME_FADEOUT_MSEC).animate({
      height: expectedNextHeight
    }, TIME_HEIGHT_CHANGE_MSEC).animate({
      opacity: 1
    }, TIME_FADEIN_MSEC, function() {
      element.css('height', '');
      done();
    });

    return function(cancel) {
      if (cancel) {
        element.css('opacity', '1.0');
        element.css('height', '');
        element.stop();
      }
    };
  };

  return {
    addClass: animateCardChange
  };
});

oppia.directive('conversationSkin', [function() {
  return {
    restrict: 'E',
    scope: {},
    templateUrl: 'skins/Conversation',
    controller: [
      '$scope', '$timeout', '$rootScope', '$window', '$translate',
       'messengerService', 'oppiaPlayerService', 'urlService', 'focusService',
      'LearnerViewRatingService', 'windowDimensionsService',
      'playerTranscriptService', 'LearnerParamsService',
      'playerPositionService', 'explorationRecommendationsService',
      'StatsReportingService',
      function(
          $scope, $timeout, $rootScope, $window, $translate,
          messengerService, oppiaPlayerService, urlService, focusService,
          LearnerViewRatingService, windowDimensionsService,
          playerTranscriptService, LearnerParamsService,
          playerPositionService, explorationRecommendationsService,
          StatsReportingService) {
        $scope.CONTINUE_BUTTON_FOCUS_LABEL = 'continueButton';
        // The exploration domain object.
        $scope.exploration = null;

        // The minimum width, in pixels, needed to be able to show two cards
        // side-by-side.
        var TWO_CARD_THRESHOLD_PX = 960;
        var TIME_PADDING_MSEC = 250;
        var TIME_SCROLL_MSEC = 600;
        var MIN_CARD_LOADING_DELAY_MSEC = 950;
        var CONTENT_FOCUS_LABEL_PREFIX = 'content-focus-label-';

        var hasInteractedAtLeastOnce = false;
        var _answerIsBeingProcessed = false;
        var _nextFocusLabel = null;
        // This variable is used only when viewport is narrow.
        // Indicates whether the tutor card is displayed.
        var tutorCardIsDisplayedIfNarrow = true;

        $scope.explorationId = oppiaPlayerService.getExplorationId();
        $scope.isInPreviewMode = oppiaPlayerService.isInPreviewMode();
        $scope.isIframed = urlService.isIframed();
        $rootScope.loadingMessage = '加载中';
        $scope.hasFullyLoaded = false;
        $scope.recommendedExplorationSummaries = [];

        $scope.OPPIA_AVATAR_IMAGE_URL = '/images/avatar/oppia_black_72px.png';

        $scope.activeCard = null;
        $scope.numProgressDots = 0;
        $scope.arePreviousResponsesShown = false;

        $scope.upcomingStateName = null;
        $scope.upcomingContentHtml = null;
        $scope.upcomingInlineInteractionHtml = null;

        $scope.helpCardHtml = null;
        $scope.helpCardHasContinueButton = false;

        $scope.DEFAULT_TWITTER_SHARE_MESSAGE_PLAYER =
          GLOBALS.DEFAULT_TWITTER_SHARE_MESSAGE_PLAYER;

        $scope.profilePicture = '/images/avatar/user_blue_72px.png';
        oppiaPlayerService.getUserProfileImage().then(function(result) {
          $scope.profilePicture = result;
        });

        $scope.clearHelpCard = function() {
          $scope.helpCardHtml = null;
          $scope.helpCardHasContinueButton = false;
        };

        $scope.getContentFocusLabel = function(index) {
          return CONTENT_FOCUS_LABEL_PREFIX + index;
        };

        // If the exploration is iframed, send data to its parent about its
        // height so that the parent can be resized as necessary.
        $scope.lastRequestedHeight = 0;
        $scope.lastRequestedScroll = false;
        $scope.adjustPageHeight = function(scroll, callback) {
          $timeout(function() {
            var newHeight = document.body.scrollHeight;
            if (Math.abs($scope.lastRequestedHeight - newHeight) > 50.5 ||
                (scroll && !$scope.lastRequestedScroll)) {
              // Sometimes setting iframe height to the exact content height
              // still produces scrollbar, so adding 50 extra px.
              newHeight += 50;
              messengerService.sendMessage(messengerService.HEIGHT_CHANGE, {
                height: newHeight,
                scroll: scroll
              });
              $scope.lastRequestedHeight = newHeight;
              $scope.lastRequestedScroll = scroll;
            }

            if (callback) {
              callback();
            }
          }, 100);
        };

        $scope.isOnTerminalCard = function() {
          return $scope.activeCard &&
            $scope.exploration.isStateTerminal($scope.activeCard.stateName);
        };

        var isSupplementalCardNonempty = function(card) {
          return !$scope.exploration.isInteractionInline(card.stateName);
        };

        $scope.isCurrentSupplementalCardNonempty = function() {
          return $scope.activeCard && isSupplementalCardNonempty(
            $scope.activeCard);
        };

        // Navigates to the currently-active card, and resets the 'show previous
        // responses' setting.
        var _navigateToActiveCard = function() {
          var index = playerPositionService.getActiveCardIndex();
          $scope.activeCard = playerTranscriptService.getCard(index);
          $scope.arePreviousResponsesShown = false;
          $scope.clearHelpCard();
          tutorCardIsDisplayedIfNarrow = true;
          if (_nextFocusLabel && playerTranscriptService.isLastCard(index)) {
            focusService.setFocusIfOnDesktop(_nextFocusLabel);
          } else {
            focusService.setFocusIfOnDesktop(
              $scope.getContentFocusLabel(index));
          }
        };

        var animateToTwoCards = function(doneCallback) {
          $scope.isAnimatingToTwoCards = true;
          $timeout(function() {
            $scope.isAnimatingToTwoCards = false;
            if (doneCallback) {
              doneCallback();
            }
          }, TIME_NUM_CARDS_CHANGE_MSEC + TIME_FADEIN_MSEC + TIME_PADDING_MSEC);
        };

        var animateToOneCard = function(doneCallback) {
          $scope.isAnimatingToOneCard = true;
          $timeout(function() {
            $scope.isAnimatingToOneCard = false;
            if (doneCallback) {
              doneCallback();
            }
          }, TIME_NUM_CARDS_CHANGE_MSEC);
        };

        $scope.isCurrentCardAtEndOfTranscript = function() {
          return playerTranscriptService.isLastCard(
            playerPositionService.getActiveCardIndex());
        };
        var _addNewCard = function(
            stateName, newParams, contentHtml, interactionHtml) {
          playerTranscriptService.addNewCard(
            stateName, newParams, contentHtml, interactionHtml);

          if (newParams) {
            LearnerParamsService.init(newParams);
          }

          $scope.numProgressDots++;

          var totalNumCards = playerTranscriptService.getNumCards();

          var previousSupplementalCardIsNonempty = (
            totalNumCards > 1 &&
            isSupplementalCardNonempty(
              playerTranscriptService.getCard(totalNumCards - 2)));
          var nextSupplementalCardIsNonempty = isSupplementalCardNonempty(
            playerTranscriptService.getLastCard());

          if (totalNumCards > 1 && $scope.canWindowFitTwoCards() &&
              !previousSupplementalCardIsNonempty &&
              nextSupplementalCardIsNonempty) {
            playerPositionService.setActiveCardIndex(
                $scope.numProgressDots - 1);
            animateToTwoCards(function() {});
          } else if (
              totalNumCards > 1 && $scope.canWindowFitTwoCards() &&
              previousSupplementalCardIsNonempty &&
              !nextSupplementalCardIsNonempty) {
            animateToOneCard(function() {
              playerPositionService.setActiveCardIndex(
                $scope.numProgressDots - 1);
            });
          } else {
            playerPositionService.setActiveCardIndex(
              $scope.numProgressDots - 1);
          }

          if ($scope.exploration.isStateTerminal(stateName)) {
            explorationRecommendationsService.getRecommendedSummaryDicts(
              $scope.exploration.getAuthorRecommendedExpIds(stateName),
              function(summaries) {
                $scope.recommendedExplorationSummaries = summaries;
              });
          }
        };

        $scope.toggleShowPreviousResponses = function() {
          $scope.arePreviousResponsesShown = !$scope.arePreviousResponsesShown;
        };

        $scope.initializePage = function() {
          $scope.waitingForOppiaFeedback = false;
          hasInteractedAtLeastOnce = false;
          $scope.recommendedExplorationSummaries = [];

          playerPositionService.init(_navigateToActiveCard);
          oppiaPlayerService.init(function(exploration, initHtml, newParams) {
            $scope.exploration = exploration;

            $scope.isLoggedIn = oppiaPlayerService.isLoggedIn();
            _nextFocusLabel = focusService.generateFocusLabel();

            _addNewCard(
              exploration.initStateName,
              newParams,
              initHtml,
              oppiaPlayerService.getInteractionHtml(
                exploration.initStateName, _nextFocusLabel));
            $rootScope.loadingMessage = '';
            $scope.hasFullyLoaded = true;

            // If the exploration is embedded, use the exploration language
            // as site language. If the exploration language is not supported
            // as site language, English is used as default.
            if ($scope.isIframed) {
              var explorationLanguageCode = (
                oppiaPlayerService.getExplorationLanguageCode());
              if ($window.GLOBALS.SUPPORTED_SITE_LANGUAGES[
                    explorationLanguageCode]) {
                $translate.use(explorationLanguageCode);
              } else {
                $translate.use('en');
              }
            }
            $scope.adjustPageHeight(false, null);
            $window.scrollTo(0, 0);
            focusService.setFocusIfOnDesktop(_nextFocusLabel);
          });
        };

        $scope.submitAnswer = function(answer, interactionRulesService) {
          // For some reason, answers are getting submitted twice when the
          // submit button is clicked. This guards against that.
          if (_answerIsBeingProcessed ||
              !$scope.isCurrentCardAtEndOfTranscript() ||
              $scope.activeCard.destStateName) {
            return;
          }

          $scope.clearHelpCard();

          _answerIsBeingProcessed = true;
          hasInteractedAtLeastOnce = true;
          $scope.waitingForOppiaFeedback = true;

          var _oldStateName = playerTranscriptService.getLastCard().stateName;
          playerTranscriptService.addNewAnswer(answer);

          var timeAtServerCall = new Date().getTime();

          oppiaPlayerService.submitAnswer(
            answer, interactionRulesService, function(
                newStateName, refreshInteraction, feedbackHtml, contentHtml,
                newParams) {
              // Do not wait if the interaction is supplemental -- there's
              // already a delay bringing in the help card.
              var millisecsLeftToWait = (
                !$scope.exploration.isInteractionInline(_oldStateName) ? 1.0 :
                Math.max(MIN_CARD_LOADING_DELAY_MSEC - (
                  new Date().getTime() - timeAtServerCall),
                1.0));

              $timeout(function() {
                $scope.waitingForOppiaFeedback = false;
                var pairs = (
                  playerTranscriptService.getLastCard().answerFeedbackPairs);
                var lastAnswerFeedbackPair = pairs[pairs.length - 1];

                if (_oldStateName === newStateName) {
                  // Stay on the same card.
                  playerTranscriptService.addNewFeedback(feedbackHtml);
                  if (feedbackHtml &&
                      !$scope.exploration.isInteractionInline(
                        $scope.activeCard.stateName)) {
                    $scope.helpCardHtml = feedbackHtml;
                  }
                  if (refreshInteraction) {
                    // Replace the previous interaction with another of the
                    // same type.
                    _nextFocusLabel = focusService.generateFocusLabel();
                    playerTranscriptService.updateLatestInteractionHtml(
                      oppiaPlayerService.getInteractionHtml(
                        newStateName, _nextFocusLabel) +
                      oppiaPlayerService.getRandomSuffix());
                  }
                  focusService.setFocusIfOnDesktop(_nextFocusLabel);
                  scrollToBottom();
                } else {
                  // There is a new card. If there is no feedback, move on
                  // immediately. Otherwise, give the learner a chance to read
                  // the feedback, and display a 'Continue' button.

                  _nextFocusLabel = focusService.generateFocusLabel();

                  playerTranscriptService.setDestination(newStateName);

                  // These are used to compute the dimensions for the next card.
                  $scope.upcomingStateName = newStateName;
                  $scope.upcomingParams = newParams;
                  $scope.upcomingContentHtml = (
                    contentHtml + oppiaPlayerService.getRandomSuffix());
                  var _isNextInteractionInline = (
                    $scope.exploration.isInteractionInline(newStateName));
                  $scope.upcomingInlineInteractionHtml = (
                    _isNextInteractionInline ?
                    oppiaPlayerService.getInteractionHtml(
                      newStateName, _nextFocusLabel
                    ) + oppiaPlayerService.getRandomSuffix() : '');

                  if (feedbackHtml) {
                    playerTranscriptService.addNewFeedback(feedbackHtml);

                    if (!$scope.exploration.isInteractionInline(
                          $scope.activeCard.stateName)) {
                      $scope.helpCardHtml = feedbackHtml;
                      $scope.helpCardHasContinueButton = true;
                    }

                    _nextFocusLabel = $scope.CONTINUE_BUTTON_FOCUS_LABEL;
                    focusService.setFocusIfOnDesktop(_nextFocusLabel);
                    scrollToBottom();
                  } else {
                    playerTranscriptService.addNewFeedback(feedbackHtml);
                    $scope.showPendingCard(
                      newStateName,
                      newParams,
                      contentHtml + oppiaPlayerService.getRandomSuffix());
                  }
                }

                _answerIsBeingProcessed = false;
              }, millisecsLeftToWait);
            }
          );
        };
        $scope.startCardChangeAnimation = false;
        $scope.showPendingCard = function(
            newStateName, newParams, newContentHtml) {
          $scope.startCardChangeAnimation = true;

          $timeout(function() {
            var newInteractionHtml = oppiaPlayerService.getInteractionHtml(
              newStateName, _nextFocusLabel);
            // Note that newInteractionHtml may be null.
            if (newInteractionHtml) {
              newInteractionHtml += oppiaPlayerService.getRandomSuffix();
            }

            _addNewCard(
              newStateName, newParams, newContentHtml, newInteractionHtml);

            $scope.upcomingStateName = null;
            $scope.upcomingParams = null;
            $scope.upcomingContentHtml = null;
            $scope.upcomingInlineInteractionHtml = null;
          }, TIME_FADEOUT_MSEC + 0.1 * TIME_HEIGHT_CHANGE_MSEC);

          $timeout(function() {
            focusService.setFocusIfOnDesktop(_nextFocusLabel);
            scrollToTop();
          },
          TIME_FADEOUT_MSEC + TIME_HEIGHT_CHANGE_MSEC + 0.5 * TIME_FADEIN_MSEC);

          $timeout(function() {
            $scope.startCardChangeAnimation = false;
          },
          TIME_FADEOUT_MSEC + TIME_HEIGHT_CHANGE_MSEC + TIME_FADEIN_MSEC +
          TIME_PADDING_MSEC);
        };

        var scrollToBottom = function() {
          $timeout(function() {
            var tutorCard = $('.conversation-skin-main-tutor-card');

            if (tutorCard.length === 0) {
              return;
            }
            var tutorCardBottom = (
              tutorCard.offset().top + tutorCard.outerHeight());
            if ($(window).scrollTop() + $(window).height() < tutorCardBottom) {
              $('html, body').animate({
                scrollTop: tutorCardBottom - $(window).height() + 12
              }, {
                duration: TIME_SCROLL_MSEC,
                easing: 'easeOutQuad'
              });
            }
          }, 100);
        };

        var scrollToTop = function() {
          $timeout(function() {
            $('html, body').animate({
              scrollTop: 0
            }, 800, 'easeOutQuart');
            return false;
          });
        };

        $scope.submitUserRating = function(ratingValue) {
          LearnerViewRatingService.submitUserRating(ratingValue);
        };
        $scope.$on('ratingUpdated', function() {
          $scope.userRating = LearnerViewRatingService.getUserRating();
        });

        $window.addEventListener('beforeunload', function(e) {
          if (hasInteractedAtLeastOnce && !$scope.isInPreviewMode &&
              !$scope.exploration.isStateTerminal(
                playerTranscriptService.getLastCard().stateName)) {
            StatsReportingService.recordMaybeLeaveEvent(
              playerTranscriptService.getLastStateName(),
              LearnerParamsService.getAllParams());
            var confirmationMessage = (
              'If you navigate away from this page, your progress on the ' +
              'exploration will be lost.');
            (e || $window.event).returnValue = confirmationMessage;
            return confirmationMessage;
          }
        });

        $scope.windowWidth = windowDimensionsService.getWidth();
        $window.onresize = function() {
          $scope.adjustPageHeight(false, null);
          $scope.windowWidth = windowDimensionsService.getWidth();
        };

        $window.addEventListener('scroll', function() {
          fadeDotsOnScroll();
          fixSupplementOnScroll();
        });

        var fadeDotsOnScroll = function() {
          var progressDots = $('.conversation-skin-progress-dots');
          var progressDotsTop = progressDots.height();
          var newOpacity = Math.max(
            (progressDotsTop - $(window).scrollTop()) / progressDotsTop, 0);
          progressDots.css({
            opacity: newOpacity
          });
        };

        var fixSupplementOnScroll = function() {
          var supplementCard = $('div.conversation-skin-supplemental-card');
          var topMargin = $('.navbar-container').height() - 20;
          if ($(window).scrollTop() > topMargin) {
            supplementCard.addClass(
              'conversation-skin-supplemental-card-fixed');
          } else {
            supplementCard.removeClass(
              'conversation-skin-supplemental-card-fixed');
          }
        };

        $scope.canWindowFitTwoCards = function() {
          return $scope.windowWidth >= TWO_CARD_THRESHOLD_PX;
        };

        $scope.isViewportNarrow = function() {
          return $scope.windowWidth < TWO_CARD_THRESHOLD_PX;
        };

        $scope.isWindowTall = function() {
          return document.body.scrollHeight > $window.innerHeight;
        };

        $scope.isScreenNarrowAndShowingTutorCard = function() {
          if (!$scope.isCurrentSupplementalCardNonempty()) {
            return $scope.isViewportNarrow();
          }
          return $scope.isViewportNarrow() &&
                 tutorCardIsDisplayedIfNarrow;
        };

        $scope.isScreenNarrowAndShowingSupplementalCard = function() {
          return $scope.isViewportNarrow() &&
                 !tutorCardIsDisplayedIfNarrow;
        };

        $scope.showTutorCardIfScreenIsNarrow = function() {
          if ($scope.isViewportNarrow()) {
            tutorCardIsDisplayedIfNarrow = true;
          }
        };

        $scope.showSupplementalCardIfScreenIsNarrow = function() {
          if ($scope.isViewportNarrow()) {
            tutorCardIsDisplayedIfNarrow = false;
          }
        };

        $scope.initializePage();
        LearnerViewRatingService.init(function(userRating) {
          $scope.userRating = userRating;
        });

        $scope.collectionId = GLOBALS.collectionId;
        $scope.collectionTitle = GLOBALS.collectionTitle;
      }
    ]
  };
}]);


text:
package uwp.cs.edu.parkingtracker;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

import uwp.cs.edu.parkingtracker.mapping.MapTransform;
import uwp.cs.edu.parkingtracker.parking.ParkDialogFragment;
import uwp.cs.edu.parkingtracker.parking.ParkingSpotDialogFragment;
import uwp.cs.edu.parkingtracker.parking.ZoneService;

/**
 * Created by Nate Eisner on 4/14/15.
 */
public class MainActivity extends ActionBarActivity implements LocationListener {
    //variables
    private ProgressBar progress;
    private MapTransform mapTransform = null;
    private final int SERVICE_DELAY = 5000;
//    private final int TIMEOUT = 45000;
//    private ListView mDrawerList;
//    private DrawerLayout mDrawerLayout;
//    private ArrayAdapter<String> mAdapter;
//    private ActionBarDrawerToggle mDrawerToggle;
    private String mActivityTitle;
    private ActionBar actionBar;
//    private String[] drawerItems;
    private SharedPreferences preferences;
    private boolean loadComplete;
    private Intent mServiceIntent = null;
    private ProgressDialog pD;
    private Menu actionBarMenu;
    protected LocationManager locationManager;
//    private SlidingUpPanelLayout slidingUpPanel;
    private ThisApp thisApp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            setupTools();
            return;
        }
        setContentView(R.layout.activity_main);
        thisApp = (ThisApp) getApplication();
        thisApp.setMain(this);

        //progress dialog for initial loading
        pD = new ProgressDialog(this, R.style.TransparentProgressDialog);
        pD.setIndeterminate(true);
        pD.setCancelable(false);
        pD.show();
        //get prefs for roles
        preferences = getSharedPreferences(CONSTANTS.PREFS_NAME, 0);
        //set up different parts
        setupGoogleAnalytics();
        setupTools();
//        setupBottomPanel();
        //create map
        if (mapTransform == null) {
            mapTransform = new MapTransform(MainActivity.this);
            mapTransform.setUpMap();
        }
        //location manager
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager != null) {
            locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 6000, 10, this);
        }
//        slidingUpPanel = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!loadComplete && mServiceIntent != null) {
            stopService(mServiceIntent);
        }
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Unregister the listener when the application is paused
        //LocalBroadcastManager.getInstance(this).unregisterReceiver(loadingStatus);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Register for the particular broadcast based on ACTION string
        IntentFilter filter = new IntentFilter(ZoneService.ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(loadingStatus, filter);
        if (mapTransform == null) {
            mapTransform = new MapTransform(MainActivity.this);
            mapTransform.setUpMap();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(loadingStatus);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
//        mDrawerToggle.syncState();
        Log.i("drawer", "onpostcreate");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        mDrawerToggle.onConfigurationChanged(newConfig);
        Log.i("drawer", "onconfigchange");
    }

    //assign options menu to bar menu object
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        actionBarMenu = menu;
//        if (mapTransform.isPathDrawn()) {
//            actionBarMenu.findItem(R.id.action_cancel).setVisible(true);
//        } else {
//            actionBarMenu.findItem(R.id.action_cancel).setVisible(false);
//        }
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            actionBarMenu.findItem(R.id.action_park).setVisible(true);
        } else if (locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

            actionBarMenu.findItem(R.id.action_park).setVisible(true);
        } else {
            //location is not working
            actionBarMenu.findItem(R.id.action_park).setVisible(false);
        }
        return true;
    }

    //when an option item is selected
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        handleMenuItem(item);

        // Activate the navigation drawer toggle
//        if (mDrawerToggle.onOptionsItemSelected(item)) {
//            return true;
//        }

        return super.onOptionsItemSelected(item);
    }

    //all google analytics should be set here
    private void setupGoogleAnalytics() {
        // Google Analytics

        // Get tracker.
        Tracker t = thisApp.getTracker();

        // Set screen name.
        t.setScreenName("Main");

        // Send a screen view.
        t.send(new HitBuilders.ScreenViewBuilder()
                .setNewSession()
                .build());
    }

    //shows parkdialogfragment
    public void showParkDialogFragment(String zID) {
        ParkDialogFragment parkDialogFragment = new ParkDialogFragment();
        parkDialogFragment.setzID(zID);
        parkDialogFragment.show(getSupportFragmentManager(), "map");
    }

    //handles and changes from a menu item selected
    private boolean handleMenuItem(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
//            case R.id.action_cancel:
//                mapTransform.clearPath();
//                setCancelItem(false);
//                return true;
            case R.id.action_park:
                ParkingSpotDialogFragment dia = new ParkingSpotDialogFragment();
                dia.setMapTransform(mapTransform);
                dia.show(getFragmentManager(), "Diag");
                return true;
//            case R.id.action_student:
//                modifyDrawerItems("student");
//                return true;
//            case R.id.action_visitor:
//                modifyDrawerItems("visitor");
//                return true;
        }

        return false;
    }

    //setup toolbar draw
    public void setupTools() {
        progress = (ProgressBar) findViewById(R.id.loadingProgress);
        if (progress != null) {
            progress.setMax(CONSTANTS.zones.size());
            progress.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            progress.getProgressDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
        }
//        mDrawerList = (ListView) findViewById(R.id.navList);
//        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        mActivityTitle = getTitle().toString();

//        setupDrawer();
        // get role for drawer customization
        String role = preferences.getString("role", "");
//        modifyDrawerItems(role);
        actionBar = getSupportActionBar();
//        actionBar.setDisplayHomeAsUpEnabled(true);
//        actionBar.setHomeButtonEnabled(true);
    }

    //sets up side drawer
//    private void setupDrawer() {
//        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
//
//            /** Called when a drawer has settled in a completely open state. */
//            public void onDrawerOpened(View drawerView) {
//                super.onDrawerOpened(drawerView);
//                actionBar.setTitle("Links");
//                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
//            }
//
//            /** Called when a drawer has settled in a completely closed state. */
//            public void onDrawerClosed(View view) {
//                super.onDrawerClosed(view);
//                actionBar.setTitle(mActivityTitle);
//                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
//            }
//        };
//
//        mDrawerToggle.setDrawerIndicatorEnabled(true);
//        mDrawerLayout.setDrawerListener(mDrawerToggle);
//    }

//    //change items to drawer based off of role.
//    private void modifyDrawerItems(String role) {
//        //STUDENT ROLE
//        if (role.equals("student")) {
//            drawerItems = new String[]{"uwp.edu", "D2L", "SOLAR", "Campus Connect"};
//        }
//        if (role.equals("visitor")) {
//            //TODO: CHANGE LINKS BASED OFF OF VISITOR
//            drawerItems = new String[]{"Information", "uwp.edu", "Events", "Admissions"};
//        }
//        mAdapter = new ArrayAdapter<>(this, R.layout.color_textview, drawerItems);
//        mDrawerList.setAdapter(mAdapter);
//
//        //for handling links in the side drawer
//        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                //Toast.makeText(MainActivity.this, "Link", Toast.LENGTH_SHORT).show();
//                switch (drawerItems[position]) {
//                    case "D2L":
//                        openUrl("https://uwp.courses.wisconsin.edu/Shibboleth.sso/Login?target=https://uwp.courses.wisconsin.edu/d2l/shibbolethSSO/deepLinkLogin.d2l");
//                        break;
//                    case "SOLAR":
//                        openUrl("https://solar.uwp.edu/solar/signon.html");
//                        break;
//                    case "Campus Connect":
//                        openUrl("https://campusconnect.uwp.edu/");
//                        break;
//                    case "uwp.edu":
//                        openUrl("http://www.uwp.edu/");
//                        break;
//                    case "Events":
//                        openUrl("http://www.uwp.edu/events.cfm");
//                        break;
//                    case "Information":
//                        openUrl("http://www.uwp.edu/explore/aboutuwp/index.cfm");
//                        break;
//                    case "Admissions":
//                        openUrl("http://www.uwp.edu/apply/admissions/index.cfm");
//                        break;
//                }
//            }
//        });
//    }

//    //setup the bottom panel
//    private void setupBottomPanel() {
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                //hide bottom sliding panel
//                SlidingUpPanelLayout sUPL = ((SlidingUpPanelLayout)
//                        findViewById(R.id.sliding_layout));
//                //sUPL.setVisibility(View.GONE);
//                sUPL.setPanelState(SlidingUpPanelLayout.PanelState.HIDDEN);
//            }
//        }, 1000);
//    }

//    //used to launch new browser intent with given url
//    private void openUrl(String url) {
//        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//        startActivity(browserIntent);
//    }

    public boolean isLoadingComplete() {
        return loadComplete;
    }

    //receiver to get loading status and loading amount
    private BroadcastReceiver loadingStatus = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //gets status of loading
            loadComplete = intent.getBooleanExtra(CONSTANTS.DATA_STATUS, true);
            if (!loadComplete) {
                if (progress != null) {
                    progress.setVisibility(View.VISIBLE);
                    progress.setIndeterminate(false);
                    //gets amount of zones loaded
                    int status = intent.getIntExtra(CONSTANTS.DATA_AMOUNT, 0);
                    progress.setProgress(status);
                }
            }
        }
    };

    //ran when service loading complete
    public void loadingComplete() {
        loadComplete = true;
        progress.setProgress(0);
        progress.setIndeterminate(false);
        if (pD.isShowing()) {
            pD.dismiss();
        }
        mapTransform.refreshMap();

        // Timer
        final Handler timerHandler = new Handler();
        //server refresh timer
        Runnable timerRunnable = new Runnable() {
            @Override
            public void run() {
                serviceRunner();
                return;
            }
        };
        //start service loop
        timerHandler.postDelayed(timerRunnable, SERVICE_DELAY);
    }

//    //shows cancel button in the actionbar
//    public void setCancelItem(boolean option) {
//        actionBarMenu.findItem(R.id.action_cancel).setVisible(option);
//        //    invalidateOptionsMenu();
//    }

    @Override
    public void onBackPressed() {
        //Handle the back button
        //if the sliding is open
//        if (slidingUpPanel.getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED || slidingUpPanel.getPanelState() == SlidingUpPanelLayout.PanelState.ANCHORED) {
//            slidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
//        } else {
            //Ask the user if they want to quit
            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Exit")
                    .setMessage("Do you wish to exit?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //Stop the activity
                            MainActivity.this.finish();
                            System.exit(0);
                        }
                    })
                    .setNegativeButton("No", null)
                    .show();
//        }
    }

    @Override
    public void onLocationChanged(Location location) {
        //do nothing
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        //status of gps changed
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 10000,
                    1, this);
            actionBarMenu.findItem(R.id.action_park).setVisible(true);
        } else if (locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 10000,
                    1, this);
            actionBarMenu.findItem(R.id.action_park).setVisible(true);
        } else {
            //location is not working
            Toast.makeText(getApplicationContext(), "Please Check Location", Toast.LENGTH_LONG).show();
            actionBarMenu.findItem(R.id.action_park).setVisible(false);
        }
    }

    @Override
    public void onProviderEnabled(String provider) {
        //location is enabled
        actionBarMenu.findItem(R.id.action_park).setVisible(true);
    }

    @Override
    public void onProviderDisabled(String provider) {
        //location is disabled
        Toast.makeText(getApplicationContext(), "Please Enable Location", Toast.LENGTH_LONG).show();
        if (actionBarMenu != null) {
            actionBarMenu.findItem(R.id.action_park).setVisible(false);
        }
    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    public void serviceRunner() {
        Intent mServiceIntent = new Intent(getApplicationContext(), ZoneService.class);
        mServiceIntent.addCategory(ZoneService.TAG);
        final Handler timeOutHandler = new Handler();
//        Runnable timeOut = new Runnable() {
//            @Override
//            public void run() {
//                if (isMyServiceRunning(ZoneService.class)) {
//                    //service is taking too long
//                    if (pD.isShowing()) {
//                        pD.dismiss();
//                    }
//                    Toast.makeText(getApplicationContext(), "Network Connection Poor", Toast.LENGTH_LONG).show();
//                }
//                return;
//            }
//        };
        mServiceIntent.addCategory(ZoneService.TAG);
        startService(mServiceIntent);
//        timeOutHandler.postDelayed(timeOut, TIMEOUT);
    }
}


text:
namespace TravelShare.Services.Data
{
    using System.Linq;
    using Bytes2you.Validation;
    using TravelShare.Common;
    using TravelShare.Data.Common;
    using TravelShare.Data.Common.Contracts;
    using TravelShare.Data.Models;
    using TravelShare.Services.Data.Common.Contracts;

    public class CityService : ICityService
    {
        private const string CityNameNullExceptionMessage = "city name cannot be null";
        private readonly IEfDbRepository<City> cityRepository;

        private readonly IApplicationDbContextSaveChanges dbSaveChanges;

        public CityService(IEfDbRepository<City> cityRepository, IApplicationDbContextSaveChanges dbSaveChanges)
        {
            Guard.WhenArgument(cityRepository, GlobalConstants.CityRepositoryNullExceptionMessage).IsNull().Throw();
            Guard.WhenArgument<IApplicationDbContextSaveChanges>(dbSaveChanges, GlobalConstants.DbContextSaveChangesNullExceptionMessage)
               .IsNull()
               .Throw();
            this.cityRepository = cityRepository;
            this.dbSaveChanges = dbSaveChanges;
        }

        public City Create(string name)
        {
            Guard.WhenArgument(name, CityNameNullExceptionMessage).IsNullOrEmpty().Throw();

            // TODO : CityFactory
            var city = new City { Name = name };
            this.cityRepository.Add(city);
            this.dbSaveChanges.SaveChanges();
            return city;
        }

        public City GetCityByName(string name)
        {
            Guard.WhenArgument(name, CityNameNullExceptionMessage).IsNullOrEmpty().Throw();
            return this.cityRepository.All().Where(x => x.Name == name).FirstOrDefault();
        }
    }
}


text:
'use strict';

class User {
	constructor(socket) {
		this.socket = socket;
		socket.user = this;
		this.guestNum = User.guestNumGenerator.next().value;
		this.generateId();
		this.ips = [socket.remoteAddress];
		this.currentIp = socket.remoteAddress;
		this.bacteriaPrototype = {owner: this};
		this.defaultProto();
	}

	setName(name) {
		this.name = '' + name;
		if(!name) {
			this.name = 'Guest ' + this.guestNum;
		}
	}

	defaultProto() {
		this.bacteriaPrototype.genetics = this.bacteriaPrototype.genetics || {fertility: 3, solitude: 1, overpopulation: 4, color: '#000'};
		this.bacteriaPrototype.pattern = this.bacteriaPrototype.pattern || [{x: 2, y: 1}, {x: 2, y: 2}, {x: 2, y: 3}];
	}

	generateId() {
		let text = '' + this.name;
		this.id = text.toLowerCase().replace(/[^a-z0-9]+/g, '');
	}

	usePrototype(proto = {}) {
		proto.owner = this;
		this.bacteriaPrototype = proto;
		this.defaultProto();
	}

	send(message) {
		if (!message || !this.socket) return;
		return this.socket.write(message);
	}

	destroy() {
		delete this.socket.user;
		this.socket.close();
		delete this.socket;
	}
}

// TODO: ¿Una manera que no requiera de un generador en un static, sin requerir de dependencias externas?
User.guestNumGenerator = (function* () {
	let guestNum = 0;
	while (true) {
		let reset = yield ++guestNum;
		if (reset) guestNum = 0;
	}
})();

module.exports = User;


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

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.trino.spi.connector.ColumnHandle;
import io.trino.spi.connector.ColumnMetadata;
import io.trino.spi.connector.ConnectorTableMetadata;
import org.openjdk.jol.info.ClassLayout;

import java.util.Map;

import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static io.airlift.slice.SizeOf.estimatedSizeOf;
import static java.util.Objects.requireNonNull;

public class SystemColumnHandle
        implements ColumnHandle
{
    private static final int INSTANCE_SIZE = ClassLayout.parseClass(SystemColumnHandle.class).instanceSize();

    private final String columnName;

    @JsonCreator
    public SystemColumnHandle(
            @JsonProperty("columnName") String columnName)
    {
        this.columnName = requireNonNull(columnName, "columnName is null");
    }

    @JsonProperty
    public String getColumnName()
    {
        return columnName;
    }

    @Override
    public int hashCode()
    {
        return columnName.hashCode();
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        SystemColumnHandle other = (SystemColumnHandle) obj;
        return columnName.equals(other.columnName);
    }

    @Override
    public String toString()
    {
        return columnName;
    }

    public long getRetainedSizeInBytes()
    {
        return INSTANCE_SIZE
                + estimatedSizeOf(columnName);
    }

    public static Map<String, ColumnHandle> toSystemColumnHandles(ConnectorTableMetadata tableMetadata)
    {
        return tableMetadata.getColumns().stream().collect(toImmutableMap(
                ColumnMetadata::getName,
                column -> new SystemColumnHandle(column.getName())));
    }
}


text:
<?php
/**
 * CategoryRepository.php
 *
 * @since 02/09/14
 * @author Gerhard Seidel <gseidel.message@googlemail.com>
 */

namespace Enhavo\Bundle\CategoryBundle\Repository;

use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;

class CategoryRepository extends EntityRepository
{
    /**
     * @param $name
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function getByCollectionQuery($name)
    {
        if($name) {
            return $this->createQueryBuilder('u')
                ->leftJoin('u.collection', 'r')
                ->where('r.name = ?1')
                ->setParameter(1, $name);
        } else {
            return $this->createQueryBuilder('u');
        }
    }

    /**
     * @param $criteria
     * @return array|\Pagerfanta\Pagerfanta
     */
    public function findByCollection($criteria)
    {
        if(is_string($criteria)) {
            $collectionName = $criteria;
        } elseif(!isset($criteria['collection'])) {
            throw new \InvalidArgumentException(
                'CategoryRepository called with findByCollection but no collection name was passed. Use an array like [\'collection\' => \'collectionName\'] or pass name directly'
            );
        } else {
            $collectionName = $criteria['collection'];
        }

        $query = $this->getByCollectionQuery($collectionName);
        if(isset($criteria['paging']) && $criteria['paging']) {
            return $this->getPaginator($query);
        }
        return $query->getQuery()->getResult();
    }
}


text:
<?php
	function calculateScores($activities, $conditions)
	{
		$weightings = Array(
			new Weighting(0, 0, 0),
			new Weighting(1, 1, 0.5),
			new Weighting(-0.5, 0, 0.5),
			new Weighting(0.5, 1, 1),
			new Weighting(0, 1, 0.2)
		);

		$activitiesLength = sizeOf($activities);

		for ($i = 0; $i < activitiesLength; $i++)
		{
			$activities[$i]->score = 0;
			$activities[$i]->score += $weightings[$activities[$i]->type]->condition * getConditionNumber($conditions->weather->condition);
			$activities[$i]->score += $weightings[$activities[$i]->type]->temperature * $conditions->weather->temperature;
			$activities[$i]->score += $weightings[$activities[$i]->type]->precipitation * $conditions->weather->precipitation;

			$activities[$i]->score += $weightings[$activities[$i]->type]->distance * (1 - $activities[$i]->distance);
		}

		return $activities;
	}

	function getConditionNumber($condition)
	{
		if ($condition == "sun")
		{
			return 1;
		}
		else if ($condition == "cloud")
		{
			return 0.5;
		}
		else
		{
			return 0;
		}
	}

	class Weighting
	{
		public $condition;
		public $temperature;
		public $precipitation;
		public $_time;
		public $distance;

		function __construct($weather, $_time, $distance)
		{
			$this->condition = $weather / 3;
			$this->temperature = $weather / 3;
			$this->precipitation = -$weather / 3;
			$this->_time = $_time;
			$this->distance = $distance;
		}
	}
?>


text:
package com.google.appengine.tck.datastore;

import java.util.List;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;

import static com.google.appengine.api.datastore.Query.SortDirection.ASCENDING;
import static com.google.appengine.api.datastore.Query.SortDirection.DESCENDING;
import static org.junit.Assert.assertTrue;

/**
 * Datastore querying tests.
 *
 * @author Marko Luksa
 */
@RunWith(Arquillian.class)
public class QuerySortingTest extends QueryTestBase {

    private static String QUERY_SORTING_ENTITY = "QuerySortingEntity";

    @Test
    public void testSortingByStringProperty() throws Exception {
        String methodName = "testSortingByStringProperty";
        Entity parent = createTestEntityWithUniqueMethodNameKey(QUERY_SORTING_ENTITY, methodName);
        Key key = parent.getKey();

        // NOTE: intentionally storing entities in non-alphabetic order
        Entity bill = storeTestEntityWithSingleProperty(key, "Bill");
        Entity abraham = storeTestEntityWithSingleProperty(key, "Abraham");
        Entity carl = storeTestEntityWithSingleProperty(key, "Carl");

        assertList(whenSortingByTheSingleProperty(ASCENDING, key), containsResultsInOrder(abraham, bill, carl));
        assertList(whenSortingByTheSingleProperty(DESCENDING, key), containsResultsInOrder(carl, bill, abraham));

        service.delete(bill.getKey(), abraham.getKey(), carl.getKey());
    }

    @Test
    public void testSortingByIntegerProperty() throws Exception {
        String methodName = "testSortingByIntegerProperty";
        Entity parent = createTestEntityWithUniqueMethodNameKey(QUERY_SORTING_ENTITY, methodName);
        Key key = parent.getKey();

        Entity two = storeTestEntityWithSingleProperty(key, 2);
        Entity one = storeTestEntityWithSingleProperty(key, 1);
        Entity three = storeTestEntityWithSingleProperty(key, 3);

        assertList(whenSortingByTheSingleProperty(ASCENDING, key), containsResultsInOrder(one, two, three));
        assertList(whenSortingByTheSingleProperty(DESCENDING, key), containsResultsInOrder(three, two, one));

        service.delete(two.getKey(), one.getKey(), three.getKey());
    }

    @Test
    public void testSortingByFloatProperty() throws Exception {
        String methodName = "testSortingByFloatProperty";
        Entity parent = createTestEntityWithUniqueMethodNameKey(QUERY_SORTING_ENTITY, methodName);
        Key key = parent.getKey();

        Entity thirty = storeTestEntityWithSingleProperty(key, 30f);
        Entity two = storeTestEntityWithSingleProperty(key, 2f);
        Entity hundred = storeTestEntityWithSingleProperty(key, 100f);

        assertList(whenSortingByTheSingleProperty(ASCENDING, key), containsResultsInOrder(two, thirty, hundred));
        assertList(whenSortingByTheSingleProperty(DESCENDING, key), containsResultsInOrder(hundred, thirty, two));

        service.delete(thirty.getKey(), two.getKey(), hundred.getKey());
    }

    @Test
    public void testIntegerPropertySortingIsNotLexicographic() throws Exception {
        String methodName = "testIntegerPropertySortingIsNotLexicographic";
        Entity parent = createTestEntityWithUniqueMethodNameKey(QUERY_SORTING_ENTITY, methodName);
        Key key = parent.getKey();

        Entity ten = storeTestEntityWithSingleProperty(key, 10);
        Entity five = storeTestEntityWithSingleProperty(key, 5);

        Query query = createQuery().setAncestor(key).addSort(SINGLE_PROPERTY_NAME, ASCENDING);
        List<Entity> results = service.prepare(query).asList(withDefaults());

        assertTrue(results.indexOf(five) < results.indexOf(ten));   // if sorting were lexicographic, "10" would come before "5"
        service.delete(ten.getKey(), five.getKey());
    }

    @Test
    public void testSortingByDateProperty() throws Exception {
        String methodName = "testSortingByDateProperty";
        Entity parent = createTestEntityWithUniqueMethodNameKey(QUERY_SORTING_ENTITY, methodName);
        Key key = parent.getKey();

        Entity february2 = storeTestEntityWithSingleProperty(key, createDate(2011, 2, 2));
        Entity march3 = storeTestEntityWithSingleProperty(key, createDate(2011, 3, 3));
        Entity january1 = storeTestEntityWithSingleProperty(key, createDate(2011, 1, 1));

        assertList(whenSortingByTheSingleProperty(ASCENDING, key), containsResultsInOrder(january1, february2, march3));
        assertList(whenSortingByTheSingleProperty(DESCENDING, key), containsResultsInOrder(march3, february2, january1));

        service.delete(february2.getKey(), march3.getKey(), january1.getKey());
    }

    private List<Entity> whenSortingByTheSingleProperty(Query.SortDirection direction, Key parentKey) {
        Query query = createQuery().setAncestor(parentKey).addSort(SINGLE_PROPERTY_NAME, direction);
        return service.prepare(query).asList(withDefaults());
    }

}


text:
mkdir build32 & pushd build32
cmake -G "Visual Studio 15 2017" ..
popd
cmake --build build32 --config Release
md plugin_lua53\Plugins\x86
copy /Y build32\Release\xlua.dll plugin_lua53\Plugins\x86\xlua.dll
pause


text:
package org.sleuthkit.autopsy.ingest;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.openide.util.Exceptions;
import org.sleuthkit.autopsy.coreutils.ModuleSettings;
import org.sleuthkit.autopsy.coreutils.PlatformUtil;

/**
 * Class for managing the access to the
 */
public final class IngestProfiles {

    private static final String PROFILE_FOLDER = "IngestProfiles";
    private static final String PROFILE_NAME_KEY = "Profile_Name";
    private static final String PROFILE_DESC_KEY = "Profile_Description";
    private static final String PROFILE_FILTER_KEY = "Profile_Filter";
    private static final String PROFILE_FILE_EXT = ".properties";

    /**
     * Gets the collection of profiles which currently exist.
     *
     * @return profileList
     */
    public synchronized static List<IngestProfile> getIngestProfiles() {
        File dir = Paths.get(PlatformUtil.getUserConfigDirectory(), PROFILE_FOLDER).toFile();
        File[] directoryListing = dir.listFiles();
        List<IngestProfile> profileList = new ArrayList<>();
        if (directoryListing != null) {
            for (File child : directoryListing) {
                String name = FilenameUtils.removeExtension(child.getName());
                String context = PROFILE_FOLDER + File.separator + name;
                String desc = ModuleSettings.getConfigSetting(context, PROFILE_DESC_KEY);
                String fileIngestFilter = ModuleSettings.getConfigSetting(context, PROFILE_FILTER_KEY);
                profileList.add(new IngestProfile(name, desc, fileIngestFilter));
            }
        }
        return profileList;
    }

    /**
     * Saves the list of profiles which currently exist to disk.
     */
    synchronized static void setProfiles(List<IngestProfile> profiles) {
        for (IngestProfile profile : profiles) {
            IngestProfile.saveProfile(profile);
        }
    }

    /**
     * An individual Ingest Profile, consists of a name, a description, and a
     * FileIngestFilter. The name can be used to find the ModuleSettings for
     * this profile.
     */
    public static final class IngestProfile {

        private final String name;
        private final String description;
        private final String fileIngestFilter;

        /**
         * Creates a new IngestProfile
         *
         * @param name           - unique name of the profile
         * @param desc           - optional description of profile
         * @param selectedFilter - the File Ingest Filter used for this profile
         */
        IngestProfile(String name, String desc, String selectedFilter) {
            this.name = name;
            this.description = desc;
            this.fileIngestFilter = selectedFilter;
        }

        /**
         * The string value of an IngestProfile is simply its name
         *
         * @return getName();
         */
        @Override
        public String toString() {
            return getName();
        }

        /**
         * The unique name field for this Ingest Profile.
         *
         * @return the name
         */
        String getName() {
            return name;
        }

        /**
         * The optional user defined description of this Ingest Profile.
         *
         * @return the description
         */
        public String getDescription() {
            return description;
        }

        /**
         * The file ingest filter which was selected to be used.
         *
         * @return the fileIngestFilter
         */
        public String getFileIngestFilter() {
            return fileIngestFilter;
        }

        /**
         * Deletes all of the files which are currently storing a profile.
         *
         * @param selectedProfile
         */
        synchronized static void deleteProfile(IngestProfile selectedProfile) {
            try {
                Files.deleteIfExists(Paths.get(PlatformUtil.getUserConfigDirectory(), PROFILE_FOLDER, selectedProfile.getName() + PROFILE_FILE_EXT));
                Files.deleteIfExists(Paths.get(PlatformUtil.getUserConfigDirectory(), selectedProfile.getName() + PROFILE_FILE_EXT));
                FileUtils.deleteDirectory(IngestJobSettings.getSavedModuleSettingsFolder(selectedProfile.getName() + File.separator).toFile());
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }

        /**
         * Renames the files and directories associated with a profile
         *
         * @param oldName the name of the profile you want to rename
         * @param newName the name which you want the profile to have
         */
        synchronized static void renameProfile(String oldName, String newName) {
            if (!oldName.equals(newName)) { //if renameProfile was called with the new name being the same as the old name, it is complete already
                File oldFile = Paths.get(PlatformUtil.getUserConfigDirectory(), PROFILE_FOLDER, oldName + PROFILE_FILE_EXT).toFile();
                File newFile = Paths.get(PlatformUtil.getUserConfigDirectory(), PROFILE_FOLDER, newName + PROFILE_FILE_EXT).toFile();
                oldFile.renameTo(newFile);
                oldFile = Paths.get(PlatformUtil.getUserConfigDirectory(), oldName + PROFILE_FILE_EXT).toFile();
                newFile = Paths.get(PlatformUtil.getUserConfigDirectory(), newName + PROFILE_FILE_EXT).toFile();
                oldFile.renameTo(newFile);
                oldFile = IngestJobSettings.getSavedModuleSettingsFolder(oldName + File.separator).toFile();
                newFile = IngestJobSettings.getSavedModuleSettingsFolder(newName + File.separator).toFile();
                oldFile.renameTo(newFile);
            }
        }

        /**
         * Save a Ingest profile file in the profile folder.
         *
         * @param profile
         */
        synchronized static void saveProfile(IngestProfile profile) {
            String context = PROFILE_FOLDER + File.separator + profile.getName();
            ModuleSettings.setConfigSetting(context, PROFILE_NAME_KEY, profile.getName());
            ModuleSettings.setConfigSetting(context, PROFILE_DESC_KEY, profile.getDescription());
            ModuleSettings.setConfigSetting(context, PROFILE_FILTER_KEY, profile.getFileIngestFilter());
        }
    }
}