text:
package org.xcri.core;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Element;
import org.jdom.Namespace;
import org.xcri.Namespaces;
import org.xcri.common.Identifier;
import org.xcri.course.Credit;
import org.xcri.course.Qualification;
import org.xcri.exceptions.InvalidElementException;
import org.xcri.types.CommonDescriptiveType;
import org.xcri.util.lax.Lax;

public class Course extends CommonDescriptiveType{

	private Log log = LogFactory.getLog(Course.class);

	private Presentation[] presentations;
	private Qualification[] qualifications;
	private Credit[] credits;
	// Note we ignore Level as it isn't used by XCRI

	/**
	 * @return the presentations
	 */
	public Presentation[] getPresentations() {
		return presentations;
	}

	/**
	 * @param presentations the presentations to set
	 */
	public void setPresentations(Presentation[] presentations) {
		this.presentations = presentations;
	}

	/* (non-Javadoc)
	 * @see org.xcri.types.CommonType#toXml()
	 */
	@Override
	public Element toXml() {
		Element element = super.toXml();
		if (this.getPresentations()!= null) for (Presentation presentation:this.getPresentations()) element.addContent(presentation.toXml());
		if (this.getQualifications()!= null) for (Qualification qualification:this.getQualifications()) element.addContent(qualification.toXml());
		if (this.getCredits()!= null) for (Credit credit:this.getCredits()) element.addContent(credit.toXml());
		return element;
	}

	/* (non-Javadoc)
	 * @see org.xcri.types.CommonType#fromXml(org.jdom.Element)
	 */
	@Override
	public void fromXml(Element element) throws InvalidElementException {
		super.fromXml(element);

		//
		// Check identifiers
		//
		if (this.getIdentifiers() == null || this.getIdentifiers().length == 0){
			log.warn("course: course does not contain any identifiers");
		} else {
			boolean hasUrl = false;
			for (Identifier identifier: this.getIdentifiers()){
				try {
					new URL(identifier.getValue());
					hasUrl = true;
				} catch (MalformedURLException e) {
					if (identifier.getType() == null){
						log.warn("course: course contains a non-URI identifier with no type:"+identifier.getValue());
					}
				}
			}
			if (!hasUrl){
				log.warn("course: course does not contain a URI identifier");
			}
		}

		//
		// Check titles
		//
		if (this.getTitles() == null || this.getTitles().length == 0){
			log.warn("course: course has no title");
		}

		//
		// Check subjects
		//
		if (this.getSubjects() == null || this.getSubjects().length == 0){
			log.warn("course: course does not contain a subject");
		}

		//
		// Level
		//
		if (element.getChild("level", Namespaces.MLO_NAMESPACE_NS) != null){
			log.warn("course: level is not recommended");
		}

		//
		// Add children
		//
		ArrayList<Presentation> presentations = new ArrayList<Presentation>();
		for (Object obj : Lax.getChildrenQuietly(element, "presentation", Namespaces.XCRI_NAMESPACE_NS, log)){
			Presentation presentation = new Presentation();
			try {
				presentation.fromXml((Element)obj);
				presentation.setParent(this);
				presentations.add(presentation);
			} catch (InvalidElementException e) {
				log.warn("course : presentation invalid, skipping");
			}
		}
		this.setPresentations(presentations.toArray(new Presentation[presentations.size()]));

		ArrayList<Qualification> qualifications = new ArrayList<Qualification>();
		for (Object obj : Lax.getChildrenQuietly(element, "qualification", Namespaces.MLO_NAMESPACE_NS, log)){
			Qualification qualification = new Qualification();
			try {
				qualification.fromXml((Element)obj);
				qualifications.add(qualification);
			} catch (InvalidElementException e) {
				log.warn("course : qualification invalid, skipping");
			}
		}
		this.setQualifications(qualifications.toArray(new Qualification[qualifications.size()]));

		ArrayList<Credit> credits = new ArrayList<Credit>();
		for (Object obj : Lax.getChildrenQuietly(element, "credit", Namespaces.MLO_NAMESPACE_NS, log)){
			Credit credit = new Credit();
			try {
				credit.fromXml((Element)obj);
				credits.add(credit);
			} catch (InvalidElementException e) {
				log.warn("course : credit invalid, skipping");
			}
		}
		this.setCredits(credits.toArray(new Credit[credits.size()]));

	}

	/* (non-Javadoc)
	 * @see org.xcri.types.XcriElement#getNamespace()
	 */
	@Override
	public Namespace getNamespace() {
		return Namespaces.XCRI_NAMESPACE_NS;
	}

	/* (non-Javadoc)
	 * @see org.xcri.types.XcriElement#getName()
	 */
	@Override
	public String getName() {
		return "course";
	}

	/**
	 * @return the qualifications
	 */
	public Qualification[] getQualifications() {
		return qualifications;
	}

	/**
	 * @param qualifications the qualifications to set
	 */
	public void setQualifications(Qualification[] qualifications) {
		this.qualifications = qualifications;
	}

	/**
	 * @return the credits
	 */
	public Credit[] getCredits() {
		return credits;
	}

	/**
	 * @param credits the credits to set
	 */
	public void setCredits(Credit[] credits) {
		this.credits = credits;
	}

}


text:
PHP REST Server
===============

You can read the introduction on my [blog](http://zulfait.blogspot.com/2014/01/php-rest-server.html).
##Features

1. Automatically generated resources (tables and table structure) based on incomming data.
1. Routes are automatically generated from the database. Apart from the initial config.php edit, you won't need to modify the code.
1. Supports multiple databases MySQL 5+ SQLite 3.6.19+ PostgreSQL 8+ CUBRUD.
1. Can be accessed in subdirectories (Does not _have_ to be located on a different vhost / webroot)
1. Simple ACL System
1. Supports where, limit, order queries
1. Pure JSON API Server. User does not need to use the ``emulate_http`` in Backbone.js or other similar front-end frameworks
1. Lightweight. Response around 10 - 20 ms per request under untweaked PHP.

##Installation

1. Install [Composer](http://getcomposer.org/doc/00-intro.md#installation-nix).
1. Create a new project by running: ```composer create-project zulfajuniadi/php-rest-server your_directory```
1. Alternatively you can download and extract / clone this repo into your htdocs directory then run ``composer install --prefer-dist --no-dev``
2. Change the configs in config.php.default and rename it to config.php.
1. Go To: http://yourapiserver/ to make sure everything is ok. The response should be something like this : ``{"error":false,"data":"OK","status":200}``.

##Usage

1. Go To: http://yourapiserver/manage to manage your Api server.
1. Create new package by going to http://[installationpath]/manage.
1. Once created, the routes under http://[installationpath]/[packagename]/[resourcename] will be activated
1. [resourcename] will be automatically generated for you.

##Routes

1. **List Records** >> (GET) http://[installationpath]/[packagename]/[tableName]
1. **Get One** >> (GET) http://[installationpath]/[packagename]/[tableName]/[id]
1. **Create New** >> (POST) http://[installationpath]/[packagename]/[tableName]
1. **Update** >> (PUT) http://[installationpath]/[packagename]/[tableName]/[id]
1. **Delete** >> (DELETE) http://[installationpath]/[packagename]/[tableName]/[id]

Example

Let's say you create an application (package) called 'uberpackage' and you want to retrieve all users. The request should be:
``http://api.uberapp.com/uberapp/users``

*List Records is subject to the default limit as in the Querying::order section below.*

##Querying

Queries are appended as query strings to the List Records (GET) request.

###Where

Key : ``where``

Example : http://api.uberapp.com/uberapp/users?where=[["id",">",23],["name","like","%adam"]]

Generates : ``select all from users where id > 23 and name like '%adam';``

*Right now only 'and' is supported*

###Order

Key : ``order``

Example : http://api.uberapp.com/uberapp/users?order=[["age","desc"],["name","asc"]]

Generates : ``select all from users order by age desc, name asc;``

*Note that if you did not pass the second parameter in an order array, it will default to asc. The following syntax is valid*

http://api.uberapp.com/uberapp/users?order=[["age"]]

Generates : ``select all from users order by age asc;``

###Limit

Key : ``limit``

Params : [$start,$length]

Example : http://api.uberapp.com/uberapp/users?limit=[0,25]

Generates : ``select all from users limit 0, 25;``

*By default, all queries will return only 25 rows, you can change the default limit in config.php $config['default_sql_limit'] variable*

###Chained

Queries can be chained as per example below:

Example : http://api.uberapp.com/uberapp/users?where=[["age",">",18]]&order=[["age","desc"],["name"]]&limit=[0,50]

Generates : ``select * from users where age > 18 order by age desc, name asc limit 0, 50;``

##Access Control List (ACL)

This REST service offers very simple ACL system where you can set ACL per package level. You can define whether any user are able to list (and query), create, update or remove a record in any combinations. You can also disable the whole package by unchecking the 'Enabled' checkbox in /manage.

##List of HTTP Responses

* 200 : (OK) Request was successfully performed
* 201 : (Created) A new entry was created (During the POST method)
* 400 : (Bad Request) Either the package has not yet been created, or the package is marked disabled or the method is disabled. (View ACL Section).
* 403 : (Forbidden) The client end did not send the authentication token (Auth-Token) inside the header or the Auth-Token is invalid.
* 404 : (Not Found) The record does not exist. May happen during the Get (GET:/packageName/resourceName/id) One request or Update (PUT:/packageName/resourceName/id) request
* 500 : (Server Error) PHP Farted. Shouldn't Happen. Check Server Logs.
* 503 : (Service Unavailable) For rate limiting.

##Data Structure

The server responds in the following data format:

```json
{
	"error" : false,
	"data" : [],
	"status" : 200
}

```

##Rate Limiting

You can set a limit on the number of request a user can make. The requests are set per package, per user, per hour. Upon hitting the limit, the REST Service will return a 503 Service Unavailable HTTP Error. Refer to the response headers ``Api-Utilization`` and ``Api-Limit`` To view the utilized requests in the current hour and the limit set on the package respectivly.

##Authentication Token

A token can be generated via the management page. Once generated and tagged to a resource. All request with invalid or missing Auth-Token header, will directly return a 403 Forbidden HTTP Error.

###Sample Backbone Auth Token Implementation

The below example demonstrates usage of the 'Auth-Token' header.

```javascript
var _sync = Backbone.sync;
Backbone.sync = function(method, model, options) {
	options.beforeSend = function(xhr) {
		xhr.setRequestHeader('Auth-Token' , [generated_token]);
	}
	_sync.call(this,method,model,options);
}

```

##Example Usage

View the ``templates/_manage.html`` and ``js/manage.js`` to view API usage with ``Backbone.js``

##Todos

1. Auto sync (Client data to be persistant on client side, can sync automatically from the server when there are new data)

redpajama_set_name: RedPajamaGithub


text:
package puzzles;

import java.util.*;

/**
 * Sorts an array of strings so that all the anagrams are next to each other.
 */
public class SortArrayOfStringsWithAnagrams {

  private static final Comparator<String> COMPARATOR = new Comparator<>() {

    private String sortChars(String input) {
      char[] content = input.toCharArray();
      Arrays.sort(content);
      return new String(content);
    }

    public int compare(String s1, String s2) {
      return s1.compareTo(sortChars(s2));
    }
  };

  public String[] sortArrayByAnagrams(String[] unsorted) {
    if (unsorted.length <= 1) {
      return unsorted;
    }

    return Arrays.sort(unsorted, COMPARATOR);
  }
}


text:
package com.adobe.acs.commons.genericlists.impl;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.adapter.AdapterFactory;

import com.adobe.acs.commons.genericlists.GenericList;
import com.day.cq.wcm.api.Page;

@Component
@Service
@Properties({ @Property(name = AdapterFactory.ADAPTABLE_CLASSES, value = "com.day.cq.wcm.api.Page"),
        @Property(name = AdapterFactory.ADAPTER_CLASSES, value = "com.adobe.acs.commons.genericlists.GenericList") })
public class GenericListAdapterFactory implements AdapterFactory {

    @SuppressWarnings("unchecked")
    @Override
    public final <AdapterType> AdapterType getAdapter(@CheckForNull Object obj, @Nonnull Class<AdapterType> clazz) {
        if (clazz == GenericList.class) {
            return (AdapterType) adaptToGenericList(obj);
        }
        return null;
    }

    private GenericList adaptToGenericList(@CheckForNull Object obj) {
        if (obj == null) {
            return null;
        }
        final Page page = (Page) obj;
        if (page.getContentResource() != null
                && page.getContentResource().isResourceType(GenericListImpl.RT_GENERIC_LIST)
                && page.getContentResource().getChild("list") != null) {
            return new GenericListImpl(page.getContentResource().getChild("list"));
        }
        return null;
    }
}


text:
'use strict';

/**
 * Serverless Revisioning Plugin
 * Karl Viiburg <karl@viiburg.ee> 2016
 */

module.exports = function(S) { // Always pass in the ServerlessPlugin Class

  const _       = require('lodash'),
      path      = require('path'),
      appPath   = require('app-root-path'),
      pJson     = require(appPath + '/package.json'),
      fs        = require('fs'),
      git       = require('git-rev'),
      Promise = require('bluebird'); // Serverless uses Bluebird Promises and we recommend you do to because they provide more than your average Promise :)

  /**
   * ServerlessPluginRevision
   */

  class ServerlessPluginRevision extends S.classes.Plugin {

    /**
     * Constructor
     * - Keep this and don't touch it unless you know what you're doing.
     */

    constructor() {
      super();
    }

    /**
     * Define your plugins name
     * - We recommend adding prefixing your personal domain to the name so people know the plugin author
     */

    static getName() {
      return 'ee.viiburg.' + ServerlessPluginRevision.name;
    }

    registerHooks() {
      S.addHook(this._addRevisionHeader.bind(this), {
        action: 'endpointBuildApiGateway',
        event:  'pre'
      });

      return Promise.resolve();
    }

    getPackageJsonVersion() {
      return pJson.version;
    }

    _addRevisionHeader(evt) {
      var packageJsonVersion = this.getPackageJsonVersion(),
          endpoint = S.getProject().getEndpoint(evt.options.name),
          populatedEndpoint = endpoint.toObjectPopulated({
            stage: evt.options.stage,
            region: evt.options.region
          });

      return new Promise(function (resolve, reject) {
        git.short(function (lastCommitHash) {
          _.each(populatedEndpoint.responses, function (response) {
            if (!response.responseParameters) {
              response.responseParameters = {};
            }

            response.responseParameters['method.response.header.API-Revision'] = '\'' + packageJsonVersion + '-' + lastCommitHash + '\'';
          });

          endpoint.fromObject(populatedEndpoint);

          resolve();
        });
      }).then(function() {
        return Promise.resolve(evt);
      });
    }
  }

  // Export Plugin Class
  return ServerlessPluginRevision;

};


text:
"""
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
"""
# Definition for an interval.
class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

class Solution(object):
    def insert(self, intervals, newInterval):
        """
        :type intervals: List[Interval]
        :type newInterval: Interval
        :rtype: List[Interval]
        """
        if intervals is None or intervals == []:
            return [newInterval]
        s = newInterval.start
        e = newInterval.end
        left = [interval for interval in intervals if interval.end < s]
        right = [interval for interval in intervals if interval.start > e]
        if len(left) + len(right) < len(intervals):
            s = min(s, intervals[len(left)].start)
            e = max(e, intervals[-1 - len(right)].end)
        return left + [Interval(s, e)] + right

intervals = [Interval(*item) for item in [[1, 3], [6, 9]]]
assert [[interval.start, interval.end] for interval in Solution().insert(intervals, Interval(2, 5))] == [[1, 5], [6, 9]]

intervals = [Interval(*item) for item in [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]]]
assert [[interval.start, interval.end] for interval in Solution().insert(intervals, Interval(4, 9))] == [[1, 2], [3, 10], [12, 16]]


text:
require 'fog/aws/models/rds/parameter_group'

module Fog
  module AWS
    class RDS
      class ParameterGroups < Fog::Collection
        model Fog::AWS::RDS::ParameterGroup

        def all
          data = service.describe_db_parameter_groups.body['DescribeDBParameterGroupsResult']['DBParameterGroups']
          load(data) # data is an array of attribute hashes
        end

        def get(identity)
          data = service.describe_db_parameter_groups(identity).body['DescribeDBParameterGroupsResult']['DBParameterGroups'].first
          new(data) # data is an attribute hash
        rescue Fog::AWS::RDS::NotFound
          nil
        end
      end
    end
  end
end


text:
namespace
{
    struct websocket_client : boost::intrusive::list_base_hook<
                                  boost::intrusive::link_mode<boost::intrusive::auto_unlink>>
    {
        typedef beast::websocket::stream<boost::asio::ip::tcp::socket &> websocket_type;
        typedef warpcoil::beast::async_stream_adaptor<websocket_type &> adaptor_type;

        boost::asio::ip::tcp::socket socket;
        beast::streambuf receive_buffer;
        websocket_type websocket;
        adaptor_type adaptor;
        warpcoil::cpp::message_splitter<adaptor_type> splitter;
        warpcoil::cpp::buffered_writer<adaptor_type> writer;
        async_publisher_server<async_publisher, adaptor_type, adaptor_type> server_adaptor;
        async_viewer_client<adaptor_type, adaptor_type> viewer_client;

        websocket_client(boost::asio::ip::tcp::socket socket, beast::streambuf receive_buffer,
                         async_publisher &server_impl)
            : socket(std::move(socket))
            , receive_buffer(std::move(receive_buffer))
            , websocket(this->socket)
            , adaptor(this->websocket, beast::streambuf())
            , splitter(this->adaptor)
            , writer(this->adaptor)
            , server_adaptor(server_impl, this->splitter, this->writer)
            , viewer_client(writer, splitter)
        {
        }
    };

    void begin_serve(std::shared_ptr<websocket_client> client)
    {
        client->server_adaptor.serve_one_request([client](boost::system::error_code const ec)
                                                 {
                                                     Si::throw_if_error(ec);
                                                     begin_serve(client);
                                                 });
    }

    struct web_site_publisher : async_publisher
    {
        typedef boost::intrusive::list<
            websocket_client, boost::intrusive::constant_time_size<false>> websocket_client_list;

        websocket_client_list all_clients;

        void publish(std::string message,
                     std::function<void(Si::error_or<std::tuple<>>)> on_result) override
        {
            for (websocket_client &client : all_clients)
            {
                client.viewer_client.display(message, [](Si::error_or<std::tuple<>> result)
                                             {
                                                 result.throw_if_error();
                                             });
            }
            // does not make sense to wait for responses from the clients here
            on_result(std::make_tuple());
        }
    };

    struct file_client
    {
        boost::asio::ip::tcp::socket socket;
        beast::streambuf receive_buffer;
        beast::http::response<beast::http::string_body> response;

        explicit file_client(boost::asio::ip::tcp::socket socket, beast::streambuf receive_buffer)
            : socket(std::move(socket))
            , receive_buffer(std::move(receive_buffer))
        {
        }
    };

    struct http_client
    {
        boost::asio::ip::tcp::socket socket;
        beast::streambuf receive_buffer;
        beast::http::request<beast::http::string_body> request;

        explicit http_client(boost::asio::ip::tcp::socket socket, beast::streambuf receive_buffer)
            : socket(std::move(socket))
            , receive_buffer(std::move(receive_buffer))
        {
        }
    };

    void begin_serve(std::shared_ptr<http_client> client, web_site_publisher &server_impl,
                     ventura::absolute_path const &document_root);

    void serve_prepared_response(std::shared_ptr<file_client> client, bool const is_keep_alive,
                                 web_site_publisher &server_impl,
                                 ventura::absolute_path const &document_root,
                                 boost::string_ref const content_type)
    {
        client->response.version = 11;
        client->response.fields.insert(
            "Content-Length", boost::lexical_cast<std::string>(client->response.body.size()));
        client->response.fields.insert("Content-Type", content_type);
        beast::http::async_write(
            client->socket, client->response,
            [client, is_keep_alive, &server_impl, document_root](boost::system::error_code const ec)
            {
                Si::throw_if_error(ec);
                if (is_keep_alive)
                {
                    auto http_client_again = std::make_shared<http_client>(
                        std::move(client->socket), std::move(client->receive_buffer));
                    begin_serve(http_client_again, server_impl, document_root);
                }
                else
                {
                    client->socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
                }
            });
    }

    void serve_static_file(std::shared_ptr<file_client> client, bool const is_keep_alive,
                           web_site_publisher &server_impl,
                           ventura::absolute_path const &document_root,
                           ventura::absolute_path const &served_document,
                           boost::string_ref const content_type)
    {
        Si::visit<void>(
            ventura::read_file(ventura::safe_c_str(ventura::to_os_string(served_document))),
            [&](std::vector<char> content)
            {
                // TODO: avoid the copy of the content
                client->response.body.assign(content.begin(), content.end());
                client->response.reason = "OK";
                client->response.status = 200;
            },
            [&](boost::system::error_code const ec)
            {
                std::cerr << "Could not read file " << served_document << ": " << ec << '\n';
                client->response.reason = "Internal Server Error";
                client->response.status = 500;
                client->response.body = client->response.reason;
            },
            [&](ventura::read_file_problem const problem)
            {
                std::cerr << "Could not read file " << served_document << " due to problem "
                          << static_cast<int>(problem) << '\n';
                client->response.reason = "Internal Server Error";
                client->response.status = 500;
                client->response.body = client->response.reason;
            });
        serve_prepared_response(client, is_keep_alive, server_impl, document_root, content_type);
    }

    void serve_interface_library(std::shared_ptr<file_client> client, bool const is_keep_alive,
                                 web_site_publisher &server_impl,
                                 ventura::absolute_path const &document_root)
    {
        auto code_writer =
            Si::Sink<char, Si::success>::erase(Si::make_container_sink(client->response.body));
        Si::append(code_writer, "\"use strict\";\n");

        Si::append(code_writer, "var library = ");
        warpcoil::javascript::generate_common_library(code_writer, warpcoil::indentation_level());
        Si::append(code_writer, ";\n");

        Si::memory_range const library = Si::make_c_str_range("library");
        Si::append(code_writer, "var make_receiver = ");
        warpcoil::javascript::generate_input_receiver(code_writer, warpcoil::indentation_level(),
                                                      warpcoil::create_viewer_interface(), library);
        Si::append(code_writer, ";\n");

        warpcoil::types::interface_definition const service =
            warpcoil::create_publisher_interface();
        Si::append(code_writer, "var make_client = ");
        warpcoil::javascript::generate_client(code_writer, warpcoil::indentation_level(), service,
                                              library);
        Si::append(code_writer, ";\n");

        client->response.reason = "OK";
        client->response.status = 200;
        serve_prepared_response(client, is_keep_alive, server_impl, document_root,
                                "text/javascript");
    }

    void begin_serve(std::shared_ptr<http_client> client, web_site_publisher &server_impl,
                     ventura::absolute_path const &document_root)
    {
        beast::http::async_read(
            client->socket, client->receive_buffer, client->request,
            [client, &server_impl, document_root](boost::system::error_code const ec)
            {
                Si::throw_if_error(ec);
                if (beast::http::is_upgrade(client->request))
                {
                    auto new_client = std::make_shared<websocket_client>(
                        std::move(client->socket), std::move(client->receive_buffer), server_impl);
                    new_client->websocket.async_accept(
                        client->request,
                        [new_client, &server_impl](boost::system::error_code const ec)
                        {
                            Si::throw_if_error(ec);
                            server_impl.all_clients.push_back(*new_client);
                            begin_serve(new_client);
                        });
                }
                else
                {
                    auto new_client = std::make_shared<file_client>(
                        std::move(client->socket), std::move(client->receive_buffer));
                    if (client->request.url == "/index.js")
                    {
                        serve_static_file(new_client, beast::http::is_keep_alive(client->request),
                                          server_impl, document_root,
                                          document_root / ventura::relative_path("index.js"),
                                          "text/javascript");
                    }
                    else if (client->request.url == "/service.js")
                    {
                        serve_interface_library(new_client,
                                                beast::http::is_keep_alive(client->request),
                                                server_impl, document_root);
                    }
                    else
                    {
                        serve_static_file(new_client, beast::http::is_keep_alive(client->request),
                                          server_impl, document_root,
                                          document_root / ventura::relative_path("index.html"),
                                          "text/html");
                    }
                }
            });
    }

    void begin_accept(boost::asio::ip::tcp::acceptor &acceptor, web_site_publisher &server_impl,
                      ventura::absolute_path const &document_root)
    {
        auto client = std::make_shared<http_client>(
            boost::asio::ip::tcp::socket(acceptor.get_io_service()), beast::streambuf());
        acceptor.async_accept(client->socket, [&acceptor, client, &server_impl,
                                               document_root](boost::system::error_code const ec)
                              {
                                  Si::throw_if_error(ec);
                                  begin_accept(acceptor, server_impl, document_root);
                                  begin_serve(client, server_impl, document_root);
                              });
    }
}

int main()
{
    using namespace boost::asio;

    web_site_publisher server_impl;
    io_service io;

    boost::uint16_t const port = 8080;

    ventura::absolute_path const document_root =
        *ventura::parent(*ventura::absolute_path::create(__FILE__));

    ip::tcp::acceptor acceptor_v6(io, ip::tcp::endpoint(ip::tcp::v6(), port), true);
    acceptor_v6.listen();
    begin_accept(acceptor_v6, server_impl, document_root);

    ip::tcp::acceptor acceptor_v4(io, ip::tcp::endpoint(ip::tcp::v4(), port), true);
    acceptor_v4.listen();
    begin_accept(acceptor_v4, server_impl, document_root);

    while (!io.stopped())
    {
        try
        {
            io.run();
        }
        catch (std::exception const &ex)
        {
            std::cerr << "Exception: " << ex.what() << '\n';
            io.reset();
        }
    }
}


text:
<?php

/***************************************************************************
 *
 *	 This program is free software; you can redistribute it and/or modify
 *	 it under the terms of the GNU General Public License as published by
 *	 the Free Software Foundation; either version 2 of the License, or
 *	 (at your option) any later version.
 *
 ***************************************************************************/
if (!defined('CPG_NUKE')) { exit; }

define('IN_PHPBB', true);
$phpbb_root_path = 'modules/Forums/';
require_once($phpbb_root_path.'nukebb.php');

$download_id = isset($_POST['id']) ? intval($_POST['id']) : (isset($_GET['id']) ? intval($_GET['id']) : 0);
$thumbnail = (isset($_POST['thumb']) || isset($_GET['thumb']));

// Send file to browser
function send_file_to_browser($attachment, $upload_dir)
{
	global $_SERVER, $lang, $db, $attach_config, $board_config;
	$filename = ($upload_dir == '') ? $attachment['physical_filename'] : $upload_dir . '/' . $attachment['physical_filename'];
	$gotit = FALSE;
	if (!intval($attach_config['allow_ftp_upload'])) {
		if (!file_exists(amod_realpath($filename))) {
			message_die(GENERAL_ERROR, $lang['Error_no_attachment'] . "

404 File Not Found: The File " . $filename . " does not exist.");
		} else {
			$gotit = TRUE;
		}
	}

	//
	// Determine the Browser the User is using, because of some nasty incompatibilities.
	// Most of the methods used in this function are from phpMyAdmin. :)
	//
	$HTTP_USER_AGENT = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
	if (preg_match('#Opera(/| )([0-9].[0-9]{1,2})#', $HTTP_USER_AGENT))	 {
		$browser_agent = 'opera';
	} else if (preg_match('#MSIE ([0-9].[0-9]{1,2})#', $HTTP_USER_AGENT)) {
		$browser_agent = 'ie';
	} else if (preg_match('#OmniWeb/([0-9].[0-9]{1,2})#', $HTTP_USER_AGENT)) {
		$browser_agent = 'omniweb';
	} else if (preg_match('#Netscape([0-9]{1})#', $HTTP_USER_AGENT)) {
		$browser_agent = 'netscape';
	} else if (preg_match('#Mozilla/([0-9].[0-9]{1,2})#', $HTTP_USER_AGENT)) {
		$browser_agent = 'mozilla';
	} else if (preg_match('#Konqueror/([0-9].[0-9]{1,2})#', $HTTP_USER_AGENT)) {
		$browser_agent = 'konqueror';
	} else {
		$browser_agent = 'other';
	}

	if (GZIPSUPPORT) {
		while (ob_end_clean());
		header('Content-Encoding: none');
	}
	// Now the tricky part... let's dance
/*
	header('Pragma: public');
	header('Content-Transfer-Encoding: none');
	header("Expires: 0"); // set expiration time
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
*/
	//
	// Now send the File Contents to the Browser
	//
	if ($gotit) {
		$size = filesize($filename);
		if ($attachment['mimetype']=='application/x-zip-compressed') {
			if (intval($attach_config['allow_ftp_upload'])) {
				if (trim($attach_config['download_path']) == '') {
					message_die(GENERAL_ERROR, 'Physical Download not possible with the current Attachment Setting');
				}
				$url = trim($attach_config['download_path']) . '/' . $attachment['physical_filename'];
				$redirect_path = $url;
			} else {
				$redirect_path = '/'.$upload_dir . '/' . $attachment['physical_filename'];
			}
			url_redirect($redirect_path);
		} else {
			// Correct the mime type - we force application/octetstream for all files, except images
			// Please do not change this, it is a security precaution
			if (false===stripos($attachment['mimetype'], 'image')) {
				$attachment['mimetype'] = ($browser_agent == 'ie' || $browser_agent == 'opera') ? 'application/octetstream' : 'application/octet-stream';
			}
			if (!($fp = fopen($filename, 'rb'))) {
				cpg_error('Could not open file for sending');
			}
			// Send out the Headers
			header('Content-Type: ' . $attachment['mimetype'] . '; name="' . $attachment['real_filename'] . '"');
			header('Content-Disposition: inline; filename="' . $attachment['real_filename'] . '"');
			print fread($fp, $size);
			fclose ($fp);
		}
	}
	else if (!$gotit && intval($attach_config['allow_ftp_upload']))
	{
		$ini_val = ( phpversion() >= '4.0.0' ) ? 'ini_get' : 'get_cfg_var';
		$tmp_path = ( !$ini_val('safe_mode') ) ? '/tmp' : $upload_dir . '/tmp';
		$tmp_filename = tempnam($tmp_path, 't0000');
		unlink($tmp_filename);

		include_once('includes/classes/cpg_ftp.php');
		$ftp = new cpg_ftp($attach_config['ftp_server'], $attach_config['ftp_user'], $attach_config['ftp_pass'], $attach_config['ftp_path'], $attach_config['ftp_pasv_mode']);
		$mode = FTP_BINARY;
		if ( (preg_match("/text/i", $attachment['mimetype'])) || (preg_match("/html/i", $attachment['mimetype'])) ) {
			$mode = FTP_ASCII;
		}
		$result = ftp_get($ftp->connect_id, $tmp_filename, $filename, $mode);
		$ftp->close();
		if (!$result) {
			message_die(GENERAL_ERROR, $lang['Error_no_attachment'] . "

404 File Not Found: The File " . $filename . " does not exist.");
		}

		$size = filesize($tmp_filename);
		if ($size) {
			header("Content-length: $size");
		}
		if ($attachment['mimetype']=='application/x-zip-compressed') {
			if (intval($attach_config['allow_ftp_upload'])) {
				if (trim($attach_config['download_path']) == '') {
					message_die(GENERAL_ERROR, 'Physical Download not possible with the current Attachment Setting');
				}
				$url = trim($attach_config['download_path']) . '/' . $attachment['physical_filename'];
				$redirect_path = $url;
			} else {
				$redirect_path = $upload_dir . '/' . $attachment['physical_filename'];
			}
			url_redirect($redirect_path);
		} else {
			// Correct the mime type - we force application/octetstream for all files, except images
			// Please do not change this, it is a security precaution
			if (!strstr($attachment['mimetype'], 'image')) {
				$attachment['mimetype'] = ($browser_agent == 'ie' || $browser_agent == 'opera') ? 'application/octetstream' : 'application/octet-stream';
			}
			// Send out the Headers
			header('Content-Type: ' . $attachment['mimetype'] . '; name="' . $attachment['real_filename'] . '"');
			header('Content-Disposition: inline; filename="' . $attachment['real_filename'] . '"');
			print readfile($filename);
			unlink($tmp_filename);
		}
	} else {
		message_die(GENERAL_ERROR, $lang['Error_no_attachment'] . "

404 File Not Found: The File " . $filename . " does not exist.");
	}
	exit;
}
//
// End Functions
//

//
// Start Session Management
//
$userdata = session_pagestart($user_ip, PAGE_INDEX);
init_userprefs($userdata);

if ($download_id < 1) {
	message_die(GENERAL_ERROR, $lang['No_attachment_selected']);
}

if ((intval($attach_config['disable_mod']) == 1) && ($userdata['user_level'] != ADMIN)) {
	message_die(GENERAL_MESSAGE, $lang['Attachment_feature_disabled']);
}

$attachment = $db->sql_ufetchrow('SELECT * FROM ' . ATTACHMENTS_DESC_TABLE . ' WHERE attach_id = '.$download_id);
if (empty($attachment)) {
	message_die(GENERAL_MESSAGE, $lang['Error_no_attachment']);
}

//
// get forum_id for attachment authorization or private message authorization
//
$authorised = FALSE;

$auth_pages = $db->sql_ufetchrowset('SELECT * FROM ' . ATTACHMENTS_TABLE . ' WHERE attach_id = ' . $attachment['attach_id']);
$num_auth_pages = count($auth_pages);

for ($i = 0; $i < $num_auth_pages && $authorised == FALSE; $i++) {
	if (intval($auth_pages[$i]['post_id']) != 0) {
		$row = $db->sql_ufetchrow('SELECT forum_id FROM ' . POSTS_TABLE . ' WHERE post_id = ' . $auth_pages[$i]['post_id']);
		$forum_id = $row['forum_id'];
		$is_auth = array();
		$is_auth = auth(AUTH_ALL, $forum_id, $userdata);
		if ($is_auth['auth_download']) {
			$authorised = TRUE;
		}
	} else {
		if (intval($attach_config['allow_pm_attach']) && ( ($userdata['user_id'] == $auth_pages[$i]['user_id_2']) || ($userdata['user_id'] == $auth_pages[$i]['user_id_1']) ) || ($userdata['user_level'] == ADMIN) ) {
			$authorised = TRUE;
		}
	}
}

if (!$authorised) {
//	  message_die(GENERAL_MESSAGE, $lang['Sorry_auth_view_attach']);
}

//
// Get Information on currently allowed Extensions
//
$rows = $db->sql_ufetchrowset("SELECT e.extension, g.download_mode FROM " . EXTENSION_GROUPS_TABLE . " g, " . EXTENSIONS_TABLE . " e WHERE (g.allow_group = 1) AND (g.group_id = e.group_id)");
$num_rows = count($rows);
for ($i = 0; $i < $num_rows; $i++) {
	$extension = strtolower(trim($rows[$i]['extension']));
	$allowed_extensions[] = $extension;
	$download_mode[$extension] = $rows[$i]['download_mode'];
}

//
// disallowed ?
//
if (!in_array($attachment['extension'], $allowed_extensions) && $userdata['user_level'] != ADMIN) {
	message_die(GENERAL_MESSAGE, sprintf($lang['Extension_disabled_after_posting'], $attachment['extension']));
}

$download_mode = intval($download_mode[$attachment['extension']]);

if ($thumbnail) {
	$attachment['physical_filename'] = THUMB_DIR . '/t_' . $attachment['physical_filename'];
} else {
	// Update download count
	$db->sql_query('UPDATE '.ATTACHMENTS_DESC_TABLE.' SET download_count = download_count + 1 WHERE attach_id = '.$attachment['attach_id']);
}

//
// Determine the 'presenting'-method
//
if ($download_mode == PHYSICAL_LINK) {
	if (intval($attach_config['allow_ftp_upload'])) {
		if (trim($attach_config['download_path']) == '') {
			message_die(GENERAL_ERROR, 'Physical Download not possible with the current Attachment Setting');
		}
		$url = trim($attach_config['download_path']) . '/' . $attachment['physical_filename'];
		$redirect_path = $url;
	} else {
		$redirect_path = '/'.$upload_dir.'/'.$attachment['physical_filename'];
	}
	url_redirect($redirect_path);
} else {
	if (intval($attach_config['allow_ftp_upload'])) {
		// We do not need a download path, we are not downloading physically
		send_file_to_browser($attachment, '');
	} else {
		send_file_to_browser($attachment, $upload_dir);
	}
}


text:
package config

import (
	"errors"
	"fmt"

	"github.com/sirupsen/logrus"
	"k8s.io/apimachinery/pkg/util/sets"
)

// Policy for the config/org/repo/branch.
// When merging policies, a nil value results in inheriting the parent policy.
type Policy struct {
	// Protect overrides whether branch protection is enabled if set.
	Protect *bool `json:"protect,omitempty"`
	// RequiredStatusChecks configures github contexts
	RequiredStatusChecks *ContextPolicy `json:"required_status_checks,omitempty"`
	// Admins overrides whether protections apply to admins if set.
	Admins *bool `json:"enforce_admins,omitempty"`
	// Restrictions limits who can merge
	Restrictions *Restrictions `json:"restrictions,omitempty"`
	// RequiredPullRequestReviews specifies github approval/review criteria.
	RequiredPullRequestReviews *ReviewPolicy `json:"required_pull_request_reviews,omitempty"`
}

func (p Policy) defined() bool {
	return p.Protect != nil || p.RequiredStatusChecks != nil || p.Admins != nil || p.Restrictions != nil || p.RequiredPullRequestReviews != nil
}

// ContextPolicy configures required github contexts.
// When merging policies, contexts are appended to context list from parent.
// Strict determines whether merging to the branch invalidates existing contexts.
type ContextPolicy struct {
	// Contexts appends required contexts that must be green to merge
	Contexts []string `json:"contexts,omitempty"`
	// Strict overrides whether new commits in the base branch require updating the PR if set
	Strict *bool `json:"strict,omitempty"`
}

// ReviewPolicy specifies github approval/review criteria.
// Any nil values inherit the policy from the parent, otherwise bool/ints are overridden.
// Non-empty lists are appended to parent lists.
type ReviewPolicy struct {
	// Restrictions appends users/teams that are allowed to merge
	DismissalRestrictions *Restrictions `json:"dismissal_restrictions,omitempty"`
	// DismissStale overrides whether new commits automatically dismiss old reviews if set
	DismissStale *bool `json:"dismiss_stale_reviews,omitempty"`
	// RequireOwners overrides whether CODEOWNERS must approve PRs if set
	RequireOwners *bool `json:"require_code_owner_reviews,omitempty"`
	// Approvals overrides the number of approvals required if set (set to 0 to disable)
	Approvals *int `json:"required_approving_review_count,omitempty"`
}

// Restrictions limits who can merge
// Users and Teams items are appended to parent lists.
type Restrictions struct {
	Users []string `json:"users"`
	Teams []string `json:"teams"`
}

// selectInt returns the child if set, else parent
func selectInt(parent, child *int) *int {
	if child != nil {
		return child
	}
	return parent
}

// selectBool returns the child argument if set, otherwise the parent
func selectBool(parent, child *bool) *bool {
	if child != nil {
		return child
	}
	return parent
}

// unionStrings merges the parent and child items together
func unionStrings(parent, child []string) []string {
	if child == nil {
		return parent
	}
	if parent == nil {
		return child
	}
	s := sets.NewString(parent...)
	s.Insert(child...)
	return s.List()
}

func mergeContextPolicy(parent, child *ContextPolicy) *ContextPolicy {
	if child == nil {
		return parent
	}
	if parent == nil {
		return child
	}
	return &ContextPolicy{
		Contexts: unionStrings(parent.Contexts, child.Contexts),
		Strict:   selectBool(parent.Strict, child.Strict),
	}
}

func mergeReviewPolicy(parent, child *ReviewPolicy) *ReviewPolicy {
	if child == nil {
		return parent
	}
	if parent == nil {
		return child
	}
	return &ReviewPolicy{
		DismissalRestrictions: mergeRestrictions(parent.DismissalRestrictions, child.DismissalRestrictions),
		DismissStale:          selectBool(parent.DismissStale, child.DismissStale),
		RequireOwners:         selectBool(parent.RequireOwners, child.RequireOwners),
		Approvals:             selectInt(parent.Approvals, child.Approvals),
	}
}

func mergeRestrictions(parent, child *Restrictions) *Restrictions {
	if child == nil {
		return parent
	}
	if parent == nil {
		return child
	}
	return &Restrictions{
		Users: unionStrings(parent.Users, child.Users),
		Teams: unionStrings(parent.Teams, child.Teams),
	}
}

// Apply returns a policy that merges the child into the parent
func (p Policy) Apply(child Policy) (Policy, error) {
	return Policy{
		Protect:                    selectBool(p.Protect, child.Protect),
		RequiredStatusChecks:       mergeContextPolicy(p.RequiredStatusChecks, child.RequiredStatusChecks),
		Admins:                     selectBool(p.Admins, child.Admins),
		Restrictions:               mergeRestrictions(p.Restrictions, child.Restrictions),
		RequiredPullRequestReviews: mergeReviewPolicy(p.RequiredPullRequestReviews, child.RequiredPullRequestReviews),
	}, nil
}

// BranchProtection specifies the global branch protection policy
type BranchProtection struct {
	Policy
	ProtectTested         bool           `json:"protect-tested-repos,omitempty"`
	Orgs                  map[string]Org `json:"orgs,omitempty"`
	AllowDisabledPolicies bool           `json:"allow_disabled_policies,omitempty"`
}

// GetOrg returns the org config after merging in any global policies.
func (bp BranchProtection) GetOrg(name string) (*Org, error) {
	o, ok := bp.Orgs[name]
	if ok {
		var err error
		if o.Policy, err = bp.Apply(o.Policy); err != nil {
			return nil, err
		}
	} else {
		o.Policy = bp.Policy
	}
	return &o, nil
}

// Org holds the default protection policy for an entire org, as well as any repo overrides.
type Org struct {
	Policy
	Repos map[string]Repo `json:"repos,omitempty"`
}

// GetRepo returns the repo config after merging in any org policies.
func (o Org) GetRepo(name string) (*Repo, error) {
	r, ok := o.Repos[name]
	if ok {
		var err error
		if r.Policy, err = o.Apply(r.Policy); err != nil {
			return nil, err
		}
	} else {
		r.Policy = o.Policy
	}
	return &r, nil
}

// Repo holds protection policy overrides for all branches in a repo, as well as specific branch overrides.
type Repo struct {
	Policy
	Branches map[string]Branch `json:"branches,omitempty"`
}

// GetBranch returns the branch config after merging in any repo policies.
func (r Repo) GetBranch(name string) (*Branch, error) {
	b, ok := r.Branches[name]
	if ok {
		var err error
		if b.Policy, err = r.Apply(b.Policy); err != nil {
			return nil, err
		}
		if b.Protect == nil {
			return nil, errors.New("defined branch policies must set protect")
		}
	} else {
		b.Policy = r.Policy
	}
	return &b, nil
}

// Branch holds protection policy overrides for a particular branch.
type Branch struct {
	Policy
}

// GetBranchProtection returns the policy for a given branch.
//
// Handles merging any policies defined at repo/org/global levels into the branch policy.
func (c *Config) GetBranchProtection(org, repo, branch string) (*Policy, error) {
	if _, present := c.BranchProtection.Orgs[org]; !present {
		return nil, nil // only consider branches in configured orgs
	}
	var b *Branch
	if o, err := c.BranchProtection.GetOrg(org); err != nil {
		return nil, fmt.Errorf("org: %v", err)
	} else if r, err := o.GetRepo(repo); err != nil {
		return nil, fmt.Errorf("repo: %v", err)
	} else if b, err = r.GetBranch(branch); err != nil {
		return nil, fmt.Errorf("branch: %v", err)
	}

	return c.GetPolicy(org, repo, branch, *b)
}

// GetPolicy returns the protection policy for the branch, after merging in presubmits.
func (c *Config) GetPolicy(org, repo, branch string, b Branch) (*Policy, error) {
	policy := b.Policy

	// Automatically require contexts from prow which must always be present
	if prowContexts, _, _ := BranchRequirements(org, repo, branch, c.Presubmits); len(prowContexts) > 0 {
		// Error if protection is disabled
		if policy.Protect != nil && !*policy.Protect {
			return nil, fmt.Errorf("required prow jobs require branch protection")
		}
		ps := Policy{
			RequiredStatusChecks: &ContextPolicy{
				Contexts: prowContexts,
			},
		}
		// Require protection by default if ProtectTested is true
		if c.BranchProtection.ProtectTested {
			yes := true
			ps.Protect = &yes
		}
		var err error
		if policy, err = policy.Apply(ps); err != nil {
			return nil, err
		}
	}

	if policy.Protect != nil && !*policy.Protect {
		// Ensure that protection is false => no protection settings
		var old *bool
		old, policy.Protect = policy.Protect, old
		switch {
		case policy.defined() && c.BranchProtection.AllowDisabledPolicies:
			logrus.Warnf("%s/%s=%s defines a policy but has protect: false", org, repo, branch)
			policy = Policy{
				Protect: policy.Protect,
			}
		case policy.defined():
			return nil, fmt.Errorf("%s/%s=%s defines a policy, which requires protect: true", org, repo, branch)
		}
		policy.Protect = old
	}

	if !policy.defined() {
		return nil, nil
	}
	return &policy, nil
}

// BranchRequirements partitions status contexts for a given org, repo branch into three buckets:
//  - contexts that are always required to be present
//  - contexts that are required, _if_ present
//  - contexts that are always optional
func BranchRequirements(org, repo, branch string, presubmits map[string][]Presubmit) ([]string, []string, []string) {
	jobs, ok := presubmits[org+"/"+repo]
	if !ok {
		return nil, nil, nil
	}
	var required, requiredIfPresent, optional []string
	for _, j := range jobs {
		if !j.CouldRun(branch) {
			continue
		}

		if j.ContextRequired() {
			if j.TriggersConditionally() {
				// jobs that trigger conditionally cannot be
				// required as their status may not exist on PRs
				requiredIfPresent = append(requiredIfPresent, j.Context)
			} else {
				// jobs that produce required contexts and will
				// always run should be required at all times
				required = append(required, j.Context)
			}
		} else {
			optional = append(optional, j.Context)
		}
	}
	return required, requiredIfPresent, optional
}


text:
using System;
using System.Collections.Generic;

namespace AutoQueryable.UnitTest.Mock.Entities
{
    public class ProductModel
    {
        public ProductModel()
        {
            Product = new HashSet<Product>();
        }

        public int ProductModelId { get; set; }
        public string Name { get; set; }
        public string CatalogDescription { get; set; }
        public Guid Rowguid { get; set; }
        public DateTime ModifiedDate { get; set; }

        public virtual IEnumerable<Product> Product { get; set; }
    }
}


text:
// <copyright file="Lms.cs" company="James Jackson-South">
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>

namespace ImageSharp.ColorSpaces
{
    using System;
    using System.ComponentModel;
    using System.Numerics;
    using System.Runtime.CompilerServices;

    /// <summary>
    /// LMS is a color space represented by the response of the three types of cones of the human eye,
    /// named after their responsivity (sensitivity) at long, medium and short wavelengths.
    /// <see href="https://en.wikipedia.org/wiki/LMS_color_space"/>
    /// </summary>
    internal struct Lms : IColorVector, IEquatable<Lms>, IAlmostEquatable<Lms, float>
    {
        /// <summary>
        /// Represents a <see cref="Lms"/> that has L, M, and S values set to zero.
        /// </summary>
        public static readonly Lms Empty = default(Lms);

        /// <summary>
        /// The backing vector for SIMD support.
        /// </summary>
        private readonly Vector3 backingVector;

        /// <summary>
        /// Initializes a new instance of the <see cref="Lms"/> struct.
        /// </summary>
        /// <param name="l">L represents the responsivity at long wavelengths.</param>
        /// <param name="m">M represents the responsivity at medium wavelengths.</param>
        /// <param name="s">S represents the responsivity at short wavelengths.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public Lms(float l, float m, float s)
            : this(new Vector3(l, m, s))
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Lms"/> struct.
        /// </summary>
        /// <param name="vector">The vector representing the l, m, s components.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public Lms(Vector3 vector)
            : this()
        {
            // Not clamping as documentation about this space seems to indicate "usual" ranges
            this.backingVector = vector;
        }

        /// <summary>
        /// Gets the L long component.
        /// <remarks>A value usually ranging between -1 and 1.</remarks>
        /// </summary>
        public float L
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => this.backingVector.X;
        }

        /// <summary>
        /// Gets the M medium component.
        /// <remarks>A value usually ranging between -1 and 1.</remarks>
        /// </summary>
        public float M
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => this.backingVector.Y;
        }

        /// <summary>
        /// Gets the S short component.
        /// <remarks>A value usually ranging between -1 and 1.</remarks>
        /// </summary>
        public float S
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => this.backingVector.Z;
        }

        /// <summary>
        /// Gets a value indicating whether this <see cref="Lms"/> is empty.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public bool IsEmpty => this.Equals(Empty);

        /// <inheritdoc />
        public Vector3 Vector
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => this.backingVector;
        }

        /// <summary>
        /// Compares two <see cref="Lms"/> objects for equality.
        /// </summary>
        /// <param name="left">
        /// The <see cref="Lms"/> on the left side of the operand.
        /// </param>
        /// <param name="right">
        /// The <see cref="Lms"/> on the right side of the operand.
        /// </param>
        /// <returns>
        /// True if the current left is equal to the <paramref name="right"/> parameter; otherwise, false.
        /// </returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool operator ==(Lms left, Lms right)
        {
            return left.Equals(right);
        }

        /// <summary>
        /// Compares two <see cref="Lms"/> objects for inequality.
        /// </summary>
        /// <param name="left">
        /// The <see cref="Lms"/> on the left side of the operand.
        /// </param>
        /// <param name="right">
        /// The <see cref="Lms"/> on the right side of the operand.
        /// </param>
        /// <returns>
        /// True if the current left is unequal to the <paramref name="right"/> parameter; otherwise, false.
        /// </returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool operator !=(Lms left, Lms right)
        {
            return !left.Equals(right);
        }

        /// <inheritdoc/>
        public override int GetHashCode()
        {
            return this.backingVector.GetHashCode();
        }

        /// <inheritdoc/>
        public override string ToString()
        {
            if (this.IsEmpty)
            {
                return "Lms [ Empty ]";
            }

            return $"Lms [ L={this.L:#0.##}, M={this.M:#0.##}, S={this.S:#0.##} ]";
        }

        /// <inheritdoc/>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override bool Equals(object obj)
        {
            if (obj is Lms)
            {
                return this.Equals((Lms)obj);
            }

            return false;
        }

        /// <inheritdoc/>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Equals(Lms other)
        {
            return this.backingVector.Equals(other.backingVector);
        }

        /// <inheritdoc/>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool AlmostEquals(Lms other, float precision)
        {
            var result = Vector3.Abs(this.backingVector - other.backingVector);

            return result.X <= precision
                && result.Y <= precision
                && result.Z <= precision;
        }
    }
}


text:
package demo.redis.ecommerce.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import demo.EnvConstant;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisDBManager
{
    private static Date date = new Date();
    private static int minimum = 1;
    private static int maximum = 100000000;

    // going with the default pool.
    private static JedisPool connectionPool = new JedisPool(EnvConstant.HOST_REDIS, EnvConstant.PORT_REDIS);

    /**
     * 获取连接
     *
     * @return
     */
    public Jedis getConnection()
    {
        return connectionPool.getResource();
    }

    /**
     * 释放连接
     *
     * @param jedis
     */
    public void returnConnection(Jedis jedis)
    {
        connectionPool.returnResource(jedis);
    }

    public static String getDate()
    {
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        String dateValue = dateFormat.format(date);
        return dateValue;
    }

    public static String getRandomSessionID()
    {
        int randomNum = minimum + (int) (Math.random() * maximum);
        return new Integer(randomNum).toString();
    }
}


text:
namespace Microsoft.Azure.Management.TrafficManager.Fluent
{
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
    using Microsoft.Azure.Management.TrafficManager.Fluent.TrafficManagerProfile.Definition;
    using Microsoft.Rest;

    /// <summary>
    /// Entry point to traffic manager profile management API in Azure.
    /// </summary>
    public interface ITrafficManagerProfiles :
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsCreating<TrafficManagerProfile.Definition.IBlank>,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsListing<Microsoft.Azure.Management.TrafficManager.Fluent.ITrafficManagerProfile>,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsListingByResourceGroup<Microsoft.Azure.Management.TrafficManager.Fluent.ITrafficManagerProfile>,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsGettingByResourceGroup<Microsoft.Azure.Management.TrafficManager.Fluent.ITrafficManagerProfile>,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsGettingById<Microsoft.Azure.Management.TrafficManager.Fluent.ITrafficManagerProfile>,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsDeletingById,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsDeletingByResourceGroup,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsBatchCreation<Microsoft.Azure.Management.TrafficManager.Fluent.ITrafficManagerProfile>,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsBatchDeletion,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasManager<Microsoft.Azure.Management.TrafficManager.Fluent.ITrafficManager>,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasInner<Microsoft.Azure.Management.TrafficManager.Fluent.IProfilesOperations>
    {
        /// <summary>
        /// Asynchronously checks that the DNS name is valid for traffic manager profile and is not in use.
        /// </summary>
        /// <param name="dnsNameLabel">The DNS name to check.</param>
        /// <return>A representation of the deferred computation of this call, returning whether the DNS is available to be used for a traffic manager profile and other info if not.</return>
        Task<Microsoft.Azure.Management.TrafficManager.Fluent.CheckProfileDnsNameAvailabilityResult> CheckDnsNameAvailabilityAsync(string dnsNameLabel, CancellationToken cancellationToken = default(CancellationToken));

        /// <return>The default geographic hierarchy used by the Geographic traffic routing method.</return>
        Microsoft.Azure.Management.TrafficManager.Fluent.IGeographicLocation GetGeographicHierarchyRoot();

        /// <summary>
        /// Checks that the DNS name is valid for traffic manager profile and is not in use.
        /// </summary>
        /// <param name="dnsNameLabel">The DNS name to check.</param>
        /// <return>Whether the DNS is available to be used for a traffic manager profile and other info if not.</return>
        Microsoft.Azure.Management.TrafficManager.Fluent.CheckProfileDnsNameAvailabilityResult CheckDnsNameAvailability(string dnsNameLabel);
    }
}