text:
package io.hua.um.web.controller;

import io.hua.um.util.UmMapping;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(method = RequestMethod.GET)
public class RedirectController {
    public RedirectController() {
        super();
    }

    // API

    @RequestMapping(value = UmMapping.Singular.PRIVILEGE)
    public ResponseEntity<Void> privilegeToPrivileges(final HttpServletRequest request) {
        return singularToPlural(request);
    }

    @RequestMapping(value = UmMapping.Singular.ROLE)
    public ResponseEntity<Void> roleToRoles(final HttpServletRequest request) {
        return singularToPlural(request);
    }

    @RequestMapping(value = UmMapping.Singular.USER)
    public ResponseEntity<Void> userToUsers(final HttpServletRequest request) {
        return singularToPlural(request);
    }

    // util

    private ResponseEntity<Void> singularToPlural(final HttpServletRequest request) {
        final String correctedUri = request.getRequestURI() + "s";
        final HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add(HttpHeaders.LOCATION, correctedUri);

        final ResponseEntity<Void> redirectedResponse = new ResponseEntity<Void>(responseHeaders, HttpStatus.MOVED_PERMANENTLY);
        return redirectedResponse;
    }
}


text:
#region License

#endregion

#region Imports

using System;
using NUnit.Framework;
using Spring.Util;

#endregion

namespace Spring.Objects.Factory.Config
{
	/// <summary>
	/// Unit tests for the TypedStringValue class.
	/// </summary>
	/// <author>Juergen Hoeller</author>
	/// <author>Rick Evans (.NET)</author>
	[TestFixture]
	public sealed class TypedStringValueTests
	{
		[Test]
		public void Instantiation()
		{
			string expectedNow = DateTime.Now.ToShortDateString();

            TypedStringValue tsv = new TypedStringValue(expectedNow, typeof (DateTime));
			Assert.AreEqual(expectedNow, tsv.Value);
			Assert.AreEqual(typeof (DateTime), tsv.TargetType);

            tsv = new TypedStringValue(expectedNow);
            Assert.AreEqual(expectedNow, tsv.Value);

            tsv = new TypedStringValue(expectedNow, typeof(DateTime).FullName);
            Assert.AreEqual(expectedNow, tsv.Value);
            Assert.AreEqual(typeof(DateTime).FullName, tsv.TargetTypeName);

		}

		[Test]
		[ExpectedException(typeof (ArgumentNullException))]
		public void InstantiationWithNullType()
		{
			new TypedStringValue(string.Empty, (Type)null);
		}

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public void InstantiationWithNullTypeName()
        {
            new TypedStringValue(string.Empty, (string)null);
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public void InstantiationWithEmptyTypeName()
        {
            new TypedStringValue(string.Empty, "  ");
        }

		[Test]
		[ExpectedException(typeof (ArgumentNullException))]
		public void SetTargetTypePropertyToNullType()
		{
			TypedStringValue tsv = new TypedStringValue(string.Empty, typeof (DateTime));
			tsv.TargetType = null;
		}

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public void SetTargetTypeNamePropertyToEmptyString()
        {
            TypedStringValue tsv = new TypedStringValue(string.Empty, typeof(DateTime));
            tsv.TargetTypeName = "  ";
        }

		[Test]
		public void IsSerializable()
		{
			Assert.IsTrue(SerializationTestUtils.IsSerializable(new TypedStringValue()),
				"Must be marked as [Serializable].");
		}

		[Test]
		public void Serialization()
		{
			TypedStringValue value = new TypedStringValue();
			Type expectedType = typeof(string);
			value.TargetType = expectedType;
			const string expectedValue = "rilo-kiley";
			value.Value = expectedValue;

			object foo = SerializationTestUtils.SerializeAndDeserialize(value);
			Assert.IsNotNull(foo, "Serialization roundtrip must never result in null.");
			TypedStringValue deser = foo as TypedStringValue;
			Assert.IsNotNull(deser,
				"Serialization roundtrip yielded the wrong Type of object.");
			Assert.AreEqual(expectedType, deser.TargetType,
				"Serialization roundtrip yielded the wrong TargetType.");
			Assert.AreEqual(expectedValue, deser.Value,
				"Serialization roundtrip yielded the wrong Value.");
		}

        [Test]
        public void HasTargetType()
        {
            TypedStringValue tsv = new TypedStringValue(string.Empty, typeof(DateTime));
            Assert.IsTrue(tsv.HasTargetType);
        }

        [Test]
        public void HasTargetTypeReturnsFalseWhenTargetTypeNotResolved()
        {
            TypedStringValue tsv = new TypedStringValue(string.Empty, typeof(DateTime).FullName);
            Assert.IsFalse(tsv.HasTargetType);

            tsv = new TypedStringValue(string.Empty, typeof(DateTime));
            Assert.IsTrue(tsv.HasTargetType);
            tsv.TargetTypeName = typeof(DateTime).FullName;
            Assert.IsFalse(tsv.HasTargetType);
        }

        [Test]
        public void ResolveTargetType()
        {
            TypedStringValue tsv = new TypedStringValue(string.Empty, typeof(DateTime).FullName);
            Assert.IsFalse(tsv.HasTargetType);
            Assert.AreEqual(typeof(DateTime), tsv.ResolveTargetType());
            Assert.IsTrue(tsv.HasTargetType);
        }
	}
}

redpajama_set_name: RedPajamaGithub


text:
ActivityTracker.configure do |config|
  #use this option to configure size of butches pushed to elastic search
  #config.batch_size = 100
end


text:
{% extends 'base.html' %}
{% block sidecontent%}
    <a href="/forum/addq">Add Question </a>
{% endblock %}

{% block maincontent %}
Hello World!
{%endblock %}


text:
/**********************************************************************
*
*	<--- DIRECTORY STRUCTURE EXPECTED FOR TRAINER --->
*
* --/
*	 --/RAW_DATA/
*				--/TRAIN
*						 --/0 					//ABSENT - SAMPLE DATA
*						 --/1 					//PRESENT - SAMPLE DATA
*						 --/2 					//Blank? - SAMPLE DATA
*
*	<--- DIRECTORY STRUCTURE EXPECTED FOR TRAINER --->
***********************************************************************/

#ifndef KNN_TRAINER_H
#define KNN_TRAINER_H

#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "unistd.h"

// To check for file on disk
#include <sys/stat.h>

// Exception classes
#include "Exceptions/Generic/FilePathInvalidException.h"

using namespace std;
using namespace cv;

//------------------------------------------------------------------------------------------
// Custom comparator
bool compareContourAreas(std::vector<cv::Point> contour1, std::vector<cv::Point> contour2) {

    double i = fabs( contourArea(cv::Mat(contour1)) );
    double j = fabs( contourArea(cv::Mat(contour2)) );
    return ( i < j );
}
//------------------------------------------------------------------------------------------

class KNN_Trainer {

private:

    Mat _samples;			// For storing samples
    Mat _labels;			// For storing labels
    Mat sample_labels;		// For storing sample's label

    int TOTAL_SAMPLES;
    int TOTAL_CLASSES;

    // Train the KNN classifier
    void train_classifier( string  PATH_TO_TRAINING_DATA);

    // Serialize (save) the training to file.
    void serialize_training();

    // Get cropped Contour (only the contour, not extra whitespace)
    Mat getCroppedContour(Mat& segment);

    // Checks if the file exists or not.
    inline bool does_file_exist (const std::string& name) {
        struct stat buffer;
        return (stat (name.c_str(), &buffer) == 0);
    }
public:

    KNN_Trainer(string  PATH_TO_TRAINING_DATA, int total_samples, int total_classes) : TOTAL_SAMPLES(total_samples),  TOTAL_CLASSES(total_classes) {

        train_classifier(PATH_TO_TRAINING_DATA);

        serialize_training();
    }

    // Convert (input) integer to String (using stringstream)
    string convertIntToString(int number) {
        stringstream ss;			//create a stringstream
        ss << number;				//add number to the stream
        return ss.str();			//return a string with the contents of the stream
    }

};

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

Mat KNN_Trainer::getCroppedContour(Mat& segment) {
    vector< vector <Point> > contours; // Vector for storing contour
    vector< Vec4i > hierarchy;
    Mat croppedContour;
    Mat seg_copy = segment.clone(); //to prevent decomposition
    GaussianBlur(segment, segment, Size(5,5), 0, 0);

    findContours( segment, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );

    //sort the contours with a custom comparator
    sort(contours.begin(), contours.end(), compareContourAreas);

    // largest contour
    vector<Point> pt_largest;

    //take largest contour
    pt_largest = contours[contours.size()-1];

    Rect r= boundingRect(pt_largest);
    croppedContour = seg_copy(r);

    return croppedContour;
}

/********************************************************************
*							TRAIN_CLASSIFIER
*
*	Input Arguments:
*		string_to_training_data  : [string] String to training data
*		TOTAL_SAMPLES_in_dir : [int] Number of files in directory
*
*
* <-- FILE NAMING EXPECTED IN INPUT FILES -->
*
* <-- Also, there should be equal number of files, in each class -->
*
*	--/TRAIN
*			--/0
*			  	--/IMG (0).png
*			  	--/IMG (1).png
*			  	...
*			  	--/IMG (n).png
*
*
* <-- FILE NAMING EXPECTED IN INPUT FILES -->
*
*********************************************************************/

// Train the KNN classifier
void KNN_Trainer::train_classifier( string string_to_training_data) {

    try {
        // Mat for storing a single sample
        Mat sample;

        // Mat for storing CV_32FC1
        Mat sample_flattened;

        // Change directory to training data directory
        chdir( string_to_training_data.c_str() );

        char stackBuffer[512];

        for(int CURR_CLASS=0; CURR_CLASS<TOTAL_CLASSES; CURR_CLASS++) {

            for(int CURR_SAMPLE=0; CURR_SAMPLE<TOTAL_SAMPLES; CURR_SAMPLE++) {

                chdir( (convertIntToString(CURR_CLASS)).c_str());

                string filename = "IMG ("+ convertIntToString(CURR_SAMPLE+1) + ").png";
                // check if the file exists on disk
                if(!does_file_exist(filename)) {
                    throw FilePathInvalidException(filename);
                }

#if DEBUG
                cout << "current dir asdfasd"  << getcwd(stackBuffer, sizeof(stackBuffer)) << endl;
                cout << filename << endl;
#endif // DEBUG

                // Read each sample
                sample = imread(filename, 0);
                //threshold(sample,sample,200,255,THRESH_BINARY_INV); //Threshold to find contour
                cv::threshold(sample, sample, 0, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU);

                sample = getCroppedContour(sample);
                //imwrite("a.png"+filename, sample);

                // Resize sample to 32,32
                resize(sample, sample, Size(32,32), 0, 0, INTER_CUBIC );

                // Convert to float - flatten the multidim to single dim (single chan)
                sample.convertTo(sample_flattened, CV_32FC1);

                // Store sample (continuous) data
                _samples.push_back(sample_flattened.reshape(1,1));

                // Store label to a mat
                sample_labels.push_back(CURR_CLASS);

            }

            // Go up 1 file directory
            chdir("../");
        }

        // Go up 2 file directories
        chdir("../..");

        // Store the data to file
        Mat sample_labels_temp;

        //make continuous
        sample_labels_temp = sample_labels.reshape(1,1);

        // Convert  to float and store in _labels
        sample_labels_temp.convertTo(_labels,CV_32FC1);
    }

    catch(FilePathInvalidException ipie) {
        std::cerr << "EXCEPTION: Input file " << ipie.getPath() << " does not exist on disk " << std::endl;
        throw ipie;
    }

    catch(...) {
        cout << "Something unusual went wrong while training " << endl;
    }

}

/********************************************************************
*						SERIALIZE_TRAINING
*
********************************************************************/

// This function serializes (writes to file) the training data.
void KNN_Trainer::serialize_training() {

    // Store the sample data in a file
    FileStorage Data("TrainedDataFiles/TrainingData.yml",FileStorage::WRITE);
    Data << "data" << _samples;
    Data.release();

    // Store the label data in a file
    FileStorage Label("TrainedDataFiles/LabelData.yml",FileStorage::WRITE);
    Label << "label" << _labels;
    Label.release();

    cout << "Training and Label data serialized successfully.... " << endl;

}
#endif // KNN_TRAINER_H


text:
using System;

namespace Platform
{
	/// <summary>
	/// A base interface for model classes (classes that contain state).
	/// </summary>
	public interface IModel
		: IOwned
	{
		/// <summary>
		/// An event that is raised when a major change occurs in the model.
		/// </summary>
		event EventHandler MajorChange;
	}
}


text:
'use strict';
define(['app'], function (app) {
    app.controller('itemController', [
        '$scope',
        'itemService',
        '$routeParams',
        '$location',
        '$window',
        function ($scope, service, $routeParams, $location, $window) {

            $scope.message = {
                text: '',
                type: '',
                messageClass: '',
                errors: null
            };

            $scope.page =
            {
                title: 'Items'
            }

            //GET LIST
            var getList = function (search, orderBy, pageNumber) {
                $scope.isCollapsed = true;
                $scope.loading = true;

                $scope.predicate = 'name';
                $scope.reverse = false;

                $scope.pageSize = 5;
                $scope.pageNumber = pageNumber || 0;

                $scope.search = search || "";
                $scope.orderBy = orderBy || "";

                //Filter
                $scope.filter = function () {
                    getList($scope.search, $scope.orderBy, $scope.pageNumber, $scope.pageSize);
                };

                //Page
                $scope.pageChanged = function () {
                    getList($scope.search, $scope.orderBy, $scope.pageNumber, $scope.pageSize);
                };

                //Sort
                $scope.changeSorting = function ($event, column) {
                    if (column != null && column != "") {
                        $scope.orderBy = EasyStitch.Common.Data.changeSorting(column, $scope.orderBy);
                        getList($scope.search, $scope.orderBy, $scope.pageNumber, $scope.pageSize);
                    }
                };

                //Sort Icon
                $scope.getIcon = function ($event, column) {
                    return EasyStitch.Common.Data.getIcon(column, $scope.orderBy);
                }

                service.getList($scope.search, $scope.orderBy, $scope.pageNumber, $scope.pageSize)
                .success(function (data, status, headers, config) {
                    $scope.items = data.data;
                    $scope.totalCount = data.total_count;
                    $scope.pageNumber = data.page_number;
                    $scope.loading = $scope.isCollapsed = false;
                })
                .error(function (data, status, headers, config) {
                    setMessage(data, 'error', data.errors);
                    $scope.loading = $scope.isCollapsed = false;
                    $scope.items = [];
                });

            }

            //GET
            var get = function (id) {
                $scope.loading = true;

                $scope.suppliers = [{ code: '', name: '[Please Select]' }];
                service.getSuppliers()
                 .success(function (data, status, headers, config) {
                     $scope.suppliers = data.data;
                     if (id == null) {
                         $scope.item = { suppler: '' };
                         $scope.loading = false;
                     }
                 })
                 .error(function (data, status, headers, config) {
                     setMessage(data, 'error', data.errors);
                     if (id == null) $scope.loading = false;
                 });

                if (id != null) {
                    service.get(id)
                    .success(function (data, status, headers, config) {
                        $scope.item = data;
                        $scope.loading = false;
                    })
                    .error(function (data, status, headers, config) {
                        setMessage(data, 'error', data.errors);
                        $scope.loading = false;
                    });
                } else {
                    $scope.item = {suppler:''};
                }
            }

            //UPDATE
            var update = function () {
                var action;
                if ($scope.form.$valid) {
                    if ($routeParams.id == 'new') {
                        action = service.insert($scope.item);
                    } else {
                        action = service.update($routeParams.id, $scope.item);
                    }
                }

                if (action) {
                    $scope.loading = true;
                    action.success(function (data, status, headers, config) {
                        if (data.errors) {
                            setMessage(data.message, 'error', data.errors);
                        } else {
                            setMessage('Saved successfully', 'success', null);
                            $location.url('/item/' + data._id);
                        }
                        $scope.loading = false;
                    })
                    .error(function (data, status, headers, config) {
                        if (data)
                            setMessage(data, 'error', data.errors);
                        else
                            setMessage('unknow error occured', 'error', null);
                        $scope.loading = false;
                    });
                }
            }

            //DELETE
            var deleteRecord = function () {
                var action;
                action = service.delete($routeParams.id, $scope.item)
                .success(function (data, status, headers, config) {
                    if (data!=null && data.message!=null) {
                        setMessage(data.message, 'error', data.errors);
                    } else {
                        setMessage('Deleted successfully', 'success', null);
                        $location.url('/item/');
                    }
                })
                .error(function (data, status, headers, config) {
                    setMessage(data, 'error', data.errors);
                });
            }

            var getSuppliers = function () {

            }

            //TODO: move it to some util class
            //private methods
            var setMessage = function (message, type, errors) {
                $scope.message = {
                    text: message,
                    type: type,
                    messageClass: type == 'error' ? 'alert alert-danger' : (type == 'success' ? 'alert alert-success' : ''),
                    errors: errors
                };
            }
            $scope.back = function () {
                $window.history.back();
            }

            //init
            if ($routeParams.id == null) {
                getList();
            } else {
                if ($routeParams.id == 'new') {
                    get();
                } else {
                    get($routeParams.id);
                }
            }

            //public method
            $scope.update = update;
            $scope.delete = deleteRecord;
        }
    ]);
});


text:
<?php
namespace wiggum\commons\util;

use \Exception;
use \LengthException;

/**
 * @deprecated
 *
 *
 */
class Encryption {

	private $key;

	/**
	 *
	 * @param string $key [default=null]
	 * @throws LengthException
	 */
	public function __construct($key = null) {
		if (isset($key)) {
			$key = str_replace(' ', '', $key);
			if ($key == '' || strlen($key) < 8)
				throw new LengthException("Key must be > 8 chars");

			$this->key = $key;
		}
	}

	/**
	 *
	 * @param string $plaintext
	 * @return string
	 * @throws Exception
	 * @throws LengthException
	 */
	public function encrypt($plaintext) {
		if (!isset($this->key)) throw new LengthException('No key set');
		if (!is_string($plaintext)) throw new Exception('Cannot encrypt non string type. [' . $plaintext . ']');
		$enc = $this->crypt($plaintext);
		return $enc;
	}

	/**
	 *
	 * @param string $enc
	 * @return string
	 * @throws Exception
	 * @throws LengthException
	 */
	public function decrypt($enc) {
		if (!isset($this->key)) throw new LengthException('No key set');
		if (!is_string($enc)) throw new Exception('Cannot decrypt non string type. [' . $enc . ']');
		$dec = $this->crypt($enc);
		return $dec;
	}

	/**
	 *
	 * @param string $plaintext
	 * @return string
	 */
	public function urlEncrypt($plaintext) {
		$enc = $this->encrypt($plaintext);
		$base64 = base64_encode($enc);
        $result = str_replace(array('+', '/', '='), array("-", "_", "."), $base64);
		return $result;
	}

	/**
	 *
	 * @param string $urlEncrypted
	 * @return string
	 */
	public function urlDecrypt($urlEncrypted) {
		$base64 = str_replace(array("-","_", "."), array("+","/", "="), $urlEncrypted);
		$enc = base64_decode($base64);
		$dec = trim($this->decrypt($enc));
		return $dec;
	}

	/**
	 *
	 * @param array $tokens
	 * @param string $seperator [default='|']
	 * @return string
	 */
	public function generateToken(array $tokens, $seperator = '|') {
		$token = implode($seperator, $tokens);
		$tokenEnc = $this->urlEncrypt($token);
		return $tokenEnc;
	}

	/**
	 *
	 * @param string $token
	 * @param string $seperator [default='|']
	 * @return array
	 */
	public function decryptToken($token, $seperator = '|') {
		$tokenDec = $this->urlDecrypt($token);
		$tokens = explode($seperator, $tokenDec);
		return $tokens;
	}

	/**
	 *
	 * @param string $text
	 * @return string
	 */
	private function crypt($text) {

		// set key length to be no more than 32 characters
		$keyLength = strlen($this->key);
		if ($keyLength > 32) {
			$keyLength = 32;
		}

		$key = substr($this->key, 0, $keyLength);
		$textLength = strlen($text);

		$lomask = str_repeat("\x1f", $textLength);
		$himask = str_repeat("\xe0", $textLength);
		$k = str_pad("", $textLength, $key);

		$text = (($text ^ $k) & $lomask) | ($text & $himask);
		return $text;
	}

	/**
	 *
	 * @param string $data
	 * @param string $salt
	 * @param string $algo [default='sha1']
	 * @return string
	 */
	public static function getHash($data, $salt, $algo = 'sha1') {
		return hash($algo, $salt . $data);
	}

}
?>


text:
define(['jquery', 'oae.core'], function($, oae) {

    return function(uid) {

        // The widget container
        var $rootel = $('#' + uid);

        /**
         * Render the enabled authentication strategies
         */
        var renderLogin = function() {
            var authStrategyInfo = oae.api.authentication.getStrategyInfo();
            var externalAuthOpts = {
                'data': {
                    'redirectUrl': window.location.pathname
                }
            };

            oae.api.util.template().render($('#adminlogin-authentication-template', $rootel), {
                'authStrategyInfo': authStrategyInfo,
                'externalAuthOpts': externalAuthOpts
            }, $('#adminlogin-authentication-container', $rootel));
        };

        /**
         * Add validation to the local login form
         */
        var setUpLocalLoginValidation = function() {
            var $localLoginForm = $('#adminlogin-local', $rootel);
            var validateOpts = {
                'messages': {
                    'adminlogin-local-username': {
                        'required': oae.api.i18n.translate('__MSG__PLEASE_ENTER_YOUR_USERNAME__'),
                        'adminlogin-failed-attempt': oae.api.i18n.translate('__MSG__INVALID_USERNAME_OR_PASSWORD__')
                    },
                    'adminlogin-local-password': oae.api.i18n.translate('__MSG__PLEASE_ENTER_YOUR_PASSWORD__')
                },
                'methods': {
                    'adminlogin-failed-attempt': {
                        'method': function(value, element) {
                            // This class will be added after a failed login attempt and is used
                            // to tell jquery.validate to mark the field as invalid
                            return false;
                        }
                    }
                },
                'submitHandler': doLogin
            };
            oae.api.util.validation().validate($localLoginForm, validateOpts);
        };

        /**
         * Attempt to log the user into the administration UI with the provided username and password using either
         * the LDAP login strategy or the local login strategy. If only one of them is enabled, only that strategy
         * will be attempted. If both of them are enabled, an LDAP login will be attempted first. If that is unsuccessful,
         * a local login will be attempted next. This function will only be executed when form validation has passed.
         */
        var doLogin = function() {
            // Check whether or not the LDAP login strategy is enabled
            var LDAPEnabled = oae.api.config.getValue('oae-authentication', 'ldap', 'enabled');
            // Check whether or not the local login strategy is enabled
            var LocalEnabled = oae.api.config.getValue('oae-authentication', 'local', 'enabled');

            // Get the entered username and password
            var username = $.trim($('#adminlogin-local-username', $rootel).val());
            var password = $.trim($('#adminlogin-local-password', $rootel).val());

            // Both LDAP and local are enabled. We try LDAP first, and try local next if LDAP has failed
            if (LDAPEnabled && LocalEnabled) {
                oae.api.authentication.LDAPLogin(username, password, function(err) {
                    if (err) {
                        oae.api.authentication.localLogin(username, password, finishLogin);
                    } else {
                        finishLogin();
                    }
                });
            // Only LDAP is enabled
            } else if (LDAPEnabled) {
                oae.api.authentication.LDAPLogin(username, password, finishLogin);
            // Only local authentication is enabled
            } else {
                oae.api.authentication.localLogin(username, password, finishLogin);
            }
        };

        /**
         * Finish the login process by showing the correct validation message in case of a failed
         * login attempt, or by redirecting the user in case of a successful login attempt
         *
         * @param  {Error}      err        Error object containing error code and error message
         */
        var finishLogin = function(err) {
            if (err) {
                // Set a `adminlogin-failed-attempt` on the fields to tell jquery.validate
                // that the field is invalid
                $('#adminlogin-local-username', $rootel).addClass('adminlogin-failed-attempt');
                $('#adminlogin-local', $rootel).valid();
                $('#adminlogin-local-username', $rootel).removeClass('adminlogin-failed-attempt');
                // Clear the password field
                $('#adminlogin-local-password', $rootel).val('');
                // Focus into the username field
                $('#adminlogin-local-username', $rootel).focus();
            } else {
                window.location.reload(true);
            }
        };

        /**
         * Initialize the adminlogin widget
         */
        var initLogin = function() {
            renderLogin();
            setUpLocalLoginValidation();
        };

        initLogin();

    };
});


text:
import os

import requests

def get_data_dir():

    return os.path.join(os.path.expanduser("~"), "lightfm_data")

def create_data_dir(path):

    if not os.path.isdir(path):
        os.makedirs(path)

def download(url, dest_path):

    req = requests.get(url, stream=True)
    req.raise_for_status()

    with open(dest_path, "wb") as fd:
        for chunk in req.iter_content(chunk_size=2 ** 20):
            fd.write(chunk)

def get_data(data_home, url, dest_subdir, dest_filename, download_if_missing):

    if data_home is None:
        data_dir = os.path.join(get_data_dir(), dest_subdir)
    else:
        data_dir = os.path.join(os.path.abspath(data_home), dest_subdir)

    create_data_dir(data_dir)

    dest_path = os.path.join(data_dir, dest_filename)

    if not os.path.isfile(dest_path):
        if download_if_missing:
            download(url, dest_path)
        else:
            raise IOError("Dataset missing.")

    return dest_path


text:
package org.javesi.id;

public class ConstantIdGenerator
    implements EntityIdGenerator
{
    private long constantValue;

    public ConstantIdGenerator(long constantValue)
    {
        this.constantValue = constantValue;
    }

    @Override
    public long getNextEntityId()
    {
        return constantValue;
    }

    @Override
    public int hashCode()
    {
        return (int)(constantValue ^ (constantValue >> 32));
    }

    @Override
    public boolean equals(Object obj)
    {
        if (obj instanceof ConstantIdGenerator)
        {
            return constantValue == ((ConstantIdGenerator)obj).constantValue;
        }
        return false;
    }
}


text:
var app = angular.module('smartEventScheduler.events', ['smartEventScheduler.common']);

app.config(function ($stateProvider) {
    $stateProvider.state('auth.myEvents', {
        templateUrl: 'templates/events/my.html',
        url: '/events/my',
        controller: 'MyEventsController'
    });

    $stateProvider.state('auth.newEvent', {
        templateUrl: 'templates/events/detail.html',
        url: '/new-event',
        controller: 'EventController'
    });

    $stateProvider.state('auth.eventDetail', {
        templateUrl: 'templates/events/detail.html',
        url: '/event/:id',
        controller: 'EventController'
    });

});

app.factory('EVENT_TIMES', function () {
    return {
        CURRENT: 'CURRENT',
        PAST: 'PAST'
    }
});

app.controller('MyEventsController', function ($scope, eventResourceService, flash, listLimitCount, EVENT_TIMES) {
    var Event = eventResourceService.getResource();

    $scope.events = [];
    $scope.limit = listLimitCount;
    $scope.limitCount = 1;
    $scope.timeOfEvents = EVENT_TIMES.CURRENT;
    $scope.EVENT_TIMES = EVENT_TIMES;

    $scope.loadList = function () {
        $scope.events = Event.getMyEvents({
            limit: $scope.limit,
            limitCount: $scope.limitCount,
            timeOfEvents: $scope.timeOfEvents
        }, function (data) {
            angular.forEach(data, function (event) {
                event.votingDeadline = new Date(event.votingDeadline);
            });
        });
    };

    $scope.removeEvent = function (event) {
        Event.delete(event, function (data) {
            var eventIndex = $scope.events.indexOf(event);

            $scope.events.splice(eventIndex, 1);
            flash.success = 'Successfully removed.'; // TODO animate deleted row
        });
    };

    $scope.setEventTimeFilter = function (eventsTime) {
        $scope.timeOfEvents = eventsTime;
        $scope.loadList();
    };
});

app.controller('EventController', function ($scope, $state, $stateParams, eventResourceService) {
    var Event = eventResourceService.getResource();

    if (angular.isDefined($stateParams.id)) {
        $scope.event = Event.get({id: $stateParams.id}, function (data) {
            angular.forEach(data.times, function (time) {
                time.from = new Date(time.from);
                time.until = new Date(time.until);
            })
        });
    } else {
        $scope.event = {
            votingDeadline: getCurrentDate().cloneAddSeconds(DAY_IN_SECONDS * 7),
            times: [],
            activities: [],
            slots: []
        };
    }

    $scope.existsItemWithoutId = function (collection) {
        var has = false;
        angular.forEach(collection, function (item) {
            if (angular.isUndefined(item.id)) {
                has = true;
            }
        });
        return has;
    };

    $scope.save = function () {
        Event.save($scope.event, function (data) {
            console.log('success event save callback');
            $state.go('auth.eventDetail', {id: data.id})
        });
    };
});

app.directive('eventActivityTimeSlot', function ($modal) {
    return {
        restrict: 'E',
        scope: {
            time: '=',
            activity: '=',
            selectedSlots: '='
        },
        templateUrl: 'templates/events/activity-time-slot.html',
        link: function (scope) {
            var notBlankString = function (text) {
                return angular.isDefined(text) && typeof text == 'string' && text.length > 0
            };

            var findTimeEntry = function (slots, timeId) {
                for (var i = 0; i < slots.length; i++) {
                    var slot = slots[i];
                    if (slot.timeDetailId == timeId) {
                        return slot;
                    }
                }

                return undefined;
            };

            var findActivityEntry = function (timeSlots, activityId) {
                for (var i = 0; i < timeSlots.length; i++) {
                    var slot = timeSlots[i];
                    if (slot.activityDetailId == activityId) {
                        return slot;
                    }
                }

                return undefined;
            };

            var findSlot = function (time, activity) {
                var slotWithTime = findTimeEntry(scope.selectedSlots, time.id);

                if (angular.isUndefined(slotWithTime)) {
                    return undefined;
                }

                return findActivityEntry(slotWithTime.activities, activity.id);
            };

            scope.slotToggleable = function () {
                return angular.isDefined(scope.time.id) && angular.isDefined(scope.activity.id)
            };

            scope.toggleSlot = function (time, activity) {
                if (angular.isUndefined(time.id) || angular.isUndefined(activity.id)) {
                    throw 'Error! Time or activity entity for this slot has not been persisted, yet!'
                }

                var slotWithTime = findTimeEntry(scope.selectedSlots, time.id);

                if (angular.isUndefined(slotWithTime)) {
                    scope.selectedSlots.push({
                        timeDetailId: time.id,
                        activities: []
                    });
                }

                var slotWithActivity = findActivityEntry(slotWithTime.activities, activity.id);

                if (angular.isDefined(slotWithActivity)) {
                    var slotIndex = slotWithTime.activities.indexOf(slotWithActivity)
                    slotWithTime.activities.splice(slotIndex, 1);
                } else {
                    slotWithTime.activities.push({
                        activityDetailId: activity.id,
                        note: ''
                    });
                }
            };

            scope.isSelected = function (time, activity) {
                return angular.isDefined(findSlot(time, activity));
            };

            scope.noteExists = function () {
                return scope.isSelected(scope.time, scope.activity) && notBlankString(scope.getSlot().note)
            };

            scope.getSlot = function () {
                return findSlot(scope.time, scope.activity);
            };

            scope.displaySlotModal = function () {
                $modal.open({
                    resolve: {
                        slot: function () {
                            return scope.getSlot();
                        }
                    },
                    templateUrl: 'templates/events/slot-modal.html',
                    controller: 'EventSlotModalController',
                    windowClass: 'modal-with-overlay'
                });
            };
        }
    }
});

app.controller('EventSlotModalController', function ($scope, $modalInstance, slot) {
    $scope.slot = slot;
});

app.factory('eventResourceService', function (apiVersion, restService) {
    return {
        getResource: function () {
            return restService.createRestResource('/' + apiVersion + '/events/:id.json', {id: '@id'},
                {
                    'getMyEvents': {method: 'GET', 'url': '/' + apiVersion + '/events/my.json', isArray: true},
                    'save': {method: 'POST', 'url': '/' + apiVersion + '/events.json'}
                }
            );
        }
    }
});


text:
/*
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "libavutil/attributes.h"
#include "libavutil/x86/cpu.h"
#include "libavcodec/alacdsp.h"
#include "config.h"

void ff_alac_decorrelate_stereo_sse4(int32_t *buffer[2], int nb_samples,
                                     int decorr_shift, int decorr_left_weight);
void ff_alac_append_extra_bits_stereo_sse2(int32_t *buffer[2], int32_t *extra_bits_buffer[2],
                                           int extra_bits, int channels, int nb_samples);
void ff_alac_append_extra_bits_mono_sse2(int32_t *buffer[2], int32_t *extra_bits_buffer[2],
                                         int extra_bits, int channels, int nb_samples);

av_cold void ff_alacdsp_init_x86(ALACDSPContext *c)
{
#if HAVE_X86ASM
    int cpu_flags = av_get_cpu_flags();

    if (EXTERNAL_SSE2(cpu_flags)) {
        c->append_extra_bits[0] = ff_alac_append_extra_bits_mono_sse2;
        c->append_extra_bits[1] = ff_alac_append_extra_bits_stereo_sse2;
    }
    if (EXTERNAL_SSE4(cpu_flags)) {
        c->decorrelate_stereo   = ff_alac_decorrelate_stereo_sse4;
    }
#endif /* HAVE_X86ASM */
}


text:
@interface DMParamBuilder : NSObject

+ (NSString*)for:(NSDictionary*)params;

+ (DMBodyBuilder)for:(NSDictionary*)params request:(DMRequest*)request;

@end


text:
/*
   ARPACK++ v1.2 2/20/2000
   c++ interface to ARPACK code.

   MODULE ARLUtil.h.
   Unaltered copy of util.h (from SuperLU package).
*/

#ifndef __SUPERLU_UTIL /* allow multiple inclusions */
#define __SUPERLU_UTIL

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <assert.h>

/* Macros */
#ifndef USER_ABORT
#define USER_ABORT(msg) superlu_abort_and_exit(msg)
#endif

#define ABORT(err_msg) \
 { char msg[256];\
   sprintf(msg,"%s at line %d in file %s\n",err_msg,__LINE__, __FILE__);\
   USER_ABORT(msg); }

#ifndef USER_MALLOC
#define USER_MALLOC(size) superlu_malloc(size)
#endif

#define SUPERLU_MALLOC(size) USER_MALLOC(size)

#ifndef USER_FREE
#define USER_FREE(addr) superlu_free(addr)
#endif

#define SUPERLU_FREE(addr) USER_FREE(addr)

#define MAX(x, y) 	( (x) > (y) ? (x) : (y) )
#define MIN(x, y) 	( (x) < (y) ? (x) : (y) )

/*
 * Constants
 */
#define EMPTY	(-1)
#define NO	(-1)
#define FALSE	0
#define TRUE	1

/*
 * Type definitions
 */
typedef float    flops_t;
typedef unsigned char Logical;

/*
 * The following enumerate type is used by the statistics variable
 * SuperLUStat, to keep track of flop count and time spent at various stages.
 *
 * Note that not all of the fields are disjoint.
 */
typedef enum {
    COLPERM, /* find a column ordering that minimizes fills */
    RELAX,   /* find artificial supernodes */
    ETREE,   /* compute column etree */
    EQUIL,   /* equilibrate the original matrix */
    FACT,    /* perform LU factorization */
    RCOND,   /* estimate reciprocal condition number */
    SOLVE,   /* forward and back solves */
    REFINE,  /* perform iterative refinement */
    TFLOAT,   /* time spent in floating-point operations */
    TRSV,    /* fraction of FACT spent in xTRSV */
    GEMV,    /* fraction of FACT spent in xGEMV */
    FERR,    /* estimate error bounds after iterative refinement */
    NPHASES  /* total number of phases */
} PhaseType;

typedef struct {
    int     *panel_histo; /* histogram of panel size distribution */
    double  *utime;       /* running time at various phases */
    flops_t *ops;         /* operation count at various phases */
} SuperLUStat_t;

/* Macros */
#define FIRSTCOL_OF_SNODE(i)	(xsup[i])

#ifdef __cplusplus
extern "C" {
#endif

extern void    superlu_abort_and_exit(char*);
extern void    *superlu_malloc (int);
extern int     *intMalloc (int);
extern int     *intCalloc (int);
extern void    superlu_free (void*);
extern void    SetIWork (int, int, int, int *, int **, int **, int **,
                         int **, int **, int **, int **);
extern void    StatInit(int, int);
extern void    StatFree();
extern int     sp_coletree (int *, int *, int *, int, int, int *);
extern void    relax_snode  (int, int *, int, int *, int *);
extern void    resetrep_col (const int, const int *, int *);
extern int     spcoletree (int *, int *, int *, int, int, int *);
extern int     *TreePostorder (int, int *);
extern double  SuperLU_timer_ ();
extern int     sp_ienv (int);
extern int     lsame_ (char *, char *);
extern int     xerbla_ (char *, int *);
extern void    ifill (int *, int, int);
extern void    snode_profile (int, int *);
extern void    super_stats (int, int *);
extern void    PrintSumm (char *, int, int, int);
extern void    PrintStat (SuperLUStat_t *);
extern void    print_panel_seg(int, int, int, int, int *, int *);
extern void    check_repfnz(int, int, int, int *);

#ifdef __cplusplus
  }
#endif

#endif /* __SUPERLU_UTIL */


text:
package io.netty.handler.codec.compression;

public class JZlibTest extends ZlibTest {

    @Override
    protected ZlibEncoder createEncoder(ZlibWrapper wrapper) {
        return new JZlibEncoder(wrapper);
    }

    @Override
    protected ZlibDecoder createDecoder(ZlibWrapper wrapper, int maxAllocation) {
        return new JZlibDecoder(wrapper, maxAllocation);
    }
}


text:
import util, { empty, each, pull } from './util'
import { REGEX_EVENT } from './const'
import BaseValidation from './validations/base'
import CheckboxValidation from './validations/checkbox'
import RadioValidation from './validations/radio'
import SelectValidation from './validations/select'

/**
 * Validator class
 */

export default class Validator {

  constructor (name, dir, groups, classes) {
    this.name = name

    this._scope = {}
    this._dir = dir
    this._validations = {}
    this._checkboxValidations = {}
    this._radioValidations = {}
    this._groups = groups
    this._groupValidations = {}
    this._events = {}
    this._modified = false
    this._classes = classes

    each(groups, (group) => {
      this._groupValidations[group] = []
    })
  }

  enableReactive () {
    let vm = this._dir.vm

    // define the validation scope
    util.Vue.util.defineReactive(vm, this.name, this._scope)
    vm._validatorMaps[this.name] = this

    // define the validation resetting meta method to vue instance
    this._defineResetValidation()

    // define the validate manually meta method to vue instance
    this._defineValidate()

    // define manually the validation errors
    this._defineSetValidationErrors()
  }

  disableReactive () {
    let vm = this._dir.vm
    vm.$setValidationErrors = null
    delete vm['$setValidationErrors']
    vm.$validate = null
    delete vm['$validate']
    vm.$validatorReset = null
    delete vm['$validatorReset']
    vm._validatorMaps[this.name] = null
    delete vm._validatorMaps[this.name]
    vm[this.name] = null
    delete vm[this.name]
  }

  registerEvents () {
    const { isSimplePath } = util.Vue.parsers.expression
    const attrs = this._dir.el.attributes
    for (let i = 0, l = attrs.length; i < l; i++) {
      let event = attrs[i].name
      if (REGEX_EVENT.test(event)) {
        let value = attrs[i].value
        if (isSimplePath(value)) {
          value += '.apply(this, $arguments)'
        }
        event = event.replace(REGEX_EVENT, '')
        this._events[this._getEventName(event)] = this._dir.vm.$eval(value, true)
      }
    }
  }

  unregisterEvents () {
    each(this._events, (handler, event) => {
      this._events[event] = null
      delete this._events[event]
    })
  }

  get validations () {
    const extend = util.Vue.util.extend

    let ret = {}
    extend(ret, this._validations)

    each(this._checkboxValidations, (dataset, key) => {
      ret[key] = dataset.validation
    })

    each(this._radioValidations, (dataset, key) => {
      ret[key] = dataset.validation
    })

    return ret
  }

  manageValidation (field, model, vm, el, scope, filters, initial, detectBlur, detectChange) {
    let validation = null

    if (el.tagName === 'SELECT') {
      validation = this._manageSelectValidation(
        field, model, vm, el, scope, filters, initial, detectBlur, detectChange
      )
    } else if (el.type === 'checkbox') {
      validation = this._manageCheckboxValidation(
        field, model, vm, el, scope, filters, initial, detectBlur, detectChange
      )
    } else if (el.type === 'radio') {
      validation = this._manageRadioValidation(
        field, model, vm, el, scope, filters, initial, detectBlur, detectChange
      )
    } else {
      validation = this._manageBaseValidation(
        field, model, vm, el, scope, filters, initial, detectBlur, detectChange
      )
    }

    validation.setValidationClasses(this._classes)

    return validation
  }

  unmanageValidation (field, el) {
    if (el.type === 'checkbox') {
      this._unmanageCheckboxValidation(field, el)
    } else if (el.type === 'radio') {
      this._unmanageRadioValidation(field, el)
    } else if (el.tagName === 'SELECT') {
      this._unmanageSelectValidation(field, el)
    } else {
      this._unmanageBaseValidation(field, el)
    }
  }

  addGroupValidation (group, field) {
    const { indexOf } = util.Vue.util
    const validation = this._getValidationFrom(field)
    const validations = this._groupValidations[group]

    validations && !~indexOf(validations, validation) && validations.push(validation)
  }

  removeGroupValidation (group, field) {
    const validation = this._getValidationFrom(field)
    const validations = this._groupValidations[group]

    validations && pull(validations, validation)
  }

  validate ({ el = null, field = null, touched = false, noopable = false, cb = null } = {}) {
    if (!field) { // all
      each(this.validations, (validation, key) => {
        validation.willUpdateFlags(touched)
      })
      this._validates(cb)
    } else { // each field
      this._validate(field, touched, noopable, el, cb)
    }
  }

  setupScope () {
    this._defineProperties(() => { return this.validations }, () => { return this._scope })

    each(this._groups, (name) => {
      let validations = this._groupValidations[name]
      let group = {}
      util.Vue.set(this._scope, name, group)
      this._defineProperties(() => { return validations }, () => { return group })
    })
  }

  waitFor (cb) {
    const method = '$activateValidator'
    let vm = this._dir.vm

    vm[method] = () => {
      cb()
      vm[method] = null
    }
  }

  _defineResetValidation () {
    this._dir.vm.$resetValidation = (cb) => {
      this._resetValidation(cb)
    }
  }

  _defineValidate () {
    this._dir.vm.$validate = (...args) => {
      let field = null
      let touched = false
      let cb = null

      each(args, (arg, index) => {
        if (typeof arg === 'string') {
          field = arg
        } else if (typeof arg === 'boolean') {
          touched = arg
        } else if (typeof arg === 'function') {
          cb = arg
        }
      })

      this.validate({ field: field, touched: touched, cb: cb })
    }
  }

  _defineSetValidationErrors () {
    this._dir.vm.$setValidationErrors = (errors) => {
      this._setValidationErrors(errors)
    }
  }

  _validate (field, touched = false, noopable = false, el = null, cb = null) {
    const scope = this._scope

    const validation = this._getValidationFrom(field)
    if (validation) {
      validation.willUpdateFlags(touched)
      validation.validate((results) => {
        util.Vue.set(scope, field, results)
        this._fireEvents()
        cb && cb()
      }, noopable, el)
    }
  }

  _validates (cb) {
    const scope = this._scope

    this._runValidates((validation, key, done) => {
      validation.validate((results) => {
        util.Vue.set(scope, key, results)
        done()
      })
    }, () => { // finished
      this._fireEvents()
      cb && cb()
    })
  }

  _getValidationFrom (field) {
    return this._validations[field]
      || (this._checkboxValidations[field] && this._checkboxValidations[field].validation)
      || (this._radioValidations[field] && this._radioValidations[field].validation)
  }

  _resetValidation (cb) {
    each(this.validations, (validation, key) => {
      validation.reset()
    })
    this._validates(cb)
  }

  _setValidationErrors (errors) {
    const { extend } = util.Vue.util

    // make tempolaly errors
    const temp = {}
    each(errors, (error, index) => {
      if (!temp[error.field]) {
        temp[error.field] = []
      }
      temp[error.field].push(error)
    })

    // set errors
    each(temp, (values, field) => {
      const results = this._scope[field]
      const newResults = {}

      each(values, (error) => {
        if (error.validator) {
          results[error.validator] = error.message
        }
      })

      results.valid = false
      results.invalid = true
      results.errors = values
      extend(newResults, results)

      const validation = this._getValidationFrom(field)
      validation.willUpdateClasses(newResults, validation.el)

      util.Vue.set(this._scope, field, newResults)
    })
  }

  _manageBaseValidation (field, model, vm, el, scope, filters, initial, detectBlur, detectChange) {
    let validation = this._validations[field] = new BaseValidation(
      field, model, vm, el, scope, this, filters, detectBlur, detectChange
    )
    validation.manageElement(el, initial)
    return validation
  }

  _unmanageBaseValidation (field, el) {
    let validation = this._validations[field]
    if (validation) {
      validation.unmanageElement(el)
      util.Vue.delete(this._scope, field)
      this._validations[field] = null
      delete this._validations[field]
    }
  }

  _manageCheckboxValidation (field, model, vm, el, scope, filters, initial, detectBlur, detectChange) {
    let validationSet = this._checkboxValidations[field]
    if (!validationSet) {
      let validation = new CheckboxValidation(field, model, vm, el, scope, this, filters, detectBlur, detectChange)
      validationSet = { validation: validation, elements: 0 }
      this._checkboxValidations[field] = validationSet
    }

    validationSet.elements++
    validationSet.validation.manageElement(el, initial)
    return validationSet.validation
  }

  _unmanageCheckboxValidation (field, el) {
    let validationSet = this._checkboxValidations[field]
    if (validationSet) {
      validationSet.elements--
      validationSet.validation.unmanageElement(el)
      if (validationSet.elements === 0) {
        util.Vue.delete(this._scope, field)
        this._checkboxValidations[field] = null
        delete this._checkboxValidations[field]
      }
    }
  }

  _manageRadioValidation (field, model, vm, el, scope, filters, initial, detectBlur, detectChange) {
    let validationSet = this._radioValidations[field]
    if (!validationSet) {
      let validation = new RadioValidation(field, model, vm, el, scope, this, filters, detectBlur, detectChange)
      validationSet = { validation: validation, elements: 0 }
      this._radioValidations[field] = validationSet
    }

    validationSet.elements++
    validationSet.validation.manageElement(el, initial)
    return validationSet.validation
  }

  _unmanageRadioValidation (field, el) {
    let validationSet = this._radioValidations[field]
    if (validationSet) {
      validationSet.elements--
      validationSet.validation.unmanageElement(el)
      if (validationSet.elements === 0) {
        util.Vue.delete(this._scope, field)
        this._radioValidations[field] = null
        delete this._radioValidations[field]
      }
    }
  }

  _manageSelectValidation (field, model, vm, el, scope, filters, initial, detectBlur, detectChange) {
    let validation = this._validations[field] = new SelectValidation(
        field, model, vm, el, scope, this, filters, detectBlur, detectChange
    )
    validation.manageElement(el, initial)
    return validation
  }

  _unmanageSelectValidation (field, el) {
    let validation = this._validations[field]
    if (validation) {
      validation.unmanageElement(el)
      util.Vue.delete(this._scope, field)
      this._validations[field] = null
      delete this._validations[field]
    }
  }

  _fireEvent (type, ...args) {
    const handler = this._events[this._getEventName(type)]
    handler && this._dir.vm.$nextTick(() => {
      handler.apply(null, args)
    })
  }

  _fireEvents () {
    const scope = this._scope

    scope.touched && this._fireEvent('touched')
    scope.dirty && this._fireEvent('dirty')

    if (this._modified !== scope.modified) {
      this._fireEvent('modified', scope.modified)
      this._modified = scope.modified
    }

    let valid = scope.valid
    this._fireEvent(valid ? 'valid' : 'invalid')
  }

  _getEventName (type) {
    return this.name + ':' + type
  }

  _defineProperties (validationsGetter, targetGetter) {
    const bind = util.Vue.util.bind

    each({
      valid: { fn: this._defineValid, arg: validationsGetter },
      invalid: { fn: this._defineInvalid, arg: targetGetter },
      touched: { fn: this._defineTouched, arg: validationsGetter },
      untouched: { fn: this._defineUntouched, arg: targetGetter },
      modified: { fn: this._defineModified, arg: validationsGetter },
      dirty: { fn: this._defineDirty, arg: validationsGetter },
      pristine: { fn: this._definePristine, arg: targetGetter },
      errors: { fn: this._defineErrors, arg: validationsGetter }
    }, (descriptor, name) => {
      Object.defineProperty(targetGetter(), name, {
        enumerable: true,
        configurable: true,
        get: () => {
          return bind(descriptor.fn, this)(descriptor.arg)
        }
      })
    })
  }

  _runValidates (fn, cb) {
    const length = Object.keys(this.validations).length

    let count = 0
    each(this.validations, (validation, key) => {
      fn(validation, key, () => {
        ++count
        count >= length && cb()
      })
    })
  }

  _walkValidations (validations, property, condition) {
    const hasOwn = util.Vue.util.hasOwn
    let ret = condition

    each(validations, (validation, key) => {
      if (ret === !condition) { return }
      if (hasOwn(this._scope, validation.field)) {
        let target = this._scope[validation.field]
        if (target && target[property] === !condition) {
          ret = !condition
        }
      }
    })

    return ret
  }

  _defineValid (validationsGetter) {
    return this._walkValidations(validationsGetter(), 'valid', true)
  }

  _defineInvalid (scopeGetter) {
    return !scopeGetter().valid
  }

  _defineTouched (validationsGetter) {
    return this._walkValidations(validationsGetter(), 'touched', false)
  }

  _defineUntouched (scopeGetter) {
    return !scopeGetter().touched
  }

  _defineModified (validationsGetter) {
    return this._walkValidations(validationsGetter(), 'modified', false)
  }

  _defineDirty (validationsGetter) {
    return this._walkValidations(validationsGetter(), 'dirty', false)
  }

  _definePristine (scopeGetter) {
    return !scopeGetter().dirty
  }

  _defineErrors (validationsGetter) {
    const hasOwn = util.Vue.util.hasOwn
    const isPlainObject = util.Vue.util.isPlainObject
    let errors = []

    each(validationsGetter(), (validation, key) => {
      if (hasOwn(this._scope, validation.field)) {
        let target = this._scope[validation.field]
        if (target && !empty(target.errors)) {
          each(target.errors, (err, index) => {
            let error = { field: validation.field }
            if (isPlainObject(err)) {
              if (err.validator) {
                error.validator = err.validator
              }
              error.message = err.message
            } else if (typeof err === 'string') {
              error.message = err
            }
            errors.push(error)
          })
        }
      }
    })

    return empty(errors) ? undefined : errors.sort((a, b) => {
      return (a.field < b.field) ? -1 : 1
    })
  }
}


text:
#include <aws/macie2/model/CreateClassificationJobRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Macie2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

CreateClassificationJobRequest::CreateClassificationJobRequest() :
    m_allowListIdsHasBeenSet(false),
    m_clientToken(Aws::Utils::UUID::RandomUUID()),
    m_clientTokenHasBeenSet(true),
    m_customDataIdentifierIdsHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_initialRun(false),
    m_initialRunHasBeenSet(false),
    m_jobType(JobType::NOT_SET),
    m_jobTypeHasBeenSet(false),
    m_managedDataIdentifierIdsHasBeenSet(false),
    m_managedDataIdentifierSelector(ManagedDataIdentifierSelector::NOT_SET),
    m_managedDataIdentifierSelectorHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_s3JobDefinitionHasBeenSet(false),
    m_samplingPercentage(0),
    m_samplingPercentageHasBeenSet(false),
    m_scheduleFrequencyHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
}

Aws::String CreateClassificationJobRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_allowListIdsHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> allowListIdsJsonList(m_allowListIds.size());
   for(unsigned allowListIdsIndex = 0; allowListIdsIndex < allowListIdsJsonList.GetLength(); ++allowListIdsIndex)
   {
     allowListIdsJsonList[allowListIdsIndex].AsString(m_allowListIds[allowListIdsIndex]);
   }
   payload.WithArray("allowListIds", std::move(allowListIdsJsonList));

  }

  if(m_clientTokenHasBeenSet)
  {
   payload.WithString("clientToken", m_clientToken);

  }

  if(m_customDataIdentifierIdsHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> customDataIdentifierIdsJsonList(m_customDataIdentifierIds.size());
   for(unsigned customDataIdentifierIdsIndex = 0; customDataIdentifierIdsIndex < customDataIdentifierIdsJsonList.GetLength(); ++customDataIdentifierIdsIndex)
   {
     customDataIdentifierIdsJsonList[customDataIdentifierIdsIndex].AsString(m_customDataIdentifierIds[customDataIdentifierIdsIndex]);
   }
   payload.WithArray("customDataIdentifierIds", std::move(customDataIdentifierIdsJsonList));

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("description", m_description);

  }

  if(m_initialRunHasBeenSet)
  {
   payload.WithBool("initialRun", m_initialRun);

  }

  if(m_jobTypeHasBeenSet)
  {
   payload.WithString("jobType", JobTypeMapper::GetNameForJobType(m_jobType));
  }

  if(m_managedDataIdentifierIdsHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> managedDataIdentifierIdsJsonList(m_managedDataIdentifierIds.size());
   for(unsigned managedDataIdentifierIdsIndex = 0; managedDataIdentifierIdsIndex < managedDataIdentifierIdsJsonList.GetLength(); ++managedDataIdentifierIdsIndex)
   {
     managedDataIdentifierIdsJsonList[managedDataIdentifierIdsIndex].AsString(m_managedDataIdentifierIds[managedDataIdentifierIdsIndex]);
   }
   payload.WithArray("managedDataIdentifierIds", std::move(managedDataIdentifierIdsJsonList));

  }

  if(m_managedDataIdentifierSelectorHasBeenSet)
  {
   payload.WithString("managedDataIdentifierSelector", ManagedDataIdentifierSelectorMapper::GetNameForManagedDataIdentifierSelector(m_managedDataIdentifierSelector));
  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("name", m_name);

  }

  if(m_s3JobDefinitionHasBeenSet)
  {
   payload.WithObject("s3JobDefinition", m_s3JobDefinition.Jsonize());

  }

  if(m_samplingPercentageHasBeenSet)
  {
   payload.WithInteger("samplingPercentage", m_samplingPercentage);

  }

  if(m_scheduleFrequencyHasBeenSet)
  {
   payload.WithObject("scheduleFrequency", m_scheduleFrequency.Jsonize());

  }

  if(m_tagsHasBeenSet)
  {
   JsonValue tagsJsonMap;
   for(auto& tagsItem : m_tags)
   {
     tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
   }
   payload.WithObject("tags", std::move(tagsJsonMap));

  }

  return payload.View().WriteReadable();
}


text:
window.browser = window.browser || {}
window.bloom = window.bloom || {}
bloom.Garden = function() {}
bloom.Garden.vineyard_url = 'http://localhost:3000/'
bloom.Garden.start = function() {
  var $injector = angular.injector(['ng'])
  window.$q = $injector.get('$q')
  bloom.Garden.query({
    trellis: 'user',
    filters: [
      {
        path: 'id',
        value: 'user',
        type: 'parameter'
      }
    ],
    version: '1.0.0.browser'
  }).then(function(response) {
    var user = response.objects[0]
    if (user.username == 'anonymous')
      bloom.Garden.goto('garden-login')
    else
      bloom.Garden.goto('garden-hub')
  })
}
bloom.Garden.goto = function(name) {
  $('.current-page').remove()
  var new_page = $('<' + name + '/>')
  new_page.addClass('current-page')
  new_page.insertAfter($('header'))
}
bloom.Garden.query = function(data) {
  return bloom.Garden.post('vineyard/query', data)
}
bloom.Garden.post = function(path, data) {
  return bloom.Garden.http('POST', path, data)
}
bloom.Garden.get = function(path) {
  return bloom.Garden.http('GET', path)
}
bloom.Garden.http = function(method, path, data) {
  if (data === undefined)
    data = null

  var def = $q.defer()
  var options = {
    method: method,
    contentType: 'application/json',
    crossDomain: true,
    xhrFields: {
      withCredentials: true
    },
    data: JSON.stringify(data),
    dataType: 'json',
    success: function(response) {
      def.resolve(response)
    }
  }
  jQuery.ajax(bloom.Garden.vineyard_url + path, options)
  return def.promise
}


text:
#pragma once
#include <aws/wafv2/WAFV2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace WAFV2
{
namespace Model
{

  /**
   *
A version of the named managed rule group, that the rule group's vendor
   * publishes for use by customers.

This is intended for use only by
   * vendors of managed rule sets. Vendors are Amazon Web Services and Amazon Web
   * Services Marketplace sellers.

Vendors, you can use the managed rule set
   * APIs to provide controlled rollout of your versioned managed rule group
   * offerings for your customers. The APIs are ListManagedRuleSets,
   * GetManagedRuleSet, PutManagedRuleSetVersions, and
   * UpdateManagedRuleSetVersionExpiryDate.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_WAFV2_API VersionToPublish
  {
  public:
    VersionToPublish();
    VersionToPublish(Aws::Utils::Json::JsonView jsonValue);
    VersionToPublish& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The Amazon Resource Name (ARN) of the vendor's rule group that's used in the
     * published managed rule group version.

     */
    inline const Aws::String& GetAssociatedRuleGroupArn() const{ return m_associatedRuleGroupArn; }

    /**
     *
The Amazon Resource Name (ARN) of the vendor's rule group that's used in the
     * published managed rule group version.

     */
    inline bool AssociatedRuleGroupArnHasBeenSet() const { return m_associatedRuleGroupArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the vendor's rule group that's used in the
     * published managed rule group version.

     */
    inline void SetAssociatedRuleGroupArn(const Aws::String& value) { m_associatedRuleGroupArnHasBeenSet = true; m_associatedRuleGroupArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the vendor's rule group that's used in the
     * published managed rule group version.

     */
    inline void SetAssociatedRuleGroupArn(Aws::String&& value) { m_associatedRuleGroupArnHasBeenSet = true; m_associatedRuleGroupArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the vendor's rule group that's used in the
     * published managed rule group version.

     */
    inline void SetAssociatedRuleGroupArn(const char* value) { m_associatedRuleGroupArnHasBeenSet = true; m_associatedRuleGroupArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the vendor's rule group that's used in the
     * published managed rule group version.

     */
    inline VersionToPublish& WithAssociatedRuleGroupArn(const Aws::String& value) { SetAssociatedRuleGroupArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the vendor's rule group that's used in the
     * published managed rule group version.

     */
    inline VersionToPublish& WithAssociatedRuleGroupArn(Aws::String&& value) { SetAssociatedRuleGroupArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the vendor's rule group that's used in the
     * published managed rule group version.

     */
    inline VersionToPublish& WithAssociatedRuleGroupArn(const char* value) { SetAssociatedRuleGroupArn(value); return *this;}

    /**
     *
The amount of time the vendor expects this version of the managed rule group
     * to last, in days.

     */
    inline int GetForecastedLifetime() const{ return m_forecastedLifetime; }

    /**
     *
The amount of time the vendor expects this version of the managed rule group
     * to last, in days.

     */
    inline bool ForecastedLifetimeHasBeenSet() const { return m_forecastedLifetimeHasBeenSet; }

    /**
     *
The amount of time the vendor expects this version of the managed rule group
     * to last, in days.

     */
    inline void SetForecastedLifetime(int value) { m_forecastedLifetimeHasBeenSet = true; m_forecastedLifetime = value; }

    /**
     *
The amount of time the vendor expects this version of the managed rule group
     * to last, in days.

     */
    inline VersionToPublish& WithForecastedLifetime(int value) { SetForecastedLifetime(value); return *this;}

  private:

    Aws::String m_associatedRuleGroupArn;
    bool m_associatedRuleGroupArnHasBeenSet = false;

    int m_forecastedLifetime;
    bool m_forecastedLifetimeHasBeenSet = false;
  };

} // namespace Model
} // namespace WAFV2
} // namespace Aws


text:
JPAttributedStringBuilder
=========================

A DSL for creating NSStrings and NSAttributedStrings

[ ![Build Status] [travis-image] ] [travis]
[ ![Version] [cocoa-version] ] [cocoadocs]
[ ![Platform] [cocoa-plaform] ] [cocoadocs]

## Installation

Install with [CocoaPods](http://cocoapods.org):

```
pod 'JPAttributedStringBuilder'
```

## Usage

#### NSAttributedString Creation

Have you ever had to append a bunch of `NSAttributedStrings`?

```
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] init];

[text appendAttributedString:
     [[NSAttributedString alloc] initWithString:firstName
                                     attributes:@{
                                                  NSFontAttributeName : [UIFont boldSystemFont:12.0f],
                                                  NSForegroundColorAttributeName : [UIColor blackColor]
                                                  }]];

[text appendAttributedString:
     [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n", self.search.neighborhoodsString]
                                     attributes:@{
                                                  NSFontAttributeName : [UIFont proximaNovaBoldWithSize:16.0f],
                                                  NSForegroundColorAttributeName : [UIColor ucDarkColor]
                                                  }]];

[text appendAttributedString:
     [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@", self.bedPriceString]
                                     attributes:@{
                                                  NSFontAttributeName : [UIFont proximaNovaRegularWithSize:14.0f],
                                                  NSForegroundColorAttributeName : [UIColor ucDarkColor]
                                                  }]];
```

Is this better?

```
JPAttributedStringBuilder *stringBuilder = [[JPAttributedStringBuilder alloc] init];
stringBuilder.font = [UIFont systemFontOfSize:14.f];
stringBuilder.foregroundColor = [UIColor redColor];
stringBuilder.backgroundColor = [UIColor lightGrayColor];
stringBuilder.text = @"This is a better string";

NSAttributedString *jpAttributedString = [stringBuilder build];
```

## Examples

There is an example included with the project. To install,

```
$ pod install
$ open ZipLocateSample.xcworkspace/
```

##Contribute

Send me pull requests!

##Authors

James Paolantonio - [@jpaolantonio](http://twitter.com/jPaolantonio)

####Extra

Let me know if you are using this or want anything changed!! :)

[travis]: https://travis-ci.org/jPaolantonio/JPAttributedStringBuilder
[travis-image]: http://img.shields.io/travis/jPaolantonio/JPAttributedStringBuilder.svg?branch=master

[cocoadocs]: http://cocoadocs.org/docsets/JPAttributedStringBuilder
[cocoa-version]: http://cocoapod-badges.herokuapp.com/v/JPAttributedStringBuilder/badge.png
[cocoa-plaform]: http://cocoapod-badges.herokuapp.com/p/JPAttributedStringBuilder/badge.png


text:
package org.springframework.web.reactive.socket.adapter;

import java.util.HashMap;
import java.util.Map;

import io.netty5.buffer.Buffer;
import io.netty5.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty5.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty5.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty5.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty5.handler.codec.http.websocketx.WebSocketFrame;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.Netty5DataBufferFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.reactive.socket.HandshakeInfo;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;

/**
 * Base class for Netty-based {@link WebSocketSession} adapters that provides
 * convenience methods to convert Netty {@link WebSocketFrame WebSocketFrames} to and from
 * {@link WebSocketMessage WebSocketMessages}.
 *
 * <p>This class is based on {@link NettyWebSocketSessionSupport}.
 *
 * @author Violeta Georgieva
 * @since 6.0
 * @param <T> the native delegate type
 */
public abstract class Netty5WebSocketSessionSupport<T> extends AbstractWebSocketSession<T> {

	/**
	 * The default max size for inbound WebSocket frames.
	 */
	public static final int DEFAULT_FRAME_MAX_SIZE = 64 * 1024;

	private static final Map<Class<?>, WebSocketMessage.Type> messageTypes;

	static {
		messageTypes = new HashMap<>(8);
		messageTypes.put(TextWebSocketFrame.class, WebSocketMessage.Type.TEXT);
		messageTypes.put(BinaryWebSocketFrame.class, WebSocketMessage.Type.BINARY);
		messageTypes.put(PingWebSocketFrame.class, WebSocketMessage.Type.PING);
		messageTypes.put(PongWebSocketFrame.class, WebSocketMessage.Type.PONG);
	}

	protected Netty5WebSocketSessionSupport(T delegate, HandshakeInfo info, Netty5DataBufferFactory factory) {
		super(delegate, ObjectUtils.getIdentityHexString(delegate), info, factory);
	}

	@Override
	public Netty5DataBufferFactory bufferFactory() {
		return (Netty5DataBufferFactory) super.bufferFactory();
	}

	protected WebSocketMessage toMessage(WebSocketFrame frame) {
		DataBuffer payload = bufferFactory().wrap(frame.binaryData());
		return new WebSocketMessage(messageTypes.get(frame.getClass()), payload, frame);
	}

	protected WebSocketFrame toFrame(WebSocketMessage message) {
		if (message.getNativeMessage() != null) {
			return message.getNativeMessage();
		}
		Buffer buffer = Netty5DataBufferFactory.toBuffer(message.getPayload());
		if (WebSocketMessage.Type.TEXT.equals(message.getType())) {
			return new TextWebSocketFrame(buffer);
		}
		else if (WebSocketMessage.Type.BINARY.equals(message.getType())) {
			return new BinaryWebSocketFrame(buffer);
		}
		else if (WebSocketMessage.Type.PING.equals(message.getType())) {
			return new PingWebSocketFrame(buffer);
		}
		else if (WebSocketMessage.Type.PONG.equals(message.getType())) {
			return new PongWebSocketFrame(buffer);
		}
		else {
			throw new IllegalArgumentException("Unexpected message type: " + message.getType());
		}
	}

}


text:
static CGEventRef MyEventTapCallBack(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon);

@interface BCAppDelegate ()
- (void)startTracking;

- (void)endTracking;
@end

@implementation BCAppDelegate
{
	CFMachPortRef eventTapPortRef;
	CFRunLoopSourceRef source;

	NSStatusItem *statusItem;
	BOOL enabled;
}

- (void)dealloc
{
	[[NSStatusBar systemStatusBar] removeStatusItem:statusItem];

	if (source) {
		CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);
		CFRelease(source);
		source = NULL;
	}

	if (eventTapPortRef) {
		CGEventTapEnable(eventTapPortRef, NO);
		CFRelease(eventTapPortRef);
		eventTapPortRef = NULL;
	}
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
	self.window.alphaValue = 0.5;

	statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:80.0];
	statusItem.title = @"Big Cursor";
	NSMenu *menu = [[NSMenu alloc] initWithTitle:@"Big Cursor"];
	NSMenuItem *enableItem = [menu addItemWithTitle:@"Enabled" action:@selector(enable:) keyEquivalent:@""];
	enableItem.target = self;
	[menu addItem:[NSMenuItem separatorItem]];
	[menu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@""];
	statusItem.menu = menu;

	enabled = YES;
	[self startTracking];
}

- (void)startTracking
{
	CGEventRef ourEvent = CGEventCreate(NULL);
	CGPoint p = CGEventGetLocation(ourEvent);
	[self moveWindowToPoint:p];
	CFRelease(ourEvent);

	if (!eventTapPortRef) {
		CGEventMask mask = \
            CGEventMaskBit(kCGEventMouseMoved) | CGEventMaskBit(kCGEventLeftMouseDragged) | CGEventMaskBit(kCGEventRightMouseDragged);
		// CGEventTapCreate requires "NSAppleEventsUsageDescription" in Info.plist file
		// since macOS Mojave.
		eventTapPortRef = CGEventTapCreate(kCGSessionEventTap, kCGTailAppendEventTap, 0, mask, MyEventTapCallBack, (__bridge void *) (self));

	}
	if (!eventTapPortRef) {
		return;
	}

	if (!source) {
		source = CFMachPortCreateRunLoopSource(NULL, eventTapPortRef, 0);
		CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);
	}
	if (!CGEventTapIsEnabled(eventTapPortRef)) {
		CGEventTapEnable(eventTapPortRef, YES);
	}
	[self.window orderFront:nil];
}

- (void)endTracking
{
	[self.window orderOut:nil];
	if (eventTapPortRef) {
		CGEventTapEnable(eventTapPortRef, NO);
	}
}

- (void)moveWindowToPoint:(CGPoint)p
{
	p.y = [[NSScreen mainScreen] frame].size.height - p.y;
	p.y -= self.window.frame.size.height;
	NSPoint nspoint = NSPointFromCGPoint(p);
	[self.window setFrameOrigin:nspoint];
}

#pragma mark -

- (IBAction)enable:(id)sender
{
	enabled = !enabled;
	enabled ? [self startTracking] : [self endTracking];
}

- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
	if (menuItem.action == @selector(enable:)) {
		menuItem.state = enabled;
		return YES;
	}
	return YES;
}

#pragma mark -

CGEventRef MyEventTapCallBack(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
	@autoreleasepool {
		BCAppDelegate *self = (__bridge BCAppDelegate *) (refcon);
		CGPoint p = CGEventGetLocation(event);
		[self moveWindowToPoint:p];
	}
	return event;
}

@end


text:
SpreeDocuments
==============

Add documents to your Spree Products!

Installation
------------

Add spree_documents to your Gemfile:

```ruby
gem 'spree_documents'
```

Bundle your dependencies and run the installation generator:

```shell
bundle
bundle exec rails g spree_documents:install
```

Testing
-------

First bundle your dependencies, then run `rake`. `rake` will default to building the dummy app if it does not exist, then it will run specs. The dummy app can be regenerated by using `rake test_app`.

```shell
bundle
bundle exec rake
```

When testing your applications integration with this extension you may use it's factories.
Simply add this require statement to your spec_helper:

```ruby
require 'spree_documents/factories'
```

Released under the New BSD License


text:
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
#[cfg(feature = "ssl")]
use std::path::PathBuf;

use time;

use num_cpus;

use url::percent_encoding::{percent_decode, percent_decode_to};
use url::{Url, SchemeData};

use hyper;
use hyper::server::Handler as HyperHandler;
use hyper::header::{Date, ContentType};
use hyper::mime::Mime;
use hyper::uri::RequestUri;
use hyper::net::HttpListener;
#[cfg(feature = "ssl")]
use hyper::net::{Openssl, HttpsListener};

pub use hyper::server::Listening;

use anymap::AnyMap;

use StatusCode;

use context::{self, Context, Uri, MaybeUtf8Owned, Parameters};
use filter::{FilterContext, ContextFilter, ContextAction, ResponseFilter};
use router::{Router, Endpoint};
use handler::Handler;
use response::Response;
use header::HttpDate;
use server::{Scheme, Global, KeepAlive};

use HttpResult;
use Server;

use utils;

///A runnable instance of a server.
///
///It's not meant to be used directly,
///unless additional control is required.
///
///```no_run
///# use rustful::{Server, Handler, Context, Response};
///# #[derive(Default)]
///# struct R;
///# impl Handler for R {
///#     fn handle_request(&self, _context: Context, _response: Response) {}
///# }
///# let router = R;
///let (server_instance, scheme) = Server {
///    host: 8080.into(),
///    handlers: router,
///    ..Server::default()
///}.build();
///```
pub struct ServerInstance<R: Router> {
    handlers: R,
    fallback_handler: Option<R::Handler>,

    host: SocketAddr,

    server: String,
    content_type: Mime,

    threads: usize,
    keep_alive: Option<KeepAlive>,
    threads_in_use: AtomicUsize,

    context_filters: Vec<Box<ContextFilter>>,
    response_filters: Vec<Box<ResponseFilter>>,

    global: Global,
}

impl<R: Router> ServerInstance<R> {
    ///Create a new server instance, with the provided configuration. This is
    ///the same as `Server{...}.build()`.
    pub fn new(config: Server<R>) -> (ServerInstance<R>, Scheme) {
        (ServerInstance {
            handlers: config.handlers,
            fallback_handler: config.fallback_handler,
            host: config.host.into(),
            server: config.server,
            content_type: config.content_type,
            threads: config.threads.unwrap_or_else(|| (num_cpus::get() * 5) / 4),
            keep_alive: config.keep_alive,
            threads_in_use: AtomicUsize::new(0),
            context_filters: config.context_filters,
            response_filters: config.response_filters,
            global: config.global,
        },
        config.scheme)
    }

    ///Start the server.
    #[cfg(feature = "ssl")]
    pub fn run(self, scheme: Scheme) -> HttpResult<Listening> {
        let host = self.host;
        let threads = self.threads;
        let mut server = match scheme {
            Scheme::Http => try!(HyperServer::http(host)),
            Scheme::Https {cert, key} => try!(HyperServer::https(host, cert, key)),
        };
        if let Some(ref keep_alive) = self.keep_alive {
            server.keep_alive(keep_alive.timeout);
        }
        server.run(self, threads)
    }

    ///Start the server.
    #[cfg(not(feature = "ssl"))]
    pub fn run(self, _scheme: Scheme) -> HttpResult<Listening> {
        let host = self.host;
        let threads = self.threads;
        let mut server = try!(HyperServer::http(host));
        if let Some(ref keep_alive) = self.keep_alive {
            server.keep_alive(keep_alive.timeout);
        }
        server.run(self, threads)
    }

    fn modify_context(&self, filter_storage: &mut AnyMap, context: &mut Context) -> ContextAction {
        let mut result = ContextAction::Next;

        for filter in &self.context_filters {
            result = match result {
                ContextAction::Next => {
                    let filter_context = FilterContext {
                        storage: filter_storage,
                        global: &self.global,
                    };
                    filter.modify(filter_context, context)
                },
                _ => return result
            };
        }

        result
    }

}

struct ParsedUri {
    host: Option<(String, Option<u16>)>,
    uri: Uri,
    query: Parameters,
    fragment: Option<MaybeUtf8Owned>
}

impl<R: Router> HyperHandler for ServerInstance<R> {
    fn handle(&self, request: hyper::server::request::Request, writer: hyper::server::response::Response) {
        let (
            request_addr,
            request_method,
            mut request_headers,
            request_uri,
            request_version,
            request_reader
        ) = request.deconstruct();

        let force_close = if let Some(ref keep_alive) = self.keep_alive {
            self.threads_in_use.load(Ordering::SeqCst) + keep_alive.free_threads > self.threads
        } else {
            false
        };

        let mut response = Response::new(writer, &self.response_filters, &self.global, force_close);
        response.headers_mut().set(Date(HttpDate(time::now_utc())));
        response.headers_mut().set(ContentType(self.content_type.clone()));
        response.headers_mut().set(hyper::header::Server(self.server.clone()));

        let path_components = match request_uri {
            RequestUri::AbsoluteUri(url) => Some(parse_url(url)),
            RequestUri::AbsolutePath(path) => Some(parse_path(&path)),
            RequestUri::Star => {
                Some(ParsedUri {
                    host: None,
                    uri: Uri::Asterisk,
                    query: Parameters::new(),
                    fragment: None
                })
            },
            _ => None
        };

        match path_components {
            Some(ParsedUri{ host, uri, query, fragment }) => {
                if let Some((name, port)) = host {
                    request_headers.set(::header::Host {
                        hostname: name,
                        port: port
                    });
                }

                let body = context::body::BodyReader::from_reader(request_reader, &request_headers);

                let mut context = Context {
                    headers: request_headers,
                    http_version: request_version,
                    method: request_method,
                    address: request_addr,
                    uri: uri,
                    hyperlinks: vec![],
                    variables: Parameters::new(),
                    query: query.into(),
                    fragment: fragment,
                    global: &self.global,
                    body: body
                };

                let mut filter_storage = AnyMap::new();

                match self.modify_context(&mut filter_storage, &mut context) {
                    ContextAction::Next => {
                        *response.filter_storage_mut() = filter_storage;

                        let endpoint = context.uri.as_path().map(|path| self.handlers.find(&context.method, &path)).unwrap_or_else(|| {
                            Endpoint {
                                handler: None,
                                variables: HashMap::new(),
                                hyperlinks: vec![]
                            }
                        });

                        let Endpoint {
                            handler,
                            variables,
                            hyperlinks
                        } = endpoint;

                        if let Some(handler) = handler.or(self.fallback_handler.as_ref()) {
                            context.hyperlinks = hyperlinks;
                            context.variables = variables.into();
                            handler.handle_request(context, response);
                        } else {
                            response.set_status(StatusCode::NotFound);
                        }
                    },
                    ContextAction::Abort(status) => {
                        *response.filter_storage_mut() = filter_storage;
                        response.set_status(status);
                    }
                }
            },
            None => {
                response.set_status(StatusCode::BadRequest);
            }
        }
    }

    fn on_connection_start(&self) {
        self.threads_in_use.fetch_add(1, Ordering::SeqCst);
    }

    fn on_connection_end(&self) {
        self.threads_in_use.fetch_sub(1, Ordering::SeqCst);
    }
}

fn parse_path(path: &str) -> ParsedUri {
    match path.find('?') {
        Some(index) => {
            let (query, fragment) = parse_fragment(&path[index+1..]);

            let mut path = percent_decode(path[..index].as_bytes());
            if path.is_empty() {
                path.push('/' as u8);
            }

            ParsedUri {
                host: None,
                uri: Uri::Path(path.into()),
                query: utils::parse_parameters(query.as_bytes()),
                fragment: fragment.map(|f| percent_decode(f.as_bytes()).into())
            }
        },
        None => {
            let (path, fragment) = parse_fragment(&path);

            let mut path = percent_decode(path.as_bytes());
            if path.is_empty() {
                path.push('/' as u8);
            }

            ParsedUri {
                host: None,
                uri: Uri::Path(path.into()),
                query: Parameters::new(),
                fragment: fragment.map(|f| percent_decode(f.as_bytes()).into())
            }
        }
    }
}

fn parse_fragment<'a>(path: &'a str) -> (&'a str, Option<&'a str>) {
    match path.find('#') {
        Some(index) => (&path[..index], Some(&path[index+1..])),
        None => (path, None)
    }
}

fn parse_url(url: Url) -> ParsedUri {
    let mut path = Vec::new();
    for component in url.path().unwrap_or(&[]) {
        path.push('/' as u8);
        percent_decode_to(component.as_bytes(), &mut path);
    }
    if path.is_empty() {
        path.push('/' as u8);
    }

    let query = url.query_pairs()
            .unwrap_or_else(|| Vec::new())
            .into_iter()
            .collect();

    let host = if let SchemeData::Relative(data) = url.scheme_data {
        Some((data.host.serialize(), data.port))
    } else {
        None
    };

    ParsedUri {
        host: host,
        uri: Uri::Path(path.into()),
        query: query,
        fragment: url.fragment.map(|f| percent_decode(f.as_bytes()).into())
    }
}

//Helper to handle multiple protocols.
enum HyperServer {
    Http(hyper::server::Server<HttpListener>),
    #[cfg(feature = "ssl")]
    Https(hyper::server::Server<HttpsListener<Openssl>>),
}

impl HyperServer {
    fn http(host: SocketAddr) -> HttpResult<HyperServer> {
        hyper::server::Server::http(host).map(HyperServer::Http)
    }

    #[cfg(feature = "ssl")]
    fn https(host: SocketAddr, cert: PathBuf, key: PathBuf) -> HttpResult<HyperServer> {
        let ssl = try!(Openssl::with_cert_and_key(cert, key));
        hyper::server::Server::https(host, ssl).map(HyperServer::Https)
    }

    #[cfg(feature = "ssl")]
    fn keep_alive(&mut self, timeout: Duration) {
        match *self {
            HyperServer::Http(ref mut s) => s.keep_alive(timeout),
            HyperServer::Https(ref mut s) => s.keep_alive(timeout),
        }
    }

    #[cfg(not(feature = "ssl"))]
    fn keep_alive(&mut self, timeout: Duration) {
        match *self {
            HyperServer::Http(ref mut s) => s.keep_alive(timeout),
        }
    }

    #[cfg(feature = "ssl")]
    fn run<R: Router>(self, server: ServerInstance<R>, threads: usize) -> HttpResult<Listening> {
        match self {
            HyperServer::Http(s) => s.handle_threads(server, threads),
            HyperServer::Https(s) => s.handle_threads(server, threads),
        }
    }

    #[cfg(not(feature = "ssl"))]
    fn run<R: Router>(self, server: ServerInstance<R>, threads: usize) -> HttpResult<Listening> {
        match self {
            HyperServer::Http(s) => s.handle_threads(server, threads),
        }
    }
}

#[test]
fn parse_path_parts() {
    let with = "this".to_owned().into();
    let and = "that".to_owned().into();
    let ParsedUri { uri, query, fragment, .. } = parse_path("/path/to/something?with=this&and=that#lol");
    assert_eq!(uri.as_path(), Some("/path/to/something".into()));
    assert_eq!(query.get_raw("with"), Some(&with));
    assert_eq!(query.get_raw("and"), Some(&and));
    assert_eq!(fragment, Some("lol".to_owned().into()));
}

#[test]
fn parse_strange_path() {
    let with = "this".to_owned().into();
    let and = "what?".to_owned().into();
    let ParsedUri { uri, query, fragment, .. } = parse_path("/path/to/something?with=this&and=what?#");
    assert_eq!(uri.as_path(), Some("/path/to/something".into()));
    assert_eq!(query.get_raw("with"), Some(&with));
    assert_eq!(query.get_raw("and"), Some(&and));
    assert_eq!(fragment, Some(String::new().into()));
}

#[test]
fn parse_missing_path_parts() {
    let with = "this".to_owned().into();
    let and = "that".to_owned().into();
    let ParsedUri { uri, query, fragment, .. } = parse_path("/path/to/something?with=this&and=that");
    assert_eq!(uri.as_path(), Some("/path/to/something".into()));
    assert_eq!(query.get_raw("with"), Some(&with));
    assert_eq!(query.get_raw("and"), Some(&and));
    assert_eq!(fragment, None);

    let ParsedUri { uri, query, fragment, .. } = parse_path("/path/to/something#lol");
    assert_eq!(uri.as_path(), Some("/path/to/something".into()));
    assert_eq!(query.len(), 0);
    assert_eq!(fragment, Some("lol".to_owned().into()));

    let ParsedUri { uri, query, fragment, .. } = parse_path("?with=this&and=that#lol");
    assert_eq!(uri.as_path(), Some("/".into()));
    assert_eq!(query.get_raw("with"), Some(&with));
    assert_eq!(query.get_raw("and"), Some(&and));
    assert_eq!(fragment, Some("lol".to_owned().into()));
}

#[test]
fn parse_url_parts() {
    let with = "this".to_owned().into();
    let and = "that".to_owned().into();
    let url = Url::parse("http://example.com/path/to/something?with=this&and=that#lol").unwrap();
    let ParsedUri { uri, query, fragment, .. } = parse_url(url);
    assert_eq!(uri.as_path(), Some("/path/to/something".into()));
    assert_eq!(query.get_raw("with"), Some(&with));
    assert_eq!(query.get_raw("and"), Some(&and));
    assert_eq!(fragment, Some("lol".to_owned().into()));
}

#[test]
fn parse_strange_url() {
    let with = "this".to_owned().into();
    let and = "what?".to_owned().into();
    let url = Url::parse("http://example.com/path/to/something?with=this&and=what?#").unwrap();
    let ParsedUri { uri, query, fragment, .. } = parse_url(url);
    assert_eq!(uri.as_path(), Some("/path/to/something".into()));
    assert_eq!(query.get_raw("with"), Some(&with));
    assert_eq!(query.get_raw("and"), Some(&and));
    assert_eq!(fragment, Some(String::new().into()));
}

#[test]
fn parse_missing_url_parts() {
    let with = "this".to_owned().into();
    let and = "that".to_owned().into();
    let url = Url::parse("http://example.com/path/to/something?with=this&and=that").unwrap();
    let ParsedUri { uri, query, fragment, .. } = parse_url(url);
    assert_eq!(uri.as_path(), Some("/path/to/something".into()));
    assert_eq!(query.get_raw("with"), Some(&with));
    assert_eq!(query.get_raw("and"), Some(&and));
    assert_eq!(fragment, None);

    let url = Url::parse("http://example.com/path/to/something#lol").unwrap();
    let ParsedUri { uri, query, fragment, .. } = parse_url(url);
    assert_eq!(uri.as_path(), Some("/path/to/something".into()));
    assert_eq!(query.len(), 0);
    assert_eq!(fragment, Some("lol".to_owned().into()));

    let url = Url::parse("http://example.com?with=this&and=that#lol").unwrap();
    let ParsedUri { uri, query, fragment, .. } = parse_url(url);
    assert_eq!(uri.as_path(), Some("/".into()));
    assert_eq!(query.get_raw("with"), Some(&with));
    assert_eq!(query.get_raw("and"), Some(&and));
    assert_eq!(fragment, Some("lol".to_owned().into()));
}


text:
<?php

namespace Academe\Csp\Value;

/**
 * Hash source expression.
 * TODO: the Hash can just extend the Nonce (except for the constructor parameters?).
 */

class SourceHash extends SourceAbstract
{
    /**
     * The source type.
     */

    const SOURCE_TYPE = 'hash';

    /**
     * The valid algorithms.
     */

    const ALGO_SHE256 = 'sha256';
    const ALGO_SHE384 = 'sha384';
    const ALGO_SHE512 = 'sha512';

    const VALUE_LIST_PREFIX = 'ALGO_';

    /**
     * The selected algorithm.
     */

    protected $algo;

    /**
     * The hash base64 value.
     */

    protected $base64_value = '';

    /**
     * Set the algo on construction and optionally the non-encoded value.
     */

    public function __construct($algo, $hash_value = null)
    {
        $this->setAlgo($algo);

        if (isset($hash_value)) {
            $this->setValue($hash_value);
        }
    }

    /**
     * Return an array of lower-case valid algos, keyed on the constant name.
     */

    public static function validAlgos()
    {
        return static::getPrefixedConstants(static::VALUE_LIST_PREFIX);
    }

    /**
     * Set the hash algo.
     */

    public function setAlgo($algo)
    {
        // Algo is case-insensitive. We will just make it lower case, as we don't
        // know where it could have come from while parsing.

        // Can also pass in the string name of the constant, which will be useful
        // as keys in drop-down lists.
        if (defined('static::' . $algo)) {
            $algo = constant('static::' . $algo);
        }

        if ( ! $this->isValidValue(self::VALUE_LIST_PREFIX, $algo)) {
            // TODO: throw custom exception
            throw new \InvalidArgumentException('Invalid source hash algo ' . $algo);
        }

        $this->algo = $algo;

        return $this;
    }

    /**
     * Set the hash base64 value.
     * This is handy when parsing, to reduce the number of decode/encode cycles.
     */

    public function setValueBase64($value)
    {
        // TODO: validate the value; make sure it is a base64 string.

        $this->base64_value = $value;

        return $this;
    }

    /**
     * Set the hash actual value.
     */

    public function setValue($value)
    {
        $this->setValueBase64(base64_encode($value));

        return $this;
    }

    /**
     * Get the actual hash value.
     * TODO: we probably want to handle invalid base64 strings, since they
     * can come from unknown sources.
     */

    public function getValue()
    {
        return base64_decode($this->base64_value);
    }

    /**
     * Render the source expression.
     */

    public function render()
    {
        return "'" . $this->algo . '-' . $this->base64_value . "'";
    }
}


text:
layout: blog_by_tag
title: 'Articles by tag: review'
tag: review?
---