text:
package ec.gp.build;
import ec.*;
import ec.util.*;
import ec.gp.*;

/*
 * PTCFunctionSet.java
 *
 * Created: Wed Jan 26 21:10:59 2000
 * By: Sean Luke
 */

/**
 * PTCFunctionSet is a GPFunctionSet which adheres to PTCFunctionSetForm, and thus
 * can be used with the PTC1 and PTC2 methods.  Terminal and nonterminal probabilities
 * for nodes used in this function set are determined by the <tt>prob</tt> parameter
 * for the nodes' GPNodeConstraints object.  That's not the greatest solution,
 * because it could require making a lot of different GPNodeConstraints, customized for each
 * node, but it's the best I can do for now.
 *
 * The nonterminalSelectionProbabilities() method computes nonterminal selection
 * probability using the probabilities above, per type, for the size requested.
 * If the size is small enough (smaller than CACHE_SIZE), then the result is
 * memoized so it doesn't need to be computed again next time.
 *
 * @author Sean Luke
 * @version 1.0
 */

public class PTCFunctionSet extends GPFunctionSet implements PTCFunctionSetForm
    {
    /** terminal probabilities[type][thenodes], in organized form */
    public double q_ty[][];
    /** nonterminal probabilities[type][thenodes], in organized form */
    public double q_ny[][];

    public static final int CACHE_SIZE = 1024;
    /** cache of nonterminal selection probabilities -- dense array
        [size-1][type].  If any items are null, they're not in the dense cache. */
    public double p_y[][];

    public double[] terminalProbabilities(final int type)
        { return q_ty[type]; }

    public double[] nonterminalProbabilities(final int type)
        { return q_ny[type]; }

    public void setup(final EvolutionState state, final Parameter base)
        {
        super.setup(state,base);

        // load our probabilities here.

        q_ny = new double[nonterminals.length][];
        q_ty = new double[terminals.length][];

        boolean allOnes = true;
        boolean noOnes = true;
        boolean allZeros = true;
        GPInitializer initializer = ((GPInitializer)state.initializer);

        for(int type=0;type<nonterminals.length;type++)
            {
            q_ny[type] = new double[nonterminals[type].length];
            for(int x=0;x<nonterminals[type].length;x++)
                {
                q_ny[type][x] = nonterminals[type][x].constraints(initializer).probabilityOfSelection;
                if (q_ny[type][x] != 0.0f) allZeros = false;
                if (q_ny[type][x] == 1.0f) noOnes = false;
                else allOnes = false;
                }
            }

        if (allZeros)
            state.output.warning("In this function set, the probabilities of all nonterminal function have a 0.0 selection probability -- this will cause them all to be selected uniformly.  That could be an error.", base);
        allZeros = false;

        for(int type=0;type<terminals.length;type++)
            {
            q_ty[type] = new double[terminals[type].length];
            for(int x=0;x<terminals[type].length;x++)
                {
                q_ty[type][x] = terminals[type][x].constraints(initializer).probabilityOfSelection;
                if (q_ty[type][x] != 0.0f) allZeros = false;
                if (q_ty[type][x] == 1.0f) noOnes = false;
                else allOnes = false;
                }
            }

        if (allZeros)
            state.output.warning("In this function set, the probabilities of all terminal function have a 0.0 selection probability -- this will cause them all to be selected uniformly.  That could be an error.", base);

        if (!allOnes && !noOnes)
            state.output.warning("In this function set, there are some function with a selection probability of 1.0, but not all of them.  That could be an error.",base);

        // set up our node probabilities.  Allow all zeros.
        for(int x=0;x<q_ty.length;x++)
            {
            if (q_ty[x].length == 0) state.output.warning("Function Set " + name + " has no terminal for type number " + x + ".  This may cause problems for you.");
            else RandomChoice.organizeDistribution(q_ty[x], true);
            if (q_ny[x].length == 0) state.output.warning("Function Set " + name + " has no nonterminals for type number " + x + ".  This may cause problems for you.");
            else RandomChoice.organizeDistribution(q_ny[x], true);
            }

        // set up cache
        p_y = new double[CACHE_SIZE][];
        }

    public double[] nonterminalSelectionProbabilities(final int expectedTreeSize)
        {
        // check cache first
        if (expectedTreeSize<CACHE_SIZE)
            {
            if (p_y[expectedTreeSize-1]!=null) return p_y[expectedTreeSize-1];
            else return p_y[expectedTreeSize-1] =
                     computeNonterminalSelectionProbabilities(expectedTreeSize);
            }
        else
            // we'll have to compute it
            return computeNonterminalSelectionProbabilities(expectedTreeSize);
        }

    public double[] computeNonterminalSelectionProbabilities(final int expectedTreeSize)
        {
        double[] p = new double[q_ny.length];

        // for each type...
        for(int x=0;x<q_ny.length;x++)
            {
            double count=0;
            // gather branching factor * prob for each nonterminal
            for(int y=0;y<q_ny[x].length;y++)
                count += (y==0 ? q_ny[x][y] : q_ny[x][y]-q_ny[x][y-1]) // it's organized
                    * nonterminals[x][y].children.length;

            p[x] = (double)((1.0-(1.0/expectedTreeSize))/count);
            }
        return p;
        }
    }


text:
import Mailgun from 'mailgun-js';
import mailComposer from 'mailcomposer';

import logger from '../logger';
const log = logger.create('Email:Client');

function validationError(message, data) {
  log.error(`Validation: [${message}]`, data);
  return { message, reason: 'validation', data };
}

export class EmailClient {
  constructor({ apiKey, domain, from }) {
    this.mailgun = new Mailgun({ apiKey, domain });
    this.credentials = { apiKey, domain };
    this.from = from;
  }

  buildAndSend(options) {
    return this.build(options, true);
  }

  /**
   * Build a message object
   *
   * options: {
   *  from:     string (optional, will be pulled from config)
   *  to:       string
   *  subject:  string
   *  html:     string
   * }
   * Either body or html is required
   *
   * @param object  options           Message contents
   * @param boolean sendImmediately   Send the built mail right away (requires options.to)
   */
  build(options, sendImmediately = false) {
    return new Promise((resolve, reject) => {
      if (!options.from) {
        options.from = this.from;
      }

      return mailComposer(options).build((err, message) => {
        if (err) {
          throw err;
        }
        const builtMail = { to: options.to, message, built: true };
        if (sendImmediately) {
          if (!builtMail.to) {
            throw validationError('No recipient was provided', { to: options.to });
          }
          return this.send(builtMail)
            .then((body) => resolve(body))
            .catch((error) => reject(error));
        }
        return resolve(builtMail);
      });
    });
  }

  /**
   * Send an email
   * Can be called by using {@link build} or passing a custom object.
   *
   * custom = {
   *  from:     string (optional, will be pulled from config)
   *  to:       string
   *  subject:  string
   *  html:     string
   * }
   *
   * @param object mail Either built mail or custom object
   */
  send(mail = false) {
    return new Promise((resolve, reject) => {
      // Validate mail object
      if (!mail) {
        throw validationError('Mail object was not defined');
      } else if (!mail.to) {
        throw validationError('No recipient was provided', { to: mail.to });
      }

      if (!this.credentials.apiKey) {
        throw validationError('No api key was specified');
      } else if (!this.credentials.domain) {
        throw validationError('No domain was specified');
      }

      // Validate built or custom mail object
      if (!mail.built) {
        if (!mail.subject) {
          throw validationError('No subject was provided');
        } else if (!mail.html) {
          throw validationError('No message was provided');
        }
      }

      const callback = (err, body) => {
        if (err) {
          log.error('Mailgun error', err);
          return reject(err);
        }
        log.debug('Message was sent');
        return resolve(body);
      };

      // Send the email
      if (mail.built) {
        const mimeMail = Object.assign(mail, { message: mail.message.toString('ascii') });
        this.mailgun.messages().sendMime(mimeMail, callback);
      } else {
        this.mailgun.messages().send(mail, callback);
      }
    });
  }
}

export default EmailClient;

redpajama_set_name: RedPajamaGithub


text:
package org.apache.servicemix.executors;

import org.apache.servicemix.executors.impl.ExecutorConfig;

import java.util.Map;

/**
 * Factory to create Executors.
 *
 * @author Guillaume Nodet
 */
public interface ExecutorFactory {

    /*
     * Configuration properties than can be passed along when creating an executor.
     * Every ExecutorFactory implementation can support one or more of these options, ignoring the unsupported ones.
     */
    String ALLOW_CORE_THREADS_TIMEOUT = ExecutorFactory.class.getName() + ".AllowCoreThreadTimeOut";
    String BYPASS_IF_SYNCHRONOUS = ExecutorFactory.class.getName() + ".BypassIfSynchronous";
    String CORE_POOL_SIZE = ExecutorFactory.class.getName() + ".CorePoolSize";
    String KEEP_ALIVE_TIME = ExecutorFactory.class.getName() + ".KeepAliveTime";
    String MAXIMUM_POOL_SIZE = ExecutorFactory.class.getName() + ".MaximumPoolSize";
    String QUEUE_SIZE = ExecutorFactory.class.getName() + ".QueueSize";
    String SHUTDOWN_DELAY = ExecutorFactory.class.getName() + ".ShutdownDelay";
    String THREAD_DAEMON = ExecutorFactory.class.getName() + ".ThreadDaemon";
    String THREAD_PRIORITY = ExecutorFactory.class.getName() + ".ThreadPriority";

    /**
     * Create a new executor for the given Id.
     * The id may be used to provide per executor
     * configuration.
     *
     * @param id the id of the executor to create
     * @return a configured Executor
     */
    Executor createExecutor(String id);

    /**
     * Create a new executor for the given id
     * using the additional configuration options provided.
     *
     * Note that not every ExecutorFactory implementation will support all available options.  If the factory does
     * not support the option, it will get ignored.
     *
     * @param id the id of the executor to create
     * @param config the additional executor configuration options
     * @return a configured Executor
     */
    Executor createExecutor(String id, Map<String, Object> config);

    /**
     * Create a new daemon executor for the given Id.
     * The excutor should use daemon thread underlying
     * The id may be used to provide per executor
     * configuration.
     *
     * @param id the id of the executor to create
     * @return a configured Executor
     */
    Executor createDaemonExecutor(String id);

}


text:
namespace chromecast {

// Describes visual context of the window within the UI.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chromecast.shell
enum class VisibilityType {
  // Unknown visibility state.
  UNKNOWN = 0,

  // Window is occupying the entire screen and can be interacted with.
  FULL_SCREEN = 1,

  // Window occupies a portion of the screen, supporting user interaction.
  PARTIAL_OUT = 2,

  // Window is hidden after dismissal by back gesture, and cannot be interacted
  // with via touch.
  HIDDEN = 3,

  // Window is being displayed as a small visible tile.
  TILE = 4,

  // Window is covered by other activities and cannot be interacted with via
  // touch.
  TRANSIENTLY_HIDDEN = 5
};

// Represents requested activity windowing behavior. Behavior includes:
// 1. How long the activity should show
// 2. Whether the window should become immediately visible
// 3. How much screen space the window should occupy
// 4. What state to return to when the activity is completed
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chromecast.shell
enum class VisibilityPriority {
  // Default priority. It is up to system to decide how to show the activity.
  DEFAULT = 0,

  // The activity wants to occupy the full screen for some period of time and
  // then become hidden after a timeout. When timeout, it returns to the
  // previous activity.
  TRANSIENT_TIMEOUTABLE = 1,

  // A high priority interruption occupies half of the screen if a sticky
  // activity is showing on the screen. Otherwise, it occupies the full screen.
  HIGH_PRIORITY_INTERRUPTION = 2,

  // The activity takes place of other activity and won't be timeout.
  STICKY_ACTIVITY = 3,

  // The activity stays on top of others (transient) but won't be timeout.
  // When the activity finishes, it returns to the previous one.
  TRANSIENT_STICKY = 4,

  // The activity should not be visible.
  HIDDEN = 5,

  // The activity should not be visible, but the activity will consider itself
  // to be visible. This is useful for opaque overlays while the activity is
  // still active.
  HIDDEN_STICKY = 6,
};

// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chromecast.shell
enum class GestureType {
  NO_GESTURE = 0,
  GO_BACK = 1,
  TAP = 2,
  TAP_DOWN = 3,
  TOP_DRAG = 4,
  RIGHT_DRAG = 5,
};

}  // namespace chromecast

#endif  // CHROMECAST_BROWSER_VISIBILITY_TYPES_H_


text:
package orm

import (
	"context"
	"database/sql"
	"fmt"
	"io"
	"log"
	"strings"
	"time"
)

// Log implement the log.Logger
type Log struct {
	*log.Logger
}

//costomer log func
var LogFunc func(query map[string]interface{})

// NewLog set io.Writer to create a Logger.
func NewLog(out io.Writer) *Log {
	d := new(Log)
	d.Logger = log.New(out, "[ORM]", log.LstdFlags)
	return d
}

func debugLogQueies(alias *alias, operaton, query string, t time.Time, err error, args ...interface{}) {
	var logMap = make(map[string]interface{})
	sub := time.Now().Sub(t) / 1e5
	elsp := float64(int(sub)) / 10.0
	logMap["cost_time"] = elsp
	flag := "  OK"
	if err != nil {
		flag = "FAIL"
	}
	logMap["flag"] = flag
	con := fmt.Sprintf(" -[Queries/%s] - [%s / %11s / %7.1fms] - [%s]", alias.Name, flag, operaton, elsp, query)
	cons := make([]string, 0, len(args))
	for _, arg := range args {
		cons = append(cons, fmt.Sprintf("%v", arg))
	}
	if len(cons) > 0 {
		con += fmt.Sprintf(" - `%s`", strings.Join(cons, "`, `"))
	}
	if err != nil {
		con += " - " + err.Error()
	}
	logMap["sql"] = fmt.Sprintf("%s-`%s`", query, strings.Join(cons, "`, `"))
	if LogFunc != nil {
		LogFunc(logMap)
	}
	DebugLog.Println(con)
}

// statement query logger struct.
// if dev mode, use stmtQueryLog, or use stmtQuerier.
type stmtQueryLog struct {
	alias *alias
	query string
	stmt  stmtQuerier
}

var _ stmtQuerier = new(stmtQueryLog)

func (d *stmtQueryLog) Close() error {
	a := time.Now()
	err := d.stmt.Close()
	debugLogQueies(d.alias, "st.Close", d.query, a, err)
	return err
}

func (d *stmtQueryLog) Exec(args ...interface{}) (sql.Result, error) {
	a := time.Now()
	res, err := d.stmt.Exec(args...)
	debugLogQueies(d.alias, "st.Exec", d.query, a, err, args...)
	return res, err
}

func (d *stmtQueryLog) Query(args ...interface{}) (*sql.Rows, error) {
	a := time.Now()
	res, err := d.stmt.Query(args...)
	debugLogQueies(d.alias, "st.Query", d.query, a, err, args...)
	return res, err
}

func (d *stmtQueryLog) QueryRow(args ...interface{}) *sql.Row {
	a := time.Now()
	res := d.stmt.QueryRow(args...)
	debugLogQueies(d.alias, "st.QueryRow", d.query, a, nil, args...)
	return res
}

func newStmtQueryLog(alias *alias, stmt stmtQuerier, query string) stmtQuerier {
	d := new(stmtQueryLog)
	d.stmt = stmt
	d.alias = alias
	d.query = query
	return d
}

// database query logger struct.
// if dev mode, use dbQueryLog, or use dbQuerier.
type dbQueryLog struct {
	alias *alias
	db    dbQuerier
	tx    txer
	txe   txEnder
}

var _ dbQuerier = new(dbQueryLog)
var _ txer = new(dbQueryLog)
var _ txEnder = new(dbQueryLog)

func (d *dbQueryLog) Prepare(query string) (*sql.Stmt, error) {
	a := time.Now()
	stmt, err := d.db.Prepare(query)
	debugLogQueies(d.alias, "db.Prepare", query, a, err)
	return stmt, err
}

func (d *dbQueryLog) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) {
	a := time.Now()
	stmt, err := d.db.PrepareContext(ctx, query)
	debugLogQueies(d.alias, "db.Prepare", query, a, err)
	return stmt, err
}

func (d *dbQueryLog) Exec(query string, args ...interface{}) (sql.Result, error) {
	a := time.Now()
	res, err := d.db.Exec(query, args...)
	debugLogQueies(d.alias, "db.Exec", query, a, err, args...)
	return res, err
}

func (d *dbQueryLog) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
	a := time.Now()
	res, err := d.db.ExecContext(ctx, query, args...)
	debugLogQueies(d.alias, "db.Exec", query, a, err, args...)
	return res, err
}

func (d *dbQueryLog) Query(query string, args ...interface{}) (*sql.Rows, error) {
	a := time.Now()
	res, err := d.db.Query(query, args...)
	debugLogQueies(d.alias, "db.Query", query, a, err, args...)
	return res, err
}

func (d *dbQueryLog) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
	a := time.Now()
	res, err := d.db.QueryContext(ctx, query, args...)
	debugLogQueies(d.alias, "db.Query", query, a, err, args...)
	return res, err
}

func (d *dbQueryLog) QueryRow(query string, args ...interface{}) *sql.Row {
	a := time.Now()
	res := d.db.QueryRow(query, args...)
	debugLogQueies(d.alias, "db.QueryRow", query, a, nil, args...)
	return res
}

func (d *dbQueryLog) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
	a := time.Now()
	res := d.db.QueryRowContext(ctx, query, args...)
	debugLogQueies(d.alias, "db.QueryRow", query, a, nil, args...)
	return res
}

func (d *dbQueryLog) Begin() (*sql.Tx, error) {
	a := time.Now()
	tx, err := d.db.(txer).Begin()
	debugLogQueies(d.alias, "db.Begin", "START TRANSACTION", a, err)
	return tx, err
}

func (d *dbQueryLog) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) {
	a := time.Now()
	tx, err := d.db.(txer).BeginTx(ctx, opts)
	debugLogQueies(d.alias, "db.BeginTx", "START TRANSACTION", a, err)
	return tx, err
}

func (d *dbQueryLog) Commit() error {
	a := time.Now()
	err := d.db.(txEnder).Commit()
	debugLogQueies(d.alias, "tx.Commit", "COMMIT", a, err)
	return err
}

func (d *dbQueryLog) Rollback() error {
	a := time.Now()
	err := d.db.(txEnder).Rollback()
	debugLogQueies(d.alias, "tx.Rollback", "ROLLBACK", a, err)
	return err
}

func (d *dbQueryLog) SetDB(db dbQuerier) {
	d.db = db
}

func newDbQueryLog(alias *alias, db dbQuerier) dbQuerier {
	d := new(dbQueryLog)
	d.alias = alias
	d.db = db
	return d
}


text:
/* global require, describe, it */
'use strict';

// MODULES //

var chai = require( 'chai' ),
	DTYPES = require( './../lib/dtypes.js' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'dtypes', function tests() {

	it( 'should export an array', function test() {
		expect( DTYPES ).to.be.an( 'array' );
	});

});


text:
'
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2012
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
'

Imports DotNetNuke.Services.Exceptions
Imports System.Text
Imports DotNetNuke.Entities.Portals
Imports DotNetNuke.Entities.Modules
Imports DotNetNuke.Modules.News.Entities.Feeds

Namespace Services.Retrieval
 Public Class BackgroundLoader
  Inherits DotNetNuke.Services.Scheduling.SchedulerClient

  Private Log As New StringBuilder

  Public Sub New(ByVal objScheduleHistoryItem As DotNetNuke.Services.Scheduling.ScheduleHistoryItem)
   MyBase.new()
   Me.ScheduleHistoryItem = objScheduleHistoryItem
  End Sub

  Public Overrides Sub DoWork()

   Try

    Me.Progressing() ' Start

    For Each portal As PortalInfo In (New PortalController).GetPortals
     Log.AppendLine(String.Format("Checking Portal '{0}' (ID: {1})", portal.PortalName, portal.PortalID))
     Using ir As IDataReader = Data.DataProvider.Instance.GetUpdatableModules(portal.PortalID)
      Do While ir.Read
       Dim ModuleId As Integer = CInt(ir.Item("ModuleId"))
       Dim TabId As Integer = CInt(ir.Item("TabId"))
       Dim m As ModuleInfo = (New ModuleController).GetModule(ModuleId, TabId, False)
       Dim ModuleTitle As String = m.ModuleTitle
       Dim RetryTimes As Integer = CInt(ir.Item("RetryTimes"))
       Dim RetryTimeOut As Integer = CInt(ir.Item("RetryTimeOut"))
       If FeedController.HasExpiredFeeds(ModuleId, RetryTimes, RetryTimeOut) Then
        Log.Append(String.Format("Refreshing Module '{0}' (ID: {1})", ModuleTitle, ModuleId))
        If Not IO.Directory.Exists(portal.HomeDirectoryMapPath & "\Cache\") Then
         IO.Directory.CreateDirectory(portal.HomeDirectoryMapPath & "\Cache\")
        End If
        Dim settings As ModuleSettings = ModuleSettings.GetSettings(m)
        Dim aggregator As New FeedAggregator(portal.HomeDirectoryMapPath & "\Cache\", settings, ModuleTitle)
        aggregator.Load(FeedController.GetFeedsByModule(ModuleId))
        Common.SaveResultFeed(aggregator.ToXml, ModuleId, portal.HomeDirectoryMapPath & "\Cache\")
        Log.AppendLine(" - Success")
       End If
      Loop
     End Using
    Next

    Me.ScheduleHistoryItem.AddLogNote(Log.ToString.Replace(vbCrLf, "<br />"))
    Me.ScheduleHistoryItem.Succeeded = True

   Catch ex As Exception
    Me.ScheduleHistoryItem.AddLogNote(Log.ToString & vbCrLf & "Failure: " & ex.Message & "(" & ex.StackTrace & ")" & vbCrLf & Log.ToString)
    Me.ScheduleHistoryItem.Succeeded = False
    Me.Errored(ex)
    LogException(ex)
   End Try

  End Sub
 End Class
End Namespace


text:
package net.sf.jlinkgrammar;

/**
 * TODO add javadoc
 *
 */
public class StartingLinkAndDomain {
    String  starting_link;
    int   domain;       /* domain which the link belongs to (-1: terminator)*/

}


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

namespace GameClub
{
    class Boletin
    {
        uint idBoletin;
        string texto;
        uint imagen;    //numeradas
        DateTime fecha;     //aaaammdd
    }
}


text:
package org.apache.http.impl.nio.reactor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadFactory;

import org.apache.http.annotation.ThreadSafe;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
import org.apache.http.params.HttpParams;
import org.apache.http.util.Asserts;

/**
 * Default implementation of {@link ConnectingIOReactor}. This class extends
 * {@link AbstractMultiworkerIOReactor} with capability to connect to remote
 * hosts.
 *
 * @since 4.0
 */
@SuppressWarnings("deprecation")
@ThreadSafe // public methods only
public class DefaultConnectingIOReactor extends AbstractMultiworkerIOReactor
        implements ConnectingIOReactor {

    private final Queue<SessionRequestImpl> requestQueue;

    private long lastTimeoutCheck;

    /**
     * Creates an instance of DefaultConnectingIOReactor with the given configuration.
     *
     * @param config I/O reactor configuration.
     * @param threadFactory the factory to create threads.
     *   Can be null.
     * @throws IOReactorException in case if a non-recoverable I/O error.
     *
     * @since 4.2
     */
    public DefaultConnectingIOReactor(
            final IOReactorConfig config,
            final ThreadFactory threadFactory) throws IOReactorException {
        super(config, threadFactory);
        this.requestQueue = new ConcurrentLinkedQueue<SessionRequestImpl>();
        this.lastTimeoutCheck = System.currentTimeMillis();
    }

    /**
     * Creates an instance of DefaultConnectingIOReactor with the given configuration.
     *
     * @param config I/O reactor configuration.
     *   Can be null.
     * @throws IOReactorException in case if a non-recoverable I/O error.
     *
     * @since 4.2
     */
    public DefaultConnectingIOReactor(final IOReactorConfig config) throws IOReactorException {
        this(config, null);
    }

    /**
     * Creates an instance of DefaultConnectingIOReactor with default configuration.
     *
     * @throws IOReactorException in case if a non-recoverable I/O error.
     *
     * @since 4.2
     */
    public DefaultConnectingIOReactor() throws IOReactorException {
        this(null, null);
    }

    /**
     * @deprecated (4.2) use {@link DefaultConnectingIOReactor#DefaultConnectingIOReactor(IOReactorConfig, ThreadFactory)}
     */
    @Deprecated
    public DefaultConnectingIOReactor(
            final int workerCount,
            final ThreadFactory threadFactory,
            final HttpParams params) throws IOReactorException {
        this(convert(workerCount, params), threadFactory);
    }

    /**
     * @deprecated (4.2) use {@link DefaultConnectingIOReactor#DefaultConnectingIOReactor(IOReactorConfig)}
     */
    @Deprecated
    public DefaultConnectingIOReactor(
            final int workerCount,
            final HttpParams params) throws IOReactorException {
        this(convert(workerCount, params), null);
    }

    @Override
    protected void cancelRequests() throws IOReactorException {
        SessionRequestImpl request;
        while ((request = this.requestQueue.poll()) != null) {
            request.cancel();
        }
    }

    @Override
    protected void processEvents(final int readyCount) throws IOReactorException {
        processSessionRequests();

        if (readyCount > 0) {
            final Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
            for (final SelectionKey key : selectedKeys) {

                processEvent(key);

            }
            selectedKeys.clear();
        }

        final long currentTime = System.currentTimeMillis();
        if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) {
            this.lastTimeoutCheck = currentTime;
            final Set<SelectionKey> keys = this.selector.keys();
            processTimeouts(keys);
        }
    }

    private void processEvent(final SelectionKey key) {
        try {

            if (key.isConnectable()) {

                final SocketChannel channel = (SocketChannel) key.channel();
                // Get request handle
                final SessionRequestHandle requestHandle = (SessionRequestHandle) key.attachment();
                final SessionRequestImpl sessionRequest = requestHandle.getSessionRequest();

                // Finish connection process
                try {
                    channel.finishConnect();
                } catch (final IOException ex) {
                    sessionRequest.failed(ex);
                }
                key.cancel();
                key.attach(null);
                if (!sessionRequest.isCompleted()) {
                    addChannel(new ChannelEntry(channel, sessionRequest));
                } else {
                    try {
                        channel.close();
                    } catch (IOException ignore) {
                    }
                }
            }

        } catch (final CancelledKeyException ex) {
            final SessionRequestHandle requestHandle = (SessionRequestHandle) key.attachment();
            key.attach(null);
            if (requestHandle != null) {
                final SessionRequestImpl sessionRequest = requestHandle.getSessionRequest();
                if (sessionRequest != null) {
                    sessionRequest.cancel();
                }
            }
        }
    }

    private void processTimeouts(final Set<SelectionKey> keys) {
        final long now = System.currentTimeMillis();
        for (final SelectionKey key : keys) {
            final Object attachment = key.attachment();

            if (attachment instanceof SessionRequestHandle) {
                final SessionRequestHandle handle = (SessionRequestHandle) key.attachment();
                final SessionRequestImpl sessionRequest = handle.getSessionRequest();
                final int timeout = sessionRequest.getConnectTimeout();
                if (timeout > 0) {
                    if (handle.getRequestTime() + timeout < now) {
                        sessionRequest.timeout();
                    }
                }
            }

        }
    }

    public SessionRequest connect(
            final SocketAddress remoteAddress,
            final SocketAddress localAddress,
            final Object attachment,
            final SessionRequestCallback callback) {
        Asserts.check(this.status.compareTo(IOReactorStatus.ACTIVE) <= 0,
            "I/O reactor has been shut down");
        final SessionRequestImpl sessionRequest = new SessionRequestImpl(
                remoteAddress, localAddress, attachment, callback);
        sessionRequest.setConnectTimeout(this.config.getConnectTimeout());

        this.requestQueue.add(sessionRequest);
        this.selector.wakeup();

        return sessionRequest;
    }

    private void validateAddress(final SocketAddress address) throws UnknownHostException {
        if (address == null) {
            return;
        }
        if (address instanceof InetSocketAddress) {
            final InetSocketAddress endpoint = (InetSocketAddress) address;
            if (endpoint.isUnresolved()) {
                throw new UnknownHostException(endpoint.getHostName());
            }
        }
    }

    private void processSessionRequests() throws IOReactorException {
        SessionRequestImpl request;
        while ((request = this.requestQueue.poll()) != null) {
            if (request.isCompleted()) {
                continue;
            }
            final SocketChannel socketChannel;
            try {
                socketChannel = SocketChannel.open();
            } catch (final IOException ex) {
                throw new IOReactorException("Failure opening socket", ex);
            }
            try {
                socketChannel.configureBlocking(false);
                validateAddress(request.getLocalAddress());
                validateAddress(request.getRemoteAddress());

                if (request.getLocalAddress() != null) {
                    final Socket sock = socketChannel.socket();
                    sock.setReuseAddress(this.config.isSoReuseAddress());
                    sock.bind(request.getLocalAddress());
                }
                prepareSocket(socketChannel.socket());
                final boolean connected = socketChannel.connect(request.getRemoteAddress());
                if (connected) {
                    final ChannelEntry entry = new ChannelEntry(socketChannel, request);
                    addChannel(entry);
                    continue;
                }
            } catch (final IOException ex) {
                closeChannel(socketChannel);
                request.failed(ex);
                return;
            }

            final SessionRequestHandle requestHandle = new SessionRequestHandle(request);
            try {
                final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT,
                        requestHandle);
                request.setKey(key);
            } catch (final IOException ex) {
                closeChannel(socketChannel);
                throw new IOReactorException("Failure registering channel " +
                        "with the selector", ex);
            }
        }
    }

}


text:
ng2-materialize

    This library is an Angular 2+ wrap around Materialize library, a responsive CSS/JS framework that implements Material Design specifications from Google.

    The purpose of this library is to simplify the usage within the Angular framework.

    Demo and documentation : https://sherweb.github.io/ng2-materialize/

## Why ng2-materialize?

We are aware that alternatives exposing Material Design components already exist. But, in our case, we want to rely on a stable css framework that does not depend on a specific js framework.

We already know the possibilities Materialize offers. What is left to do is to wrap components that we want to use in Angular component.

If you want to use a component that is not yet implemented, simply wrap the existing Materialize components that already meets the Material Design specifications. No need to be an HTML/CSS expert, only to know the Angular 2+ components. Or if you are in a hurry, you can use it directly in HTML rather than in Angular component.

## Installation

The following commands will add Ng2-Materialize library to your `package.json` file along with it dependencies: Materialize CSS, jQuery and Mdi (Mdi icons library is optional as your are free to use the icon library of your choice).

```
npm install --save ng2-materialize
npm install --save mdi    #optional
```

Don't forget to include jQuery, Materialize, and Mdi in your application.

If you are using [Angular-CLI](https://github.com/angular/angular-cli) you can follow the example below :

#### .angular-cli.json

```diff
"styles": [
  "styles.scss",
+ "../node_modules/materialize-css/dist/css/materialize.min.css",
+ "../node_modules/mdi/css/materialdesignicons.min.css"   #optional
],
"scripts": [
+ "../node_modules/jquery/dist/jquery.min.js",
+ "../node_modules/materialize-css/dist/js/materialize.min.js"
],
```

#### tsconfig

```diff
{
  "compilerOptions": {
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2016",
      "dom"
    ],
    "outDir": "../out-tsc/app",
    "target": "es5",
    "module": "es2015",
    "baseUrl": "",
    "types": [
+      "jquery",
+      "materialize-css"
    ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
```

See also [Angular CLI 3rd Party Library Installation](https://github.com/angular/angular-cli/wiki/overview#global-library-installation) and [Using MaterializeCSS with your Angular 2 Angular CLI App](https://medium.com/@ladyleet/using-materializecss-with-your-angular-2-angular-cli-app-2eb64b05a1d2#.8p3uba85g).

## Animation
Some components are using advance animation transition. You need to install `@angular/animations` and include `BrowserAnimationsModule` if you want those animation to work.

```
npm install --save @angular/animations
```
```diff
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
+ import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { AppModule } from './app.module';

@NgModule({
  imports: [
+    BrowserAnimationsModule,
  ],
})
export class AppModule { }
```

If you don't want to install a new dependency in your application, you can include `NoopAnimationsModule`.
```diff
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
+ import { NoopAnimationsModule } from '@angular/platform-browser/animations';

import { AppModule } from './app.module';

@NgModule({
  imports: [
+    NoopAnimationsModule,
  ],
})
export class AppModule { }
```

## Usage

You must import `MaterializeModule` inside your module to be able to use Materialize components.

```diff
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
+ import { MaterializeModule } from 'ng2-materialize';

import { HomeComponent } from './home.component';

@NgModule({
  imports: [
    CommonModule,
+    MaterializeModule.forRoot(),
  ],
  declarations: [ HomeComponent ],
})
export class HomeModule { }
```

## Available features

 Page listed in [Native CCS Class](./native-css-class) will not be wrapped.

### Components

* Badge
* Button
* Card
* Checkbox
* Collapsible
* Collection
* Datepicker
* Dropdown
* Form validation
* Icon
* Input
* Modal
* Navbar
* Parallax
* Progress
* Radio-Button
* Select
* Sidenav
* Spinner
* Switch
* Tab
* Textarea
* Timepicker
* Toast
* Tooltip

### Services

* Media

## Demo application

A demo application is available at [https://sherweb.github.io/ng2-materialize/](https://sherweb.github.io/ng2-materialize/), or refer to the `./demo-app` folder and its [README](./demo-app/README.md).

## Road map

We (at SherWeb) are currently wrapping the components as we need them, and unfortunately, we cannot provide a specific road map.

If some components are missing, feel free to contribute.

## Contribute

Contributions are always welcome.

Make sure that :
- Your code style matches with the rest of the project
- Unit tests pass
- Linter passes

And you are ready to go!

## Credits

Thanks to [Ali Mohammadi](https://github.com/ayalma) for donating the npm package name.


text:
package syp.dao.impl;

import java.sql.Date;
import java.util.Calendar;

public class User {
	private int id;
	private String loginName;
	private String screenName;
	private String password;
	private String email;
	private String formSourceId;
	private String passwordNonce;
	private Date PasswordNonceCreatedOn;

	public String getLoginName() {
		return loginName;
	}
	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}
	public String getScreenName() {
		return screenName;
	}
	public void setScreenName(String screenName) {
		this.screenName = screenName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getFormSourceId() {
		return formSourceId;
	}
	public void setFormSourceId(String formSourceId) {
		this.formSourceId = formSourceId;
	}
	public String getPasswordNonce() {
		return passwordNonce;
	}
	public void setPasswordNonce(String passwordNonce) {
		this.passwordNonce = passwordNonce;
	}
	public Date getPasswordNonceCreatedOn() {
		return PasswordNonceCreatedOn;
	}
	public void setPasswordNonceCreatedOn(Date passwordNonceCreatedOn) {
		PasswordNonceCreatedOn = passwordNonceCreatedOn;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
}


text:
package receiver

import (
	"github.com/stretchr/testify/assert"
	"io"
	"io/ioutil"
	"net/rpc"
	"path"
	"testing"
	//"log"
	"fmt"
	"os"
)

type pipePair struct {
	reader *io.PipeReader
	writer *io.PipeWriter
	io.WriteCloser
}

func (this *pipePair) Read(p []byte) (int, error) {
	return this.reader.Read(p)
}

func (this *pipePair) Write(p []byte) (int, error) {
	return this.writer.Write(p)
}

func (this *pipePair) Close() error {
	this.writer.Close()
	return this.reader.Close()
}

type context struct {
	assert     *assert.Assertions
	in         pipePair
	out        pipePair
	client     *rpc.Client
	baseFolder string
}

func (this *context) createBaseFolder() {
	var err error
	this.baseFolder, err = ioutil.TempDir("", "test_")
	this.assert.NoError(err)
}

func (this *context) createServer() {
	rpc.DefaultServer = rpc.NewServer()
	this.in.reader, this.out.writer = io.Pipe()
	this.out.reader, this.in.writer = io.Pipe()
	go RunSynchronizerService(&this.out)
	this.client = rpc.NewClient(&this.in)
}

func (this *context) startFile(name string) (pathname string, token string) {
	pathname = path.Join(this.baseFolder, name)
	err := this.client.Call("Synchronizer.StartFile", pathname, &token)
	this.assert.NoError(err)
	return
}

func (this *context) nextSignature(token string) Signature {
	var signature Signature
	err := this.client.Call(fmt.Sprint(token, ".NextSignature"), 0, &signature)
	this.assert.NoError(err)
	return signature
}

func (this *context) startStream(token string) string {
	var stream string
	err := this.client.Call(fmt.Sprint(token, ".StartStream"), 0, &stream)
	this.assert.NoError(err)
	return stream
}

func (this *context) writeStream(token string, data []byte) {
	var n int
	err := this.client.Call(fmt.Sprint(token, ".Write"), data, &n)
	this.assert.NoError(err)
	this.assert.Equal(len(data), n)
}

func (this *context) closeStream(token string) {
	err := this.client.Call(fmt.Sprint(token, ".Close"), 0, nil)
	this.assert.NoError(err)
}

func TestSynchronizerStartFile(t *testing.T) {
	assert := assert.New(t)
	ctx := context{assert: assert}
	ctx.createBaseFolder()
	ctx.createServer()
	defer ctx.client.Close()
	pathname, token := ctx.startFile("test")
	_, err := os.Stat(pathname)
	assert.False(os.IsNotExist(err))
	assert.NotEqual(0, len(token))
}

func TestSynchronizerFileNextSignature(t *testing.T) {
	assert := assert.New(t)
	ctx := context{assert: assert}
	ctx.createBaseFolder()

	sigPath := path.Join(ctx.baseFolder, "test", "ffffeeee")
	err := os.MkdirAll(sigPath, os.ModeDir|os.ModePerm)
	assert.NoError(err)
	err = ioutil.WriteFile(path.Join(sigPath, "6a900ff954cc07f2ea7b0fa2b862c480"), []byte("123"), os.ModePerm)
	assert.NoError(err)

	ctx.createServer()
	defer ctx.client.Close()
	_, token := ctx.startFile("test")
	signature := ctx.nextSignature(token)
	assert.Equal("ffffeeee", signature.Rolling)
	assert.Equal("6a900ff954cc07f2ea7b0fa2b862c480", signature.Strong)
	ctx.client.Close()
}

func TestSynchronizerFileStartStream(t *testing.T) {
	assert := assert.New(t)
	ctx := context{assert: assert}
	ctx.createBaseFolder()
	ctx.createServer()
	defer ctx.client.Close()
	pathname, token := ctx.startFile("test")
	stream := ctx.startStream(token)
	_, err := os.Stat(path.Join(pathname, "stream"))
	assert.False(os.IsNotExist(err))
	assert.NotEqual(0, len(stream))
}

func TestSynchronizerWriteStream(t *testing.T) {
	assert := assert.New(t)
	ctx := context{assert: assert}
	ctx.createBaseFolder()
	ctx.createServer()
	defer ctx.client.Close()
	pathname, token := ctx.startFile("test")
	stream := ctx.startStream(token)
	ctx.writeStream(stream, []byte("123456"))
	ctx.closeStream(stream)
	data, err := ioutil.ReadFile(path.Join(pathname, "stream"))
	assert.NoError(err)
	assert.Equal([]byte("123456"), data)
}


text:
Radno Mesto

           Šifra
           Naziv

          {{article.sifraRadnogMesta}}
          {{article.nazivRadnogMesta}}

    <button class="btn btn-default" ng-click="add()">Dodaj</button>
       <button class="btn btn-default" ng-click="delete()">Obriši</button>
        <button class="btn btn-default" ng-click="update()">Izmeni</button>
        <button class="btn btn-default" ng-click="selektuj()">Selektuj</button>


text:
//
//  DYIndicatorView.h
//  LoveMovie
//
//  Created by xudingyang on 16/5/15.
//  Copyright © 2016年 许定阳. All rights reserved.
//

#import <UIKit/UIKit.h>

@protocol DyIndicatorViewDelegate <NSObject>

@optional
/** 点击了标题为title的按钮 */
- (void)indicatorViewDidSelectedButtonTitle:(NSString *)title;

@end

@interface DYIndicatorView : UIView

/** title数组 */
@property (strong, nonatomic) NSArray *titles;

/** delegate */
@property (weak, nonatomic) id<DyIndicatorViewDelegate> delegate;

+ (instancetype)indicatorView;

@end


text:
class Admin::UserPolicy < Admin::ApplicationPolicy
  def index?
    true
  end

  def show?
    true
  end

  class Scope < Admin::ApplicationPolicy::Scope
  end
end


text:
<?php
class Compra extends ActiveRecord{

}
 ?>


text:
package com.cpacm.moemusic.moe_music1s.ui.login;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.cpacm.moemusic.moe_music1s.ui.web.BaseWebActivity;

/**
 * Created by DIY on 2016/11/19.
 * @desciption: 浏览器界面
 */

public class RegisterActivity extends BaseWebActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startUrl();
    }
}


text:
package dataContracts.files;

public enum FileType
{
    Unspecified,
    Dna,
    Text
}


text:
package ch.rasc.bsoncodec.test.pojo;

import java.time.Year;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.bson.types.ObjectId;

import ch.rasc.bsoncodec.annotation.BsonDocument;

@BsonDocument
public class YearPojo {

	private ObjectId id;

	private Year scalar;
	private Year[] array;
	private Year[][] array2;
	private List<Year> list;
	private Set<Year> set;
	private Map<String, Year> map;

	public ObjectId getId() {
		return this.id;
	}

	public void setId(ObjectId id) {
		this.id = id;
	}

	public Year getScalar() {
		return this.scalar;
	}

	public void setScalar(Year scalar) {
		this.scalar = scalar;
	}

	public Year[] getArray() {
		return this.array;
	}

	public void setArray(Year[] array) {
		this.array = array;
	}

	public Year[][] getArray2() {
		return this.array2;
	}

	public void setArray2(Year[][] array2) {
		this.array2 = array2;
	}

	public List<Year> getList() {
		return this.list;
	}

	public void setList(List<Year> list) {
		this.list = list;
	}

	public Set<Year> getSet() {
		return this.set;
	}

	public void setSet(Set<Year> set) {
		this.set = set;
	}

	public Map<String, Year> getMap() {
		return this.map;
	}

	public void setMap(Map<String, Year> map) {
		this.map = map;
	}

}


text:
@interface PXView : UIView

@property UIButton* button1;
@property UIButton* button2;
@property UIButton* button3;

@end


text:
function jarList = getOmeroJars()
% GETOMEROJARS List the JAR files required for the OMERO.matlab toolbox
%
%   jarList = getOmeroJars() return a cell array containing the paths to
%   the JAR files necessary to use all the functionalities of the
%   OMERO.matlab toolbox.
%
% See also: LOADOMERO, UNLOADOMERO

% Copyright (C) 2014 University of Dundee & Open Microscopy Environment.
% All rights reserved.
%
% 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.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License along
% with this program; if not, write to the Free Software Foundation, Inc.,
% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
%   Detailed explanation goes here

% Retrieve path to the toolbox libraries
libpath = fullfile(findOmero(), 'libs');

% Create a cell array with the dependency jars
guava_jar = fullfile(libpath, 'guava.jar');
jarList = {guava_jar};

% For recent versions of MATLAB, some JAR dependencies are  shipped with
% the external Java libraries:
% * log4j.jar is under $matlabroot/java/jarext,
% * sl4j-api.jar and sl4j-log4j12.jar are under
%   $matlabroot/java/jarext/jxbrowser.
javaPath = javaclasspath('-all');
has_log4j = any(~cellfun(@isempty, regexp(javaPath, '.*log4j.jar$',...
    'match', 'once')));
has_slf4j = any(~cellfun(@isempty, regexp(javaPath, '.*slf4j-api.jar$',...
    'match', 'once')));

% Include log4j dependency if not present in MATLAB java classpath
if ~has_log4j
    log4j_jar = fullfile(libpath, 'log4j.jar');
    jarList = horzcat(jarList, {log4j_jar});
end

% Include slf4j dependencies if not present in MATLAB java classpath
if ~has_slf4j
    slf4j_api_jar = fullfile(libpath, 'slf4j-api.jar');
    slf4j_log4j12_jar = fullfile(libpath, 'slf4j-log4j12.jar');
    jarList = horzcat(jarList, {slf4j_api_jar, slf4j_log4j12_jar});
end

% Finally add omero_client.jar
omero_client_jar = fullfile(libpath, 'omero_client.jar');
jarList = horzcat(jarList, {omero_client_jar});

end


text:
using System;

namespace OrigoDB.Core
{
    public class LocalEngineClient<TModel> : IEngine<TModel> where TModel : Model
    {

        public readonly Engine<TModel> Engine;

        public LocalEngineClient(Engine<TModel> engine)
        {
            Engine = engine;
        }

        public TResult Execute<TResult>(Query<TModel, TResult> query)
        {
            return Engine.Execute(query);
        }

        public void Execute(Command<TModel> command)
        {
            Engine.Execute(command);
        }

        public TResult Execute<TResult>(Command<TModel, TResult> command)
        {
            return Engine.Execute(command);
        }

        public object Execute(Command command)
        {
            return Engine.Execute(command);
        }

        public object Execute(Query query)
        {
            return Engine.Execute(query);
        }

        public TResult Execute<TResult>(Func<TModel, TResult> query)
        {
            return Engine.Execute(query);
        }
    }
}


text:
from django.conf.urls.defaults import *
from django.contrib.comments.feeds import LatestCommentFeed

feeds = {
     'comments': LatestCommentFeed,
}

urlpatterns = patterns('regressiontests.comment_tests.custom_comments.views',
    url(r'^post/$',          'custom_submit_comment'),
    url(r'^flag/(\d+)/$',    'custom_flag_comment'),
    url(r'^delete/(\d+)/$',  'custom_delete_comment'),
    url(r'^approve/(\d+)/$', 'custom_approve_comment'),
)

urlpatterns += patterns('',
    (r'^rss/legacy/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}),
    (r'^rss/comments/$', LatestCommentFeed()),
)


text:
(function () {
    'use strict';

    angular.module('gg.directives', []);
})();


text:
/*!
 * \file   atomic/atomic_flag.hpp
 *
 * This header contains definition of \c atomic_flag.
 */

#ifndef BOOST_ATOMIC_ATOMIC_FLAG_HPP_INCLUDED_
#define BOOST_ATOMIC_ATOMIC_FLAG_HPP_INCLUDED_

#include <boost_1_56_0/atomic/capabilities.hpp>
#include <boost_1_56_0/atomic/detail/operations.hpp>
#include <boost_1_56_0/atomic/detail/atomic_flag.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost_1_56_0 {

using atomics::atomic_flag;

} // namespace boost_1_56_0

#endif // BOOST_ATOMIC_ATOMIC_FLAG_HPP_INCLUDED_


text:
* Compatable with Ghost V2 +
* Improved site performance via lighthouse audit

# v2.0.0
* Compatable with Ghost V1 +


text:
#ifndef CAFFE2_CORE_WORKSPACE_H_
#define CAFFE2_CORE_WORKSPACE_H_

#include "caffe2/core/common.h"

#ifndef CAFFE2_MOBILE
#error "mobile build state not defined"
#endif

#include <climits>
#include <cstddef>
#include <mutex>
#include <typeinfo>
#include <vector>

#include "caffe2/core/blob.h"
#include "caffe2/core/registry.h"
#include "caffe2/core/net.h"
#include "caffe2/proto/caffe2.pb.h"
#include "caffe2/utils/signal_handler.h"
#if CAFFE2_MOBILE
#include "caffe2/utils/threadpool/ThreadPool.h"
#endif // CAFFE2_MOBILE

CAFFE2_DECLARE_bool(caffe2_print_blob_sizes_at_exit);

namespace caffe2 {

class NetBase;
struct CompiledExecutionStep;

struct StopOnSignal {
  StopOnSignal()
      : handler_(std::make_shared<SignalHandler>(
            SignalHandler::Action::STOP,
            SignalHandler::Action::STOP)) {}

  StopOnSignal(const StopOnSignal& other) : handler_(other.handler_) {}

  bool operator()(int iter) {
    return handler_->CheckForSignals() != SignalHandler::Action::STOP;
  }

  std::shared_ptr<SignalHandler> handler_;
};

/**
 * Workspace is a class that holds all the related objects created during
 * runtime: (1) all blobs, and (2) all instantiated networks. It is the owner of
 * all these objects and deals with the scaffolding logistics.
 */
class Workspace {
 public:
  typedef std::function<bool(int)> ShouldContinue;
  typedef CaffeMap<string, unique_ptr<Blob> > BlobMap;
  typedef CaffeMap<string, unique_ptr<NetBase> > NetMap;
  /**
   * Initializes an empty workspace.
   */
  Workspace() {
  }
  /**
   * Initializes an empty workspace with the given root folder.
   *
   * For any operators that are going to interface with the file system, such
   * as load operators, they will write things under this root folder given
   * by the workspace.
   */
  explicit Workspace(const string& root_folder)
      : root_folder_(root_folder) {}
  /**
   * Initializes a workspace with a shared workspace.
   *
   * When we access a Blob, we will first try to access the blob that exists
   * in the local workspace, and if not, access the blob that exists in the
   * shared workspace. The caller keeps the ownership of the shared workspace
   * and is responsible for making sure that its lifetime is longer than the
   * created workspace.
   */
  explicit Workspace(Workspace* const shared)
      : shared_(shared) {}
  /**
   * Initializes a workspace with a root folder and a shared workspace.
   */
  Workspace(const string& root_folder, Workspace* shared)
      : root_folder_(root_folder), shared_(shared) {}
  ~Workspace() {
    if (FLAGS_caffe2_print_blob_sizes_at_exit) {
      PrintBlobSizes();
    }
  }

  /**
   * Allows to add a parent workspace post factum after the object
   * was already constructed.
   */
  void SetParentWorkspace(Workspace* shared) {
    shared_ = shared;
  }

  /**
   * Return list of blobs owned by this Workspace, not including blobs
   * shared from parent workspace.
   */
  vector<string> LocalBlobs() const;

  /**
   * Return a list of blob names. This may be a bit slow since it will involve
   * creation of multiple temp variables. For best performance, simply use
   * HasBlob() and GetBlob().
   */
  vector<string> Blobs() const;

  /**
   * Return the root folder of the workspace.
   */
  const string& RootFolder() { return root_folder_; }
  /**
   * Checks if a blob with the given name is present in the current workspace.
   */
  inline bool HasBlob(const string& name) const {
    return (blob_map_.count(name) || (shared_ && shared_->HasBlob(name)));
  }

  void PrintBlobSizes();

  /**
   * Creates a blob of the given name. The pointer to the blob is returned, but
   * the workspace keeps ownership of the pointer. If a blob of the given name
   * already exists, the creation is skipped and the existing blob is returned.
   */
  Blob* CreateBlob(const string& name);
  /**
   * Remove the blob of the given name. Return true if removed and false if
   * not exist.
   * Will NOT remove from the shared workspace.
   */
  bool RemoveBlob(const string& name);
  /**
   * Gets the blob with the given name as a const pointer. If the blob does not
   * exist, a nullptr is returned.
   */
  const Blob* GetBlob(const string& name) const;
  /**
   * Gets the blob with the given name as a mutable pointer. If the blob does
   * not exist, a nullptr is returned.
   */
  Blob* GetBlob(const string& name);

  /**
   * Creates a network with the given NetDef, and returns the pointer to the
   * network. If there is anything wrong during the creation of the network, a
   * nullptr is returned. The Workspace keeps ownership of the pointer.
   *
   * If there is already a net created in the workspace with the given name,
   * CreateNet will overwrite it if overwrite=true is specified. Otherwise, an
   * exception is thrown.
   */
  NetBase* CreateNet(const NetDef& net_def, bool overwrite = false);

  /**
   * Gets the pointer to a created net. The workspace keeps ownership of the
   * network.
   */
  NetBase* GetNet(const string& net_name);
  /**
   * Deletes the instantiated network with the given name.
   */
  void DeleteNet(const string& net_name);
  /**
   * Finds and runs the instantiated network with the given name. If the network
   * does not exist or there are errors running the network, the function
   * returns false.
   */
  bool RunNet(const string& net_name);

  /**
   * Returns a list of names of the currently instantiated networks.
   */
  vector<string> Nets() const {
    vector<string> names;
    for (auto& entry : net_map_) {
      names.push_back(entry.first);
    }
    return names;
  }

  /**
   * Runs a plan that has multiple nets and execution steps.
   */
  bool RunPlan(const PlanDef& plan_def,
               ShouldContinue should_continue = StopOnSignal{});

#if CAFFE2_MOBILE
  /*
   * Returns a CPU threadpool instace for parallel execution of
   * work. The threadpool is created lazily; if no operators use it,
   * then no threadpool will be created.
   */
  ThreadPool* GetThreadPool();
#endif

  // RunOperatorOnce and RunNetOnce runs an operator or net once. The difference
  // between RunNet and RunNetOnce lies in the fact that RunNet allows you to
  // have a persistent net object, while RunNetOnce creates a net and discards
  // it on the fly - this may make things like database read and random number
  // generators repeat the same thing over multiple calls.
  bool RunOperatorOnce(const OperatorDef& op_def);
  bool RunNetOnce(const NetDef& net_def);

 protected:
  bool ExecuteStepRecursive(CompiledExecutionStep& execution);

 private:
  BlobMap blob_map_;
  NetMap net_map_;
  string root_folder_ = ".";
  Workspace* shared_ = nullptr;
#if CAFFE2_MOBILE
  std::unique_ptr<ThreadPool> thread_pool_;
  std::mutex thread_pool_creation_mutex_;
#endif // CAFFE2_MOBILE

  DISABLE_COPY_AND_ASSIGN(Workspace);
};

}  // namespace caffe2

#endif  // CAFFE2_CORE_WORKSPACE_H_


text:
{% extends 'base_a.html' %}
{% load staticfiles %}

{% block title %}<title> Simple Dashboard</title>{% endblock %}

{% block stylesheet %}

{% endblock stylesheet %}

{% block javascript %}

{% endblock javascript %}

{% block content %}

Ideas from: {{author}}

            Explore the ideas provided by author and learn potential areas of interest for you

{% endblock %}


text:
using System;

namespace Linked_List_Find_Remove_Node
{
    public class LinkedList
    {
        public Node head;
        public Node curr;
        public int count;
        public int midCount;

        public LinkedList(int data)
        {
            head = new Node(data);
            curr = head;
        }

        public void Add(int data)
        {
            Node newNode = new Node(data);
            newNode.Data = data;
            curr.Next = newNode;
            curr = newNode;
            count++;
            if (count % 2 == 1)
            {
                midCount++;
            }
        }

        public void PrintAllNodes()
        {
            Console.Write("Head ->");
            Node curr = head;
            Console.Write(curr.Data);
            while (curr.Next != null)
            {
                curr = curr.Next;
                Console.Write("->");
                Console.Write(curr.Data);

            }
            Console.Write("<----You've steped on my tail");
        }
        public void NthFromEnd(int Nth)
        {
            int counts = 1;
            Node curr = head;
            while (curr.Next != null)
            {
                curr = curr.Next;
                counts++;
            }
            Node curr2 = head;
            for (int i = 0; i < counts - Nth; i++)
            {
                curr2 = curr2.Next;
            }
            Console.WriteLine(curr2.Data);
        }

        public void PrintMiddle()
        {
            int start = 0;
            Console.Write("Head ->");
            Node curr = head;
            while (start < midCount)
            {
                curr = curr.Next;
                Console.Write(curr.Data.ToString());
                Console.Write("->");
                start++;
            }
            Console.Write("<---- This is the Mid");
            Console.WriteLine();
            Console.Read();
        }

        public void Remove(int nodeToRemove)
        {
            Console.Write("Head ->");
            Node curr = head;
            Node curr2 = head;

            do
            {
                if (nodeToRemove.Equals(curr.Data))
                {
                    curr2 = curr;
                    curr2 = null;
                    curr = curr.Next;

                }
                Console.Write(curr.Data);
                curr = curr.Next;
                Console.Write("->");

            }
            while (curr != null) ;
            Console.Write("<----Tail");

        }

    }
}


text:
layout: page
title: Carpenter Cliffs Global Conference
date: 2016-05-24
author: Terry Aguilar
tags: weekly links, java
status: published
summary: Mauris ornare nec turpis et eleifend.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 12/23/2017
  endDate: 12/28/2017
  ctyhocn: PETMIHX
  groupCode: CCGC
published: true
---
Proin purus sapien, pellentesque vel luctus in, feugiat ut nunc. Aliquam egestas tincidunt magna non accumsan. Fusce quis vestibulum est, ac malesuada dui. Nullam at sollicitudin orci, sed aliquam magna. Curabitur iaculis mollis felis, in tristique nunc viverra sed. Fusce ornare odio enim, ut finibus purus venenatis non. Integer eget nisi sit amet tellus pulvinar imperdiet sit amet vitae lorem. Pellentesque libero urna, elementum quis consectetur ac, malesuada facilisis magna. Donec lobortis orci quis lectus pellentesque facilisis.

* Cras et neque ac erat tristique congue ac sed tellus
* Aliquam lacinia metus sit amet justo scelerisque lacinia
* Aliquam vitae metus vehicula, mollis quam at, finibus quam
* Vestibulum pellentesque nisl at lectus mattis, in congue lorem rutrum.

Nulla facilisi. Nulla dignissim est eu dolor gravida semper. Interdum et malesuada fames ac ante ipsum primis in faucibus. Morbi imperdiet dictum magna, nec accumsan leo feugiat nec. Praesent at rutrum magna. Vivamus eget orci et metus condimentum blandit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi eget enim sed urna pretium interdum in a ante.


text:
class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class LRUCache(object):

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.capacity = capacity
        self.size = 0
        self.dummyNode = Node(-1, -1)
        self.tail = self.dummyNode
        self.entryFinder = {}

    def get(self, key):
        """
        :rtype: int
        """
        entry = self.entryFinder.get(key)
        if entry is None:
            return -1
        else:
            self.renew(entry)
            return entry.val

    def set(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: nothing
        """
        entry = self.entryFinder.get(key)
        if entry is None:
            entry = Node(key, value)
            self.entryFinder[key] = entry
            self.tail.next = entry
            entry.prev = self.tail
            self.tail = entry
            if self.size < self.capacity:
                self.size += 1
            else:
                headNode = self.dummyNode.next
                if headNode is not None:
                    self.dummyNode.next = headNode.next
                    headNode.next.prev = self.dummyNode
                del self.entryFinder[headNode.key]
        else:
            entry.val = value
            self.renew(entry)

    def renew(self, entry):
        if self.tail != entry:
            prevNode = entry.prev
            nextNode = entry.next
            prevNode.next = nextNode
            nextNode.prev = prevNode
            entry.next = None
            self.tail.next = entry
            entry.prev = self.tail
            self.tail = entry


text:
# jpath-py
XPath-like querying for JSON. Written in python

Example:

```python
d={
    "students": [
        {
            "name": "bob",
            "projects": [
                {
                    "name": "banana"
                },
                {
                    "name": "apple"
                }
            ]
        },
        {
            "name": "alice",
            "projects": [
                {
                    "name": "orange"
                }
            ]
        }
    ]
}

from jpathpy import jpath

# get me the second project's name of the first student
print jpath.get_dict_value(d, "students[0]/projects[1]/name")
>> apple

# get me all the project objects of the first student
print jpath.get_dict_value(d, "students[0]/projects/*")
>> [{'name': 'banana'}, {'name': 'apple'}]

# get me all the project names of all the students
print jpath.get_dict_value(d, "students/*/projects/*/name")
>> [['banana', 'apple'], ['orange']]
```


text:
return Def.Sprite {
	Texture=NOTESKIN:GetPath('UpRightFoot','Roll Head Active');
	InitCommand=cmd(basezoomx,-1);
};


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

#ifndef RUNPARAMETERS_H_
#define RUNPARAMETERS_H_

using namespace std;

// dependencies
#include <iostream>  // basic i/o commands: cout, cin, scientific, fixed
#include "../modules/Val_type.h"

// class containing the parameters defining the evolution
class RunParameters
{
	public:
			int seed;
			int nvar;				// number of variables
			Val minrand;
			Val maxrand;
			Val step;
			double max_n_periods;	// maximum number of complete oscillations in each direction
			int nfitcases;			// total number of fitness cases (no of rows of the sample matrix)
			int method;				// method for generating the initial pop. -> 1=no limits, 2=FULL, 3=GROW, 4=RAMPED
			int depth_max;			// maximum depth of newly generated tree (must be > 0 or > depth_min)
			int depth_min;			// minimum depth of newly generated tree (must be > 0)  --- only for RAMPED method
			int depth_lim;			// limit on depth during the evolution (no trees will ever reach a depth bigger than depth_lim)
			double p_FULL;			// percentage of trees built with FULL method (p_FULL + p_GROW = 1)    --- only for RAMPED method
			double repr_rate;		// reproduction rate
			double cross_rate;	 	// crossover rate
			double mut_rate;		// mutation rate
			double comp_rate;		//percentage of the individuals created composing two trees, with respect to the individual killed
			double new_rate;		//percentage of the new individuals randomly initialized, with respect to the individual killed
			int M;					// size of the population - number of trees
			int G;					// number of generations
			int bounded;			// flag to activate the editing strategy to remove high level polynomials and other diverging terms, to limit the search to bounded functions

			bool normalised;		// 9/12/20 PARAMETER NOT USED ANY LONGER: 1 if normalised RMSE is used; 0 for normal RMSE (see Population::fitness_func)
			bool minmax;			// 9/12/20 PARAMETER NOT USED ANY LONGER: 1 if MinMax F function, 0 if usual weighted function

			int pso_nparticles; 	// PSO no. of particles in case PSO is used before SQP to optimise numerical coefficients
			int pso_niterations; 	// PSO no. of iterations in case PSO is used before SQP to optimise numerical coefficients

			int strat_statp;		// Strategy to handle statistical moments as objectives - see Population::aggregate_F
			double w_strat_statp;	// Numerical weight of strategy to handle statistical moments as objectives - see Population::aggregate_F
			double w_ACF;			// weight related to autocorrelation finction (ACF) properties - only used for 1D problems
			double w_tvariation;	// weight related to total variation
			double w_complexity;	// weight given to the second normalized objective (measure of complexity of the tree)
			double w_n_corrections;	// weight given to the number of times protected division "corrects" the result (division by zero)
			double w_size;			// weight given to the number of nodes a tree is made of
			double w_factorisation; // penalisation for lack of factorisation
			int n_guesses;			// no. of guesses for the SQP optimization
			int crossvalidation;	// 1 if data set is split each generation, 0 if not
			int folds_n;			// number of rows containing validating points (from the upper row of the matrix)
			double threshold;		//value of fitness (RMSE) under which the evolution stops
			int n_inequality0;  	//total number of order 0 inequality constraints (number of points constrained)
			double w_pen_ord0;  	//weight for the penalisation on order 0 inequality constraint
			int n_inequality1;    	//total number of order 1 inequality constraints (number of points constrained)
			double w_pen_ord1;    //weight for the penalisation on order 1 inequality constraint

			// constructor
			RunParameters(void);
			// function to show data
			void show(void);
};

#endif  /* RUNPARAMETERS_H_ */


text:
angular
    .module('RDash')
    .controller('restaurantCtrl', ['$scope', '$http',restaurantCtrl]);

/*var res = angular.module('res', []);

res.controller('restaurantCtrl', function($scope, $http) {
  $http.get("http://viands.in:3000/restaurants")
  .success(function (response) {$scope.names = response.restaurants});
});*/

function restaurantCtrl($scope,$http) {
    $http.get("http://viands.in:3000/restaurants")
  .success(function (response) {$scope.names = response.restaurants});
}


text:
package com.example.android.hcgallery;

public class Directory {
    private static DirectoryCategory[] mCategories;

    public static void initializeDirectory() {
      mCategories = new DirectoryCategory[] {
                new DirectoryCategory("Balloons", new DirectoryEntry[] {
                        new DirectoryEntry("Red Balloon", R.drawable.red_balloon),
                        new DirectoryEntry("Green Balloon", R.drawable.green_balloon),
                        new DirectoryEntry("Blue Balloon", R.drawable.blue_balloon)}),
                new DirectoryCategory("Bikes", new DirectoryEntry[] {
                        new DirectoryEntry("Old school huffy", R.drawable.blue_bike),
                        new DirectoryEntry("New Bikes", R.drawable.rainbow_bike),
                        new DirectoryEntry("Chrome Fast", R.drawable.chrome_wheel)}),
                new DirectoryCategory("Androids", new DirectoryEntry[] {
                        new DirectoryEntry("Steampunk Android", R.drawable.punk_droid),
                        new DirectoryEntry("Stargazing Android", R.drawable.stargazer_droid),
                        new DirectoryEntry("Big Android", R.drawable.big_droid) }),
                new DirectoryCategory("Pastries", new DirectoryEntry[] {
                        new DirectoryEntry("Cupcake", R.drawable.cupcake),
                        new DirectoryEntry("Donut", R.drawable.donut),
                        new DirectoryEntry("Eclair", R.drawable.eclair),
                        new DirectoryEntry("Froyo", R.drawable.froyo), }), };

    }

    public static int getCategoryCount() {
        return mCategories.length;
    }

    public static DirectoryCategory getCategory(int i) {
        return mCategories[i];
    }
}


text:
import _ from 'lodash'
import { MAX_MEMOIZE_SIZE } from '../constants'

export default function memoizeCapped(func) {
  const result = _.memoize(func, (key) => {
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear()
    }
    return key
  })

  const cache = result.cache
  return result
}


text:
package com.adaptris.core.http.client.net;

import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URLConnection;
import javax.validation.constraints.NotBlank;
import com.adaptris.annotation.InputFieldHint;
import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.CoreException;
import com.adaptris.core.http.HttpConstants;
import com.adaptris.core.http.auth.ResourceTargetMatcher;
import com.adaptris.core.http.auth.UserPassAuthentication;
import com.adaptris.core.util.Args;
import com.adaptris.core.util.ExceptionHelper;
import com.adaptris.security.exc.PasswordException;
import com.adaptris.security.password.Password;
import com.adaptris.util.text.Base64ByteTranslator;
import com.thoughtworks.xstream.annotations.XStreamAlias;

/**
 * Build a {@link HttpConstants#AUTHORIZATION} (Basic only) from configuration (or metadata).
 * <p>
 * In some situations it may be preferred to build the {@link HttpConstants#AUTHORIZATION} header rather than relying on the
 * behaviour of {@link URLConnection} to request a {@link PasswordAuthentication} object when accessing protected resources (this is
 * what happens if you use {@link UserPassAuthentication}). You can use this class to create a Basic authorization.
 * </p>
 *
 * @config http-dynamic-authorization-header
 *
 */
@XStreamAlias("http-dynamic-authorization-header")
public class DynamicBasicAuthorizationHeader implements HttpURLConnectionAuthenticator {

  @NotBlank
  @InputFieldHint(expression = true)
  private String username;
  @NotBlank
  @InputFieldHint(expression = true, style = "PASSWORD")
  private String password;

  private transient String authHeader;

  public DynamicBasicAuthorizationHeader() {

  }

  public DynamicBasicAuthorizationHeader(String username, String password) {
    this();
    setUsername(username);
    setPassword(password);
  }

  @Override
  public void setup(String target, AdaptrisMessage msg, ResourceTargetMatcher auth) throws CoreException {
    try {
      String username = Args.notBlank(msg.resolve(getUsername()), "username");
      String password = Args.notBlank(msg.resolve(getPassword()), "password");
      String encoded = new Base64ByteTranslator().translate(String.format("%s:%s", username, Password.decode(password)).getBytes("UTF-8"));
      authHeader = String.format("Basic %s", encoded);
    } catch (UnsupportedEncodingException | IllegalArgumentException | PasswordException e) {
      throw ExceptionHelper.wrapCoreException(e);
    }
  }

  @Override
  public void configureConnection(HttpURLConnection conn) {
    conn.addRequestProperty(HttpConstants.AUTHORIZATION, authHeader);
  }

  @Override
  public void close() {
  }

  public String getUsername() {
    return username;
  }

  /**
   * Set the username
   *
   * @param s the username, supports metadata resolution via {@link AdaptrisMessage#resolve(String)}.
   */
  public void setUsername(String s) {
    this.username = Args.notBlank(s, "username");
  }

  /**
   * @return the password
   */
  public String getPassword() {
    return password;
  }

  /**
   * @param pw the password to set, supports metadata resolution via {@link AdaptrisMessage#resolve(String)}.
   */
  public void setPassword(String pw) {
    this.password = Args.notBlank(pw, "password");
  }

}


text:
package com.jwetherell.algorithms.mathematics.test;

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;

import com.jwetherell.algorithms.mathematics.RamerDouglasPeucker;

public class RamerDouglasPeuckerTests {

    @Test
    public void test1() {
        final List<Double[]> list = new ArrayList<Double[]>();
        list.add(new Double[]{3.14d, 5.2d});
        list.add(new Double[]{5.7d,  8.1d});
        list.add(new Double[]{4.6d, -1.3d});

        final List<Double[]> simplified = RamerDouglasPeucker.douglasPeucker(list, 5.0d);
        final List<Double[]> expected = new ArrayList<Double[]>();
        expected.add(list.get(0));
        expected.add(list.get(2));
        Assert.assertTrue(simplified.size()==2 && simplified.equals(expected));
    }

    @Test
    public void test2() {
        final List<Double[]> list = new ArrayList<Double[]>();
        list.add(new Double[]{0.0d,0.0d});
        list.add(new Double[]{2.5d, 3.0d});
        list.add(new Double[]{5.0d, 0.0d});

        final List<Double[]> simplified = RamerDouglasPeucker.douglasPeucker(list, 2.9d);
        final List<Double[]> expected = new ArrayList<Double[]>();
        expected.add(list.get(0));
        expected.add(list.get(1));
        expected.add(list.get(2));
        Assert.assertTrue(simplified.size()==3 && simplified.equals(expected));
    }

    @Test
    public void test3() {
        final List<Double[]> list = new ArrayList<Double[]>();
        list.add(new Double[]{0.0d,0.0d});
        list.add(new Double[]{2.5d, 3.0d});
        list.add(new Double[]{5.0d, 0.0d});

        final List<Double[]> simplified = RamerDouglasPeucker.douglasPeucker(list, 3.0d);
        final List<Double[]> expected = new ArrayList<Double[]>();
        expected.add(list.get(0));
        expected.add(list.get(2));
        Assert.assertTrue(simplified.size()==2 && simplified.equals(expected));
    }
}


text:
package org.apache.spark.internal.config

import java.util.{Map => JMap}
import java.util.regex.Pattern

import scala.collection.mutable.HashMap
import scala.util.matching.Regex

private object ConfigReader {

  private val REF_RE = "\\$\\{(?:(\\w+?):)?(\\S+?)\\}".r

}

/**
 * A helper class for reading config entries and performing variable substitution.
 *
 * If a config value contains variable references of the form "${prefix:variableName}", the
 * reference will be replaced with the value of the variable depending on the prefix. By default,
 * the following prefixes are handled:
 *
 * - no prefix: use the default config provider
 * - system: looks for the value in the system properties
 * - env: looks for the value in the environment
 *
 * Different prefixes can be bound to a `ConfigProvider`, which is used to read configuration
 * values from the data source for the prefix, and both the system and env providers can be
 * overridden.
 *
 * If the reference cannot be resolved, the original string will be retained.
 *
 * @param conf The config provider for the default namespace (no prefix).
 */
private[spark] class ConfigReader(conf: ConfigProvider) {

  def this(conf: JMap[String, String]) = this(new MapProvider(conf))

  private val bindings = new HashMap[String, ConfigProvider]()
  bind(null, conf)
  bindEnv(new EnvProvider())
  bindSystem(new SystemProvider())

  /**
   * Binds a prefix to a provider. This method is not thread-safe and should be called
   * before the instance is used to expand values.
   */
  def bind(prefix: String, provider: ConfigProvider): ConfigReader = {
    bindings(prefix) = provider
    this
  }

  def bind(prefix: String, values: JMap[String, String]): ConfigReader = {
    bind(prefix, new MapProvider(values))
  }

  def bindEnv(provider: ConfigProvider): ConfigReader = bind("env", provider)

  def bindSystem(provider: ConfigProvider): ConfigReader = bind("system", provider)

  /**
   * Reads a configuration key from the default provider, and apply variable substitution.
   */
  def get(key: String): Option[String] = conf.get(key).map(substitute)

  /**
   * Perform variable substitution on the given input string.
   */
  def substitute(input: String): String = substitute(input, Set())

  private def substitute(input: String, usedRefs: Set[String]): String = {
    if (input != null) {
      ConfigReader.REF_RE.replaceAllIn(input, { m =>
        val prefix = m.group(1)
        val name = m.group(2)
        val ref = if (prefix == null) name else s"$prefix:$name"
        require(!usedRefs.contains(ref), s"Circular reference in $input: $ref")

        val replacement = bindings.get(prefix)
          .flatMap(_.get(name))
          .map { v => substitute(v, usedRefs + ref) }
          .getOrElse(m.matched)
        Regex.quoteReplacement(replacement)
      })
    } else {
      input
    }
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >

    <data>

        <variable
            name="view"
            type="com.petar.weather.logic.models.AForecast"
            />

        <import
            type="com.petar.weather.util.FormatUtil"
            />

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <LinearLayout
            android:baselineAligned="false"
            style="@style/RecyclerItems"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{() -> view.onItemClick()}"
            >

            <android.support.constraint.ConstraintLayout
                style="@style/RecyclerItems.Forecast"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.4"
                >

                <ImageView
                    style="@style/Icon.WhiteTinted"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:contentDescription="@{@string/content_description_weather_state_icon(view.weatherState)}"
                    app:imageUrl="@{view.imageType}"
                    app:layout_constraintDimensionRatio="W, 1:1"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    />

            </android.support.constraint.ConstraintLayout>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_weight="0.6"
                android:gravity="center"
                android:orientation="vertical"
                >

                <TextView
                    style="@style/Text.L.Bold"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@{view.weatherState}"
                    />

                <TextView
                    style="@style/Text.M.Bold"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@{FormatUtil.formatMinMaxTemperature(view.minTemp, view.maxTemp)}"
                    />

                <TextView
                    style="@style/Text.M"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@{FormatUtil.formatForecastDate(view)}"
                    />

            </LinearLayout>

        </LinearLayout>

        <include
            layout="@layout/item_separator"
            />

    </LinearLayout>

</layout>


text:
def CreateDataLoader(datafolder,dataroot='./dataset',dataset_mode='2afc',load_size=64,batch_size=1,serial_batches=True,nThreads=4):
    from data.custom_dataset_data_loader import CustomDatasetDataLoader
    data_loader = CustomDatasetDataLoader()
    # print(data_loader.name())
    data_loader.initialize(datafolder,dataroot=dataroot+'/'+dataset_mode,dataset_mode=dataset_mode,load_size=load_size,batch_size=batch_size,serial_batches=serial_batches, nThreads=nThreads)
    return data_loader


text:
package org.gradle.plugin.use.resolve.service.internal;

import org.gradle.api.specs.Spec;
import org.gradle.api.specs.Specs;
import org.gradle.cache.PersistentCache;
import org.gradle.cache.PersistentIndexedCache;
import org.gradle.cache.PersistentIndexedCacheParameters;
import org.gradle.internal.Factory;
import org.gradle.internal.concurrent.CompositeStoppable;
import org.gradle.internal.serialize.Decoder;
import org.gradle.internal.serialize.Encoder;
import org.gradle.internal.serialize.Serializer;
import org.gradle.plugin.use.internal.PluginRequest;

import java.io.IOException;

public class PersistentCachingPluginResolutionServiceClient implements PluginResolutionServiceClient {

    public static final String PLUGIN_USE_METADATA_CACHE_NAME = "plugin-use-metadata";
    public static final String PLUGIN_USE_METADATA_OP_NAME = "queryPluginMetadata";
    public static final String CLIENT_STATUS_CACHE_NAME = "client-status";
    public static final String CLIENT_STATUS_OP_NAME = "queryClientStatus";

    private final PluginResolutionServiceClient delegate;
    private final PersistentCache cacheAccess;
    private final PersistentIndexedCache<PluginRequestKey, Response<PluginUseMetaData>> pluginUseMetadataCache;
    private final PersistentIndexedCache<ClientStatusKey, Response<ClientStatus>> clientStatusCache;

    public PersistentCachingPluginResolutionServiceClient(PluginResolutionServiceClient delegate, PersistentCache persistentCache) {
        this.delegate = delegate;
        this.cacheAccess = persistentCache;
        this.pluginUseMetadataCache = persistentCache.createCache(PersistentIndexedCacheParameters.of(
                        PLUGIN_USE_METADATA_CACHE_NAME, new PluginRequestKey.Serializer(), ResponseSerializer.of(new PluginUseMetaData.Serializer()))
        );
        this.clientStatusCache = persistentCache.createCache(PersistentIndexedCacheParameters.of(
                        CLIENT_STATUS_CACHE_NAME, new ClientStatusKey.Serializer(), ResponseSerializer.of(new ClientStatus.Serializer()))
        );
    }

    public Response<PluginUseMetaData> queryPluginMetadata(final String portalUrl, final boolean shouldValidate, final PluginRequest pluginRequest) {
        PluginRequestKey key = PluginRequestKey.of(portalUrl, pluginRequest);
        Factory<Response<PluginUseMetaData>> factory = new Factory<Response<PluginUseMetaData>>() {
            public Response<PluginUseMetaData> create() {
                return delegate.queryPluginMetadata(portalUrl, shouldValidate, pluginRequest);
            }
        };

        if (shouldValidate) {
            return fetch(PLUGIN_USE_METADATA_OP_NAME, pluginUseMetadataCache, key, factory);
        } else {
            return maybeFetch(PLUGIN_USE_METADATA_OP_NAME, pluginUseMetadataCache, key, factory);
        }
    }

    public Response<ClientStatus> queryClientStatus(final String portalUrl, final boolean shouldValidate, final String checksum) {
        ClientStatusKey key = new ClientStatusKey(portalUrl);
        Factory<Response<ClientStatus>> factory = new Factory<Response<ClientStatus>>() {
            public Response<ClientStatus> create() {
                return delegate.queryClientStatus(portalUrl, shouldValidate, checksum);
            }
        };

        if (shouldValidate) {
            return fetch(CLIENT_STATUS_OP_NAME, clientStatusCache, key, factory);
        } else {
            return maybeFetch(CLIENT_STATUS_OP_NAME, clientStatusCache, key, factory, new Spec<Response<ClientStatus>>() {
                public boolean isSatisfiedBy(Response<ClientStatus> element) {
                    return !element.getClientStatusChecksum().equals(checksum);
                }
            });
        }
    }

    private <K, V extends Response<?>> V maybeFetch(String operationName, final PersistentIndexedCache<K, V> cache, final K key, Factory<V> factory) {
        return maybeFetch(operationName, cache, key, factory, Specs.SATISFIES_NONE);
    }

    private <K, V extends Response<?>> V maybeFetch(String operationName, final PersistentIndexedCache<K, V> cache, final K key, Factory<V> factory, Spec<? super V> shouldFetch) {
        V cachedValue = cacheAccess.useCache(operationName + " - read", new Factory<V>() {
            public V create() {
                return cache.get(key);
            }
        });

        boolean fetch = cachedValue == null || shouldFetch.isSatisfiedBy(cachedValue);
        if (fetch) {
            return fetch(operationName, cache, key, factory);
        } else {
            return cachedValue;
        }
    }

    private <K, V extends Response<?>> V fetch(String operationName, final PersistentIndexedCache<K, V> cache, final K key, Factory<V> factory) {
        final V value = factory.create();
        if (value.isError()) {
            return value;
        }

        cacheAccess.useCache(operationName + " - write", new Runnable() {
            public void run() {
                cache.put(key, value);
            }
        });
        return value;
    }

    public void close() throws IOException {
        CompositeStoppable.stoppable(delegate, cacheAccess).stop();
    }

    private static class ResponseSerializer<T> implements Serializer<Response<T>> {

        private final Serializer<T> payloadSerializer;

        private static <T> ResponseSerializer<T> of(Serializer<T> payloadSerializer) {
            return new ResponseSerializer<T>(payloadSerializer);
        }

        private ResponseSerializer(Serializer<T> payloadSerializer) {
            this.payloadSerializer = payloadSerializer;
        }

        public Response<T> read(Decoder decoder) throws Exception {
            return new SuccessResponse<T>(
                    payloadSerializer.read(decoder),
                    decoder.readSmallInt(),
                    decoder.readString(),
                    decoder.readNullableString()
            );
        }

        public void write(Encoder encoder, Response<T> value) throws Exception {
            T response = value.getResponse();
            payloadSerializer.write(encoder, response);
            encoder.writeSmallInt(value.getStatusCode());
            encoder.writeString(value.getUrl());
            encoder.writeNullableString(value.getClientStatusChecksum());
        }
    }

    static class PluginRequestKey {
        private final String id;
        private final String version;

        private final String url;

        private static PluginRequestKey of(String url, PluginRequest pluginRequest) {
            return new PluginRequestKey(pluginRequest.getId().toString(), pluginRequest.getVersion(), url);
        }

        private PluginRequestKey(String id, String version, String url) {
            this.id = id;
            this.version = version;
            this.url = url;
        }

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

            PluginRequestKey key = (PluginRequestKey) o;

            return id.equals(key.id) && url.equals(key.url) && version.equals(key.version);
        }

        @Override
        public int hashCode() {
            int result = id.hashCode();
            result = 31 * result + version.hashCode();
            result = 31 * result + url.hashCode();
            return result;
        }

        private static class Serializer implements org.gradle.internal.serialize.Serializer<PluginRequestKey> {

            public PluginRequestKey read(Decoder decoder) throws Exception {
                return new PluginRequestKey(decoder.readString(), decoder.readString(), decoder.readString());
            }

            public void write(Encoder encoder, PluginRequestKey value) throws Exception {
                encoder.writeString(value.id);
                encoder.writeString(value.version);
                encoder.writeString(value.url);
            }
        }

    }

    public static class ClientStatusKey {

        private final String portalUrl;

        public ClientStatusKey(String portalUrl) {
            this.portalUrl = portalUrl;
        }

        public static class Serializer implements org.gradle.internal.serialize.Serializer<ClientStatusKey> {
            public ClientStatusKey read(Decoder decoder) throws Exception {
                return new ClientStatusKey(decoder.readString());
            }

            public void write(Encoder encoder, ClientStatusKey value) throws Exception {
                encoder.writeString(value.portalUrl);
            }
        }

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

            ClientStatusKey that = (ClientStatusKey) o;

            return portalUrl.equals(that.portalUrl);
        }

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

}


text:
import { isBoolean } from 'lodash-es'
import forEach from '../util/forEach'
import isNumber from '../util/isNumber'
import isString from '../util/isString'
import DOMExporter from './DOMExporter'
import DefaultDOMElement from '../ui/DefaultDOMElement'

var defaultAnnotationConverter = {
  tagName: 'annotation',
  export: function(node, el) {
    el.attr('type', node.type)
    var properties = node.toJSON()
    forEach(properties, function(value, name) {
      if (name === 'id' || name === 'type') return
      if (isString(value) || isNumber(value) || isBoolean(value)) {
        el.attr(name, value)
      }
    })
  }
}

var defaultBlockConverter = {
  tagName: 'block',
  export: function(node, el, converter) {
    el.attr('type', node.type)
    var properties = node.toJSON()
    forEach(properties, function(value, name) {
      if (name === 'id' || name === 'type') {
        return
      }
      var prop = converter.$$(name)
      if (node.getPropertyType(name) === 'string') {
        prop.append(converter.annotatedText([node.id, name]))
      } else {
        prop.text(value)
      }
      el.append(prop)
    })
  }
}

/*
  @class
  @abstract

  Base class for custom XML exporters. If you want to use HTML as your
  exchange format see {@link model/HTMLExporter}.
*/
class XMLExporter extends DOMExporter {

  constructor(config, context) {
    super(Object.assign({ idAttribute: 'id' }, config), context)

    // used internally for creating elements
    this._el = DefaultDOMElement.parseXML('<dummy></dummy>')
  }

  getDefaultBlockConverter() {
    return defaultBlockConverter
  }

  getDefaultPropertyAnnotationConverter() {
    return defaultAnnotationConverter
  }

}

export default XMLExporter


text:
<?php
declare(strict_types=1);

namespace Zelenin\MessageBus\Test\MiddlewareBus;

use PHPUnit\Framework\TestCase;
use Zelenin\MessageBus\MiddlewareBus\FinalMiddleware;
use Zelenin\MessageBus\MiddlewareBus\MiddlewareDispatcher;
use Zelenin\MessageBus\MiddlewareBus\MiddlewareStack;
use Zelenin\MessageBus\Test\Provider\MiddlewareA;
use Zelenin\MessageBus\Test\Provider\MiddlewareB;
use Zelenin\MessageBus\Test\Provider\MiddlewareC;
use Zelenin\MessageBus\Test\Provider\MiddlewareD;

final class MiddlewareDispatcherTest extends TestCase
{
    public function testHandle()
    {
        $middlewares = [
            new MiddlewareA(),
            new MiddlewareB(),
            new MiddlewareC(),
            new MiddlewareD(),
        ];

        $dispatcher = new MiddlewareDispatcher(new MiddlewareStack($middlewares), new FinalMiddleware());

        $message = new \stdClass();

        $context = $dispatcher($message);

        $this->assertEquals(count($middlewares), $context->value('i'));
        $this->assertEquals('CDBA', $context->value('order'));
    }

    public function testContext()
    {
        $middlewares = [
            new MiddlewareA(),
            new MiddlewareB(),
            new MiddlewareC(),
            new MiddlewareD(),
        ];

        $dispatcher = new MiddlewareDispatcher(new MiddlewareStack($middlewares), new FinalMiddleware());

        $message = new \stdClass();

        $context = $dispatcher($message);

        $this->assertEquals($context, $dispatcher->context());

        $valueName = 'added';
        $valueValue = 'addedValue';

        $this->assertNull($dispatcher->context()->value($valueName));

        $dispatcher = $dispatcher->withContext($dispatcher->context()->withValue($valueName, $valueValue));
        $this->assertEquals($valueValue, $dispatcher->context()->value($valueName));
    }
}


text:
#import "JPVideoPlayerWeiBoViewController.h"
#import "JPVideoPlayerWeiBoListViewController.h"
#import "JPVideoPlayerHoverViewController.h"
#import "JPVideoPlayerAudioViewController.h"

@interface JPVideoPlayerWeiBoViewController()

@property (nonatomic, strong) NSArray<NSString *> *cellTypeStrings;

@end

@implementation JPVideoPlayerWeiBoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"微博";
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cellTypeStrings.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
    cell.textLabel.text = self.cellTypeStrings[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UIViewController *viewController = nil;
    if(indexPath.row == 0){
        viewController = [[JPVideoPlayerWeiBoListViewController alloc] initWithPlayStrategyType:JPScrollPlayStrategyTypeBestVideoView];
    }
    else if(indexPath.row == 1) {
        viewController = [[JPVideoPlayerWeiBoListViewController alloc] initWithPlayStrategyType:JPScrollPlayStrategyTypeBestCell];
    }
    else if(indexPath.row == 2) {
        viewController = [JPVideoPlayerHoverViewController new];
    }
    else {
        viewController = [JPVideoPlayerAudioViewController new];
    }
    [self.navigationController pushViewController:viewController animated:YES];
}

- (NSArray<NSString *> *)cellTypeStrings {
    if(!_cellTypeStrings){
       _cellTypeStrings = @[@"不等高 Cell 自动播放", @"等高 Cell 自动播放", @"悬停播放", @"音频播放"];
    }
    return _cellTypeStrings;
}

@end