text:
@font-face {
    font-family: 'fontello';
    src: url('https://i.alipayobjects.com/common/fonts/seajs-debug/fontello.eot');
    src: url('https://i.alipayobjects.com/common/fonts/seajs-debug/fontello.eot#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('https://i.alipayobjects.com/common/fonts/seajs-debug/fontello.woff') format('woff'),  /* chrome 6+、firefox 3.6+、Safari5.1+、Opera 11+ */ url('https://i.alipayobjects.com/common/fonts/seajs-debug/fontello.ttf') format('truetype'), /* chrome、firefox、opera、Safari, Android, iOS 4.2+ */ url('https://i.alipayobjects.com/common/fonts/seajs-debug/fontello.svg') format('svg'); /* iOS 4.1- */
    font-weight: normal;
    font-style: normal;
}

#seajs-debug-console #seajs-debug-status button,
#seajs-debug-console #seajs-debug-meta button,
#seajs-debug-console #seajs-debug-map button {
    font-family: "fontello";
}

#seajs-debug-console, #seajs-debug-console * {
    margin: 0;
    padding: 0;
    border: none;
    font: 14px/1.2 Arial
}

#seajs-debug-console {
    position: fixed;
    width: 520px;

    right: 10px;
    bottom: 10px;
    border: 2px solid #564F8A;

    z-index: 2147483647;
    background: #fafafa;
}

#seajs-debug-console a, #seajs-debug-console a:hover, #seajs-debug-console a:active, #seajs-debug-console a:link {
    text-decoration: none;
}

#seajs-debug-console button {
    border: none;
    background: transparent;
    cursor: pointer;

    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
}

#seajs-debug-console #seajs-debug-header,
#seajs-debug-console #seajs-debug-editor,
#seajs-debug-console #seajs-debug-map,
#seajs-debug-console #seajs-debug-health {
    border: none;
    border-bottom: 1px solid lightgrey;
}

#seajs-debug-console #seajs-debug-header {
    margin: 0;
    padding: 5px 5px 5px 10px;
    height: 20px;
    line-height: 20px;
    font-weight: bold;
    font-size: 16px;
    background: #564F8A;
    color: #cdbfe3;
}

#seajs-debug-console #seajs-debug-editor,
#seajs-debug-console #seajs-debug-map,
#seajs-debug-console #seajs-debug-health {
    min-height: 100px;
    _height: 100px;
    background: #FFF;
}
#seajs-debug-console #seajs-debug-editor,
#seajs-debug-console #seajs-debug-map p input {
    font-family: Courier, monospace;
    color: #666;
}
#seajs-debug-console #seajs-debug-editor {
    display: block;
    width: 510px;
    padding: 5px;

    resize: vertical;
}

#seajs-debug-console #seajs-debug-map {
    padding: 5px 0;
}

#seajs-debug-console #seajs-debug-map p {
    height: 30px;
    line-height: 30px;
    overflow: hidden;
    padding-left: 10px;
}

#seajs-debug-console #seajs-debug-map p input {
    padding-left: 6px;
    height: 24px;
    line-height: 24px;
    border: 1px solid #dcdcdc;
    width: 200px;
    vertical-align: middle;
    *vertical-align: bottom;
}
#seajs-debug-console #seajs-debug-map .seajs-debug-hit input {
    border-color: #cdbfe3;
    background-color: #F6F0FF;
}
#seajs-debug-console #seajs-debug-map button {
    color: #999;
}

#seajs-debug-console #seajs-debug-map button,
#seajs-debug-console #seajs-debug-meta button {
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
}

#seajs-debug-console #seajs-debug-status {
    height: 35px;
}

#seajs-debug-console #seajs-debug-status span {
    display: inline-block;
    *display: inline;
    *zoom: 1;
    height: 35px;
    line-height: 35px;
    padding-left: 8px;
    color: #AAA;
    vertical-align: middle;
}

#seajs-debug-console #seajs-debug-status button {
    width: 35px;
    height: 35px;
    line-height: 35px;
    color: #999;
    border: none;
    font-size: 16px;
    vertical-align: middle;
    _vertical-align: top;
}

#seajs-debug-console #seajs-debug-status button:hover,
#seajs-debug-console #seajs-debug-status button.seajs-debug-status-on:hover {
    background-color: #f0f0f0;
    color: #000;
}

#seajs-debug-console #seajs-debug-status button:active,
#seajs-debug-console #seajs-debug-status button.seajs-debug-status-on {
    color: #563d7c;
    text-shadow: 0 0 6px #cdbfe3;
    background-color: #f0f0f0;
}

#seajs-debug-console #seajs-debug-action {
    float: right;
    margin-top: -31px;
    *margin-top: -32px;
    margin-right: 2px;
}

#seajs-debug-console #seajs-debug-action button {
    position: relative;
    z-index: 2;
    width: 60px;
    height: 28px;
    border-radius: 2px;
    text-align: center;
    color: #333;
    background-color: #fff;
    border: 1px solid #ccc;
    text-transform: uppercase;
    *margin-left: 4px;
}

#seajs-debug-console #seajs-debug-action button:hover,
#seajs-debug-console #seajs-debug-action button:focus,
#seajs-debug-console #seajs-debug-action button:hover,
#seajs-debug-console #seajs-debug-action button:active {
  background-color: #ebebeb;
  border-color: #adadad;
}

#seajs-debug-console #seajs-debug-action button:active {
    position: relative;
    top: 1px;
    -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
    -moz-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
    box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}

#seajs-debug-console #seajs-debug-meta {
    position: absolute;
    right: 0;
    top: 0;

}

#seajs-debug-console #seajs-debug-meta button {
    background: #3f386d;
    color: white;
}

#seajs-debug-console #seajs-debug-health {
    height: 500px;

    /* loading */
}

/*
-webkit-animation: spin 2s infinite linear;
-moz-animation: spin 2s infinite linear;
-o-animation: spin 2s infinite linear;
-ms-animation: spin 2s infinite linear;
animation: spin 2s infinite linear;

*/
#seajs-debug-console.seajs-debug-mini {
    width: 30px;
    height: 30px;
    border: none;
}

/* ie6 */
#seajs-debug-console {
    _position: absolute;
    _top: expression(documentElement.scrollTop+documentElement.clientHeight-this.clientHeight-5);
}

* html {
    _background: url(null) no-repeat fixed;
}


text:
import {Component, ViewChild} from "@angular/core";
import {Events, MenuController, Nav, Platform} from "ionic-angular";
import {SplashScreen} from "@ionic-native/splash-screen";
import {Storage} from "@ionic/storage";
import {TabsPage} from "../pages/tabs/tabs";
import {UserData} from "../providers/user-data";
import {CompanyService} from "../providers/company.service";
import {Companies} from "../interface/companies.interface";
import CompanyQueryService from "../providers/companies-query.service";

export interface PageInterface {
  title: string;
  component: any;
  icon: string;
  logsOut?: boolean;
  index?: number;
  tabComponent?: any;
}

@Component({
  templateUrl: 'app.template.html'
})
export class ConferenceApp {
  @ViewChild(Nav) nav: Nav;
  rootPage: any;
  companies: Companies[];
  goods: string[];
  queryList: Set<string>;

  constructor(public events: Events,
              public userData: UserData,
              public menu: MenuController,
              public platform: Platform,
              public storage: Storage,
              public splashScreen: SplashScreen,
              public companyService: CompanyService,
              private companyQueryService: CompanyQueryService) {
    this.queryList = new Set<string>();
    this.getAllCompanies();

    this.rootPage = TabsPage;
    this.platformReady();

  }

  addToQueryList(query: string) {
    if (this.queryList.has(query)) {
      this.queryList.delete(query);
    } else {
      this.queryList.add(query);
    }
    console.log(this.queryList);
    let queryStringArray: string[] = [];
    this.queryList.forEach(item => {
      queryStringArray.push(item)
    });
    this.companyQueryService.setQuery(queryStringArray);
  }

  platformReady() {
    // Call any initial plugins when ready
    this.platform.ready().then(() => {
      this.splashScreen.hide();
    });
  }

  getAllCompanies() {
    this.companyService.getCompanies().subscribe(
      response => {
        this.companies = response.success;
        console.log(this.companies);
        this.goods = [];
        this.goods = this.companyService.getCompaniesGoods(this.companies);
      },
      error => {

      }
    );
  }
}

redpajama_set_name: RedPajamaGithub


text:
package v1

import (
	"k8s.io/apimachinery/pkg/runtime"

	oapi "github.com/openshift/origin/pkg/api"
	userapi "github.com/openshift/origin/pkg/user/apis/user"
)

func addConversionFuncs(scheme *runtime.Scheme) error {
	if err := scheme.AddFieldLabelConversionFunc("v1", "Identity",
		oapi.GetFieldLabelConversionFunc(userapi.IdentityToSelectableFields(&userapi.Identity{}), nil),
	); err != nil {
		return err
	}

	return nil
}


text:
import svgdatashapes as s

def test_units_fluid( browser ):    #  browser:  'firefox', 'chrome', 'safari', or 'msie'

    s.svgbegin( width=500, height=400, fluidsize=True, browser=browser, testgrid=True )
    return s.svgresult()


text:
class AddVatEnabledToAccounts < ActiveRecord::Migration
  def change
    add_column :accounts, :vat_enabled, :boolean
  end
end


text:
require 'spec_helper'

describe ListsController do
  before do
    @account = Factory(:account)
    controller.stub!(:current_subdomain).and_return(@account.name)

    @current_user = Factory(:user)
    @current_user.promote_to_admin
    controller.stub!(:current_user).and_return(@current_user)
  end

  describe "GET to index" do
    before do
      @lists = (1..3).collect{ Factory(:list, :account => @account) }
      get :index
    end

    it { should assign_to(:lists).with(@list) }
    it { should respond_with(:success) }
    it { should render_with_layout(:hotink) }
    it { should respond_with_content_type(:html) }
  end

  describe "GET to new" do
    before do
      @articles = (1..3).collect{ Factory(:published_article, :account => @account) }

      get :new
    end
    it { should assign_to(:list).with_kind_of(List) }
    it { should assign_to(:articles).with(@articles) }
    it { should respond_with(:success) }
    it { should respond_with_content_type(:html) }
  end

  describe "POST to create" do
    context "with valid attributes" do
      before do
        post :create,  :list => { :name => "My list" }
      end

      it { should respond_with(:redirect) }
      it { should assign_to(:list).with_kind_of(List) }
      it "should create list" do
        assigns(:list).should_not be_new_record
        assigns(:list).name.should eql("My list")
      end
    end

    context "with invalid attributes" do
      before do
        @articles = (1..3).collect{ Factory(:published_article, :account => @account) }
        post :create,  :list => { :name => "Chris's list" }
      end

      it { should respond_with(:success) }
      it { should render_template(:new) }
      it { should assign_to(:articles).with(@articles) }
      it { should assign_to(:list).with_kind_of(List) }
      it "should not create list" do
        assigns(:list).should be_new_record
      end
    end
  end

  describe "GET to edit" do
     before do
       @articles = (1..3).collect{ Factory(:published_article, :account => @account) }
       @list = Factory(:list, :account => @account)
     end

     context "by list's owner" do
       before do
         @list.owner = @current_user
         get :edit, :id => @list.id
       end

       it { should assign_to(:articles).with(@articles) }
       it { should respond_with(:success) }
       it { should assign_to(:list).with(@list) }
     end

     context "by administrator" do
       before do
         @current_user.promote_to_admin
         get :edit, :id => @list.id
       end

       it { should assign_to(:list).with(@list) }
     end

     context "by user prohibited from editing article" do
       before do
         @current_user.has_no_role "admin"
         get :edit, :id => @list.id
       end

       it { should respond_with(:unauthorized) }
     end

     context "with search query" do
       before do
         @current_user.promote_to_admin
         Article.stub!(:search).and_return(@articles[0..1])
         get :edit, :id => @list.id, :q => "Search term"
       end

       it { should assign_to(:articles).with(@articles[0..1]) }
     end
  end

  describe "PUT to update" do
    before do
      @list = Factory(:list, :owner => @current_user, :account => @account)
    end

    context "with valid attributes" do
      before do
        put :update, :id => @list.id, :list => { :name => "Testing update" }
      end

      it { should respond_with(:redirect) }
      it { should assign_to(:list).with(@list) }
      it "should update list" do
        @list.reload.name.should == "Testing update"
      end
    end

    context "with invalid attributes" do
      before do
        @articles = (1..3).collect{ Factory(:published_article, :account => @account) }
        put :update, :id => @list.id, :list => { :name => nil }
      end

      it { should assign_to(:articles).with(@articles) }
      it { should render_template(:edit) }
      it { should respond_with(:success) }
      it { should assign_to(:list).with(@list) }
      it { should render_template(:edit)}
    end

    describe "with no document ids, empties list" do
      before do
        @list.documents = (1..3).collect { Factory(:document, :account => @account) }
        put :update, :id => @list.id, :list => { :name => "Testing update" }
      end

      it "should empty list" do
        @list.documents.reload.should be_blank
      end
    end
  end

  describe "DELETE to destroy" do
    before do
      @list = Factory(:list, :account => @account)
      @current_user.promote_to_admin
      delete :destroy, :id => @list.id
    end

    it { should respond_with(:redirect) }
    it "should destroy the list" do
      lambda { List.find(@list.id)}.should raise_error(ActiveRecord::RecordNotFound)
    end
  end
end


text:
def print_symbols(protocall, arguments, symbols):
    print "Symbols:"
    print symbols.dump()
    return None


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Package Management | React</title>
  <meta name="viewport" content="width=device-width">
  <meta property="og:title" content="Package Management | React">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://facebook.github.io/react/docs/package-management.html">
  <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
  <meta property="og:description" content="A JavaScript library for building user interfaces">
  <meta property="fb:app_id" content="623268441017527">

  <link rel="shortcut icon" href="/react/favicon.ico">
  <link rel="alternate" type="application/rss+xml" title="React" href="https://facebook.github.io/react/feed.xml">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
  <link rel="stylesheet" href="/react/css/syntax.css">
  <link rel="stylesheet" href="/react/css/codemirror.css">
  <link rel="stylesheet" href="/react/css/react.css">

          React

Docs

Support

Download

Blog

            <input id="algolia-doc-search" type="text" placeholder="Search docs..." />

GitHub

React Native

Quick Start

            Getting Started

            Tutorial

            Thinking in React

Community Resources

            Conferences

            Videos

            Complementary Tools

            Examples

Guides

            Why React?

            Displaying Data

                    JSX in Depth

                    JSX Spread Attributes

                    JSX Gotchas

            Interactivity and Dynamic UIs

            Multiple Components

            Reusable Components

            Transferring Props

            Forms

            Working With the Browser

                    Refs to Components

            Tooling Integration

                    Language Tooling

                    Package Management

                    Server-side Environments

            Add-Ons

                    Animation

                    Two-Way Binding Helpers

                    Test Utilities

                    Cloning Elements

                    Keyed Fragments

                    Immutability Helpers

                    PureRenderMixin

                    Performance Tools

                    Shallow Compare

            Advanced Performance

            Context

Reference

            Top-Level API

            Component API

            Component Specs and Lifecycle

            Supported Tags and Attributes

            Event System

            DOM Differences

            Special Non-DOM Attributes

            Reconciliation

            Web Components

            React (Virtual) DOM Terminology

Tips

            Introduction

            Inline Styles

            If-Else in JSX

            Self-Closing Tag

            Maximum Number of JSX Root Nodes

            Shorthand for Specifying Pixel Values in style props

            Type of the Children props

            Value of null for Controlled Input

            componentWillReceiveProps Not Triggered After Mounting

            Props in getInitialState Is an Anti-Pattern

            DOM Event Listeners in a Component

            Load Initial Data via AJAX

            False in JSX

            Communicate Between Components

            Expose Component Functions

            this.props.children undefined

            Use React with Other Libraries

            Dangerously Set innerHTML

Contributing

            Design Principles

    Edit on GitHub

      Package Management

CDN-hosted React #

We provide CDN-hosted versions of React on our download page. These pre-built files use the UMD module format. Dropping them in with a simple <script> tag will inject the React and ReactDOM globals into your environment. It should also work out-of-the-box in CommonJS and AMD environments.

Using React from npm #

You can use React with a CommonJS module system like browserify or webpack. Use the react and react-dom npm packages.

// main.js
var React = require('react');
var ReactDOM = require('react-dom');

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('example')
);

Configure babel with a .babelrc file:

 { "presets": ["react"] }

Note:

If you are using ES2015, you will want to also use the babel-preset-es2015 package.

To install React DOM and build your bundle with browserify:

$ npm install --save react react-dom babelify babel-preset-react
$ browserify -t [ babelify ] main.js -o bundle.js

To install React DOM and build your bundle with webpack:

$ npm install --save react react-dom babel-preset-react babel-loader babel-core
$ webpack main.js bundle.js --module-bind 'js=babel-loader'

Note:

If you are using ES2015, you will want to also use the babel-preset-es2015 package.

Note: by default, React will be in development mode, which is slower, and not advised for production. To use React in production mode, set the environment variable NODE_ENV to production (using envify or webpack's DefinePlugin). For example:

new webpack.DefinePlugin({
  "process.env": {
    NODE_ENV: JSON.stringify("production")
  }
});

Update your HTML file as below:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script src="build/react.js"></script>
    <script src="build/react-dom.js"></script>
    <!-- No need for Babel! -->
  </head>
  <body>
    <div id="example"></div>
    <script src="build/helloworld.js"></script>
  </body>
</html>

Using React from Bower #

Bower is a package manager optimized for the front-end development. If multiple packages depend on a package - jQuery for example - Bower will download jQuery just once. This is known as a flat dependency graph and it helps reduce page load. For more info, visit http://bower.io/

If you'd like to use bower, it's as easy as:

bower install --save react

<!DOCTYPE html>

<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script src="bower_components/react/react.js"></script>
    <script src="bower_components/react/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

Using master #

We have instructions for building from master in our GitHub repository.

        ← Prev

        Next →

        A Facebook & Instagram collaboration.

        Acknowledgements

        © 2013–2016 Facebook Inc.

        Documentation licensed under CC BY 4.0.


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

namespace Words
{
    class WordMapComparer : IComparer<WordMap>
    {
        static readonly char[] Vowels = new[] { 'A', 'E', 'I', 'O', 'U' };

        public int Compare(WordMap x, WordMap y)
        {
            return WordValue(x).CompareTo(WordValue(y));
        }

        private static double WordValue(WordMap word)
        {
            return word.Map.Sum(kv => (IsVowel(kv.Key) ? 1 : 1.5) / kv.Value);
        }

        private static bool IsVowel(char c)
        {
            return Vowels.Contains(c);
        }
    }
}


text:
package com.emerchantpay.gateway.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.security.Principal;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Collection;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import com.emerchantpay.gateway.api.*;
import com.emerchantpay.gateway.api.exceptions.AuthenticationException;
import com.emerchantpay.gateway.api.exceptions.DownForMaintenanceException;
import com.emerchantpay.gateway.api.exceptions.NotFoundException;
import com.emerchantpay.gateway.api.exceptions.ServerException;
import com.emerchantpay.gateway.api.exceptions.UnexpectedException;
import com.emerchantpay.gateway.api.exceptions.UpgradeRequiredException;

public class Http {

	enum RequestMethod {
		DELETE, GET, POST, PUT;
	}

	private Configuration configuration;

	public Http(Configuration configuration) {
		this.configuration = configuration;
	}

	public void delete(String url) {
		httpRequest(RequestMethod.DELETE, url);
	}

	public NodeWrapper get(String url) {
		return httpRequest(RequestMethod.GET, url);
	}

	public NodeWrapper post(String url) {
		return httpRequest(RequestMethod.POST, url, null);
	}

	public NodeWrapper post(String url, Request request) {
		return httpRequest(RequestMethod.POST, url, request.toXML());
	}

	public NodeWrapper postQuery(String url, Request request) {

		return httpRequest(RequestMethod.POST, url, request.toQueryString(""));
	}

	public NodeWrapper put(String url) {
		return httpRequest(RequestMethod.PUT, url, null);
	}

	public NodeWrapper put(String url, Request request) {
		return httpRequest(RequestMethod.PUT, url, request.toXML());
	}

	private NodeWrapper httpRequest(RequestMethod requestMethod, String url) {
		return httpRequest(requestMethod, url, null);
	}

	private NodeWrapper httpRequest(RequestMethod requestMethod, String url, String postBody) {
		HttpURLConnection connection = null;
		NodeWrapper nodeWrapper = null;

		try {
			connection = buildConnection(requestMethod, url);

			Logger logger = configuration.getLogger();
			if (postBody != null) {
				logger.log(Level.FINE, formatSanitizeBodyForLog(postBody));
			}

			if (connection instanceof HttpsURLConnection) {
				((HttpsURLConnection) connection).setSSLSocketFactory(getSSLSocketFactory());
			}

			if (postBody != null) {
				OutputStream outputStream = null;
				try {
					outputStream = connection.getOutputStream();
					outputStream.write(postBody.getBytes("UTF-8"));
				} finally {
					if (outputStream != null) {
						outputStream.close();
					}
				}
			}

			throwExceptionIfErrorStatusCode(connection.getResponseCode(), null);
			if (requestMethod.equals(RequestMethod.DELETE)) {
				return null;
			}

			InputStream responseStream = null;
			try {
				responseStream = connection.getResponseCode() == 422 ? connection.getErrorStream()
						: connection.getInputStream();

				// if ("gzip".equalsIgnoreCase(connection.getContentEncoding()))
				// {
				// responseStream = new GZIPInputStream(responseStream);
				// }

				String xml = StringUtils.inputStreamToString(responseStream);

				logger.log(Level.INFO, "[Genesis] [{0}]] {1} {2}",
						new Object[] { getCurrentTime(), requestMethod.toString(), url });
				logger.log(Level.FINE, "[Genesis] [{0}] {1} {2} {3}",
						new Object[] { getCurrentTime(), requestMethod.toString(), url, connection.getResponseCode() });

				if (xml != null) {
					logger.log(Level.FINE, formatSanitizeBodyForLog(xml));
				}

				nodeWrapper = NodeWrapperFactory.instance.create(xml);
			} finally {
				if (responseStream != null) {
					responseStream.close();
				}
			}
		} catch (IOException e) {
			try {
				throw new UnexpectedException(e.getMessage(), e);
			} catch (UnexpectedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}

		return nodeWrapper;
	}

	private String formatSanitizeBodyForLog(String body) {
		if (body == null) {
			return body;
		}

		Pattern regex = Pattern.compile("(^)", Pattern.MULTILINE);
		Matcher regexMatcher = regex.matcher(body);
		if (regexMatcher.find()) {
			body = regexMatcher.replaceAll("[Genesis] $1");
		}

		regex = Pattern.compile("<number>(.{6}).+?(.{4})</number>");
		regexMatcher = regex.matcher(body);
		if (regexMatcher.find()) {
			body = regexMatcher.replaceAll("<number>$1******$2</number>");
		}

		body = body.replaceAll("<cvv>.+?</cvv>", "<cvv>***</cvv>");

		return body;
	}

	private String getCurrentTime() {
		return new SimpleDateFormat("d/MMM/yyyy HH:mm:ss Z").format(new Date());
	}

	private SSLSocketFactory getSSLSocketFactory() {
		try {
			KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
			keyStore.load(null);

			String[] certificateFilenames = new String[] { "ca-bundle.pem" };

			for (String certificateFilename : certificateFilenames) {
				CertificateFactory cf = CertificateFactory.getInstance("X.509");
				InputStream certStream = null;
				try {
					certStream = Http.class.getClassLoader().getResourceAsStream(certificateFilename);

					Collection<? extends Certificate> coll = cf.generateCertificates(certStream);
					for (Certificate cert : coll) {
						if (cert instanceof X509Certificate) {
							X509Certificate x509cert = (X509Certificate) cert;
							Principal principal = x509cert.getSubjectDN();
							String subject = principal.getName();
							keyStore.setCertificateEntry(subject, cert);
						}
					}
				} finally {
					if (certStream != null) {
						certStream.close();
					}
				}
			}

			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			kmf.init(keyStore, null);
			TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			tmf.init(keyStore);

			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init((KeyManager[]) kmf.getKeyManagers(), tmf.getTrustManagers(),
					SecureRandom.getInstance("SHA1PRNG"));

			return sslContext.getSocketFactory();
		} catch (Exception e) {
			Logger logger = configuration.getLogger();
			logger.log(Level.SEVERE, "SSL Verification failed. Error message: {0}", new Object[] { e.getMessage() });
			try {
				throw new UnexpectedException(e.getMessage(), e);
			} catch (UnexpectedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		return null;
	}

	private HttpURLConnection buildConnection(RequestMethod requestMethod, String urlString)
			throws java.io.IOException {
		URL url = new URL(urlString);
		HttpURLConnection connection;

		String user_pass = configuration.getUsername() + ":" + configuration.getPassword();
		String encoded = Base64.getEncoder().encodeToString(user_pass.getBytes());

		connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod(requestMethod.toString());
		connection.addRequestProperty("Accept", "application/xml");
		connection.setRequestProperty("Content-Type", "application/xml");
		connection.addRequestProperty("Authorization", "Basic " + encoded);
		connection.setDoOutput(true);
		connection.setReadTimeout(60000);

		return connection;
	}

	public static void throwExceptionIfErrorStatusCode(int statusCode, String message) {
		@SuppressWarnings("unused")
		String decodedMessage = null;
		if (message != null) {
			try {
				decodedMessage = URLDecoder.decode(message, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		if (isErrorCode(statusCode)) {
			switch (statusCode) {
			case 401:
				throw new AuthenticationException();
			case 404:
				throw new NotFoundException();
			case 426:
				throw new UpgradeRequiredException();
			case 500:
				throw new ServerException();
			case 503:
				throw new DownForMaintenanceException();

			default:
				try {
					throw new UnexpectedException("Unexpected HTTP_RESPONSE " + statusCode);
				} catch (UnexpectedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	private static boolean isErrorCode(int responseCode) {
		return responseCode != 200 && responseCode != 201 && responseCode != 422;
	}
}


text:
<!DOCTYPE html>
<html lang="en" ng-app="KCLGS">

<head>
    <base href="/">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="apple-touch-icon" sizes="180x180" href="favicons/apple-touch-icon.png">
    <link rel="icon" type="image/png" href="favicons/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="favicons/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="favicons/manifest.json">
    <link rel="mask-icon" href="favicons/safari-pinned-tab.svg" color="#5bbad5">
    <meta name="theme-color" content="#ffffff">
    <title>KCL Guitar Society</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="app.css" />
    <!-- jQuery library -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/1.4.3/jquery.scrollTo.min.js"></script>
    <!-- Latest compiled JavaScript -->
</head>

<body>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-mocks/angular-mocks.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="bower_components/angular-animate/angular-animate.js"></script>
    <script src="bower_components/angular-cookies/angular-cookies.js"></script>
    <script src="../bower_components/ngSmoothScroll/lib/angular-smooth-scroll.js"></script>
    <script src="../bower_components/angular-bootstrap/ui-bootstrap-tpls.js"></script>
    <script src="app.module.js"></script>
    <script src="app.config.js"></script>
    <script src="home/home.module.js"></script>
    <script src="home/home.component.js"></script>
    <script src="book-lesson/book-lesson.module.js"></script>
    <script src="book-lesson/book-lesson.component.js"></script>
    <script src="verify/verify.module.js"></script>
    <script src="verify/verify.component.js"></script>
    <script src="add-lesson/add-lesson.module.js"></script>
    <script src="add-lesson/add-lesson.component.js"></script>
    <script src="sign-in/sign-in.module.js"></script>
    <script src="sign-in/sign-in.component.js"></script>
    <script src="purchase-lesson/purchase-lesson.module.js"></script>
    <script src="purchase-lesson/purchase-lesson.component.js"></script>
    <script src="your-lessons/your-lessons.module.js"></script>
    <script src="your-lessons/your-lessons.component.js"></script>
    <script src="forgot-password/forgot-password.module.js"></script>
    <script src="forgot-password/forgot-password.component.js"></script>
    <script src="create-account/create-account.module.js"></script>
    <script src="create-account/create-account.component.js"></script>
    <script src="reset-password/reset-password.module.js"></script>
    <script src="reset-password/reset-password.component.js"></script>
    <script src="upgrade-account/upgrade-account.module.js"></script>
    <script src="upgrade-account/upgrade-account.component.js"></script>

    <div ng-view></div>
</body>

</html>


text:
// Tout ce qui suit est exécuté lorsque le DOM est prêt.
$(function() {
  // Enroulement/déroulement des sections
  // ====================================

  // Lorsqu'on clique sur un titre h2 ou h3...
  $('h2, h3').click(function() {
    // ... la section suivante s'ouvre ou se ferme...
    $(this).next('section').slideToggle()
    // ... et le style du titre se modifie.
    $(this).toggleClass('closed')
  });

  // Les titres ayant la classe "collapsed" sont fermés par défaut.
  $('h2.collapsed, h3.collapsed').click()

  // Génération automatique des exemple d'après le code
  // ==================================================

  // Pour chaque exemple,...
  $('.exemple').each(function() {
    // ... on mémorise le nom...
    let nom = $(this).data('nom')
    // ... et on crée des éléments...
    let elements = []
    // .. d'après le data "elements".
    $(this).data('elements').split('|').forEach(function(donnee) {
      // Chaque élément comporte trois parties :
      let parties = donnee.split(/#|::/, 3)
      // 1) Le type de balise (div, a, input, ...)
      let balise = parties[0]
      // 2) La liste des attributs commençant par l'id (style, width, ...)
      let attributs = parties[1]
      // 3) Le contenu de la balise (html)
      let contenu = parties[2]
      // On sépare ces données et on les ajoute à "elements" en JSON.
      elements.push({
        attributs: attributs,
        balise: balise,
        contenu: contenu
      })
    }) // fin du forEach

    // On isole le code.
    let code = $(this).find('code').text()
    // On crée une zone d'exemple...
    let exemple = $('

')
    // ... ans laquel on insérera chaque élément...
    elements.forEach(function(element) {
      let attributs = element.attributs.split('&')
      /*
      La ligne ci-dessous a des problèmes d'affichage lorsqu'on la voit par
      le didacticiel. Merci de vérifier le code source.
      */
      let nouvelElement = $(`<${element.balise}></${element.balise}>`, {
        // ... en modifiant simplement son ID pour qu'il soit unique sur la page.
        id: `${nom}_${attributs.shift()}`,
        html: element.contenu
      })
      // On oublie pas de gérer les attributs.
      attributs.forEach(function(attribut) {
        let cleValeur = attribut.split('=')
        let cle = cleValeur[0]
        let valeur = cleValeur[1]
        nouvelElement.attr(cle, valeur)
      })
      exemple.append(nouvelElement)
    })

    // On crée un fieldset...
    let resultat = $('<fieldset></fieldset>')
    // ... auquel on donne le titre "Résultat"...
    resultat.append('<legend>Résultat</legend>')
    // ... et dans lequel on ajoute chaque élément à la zone d'exemple.
    $(resultat).append(exemple)
    // ... avant de l'ajouter à l'exemple.
    $(this).append(resultat)
    // Ensuite, on ajoute une copie du script qui soit fonctionnelle...
    $(this).append($('', {
      // ... en ajustant les ID comme plus haut.
      text: code.replace(/#(\w)/g,`#${nom}_$1`)
    }))
    // On règle encore quelques propriétés CSS.
    resultat.css('position', 'relative').css('white-space', 'normal')

    // Pour chaque élément du résultat...
    resultat.children().eq(1).children().each(function() {
      // ... on mémorise d'élément pour éviter des conflits,
      let element = $(this)
      // ... on crée un tooltip
      let tooltip = $('

', {
        // qui contient l'ID de l'élément...
        text: `#${element.attr('id').replace(/^[^_]*_/, '')}`,
        // ... et du CSS.
        css: {
          background: '#ccf',
          border: '1px solid #00f',
          boxShadow: '10px 10px 10px rgba(0, 0, 0, 0.4)',
          display: 'block',
          padding: '5px',
          position: 'absolute'
        }
      })
      // On règle le survol de l'élément comme suit :
      $(this).hover(function() {
        // On ajoute son tooltip au body quand on le survole...
        $('body').append(tooltip)
      }, function() {
        // ... et on l'enlève quand on arrête le survol.
        tooltip.detach()
      }).mousemove(function(e) {
        // Puis on place le tooltip à proximité du curseur quand il bouge.
        tooltip.css('left', e.pageX).css('top', e.pageY + 20)
      })
    })
  })

  // Exercice 1
  // ==========

  $('#exercice1Code').keyup(function() {
    $('#exercice1Script').text($('#exercice1Code').val())
  })

  // Gestion de la partie affichage de ce code
  // =========================================

  // On place le numéro de version dans l'élément spécifique.
  $('#jQueryVersion').text($(this).jquery)

  // On insère en AJAX le code de "didacticiel.js" dans l'élément spécifique.
  let jQuerySource = $('

')
  jQuerySource.load('didacticiel.js', function() {
    $('#jQuerySource').text(jQuerySource.html())
  })

  // Affichage de la licence
  // =======================

  // Lorsqu'on clique sur le lien...
  $('#license').click(function() {
    // ... on crée un masque...
    let mask = $('

', {
      // ... qui recouvre toute la page...
      css: {
        background: 'rgba(0, 0, 0, 0.5)',
        bottom: 0,
        left: 0,
        position: 'fixed',
        right: 0,
        top: 0
      },
      // ... et qui disparait quand on clique dessus.
      click: function() {
        mask.remove()
      }
    }).appendTo($('body')) // On l'ajoute au body.

    // On crée une zone de texte...
    let license = $('

', {
      css: {
        background: '#fff',
        left: '50%',
        padding: 20,
        position: 'absolute',
        top: '50%',
        transform: 'translate(-50%, -50%)',
        whiteSpace: 'pre-wrap'
      },
      // ... qui ne disparait pas quand on clique dessus...
      click: function(event) {
        event.stopPropagation()
      }
    }).load('LICENSE', function() { // ... et qu'on charge avec la licence...
      // ... ainsi qu'avec un bouton "fermer"...
      let close = $('

', {
        text: 'X',
        css: {
          border: '1px dotted black',
          cursor: 'pointer',
          padding: 10,
          position: 'absolute',
          right: 0,
          top: 0,
        },
        // ... qui retire le masque quand on le clique.
        click: function() {
          mask.remove()
        }
      }).prependTo(license) // Le bouton est ajouté à la zone de texte...
    }).appendTo(mask) // .. qui est ajoutée au masque
  }).css('cursor', 'pointer') // Curseur sur le lien.
}) // fin de $(function(){})


text:
package main

import (
	"sync/atomic"

	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"github.com/kataras/iris/websocket"
)

func main() {
	app := iris.New()
	// load templates.
	app.RegisterView(iris.HTML("./views", ".html"))

	// render the ./views/index.html.
	app.Get("/", func(ctx iris.Context) {
		ctx.View("index.html")
	})

	mvc.Configure(app.Party("/websocket"), configureMVC)
	// Or mvc.New(app.Party(...)).Configure(configureMVC)

	// http://localhost:8080
	app.Run(iris.Addr(":8080"))
}

func configureMVC(m *mvc.Application) {
	ws := websocket.New(websocket.Config{})
	// http://localhost:8080/websocket/iris-ws.js
	m.Router.Any("/iris-ws.js", websocket.ClientHandler())

	// This will bind the result of ws.Upgrade which is a websocket.Connection
	// to the controller(s) served by the `m.Handle`.
	m.Register(ws.Upgrade)
	m.Handle(new(websocketController))
}

var visits uint64

func increment() uint64 {
	return atomic.AddUint64(&visits, 1)
}

func decrement() uint64 {
	return atomic.AddUint64(&visits, ^uint64(0))
}

type websocketController struct {
	// Note that you could use an anonymous field as well, it doesn't matter, binder will find it.
	//
	// This is the current websocket connection, each client has its own instance of the *websocketController.
	Conn websocket.Connection
}

func (c *websocketController) onLeave(roomName string) {
	// visits--
	newCount := decrement()
	// This will call the "visit" event on all clients, except the current one,
	// (it can't because it's left but for any case use this type of design)
	c.Conn.To(websocket.Broadcast).Emit("visit", newCount)
}

func (c *websocketController) update() {
	// visits++
	newCount := increment()

	// This will call the "visit" event on all clients, including the current
	// with the 'newCount' variable.
	//
	// There are many ways that u can do it and faster, for example u can just send a new visitor
	// and client can increment itself, but here we are just "showcasing" the websocket controller.
	c.Conn.To(websocket.All).Emit("visit", newCount)
}

func (c *websocketController) Get( /* websocket.Connection could be lived here as well, it doesn't matter */ ) {
	c.Conn.OnLeave(c.onLeave)
	c.Conn.On("visit", c.update)

	// call it after all event callbacks registration.
	c.Conn.Wait()
}


text:
:LastChangedDate: $LastChangedDate$
:LastChangedRevision: $LastChangedRevision$
:LastChangedBy: $LastChangedBy$

Cred: Pluggable Authentication
==============================

Goals
-----

Cred is a pluggable authentication system for servers.  It allows any
number of network protocols to connect and authenticate to a system, and
communicate to those aspects of the system which are meaningful to the specific
protocol.  For example, Twisted's POP3 support passes a "username and password" set of credentials to get back a mailbox for the specified email
account.  IMAP does the same, but retrieves a slightly different view of the
same mailbox, enabling those features specific to IMAP which are not available
in other mail protocols.

Cred is designed to allow both the backend implementation of the business
logic - called the *avatar* - and the authentication database - called
the *credential checker* - to be decided during deployment. For example,
the same POP3 server should be able to authenticate against the local UNIX
password database or an LDAP server without having to know anything about how
or where mail is stored.

To sketch out how this works - a "Realm" corresponds to an application
domain and is in charge of avatars, which are network-accessible business logic
objects.  To connect this to an authentication database, a top-level object
called a :api:`twisted.cred.portal.Portal <Portal>` stores a
realm, and a number of credential checkers.  Something that wishes to log in,
such as a :api:`twisted.internet.protocol.Protocol <Protocol>` ,
stores a reference to the portal. Login consists of passing credentials and a
request interface (e.g. POP3's :api:`twisted.mail.pop3.IMailbox <IMailbox>` ) to the portal. The portal passes
the credentials to the appropriate credential checker, which returns an avatar
ID. The ID is passed to the realm, which returns the appropriate avatar.  For a
Portal that has a realm that creates mailbox objects and a credential checker
that checks /etc/passwd, login consists of passing in a username/password and
the IMailbox interface to the portal. The portal passes this to the /etc/passwd
credential checker, gets back a avatar ID corresponding to an email account,
passes that to the realm and gets back a mailbox object for that email
account.

Putting all this together, here's how a login request will typically be
processed:

.. image:: ../img/cred-login.png

Cred objects
------------

The Portal
~~~~~~~~~~

This is the core of login, the point of integration between all the objects
in the cred system.  There is one
concrete implementation of Portal, and no interface - it does a very
simple task.  A :api:`twisted.cred.portal.Portal <Portal>`
associates one (1) Realm with a collection of
CredentialChecker instances.  (More on those later.)

If you are writing a protocol that needs to authenticate against
something, you will need a reference to a Portal, and to nothing else.
This has only 2 methods -

- :api:`twisted.cred.portal.Portal.login <login>` ``(credentials, mind, *interfaces)``

  The docstring is quite expansive (see :api:`twisted.cred.portal <twisted.cred.portal>` ), but in
  brief, this is what you call when you need to call in order to connect
  a user to the system.  Typically you only pass in one interface, and the mind
  is ``None`` . The interfaces are the possible interfaces the returned
  avatar is expected to implement, in order of preference.
  The result is a deferred which fires a tuple of:

  - interface the avatar implements (which was one of the interfaces passed in the ``*interfaces``
    tuple)
  - an object that implements that interface (an avatar)
  - logout, a 0-argument callable which disconnects the connection that was
    established by this call to login

  The logout method has to be called when the avatar is logged out. For POP3 this means
  when the protocol is disconnected or logged out, etc..

- :api:`twisted.cred.portal.Portal.registerChecker <registerChecker>` ``(checker, *credentialInterfaces)``

  which adds a CredentialChecker to the portal. The optional list of interfaces are interfaces of credentials
  that the checker is able to check.

The CredentialChecker
~~~~~~~~~~~~~~~~~~~~~

This is an object implementing :api:`twisted.cred.checkers.ICredentialsChecker <ICredentialsChecker>` which resolves some
credentials to an avatar ID.

Whether the credentials are stored in an in-memory data structure, an
Apache-style htaccess file, a UNIX password database, an SSH key database,
or any other form, an implementation of ``ICredentialsChecker`` is
how this data is connected to cred.

A credential checker
stipulates some requirements of the credentials it can check by
specifying a credentialInterfaces attribute, which is a list of
interfaces.  Credentials passed to its requestAvatarId method must
implement one of those interfaces.

For the most part, these things will just check usernames and passwords
and produce the username as the result, but hopefully we will be seeing
some public-key, challenge-response, and certificate based credential
checker mechanisms soon.

A credential checker should raise an error if it cannot authenticate
the user, and return ``twisted.cred.checkers.ANONYMOUS``
for anonymous access.

The Credentials
~~~~~~~~~~~~~~~

Oddly enough, this represents some credentials that the user presents.
Usually this will just be a small static blob of data, but in some
cases it will actually be an object connected to a network protocol.
For example, a username/password pair is static, but a
challenge/response server is an active state-machine that will require
several method calls in order to determine a result.

Twisted comes with a number of credentials interfaces and implementations
in the :api:`twisted.cred.credentials <twisted.cred.credentials>` module,
such as :api:`twisted.cred.credentials.IUsernamePassword <IUsernamePassword>`
and :api:`twisted.cred.credentials.IUsernameHashedPassword <IUsernameHashedPassword>` .

The Realm
~~~~~~~~~

A realm is an interface which connects your universe of "business objects" to the authentication system.

:api:`twisted.cred.portal.IRealm <IRealm>` is another one-method interface:

- :api:`twisted.cred.portal.IRealm.requestAvatar <requestAvatar>` ``(avatarId, mind, *interfaces)``

  This method will typically be called from 'Portal.login'.  The avatarId
  is the one returned by a CredentialChecker.

  .. note::
     Note that ``avatarId``  must always be a string. In
     particular, do not use unicode strings. If internationalized support is needed,
     it is recommended to use UTF-8, and take care of decoding in the realm.

  The important thing to realize about this method is that if it is being
  called, *the user has already authenticated* .  Therefore, if possible,
  the Realm should create a new user if one does not already exist
  whenever possible.  Of course, sometimes this will be impossible
  without more information, and that is the case that the interfaces
  argument is for.

Since requestAvatar should be called from a Deferred callback, it may
return a Deferred or a synchronous result.

The Avatar
~~~~~~~~~~

An avatar is a business logic object for a specific user. For POP3, it's
a mailbox, for a first-person-shooter it's the object that interacts with
the game, the actor as it were. Avatars are specific to an application,
and each avatar represents a single "user" .

The Mind
~~~~~~~~

As mentioned before, the mind is usually ``None`` , so you can skip this
bit if you want.

Masters of Perspective Broker already know this object as the ill-named "client object" .  There is no "mind" class, or even interface, but it
is an object which serves an important role - any notifications which are to be
relayed to an authenticated client are passed through a 'mind'. In addition, it
allows passing more information to the realm during login in addition to the
avatar ID.

The name may seem rather unusual, but considering that a Mind is
representative of the entity on the "other end" of a network connection
that is both receiving updates and issuing commands, I believe it is
appropriate.

Although many protocols will not use this, it serves an important role.
It is provided as an argument both to the Portal and to the Realm,
although a CredentialChecker should interact with a client program
exclusively through a Credentials instance.

Unlike the original Perspective Broker "client object" , a Mind's
implementation is most often dictated by the protocol that is
connecting rather than the Realm.  A Realm which requires a particular
interface to issue notifications will need to wrap the Protocol's mind
implementation with an adapter in order to get one that conforms to its
expected interface - however, Perspective Broker will likely continue
to use the model where the client object has a pre-specified remote
interface.

(If you don't quite understand this, it's fine.  It's hard to explain,
and it's not used in simple usages of cred, so feel free to pass None
until you find yourself requiring something like this.)

Responsibilities
----------------

Server protocol implementation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The protocol implementor should define the interface the avatar should implement,
and design the protocol to have a portal attached. When a user logs in using the
protocol, a credential object is created, passed to the portal, and an avatar
with the appropriate interface is requested. When the user logs out or the protocol
is disconnected, the avatar should be logged out.

The protocol designer should not hardcode how users are authenticated or the
realm implemented. For example, a POP3 protocol implementation would require a portal whose
realm returns avatars implementing IMailbox and whose credential checker accepts
username/password credentials, but that is all. Here's a sketch of how the code
might look - note that USER and PASS are the protocol commands used to login, and
the DELE command can only be used after you are logged in:

:download:`pop3_server.py <listings/cred/pop3_server.py>`

.. literalinclude:: listings/cred/pop3_server.py

Application implementation
~~~~~~~~~~~~~~~~~~~~~~~~~~

The application developer can implement realms and credential checkers. For example,
they might implement a realm that returns IMailbox implementing avatars, using MySQL
for storage, or perhaps a credential checker that uses LDAP for authentication.
In the following example, the Realm for a simple remote object service (using
Twisted's Perspective Broker protocol) is implemented:

.. code-block:: python

    from zope.interface import implementer

    from twisted.spread import pb
    from twisted.cred.portal import IRealm

    class SimplePerspective(pb.Avatar):

        def perspective_echo(self, text):
            print('echoing',text)
            return text

        def logout(self):
            print(self, "logged out")

    @implementer(IRealm)
    class SimpleRealm:

        def requestAvatar(self, avatarId, mind, *interfaces):
            if pb.IPerspective in interfaces:
                avatar = SimplePerspective()
                return pb.IPerspective, avatar, avatar.logout
            else:
                raise NotImplementedError("no interface")

Deployment
~~~~~~~~~~

Deployment involves tying together a protocol, an appropriate realm and a credential
checker. For example, a POP3 server can be constructed by attaching to it a portal
that wraps the MySQL-based realm and an /etc/passwd credential checker, or perhaps
the LDAP credential checker if that is more useful. The following example shows
how the SimpleRealm in the previous example is deployed using an in-memory credential checker:

.. code-block:: python

    from twisted.spread import pb
    from twisted.internet import reactor
    from twisted.cred.portal import Portal
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse

    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "password")
    portal.registerChecker(checker)
    reactor.listenTCP(9986, pb.PBServerFactory(portal))
    reactor.run()

Cred plugins
------------

Authentication with cred plugins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Cred offers a plugin architecture for authentication methods. The
primary API for this architecture is the command-line; the plugins are
meant to be specified by the end-user when deploying a TAP (twistd
plugin).

For more information on writing a twistd plugin and using cred
plugins for your application, please refer to the :doc:`Writing a twistd plugin <tap>` document.

Building a cred plugin
~~~~~~~~~~~~~~~~~~~~~~

To build a plugin for cred, you should first define an ``authType`` , a short one-word string that defines
your plugin to the command-line. Once you have this, the convention is
to create a file named ``myapp_plugins.py`` in the :api:`twisted.plugins <twisted.plugins>` module path.

Below is an example file structure for an application that defines
such a plugin:

- MyApplication/

  - setup.py
  - myapp/

    - __init__.py
    - cred.py
    - server.py

  - twisted/

    - plugins/

      - myapp_plugins.py

Once you have created this structure within your application, you can
create the code for your cred plugin by building a factory class which
implements :api:`twisted.cred.strcred.ICheckerFactory <ICheckerFactory>` .
These factory classes should not consist of a tremendous amount of
code. Most of the real application logic should reside in the cred
checker itself. (For help on building those, scroll up.)

The core purpose of the CheckerFactory is to translate an ``argstring`` , which is passed on the command line,
into a suitable set of initialization parameters for a Checker
class. In most cases this should be little more than constructing a
dictionary or a tuple of arguments, then passing them along to a new
checker instance.

.. code-block:: python

    from zope.interface import implementer

    from twisted import plugin
    from twisted.cred.strcred import ICheckerFactory
    from myapp.cred import SpecialChecker

    # The class needs to implement both of these interfaces
    # for the plugin system to find our factory.
    @implementer(ICheckerFactory, plugin.IPlugin)
    class SpecialCheckerFactory(object):
        """
        A checker factory for a specialized (fictional) API.
        """
        # This tells AuthOptionsMixin how to find this factory.
        authType = "special"

        # This is a one-line explanation of what arguments, if any,
        # your particular cred plugin requires at the command-line.
        argStringFormat = "A colon-separated key=value list."

        # This help text can be multiple lines. It will be displayed
        # when someone uses the "--help-auth-type special" command.
        authHelp = """Some help text goes here ..."""

        # This will be called once per command-line.
        def generateChecker(self, argstring=""):
            argdict = dict((x.split('=') for x in argstring.split(':')))
            return SpecialChecker(**argdict)

    # We need to instantiate our class for the plugin to work.
    theSpecialCheckerFactory = SpecialCheckerFactory()

For more information on how your plugin can be used in your
application (and by other application developers), please see the :doc:`Writing a twistd plugin <tap>` document.

Conclusion
----------

After reading through this tutorial, you should be able to

- Understand how the cred architecture applies to your application
- Integrate your application with cred's object model
- Deploy an application that uses cred for authentication
- Allow your users to use command-line authentication plugins


text:
package com.ibm.watson.assistant.v1.model;

import static org.testng.Assert.*;

import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import com.ibm.watson.assistant.v1.utils.TestUtilities;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;

/** Unit test class for the CreateIntent model. */
public class CreateIntentTest {
  final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
  final List<FileWithMetadata> mockListFileWithMetadata =
      TestUtilities.creatMockListFileWithMetadata();

  @Test
  public void testCreateIntent() throws Throwable {
    Mention mentionModel =
        new Mention.Builder()
            .entity("testString")
            .location(java.util.Arrays.asList(Long.valueOf("26")))
            .build();
    assertEquals(mentionModel.entity(), "testString");
    assertEquals(mentionModel.location(), java.util.Arrays.asList(Long.valueOf("26")));

    Example exampleModel =
        new Example.Builder()
            .text("testString")
            .mentions(java.util.Arrays.asList(mentionModel))
            .build();
    assertEquals(exampleModel.text(), "testString");
    assertEquals(exampleModel.mentions(), java.util.Arrays.asList(mentionModel));

    CreateIntent createIntentModel =
        new CreateIntent.Builder()
            .intent("testString")
            .description("testString")
            .examples(java.util.Arrays.asList(exampleModel))
            .build();
    assertEquals(createIntentModel.intent(), "testString");
    assertEquals(createIntentModel.description(), "testString");
    assertEquals(createIntentModel.examples(), java.util.Arrays.asList(exampleModel));

    String json = TestUtilities.serialize(createIntentModel);

    CreateIntent createIntentModelNew = TestUtilities.deserialize(json, CreateIntent.class);
    assertTrue(createIntentModelNew instanceof CreateIntent);
    assertEquals(createIntentModelNew.intent(), "testString");
    assertEquals(createIntentModelNew.description(), "testString");
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testCreateIntentError() throws Throwable {
    new CreateIntent.Builder().build();
  }
}


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [[HomeViewController alloc] init];
    [self.window makeKeyAndVisible];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {

}

- (void)applicationDidEnterBackground:(UIApplication *)application {

}

- (void)applicationWillEnterForeground:(UIApplication *)application {

}

- (void)applicationDidBecomeActive:(UIApplication *)application {

}

- (void)applicationWillTerminate:(UIApplication *)application {

}

@end


text:
namespace autoboost {
namespace asio {
namespace detail {

#if defined(AUTOBOOST_ASIO_WINDOWS) || defined(__CYGWIN__) || defined(__SYMBIAN32__)
typedef socket_select_interrupter select_interrupter;
#elif defined(AUTOBOOST_ASIO_HAS_EVENTFD)
typedef eventfd_select_interrupter select_interrupter;
#else
typedef pipe_select_interrupter select_interrupter;
#endif

} // namespace detail
} // namespace asio
} // namespace autoboost

#endif // !defined(AUTOBOOST_ASIO_WINDOWS_RUNTIME)

#endif // AUTOBOOST_ASIO_DETAIL_SELECT_INTERRUPTER_HPP


text:
"use strict";

const assert       = require("chai").assert;
const binarySearch = require("binary-search");
const co           = require("co");
const fs           = require("fs-promise");
const groupBy      = require("group-by");
const path         = require("path");
const NodeGit      = require("nodegit");

const CloseUtil           = require("./close_util");
const SparseCheckoutUtil  = require("./sparse_checkout_util");
const SubmoduleUtil       = require("./submodule_util");
const SubmoduleConfigUtil = require("./submodule_config_util");
const TextUtil            = require("./text_util");
const UserError           = require("./user_error");

const FILEMODE = NodeGit.TreeEntry.FILEMODE;
const STATUS = NodeGit.Status.STATUS;

function needToRequestRecursive(path) {
    throw new UserError(
        `not removing '${path}' recursively without -r`);
}

function pluralizeHas(n) {
    return n === 1 ? "has" : "have";
}

const errorsByCause = {
    unstaged: {
        problem: "local modifications",
        solution: "use --cached to keep the file, or -f to force removal"
    },
    staged: {
        problem: "changes staged in the index",
        solution: "use -f to force removal"
    },
    stagedAndUnstaged: {
        problem: "staged content different from both the file and the HEAD",
        solution: "use -f to force removal"
    }
};

function problemMessage(badFiles, cause, entityType) {
    const error = errorsByCause[cause];
    assert.isDefined(error);
    return `the following ${TextUtil.pluralize(entityType, badFiles.length)} \
${pluralizeHas(badFiles.length)} ${error.problem}:
${TextUtil.listToIndentedString(badFiles)}
(${error.solution})`;
}

/**
 * @class Problem
 * describes a problem which prevents removal of an object
 */
class Problem {
    constructor(path, cause, entityType) {
        if (undefined === entityType) {
            entityType = "file";
        }

        this.d_path = path;
        this.d_cause = cause;
        this.d_entityType = entityType;
        Object.freeze(this);
    }
    get path() {
        return this.d_path;
    }
    get cause() {
        return this.d_cause;
    }
    get entityType() {
        return this.d_entityType;
    }
}

const checkIndexIsHead = co.wrap(function*(headTree, indexId, entryPath) {
    if (headTree === null) {
        return false;
    }
    else {
        let inRepo;
        try {
            inRepo = yield headTree.entryByPath(entryPath);
        } catch (e) {
            return false;
        }
        if (!indexId.equal(inRepo.id())) {
            return false;
        }
    }
    return true;
});

/**
 * Return null if check index == HEAD || index == workdir.  Else,
 * return a Problem
 */
const checkIndexIsHeadOrWorkdir = co.wrap(function*(repo, headTree, entry,
                                                    entryPath, displayPath) {
    const inIndex = entry.id;

    const indexIsHead = yield checkIndexIsHead(headTree, inIndex, entryPath);
    if (indexIsHead) {
        return null;
    }
    const filePath = path.join(repo.workdir(), entryPath);
    try {
        yield fs.access(filePath);
    } catch (e) {
        assert.equal("ENOENT", e.code);
        //a file that doesn't exist is considered OK for rm --cached, too
        return null;
    }

    if (entry.mode === FILEMODE.COMMIT) {
        // this is a submodule so we don't check the working tree
        return new Problem(displayPath, "staged", "submodule");
    }

    const index = yield repo.index();
    const diff = yield NodeGit.Diff.indexToWorkdir(repo, index,
                                                   {"pathspec" : [entryPath]});
    if (diff.numDeltas() === 0) {
        return null;
    }
    else {
        return new Problem(displayPath, "unstaged", "file");
    }
});

function setDefault(options, arg, def) {
    if (undefined === options[arg]) {
        options[arg] = def;
    }
    else {
        assert.isBoolean(options[arg]);
    }
}

/**
 * Check that a file is clean enough to delete, according to Git's
 * rules.  An already-deleted file is always clean.  If --cached
 * is supplied, index may match either HEAD or the worktree; otherwise,
 * only the worktree is permitted.  For unclean files, return a Problem
 * describing how the file is unclean.
 */
const checkCleanliness = co.wrap(function *(repo, headTree, index, pathname,
                                            options) {
    if (options.force) {
        return null;
    }

    let displayPath = pathname;
    if (options.prefix !== undefined) {
        displayPath = path.join(options.prefix, pathname);
    }
    const entry = index.getByPath(pathname);

    if (options.cached) {
        return yield checkIndexIsHeadOrWorkdir(repo, headTree, entry,
                                               pathname, displayPath);
    }
    let status;
    try {
        // Status.file throws errors after 0.22.0
        status = yield NodeGit.Status.file(repo, pathname);
    } catch (err) {
        return null;
    }

    if (status === 0 || status & STATUS.WT_DELETED !== 0) {
        //git considers these OK regardless
        return null;
    }
    if ((status & STATUS.WT_MODIFIED) !== 0) {
        if ((status & STATUS.INDEX_MODIFIED) !== 0) {
            return new Problem(displayPath, "stagedAndUnstaged");
        }
        else {
            return new Problem(displayPath, "unstaged");
        }
    }
    else {
        if ((status & STATUS.INDEX_MODIFIED) !== 0) {
            return new Problem(displayPath, "staged");
        }
    }
    return null;
});

const deleteEmptyParents = co.wrap(function*(fullpath) {
    const parent = path.dirname(fullpath);
    try {
        yield fs.rmdir(parent);
    } catch (e) {
        //We only want to remove empty parent dirs, but it's
        //cheaper just to try to remove them and ignore errors
        return;
    }
    yield deleteEmptyParents(parent);
});

function checkAllPathsResolved(paths, resolved) {
    const allResolvedPaths = [];
    for (const rootLevel of Object.keys(resolved)) {
        const subPaths = resolved[rootLevel];
        if (subPaths.length === 0) {
            allResolvedPaths.push(rootLevel);
        } else {
            for (const sub of subPaths) {
                allResolvedPaths.push(path.join(rootLevel, sub));
            }
        }
    }
    allResolvedPaths.sort();
    for (const spec of paths) {
        let stripped = spec;
        if (spec.endsWith("/")) {
            stripped = spec.substring(0, spec.length - 1);
        }
        const idx = binarySearch(allResolvedPaths, stripped, TextUtil.strcmp);
        if (idx < 0) {
            //spec is a/b, next item is a/b/c, OK
            const insertionPoint = -idx - 1;
            const nextResolved = allResolvedPaths[insertionPoint];
            if (insertionPoint >= allResolvedPaths.length ||
                !nextResolved.startsWith(stripped + "/")) {
                throw new UserError(`\
pathspec '${spec}' did not match any files`);
            }
        }
    }
}

/**
 * Remove the specified `paths` in the specified `repo`.  If a path in
 * `paths` refers to a file, remove it.  If it refers to a directory,
 * and recursive is true, remove it recursively.  If it's false, throw
 * a UserError.  If a path to be removed does not exist in the index,
 * throw a UserError.  If a path to be removed is not clean, and force
 * is false, throw a UserError.
 *
 * If --cached is supplied, the paths will be removed from the index
 * but not from disk.
 *
 * If there are any dirty paths, the meta or submodule indexes may be
 * dirty upon return from this function.  Unfortunately due to a
 * nodegit bug, we can't reload the index:
 * https://github.com/nodegit/nodegit/issues/1478
 *
 * @async
 * @param {NodeGit.Repository} repo
 * @param {String []}          paths
 * @param {Object}             [options]
 * @param {Boolean}            [options.recursive]
 * @param {Boolean}            [options.cached] (remove from index not disk)
 * @param {Boolean}            [options.force]
 * @param {String}             [options.prefix] Path prefix for file lookup
 */
exports.rmPaths = co.wrap(function *(repo, paths, options) {
    assert.instanceOf(repo, NodeGit.Repository);
    assert.isArray(paths);
    if (undefined === options) {
        options = {};
    }
    else {
        assert.isObject(options);
    }
    setDefault(options, "recursive", false);
    setDefault(options, "cached", false);
    setDefault(options, "force", false);
    if (undefined === options.prefix) {
        options.prefix = "";
    }
    else {
        assert.isString(options.prefix);
    }

    for (const p of paths) {
        if (p === "") {
            throw new UserError("warning: empty strings as pathspecs are " +
                                "invalid.  Please use . instead if you " +
                                "meant to match all paths.");
        }
    }

    const index = yield repo.index();
    const headCommit = yield repo.getHeadCommit();

    const indexUrls =
          yield SubmoduleConfigUtil.getSubmodulesFromIndex(repo, index);
    const headUrls =
          yield SubmoduleConfigUtil.getSubmodulesFromCommit(repo, headCommit);

    // In theory, it would be be possible for a sub to be in the
    // workdir (that is, in an unstaged change to .gitmodules) as
    // well, but since git rm generally doesn't deal with workdir
    // changes, we ignore that possibility.

    // We might, at least for easy testing, want to handle changes to
    // root-level files, so we add those files to the root level items

    const rootLevelItemSet = new Set();
    for (const submodules of [indexUrls, headUrls]) {
        for (const sub of Object.keys(submodules)) {
            rootLevelItemSet.add(sub);
        }
    }

    for (const entry of index.entries()) {
        rootLevelItemSet.add(entry.path);
    }

    const rootLevelItems = [];
    rootLevelItems.push(...rootLevelItemSet);
    const openArray = yield SubmoduleUtil.listOpenSubmodules(repo);
    const openSubmoduleSet = new Set(openArray);

    // TODO: consider changing resolvePaths to support root-level items
    // items, which would enable removal of checkAllPathsResolved
    const resolved = yield SubmoduleUtil.resolvePaths(paths,
                                                      rootLevelItems,
                                                      openArray);

    checkAllPathsResolved(paths, resolved);

    let headTree = null;
    if (headCommit !== null) {
        const treeId = headCommit.treeId();
        headTree = yield repo.getTree(treeId);
    }

    // Check that everything is clean enough to remove
    const pathSet = new Set(paths);
    const toRemove = [];
    const problems = [];
    const removedSubmodules = [];
    const toRecurse = [];
    for (const rootLevel of Object.keys(resolved)) {
        const items = resolved[rootLevel];
        if (items.length === 0) {
            if (!(options.recursive || pathSet.has(rootLevel))) {
                return needToRequestRecursive([rootLevel]);
            }
            toRemove.push(rootLevel);
            const problem = yield checkCleanliness(repo, headTree, index,
                                                   rootLevel, options);
            if (problem !== null) {
                problems.push(problem);
            }
            const entry = index.getByPath(rootLevel);
            if (entry === undefined || entry.mode === FILEMODE.COMMIT) {
                removedSubmodules.push(rootLevel);
            }
        }
        else {
            // recurse into submodule
            const subRepo = yield SubmoduleUtil.getRepo(repo, rootLevel);
            const subOptions = {};
            Object.assign(subOptions, options);
            subOptions.prefix = rootLevel;
            // We set dryRun = true here because we're just checking
            // for clean.  If there are no problems, we'll later
            // go through toRecurse and do a full run.
            subOptions.dryRun = true;
            toRecurse.push({repo : subRepo, items : items,
                            options : subOptions});
            yield exports.rmPaths(subRepo, items, subOptions);
        }
    }

    //report any problems
    if (problems.length !== 0) {
        let msg = "";
        const byType = groupBy(problems, "entityType");

        for (const type in byType) {
            const byCause = groupBy(byType[type], "cause");
            for (const cause in byCause) {
                msg += problemMessage(byCause[cause].map(x => x.path),
                                      cause, type);
            }
        }
        throw new UserError(msg);
    }

    if (options.dryRun) {
        return;
    }

    // Now do the full run on submodules
    for (const r of toRecurse) {
        r.options.dryRun = false;
        yield exports.rmPaths(r.repo, r.items, r.options);
    }

    // This "if" is necessary due to
    // https://github.com/nodegit/nodegit/issues/1487
    if (toRemove.length !== 0) {
        yield index.removeAll(toRemove);
        yield SparseCheckoutUtil.setSparseBitsAndWriteIndex(repo, index);
    }

    // close to-be-deleted submodules
    const submodulesToClose = [];
    for (const submodule of removedSubmodules) {
        if (openSubmoduleSet.has(submodule)) {
            submodulesToClose.push(submodule);
        }
    }

    yield CloseUtil.close(repo, repo.workdir(), submodulesToClose,
                          options.force);

    // Clean up the workdir
    const root = repo.workdir();
    if (!options.cached) {
        for (const file of toRemove) {
            const fullpath = path.join(root, file);
            let stat = null;
            try {
                stat = yield fs.stat(fullpath);
            } catch (e) {
                //it is possible that e doesn't exist on disk
                assert.equal("ENOENT", e.code);
            }
            if (stat !== null) {
                if (stat.isDirectory()) {
                    try {
                        yield fs.rmdir(fullpath);
                    } catch (e) {
                        if ("ENOTEMPTY" === e.code) {
                            // Repo still exists for some reason --
                            // perhaps it was reported as deleted
                            // because it's not in the index, but it
                            // does exist on disk.  For safety, do not
                            // delete it; this is a weird case.
                            console.error(
                                `Could not remove ${fullpath} -- it's not
empty.  If you are sure it is not needed, you can remove it yourself.`
                            );
                        } else {
                            throw e;
                        }
                    }
                } else {
                    yield fs.unlink(fullpath);
                }
            }
            yield deleteEmptyParents(fullpath);
        }
    }

    // And write any gitmodules files changes
    const modules = yield SubmoduleConfigUtil.getSubmodulesFromIndex(repo,
                                                                     index);
    for (const file of removedSubmodules) {
        delete modules[file];
    }

    yield SubmoduleConfigUtil.writeUrls(repo, index, modules, options.cached);
    yield index.write();
});


text:
/*
Checkbox

A checkbox is a UI element that allows users to switch between two options(checked or uncheck, on or off).

Note: The `<label>` must appear after the `<input type="checkbox" class="checkbox">` due to the lack of parent selectors in CSS.

Markup:

Default CheckBox

  <input type="checkbox" id="checkbox1" name="checkbox1" class="checkbox">
  Checkbox

Selected CheckBox

  <input type="checkbox" id="checkbox1a" name="checkbox1a" checked class="checkbox">
  Checkbox selected

Disabled CheckBox

  <input type="checkbox" id="checkbox2" disabled name="checkbox2" class="checkbox">
  Checkbox Disabled

  <input type="checkbox" id="checkbox3" disabled checked name="checkbox3" class="checkbox">
  Checkbox Disabled Checked

Styleguide Checkbox
*/

/* Make the default checkbox invisible */
input[type="checkbox"].checkbox {
  position:absolute;
  left:-10000px;
  top:auto;
  width:1px;
  height:1px;
  overflow:hidden;
}

/* The label must appear after the <input type="checkbox" class="checkbox"> */
input[type="checkbox"].checkbox + label {
  position: relative;
}
/* Add the box for the fake checkbox */
input[type="checkbox"].checkbox + label::before {
  content: "";
  width: 1em;
  height: 1em;
  border: 1px solid black;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-block;
  vertical-align: text-top;
  box-sizing: border-box;
  margin-right: 0.2em;
}
/*Adding focus styles on the outer-box of the fake checkbox*/
input[type="checkbox"].checkbox:focus + label::before {
  outline: rgb(59, 153, 252) auto 5px;
}
/* Highlight the fake checkbox by changing its background-color and border-color */
input[type="checkbox"].checkbox:checked + label::before {
  background-color: #0078d7;
  border-color: #0078d7;
}
input[type="checkbox"].checkbox:disabled + label::before {
  background-color: #a6a6a6;
}

/*Checkmark of the fake checkbox*/
input[type="checkbox"].checkbox + label::after {
  /*Hide the checkmark by default*/
  content: none;
  position: absolute;
  left: 0;
  top: 0;
  width: 0.4em;
  height: 0.6em;
  border-right: 2px solid black;
  border-bottom: 2px solid black;
  transform: rotate(45deg) translate(0.3em, -0.2em);
  border-color: white;
  box-sizing: border-box;
  cursor: pointer;
}
/*Unhide on the checked state*/
input[type="checkbox"].checkbox:checked + label::after {
  content: "";
}