text:
package edu.gemini.pot.sp;

import edu.gemini.pot.sp.version.LifespanId;
import edu.gemini.shared.util.VersionVector;
import edu.gemini.spModel.core.SPProgramID;
import edu.gemini.spModel.data.ISPDataObject;

import java.beans.PropertyChangeListener;
import java.util.Set;

/**
 * This is the base interface for all the Science Program nodes.
 * It supports three features:
 *

 *

 *
listeners - support for property change listeners
 *
user objects - arbitrary (opaque) named objects stored on behalf
 * of the client
 *
data object - an arbitrary (opaque) object stored on behalf
 * of the client
 *

 *

 *
Events

 * In addition to ordinary property change events, all nodes support
 * "composite" listeners.  Composite listeners will receive a composite
 * change event for any property change in the node or any of the node's
 * contained children or descendants.  Effectively, "composite" listeners
 * provide a way to listen to one portion of the Science Program hierarchy
 * for all property events that occur within that hierarchy.
 *

 *
Client Data

 * Client data is named opaque data stored on behalf of the client. Property
 * change events, using the name "ClientData:<name>", are fired when client
 * data is updated.
 */
public interface ISPNode {

    /**
     * Names the property change event fired when anything in this node or
     * or in any contained child is modified.
     */
    String COMPOSITE_CHANGE_PROP = "CompositeChange";

    /**
     * Names the property change event fired when a data object is added
     * or replaced.
     */
    String CLIENT_DATA_PROP_PREFIX = "ClientData";
    String TRANSIENT_CLIENT_DATA_PROP_PREFIX = "TransientClientData";

    String EVENTS_ACTIVATED = "EventsActivated";

    /**
     * Client data key for the "DataObject" client data.
     */
    String DATA_OBJECT_KEY = "DataObject";
    String CONFLICTS_KEY   = "Conflicts";

    LifespanId getLifespanId();

    /**
     * Gets the unique key of the node.  Each node is uniquely identified.
     */
    SPNodeKey getNodeKey();

    /**
     * Gets key of the program with which this node is associated.  If this
     * is a {@link ISPProgram}, then this key will be the same as the
     * {@link #getNodeKey node key}.
     */
    SPNodeKey getProgramKey();

    /**
     * Gets the program id, which is the Gemini reference number by which the
     * program is known to humans.
     */
    SPProgramID getProgramID();

    /**
     * Gets this node's parent, if there is one.
     *
     * @return containing remote node, if any; null otherwise
     */
    ISPContainerNode getParent();

    /**
     * Gets the root ancestor of this node (which may be this node itself if
     * at the top level or not nested inside of another node).
     */
    ISPRootNode getRootAncestor();

    /**
     * Gets the program in which this node lives (if any).
     */
    ISPProgram getProgram();

    /**
     * Gets the observation associated with this node (if any).
     * @return the observation in which this node lives, if any;
     * null otherwise
     */
    ISPObservation getContextObservation();

    /**
     * Returns true if events are enabled, false
     * otherwise.  Events may be disabled if a series of updates to a tree
     * of science program nodes rooted at this node will undergo a series of
     * updates.  When events are re-enabled (see
     * {@link #setSendingEvents}) a single composite change event with key
     * {@link #EVENTS_ACTIVATED} is sent.
     *
     * @return true if events are enabled, false
     *         otherwise
     */
    boolean isSendingEvents();

    /**
     * Turns on or off the state of event sending.  If true events
     * will be sent for all future changes as normal, until the events are
     * turned off again.  If transitioning from events off to events on, a
     * single composite change event is sent to all registered listeners.  It
     * will have property name {@link #EVENTS_ACTIVATED}.
     *
     * @param sendEvents whether to turn on events (if true) or
     *                   turn off events (if false)
     */
    PropagationId setSendingEvents(boolean sendEvents);

    /**
     * Adds a property change listener that will receive events for all property
     * changes with the name propName.
     *
     * @param propName name of the property to monitor
     * @param pcl the listener that will receive the events
     */
    void addPropertyChangeListener(String propName, PropertyChangeListener pcl);

    /**
     * Removes the given listener from the list of those registered to receive
     * events for changes to the named property. If the listener is not in fact
     * registered for this property, nothing is done.
     *
Note, this does not effect registrations to receive
     * generic property change event notifications.
     *
     * @param propName the name of the property whose changes should no longer
     *                 be tracked
     * @param pcl      the listener that should no longer receive the events
     */
    void removePropertyChangeListener(String propName, PropertyChangeListener pcl);

    /**
     * Adds a property change listener that will receive events for all property
     * changes in this or any contained node.
     *
     * @param pcl the listener that will receive the events
     */
    void addCompositeChangeListener(PropertyChangeListener pcl);

    /**
     * Removes the given property change listener.  If the listener is not in
     * fact registered, nothing is done.
     *
     * @param pcl the listener that should no longer receive the events
     */
    void removeCompositeChangeListener(PropertyChangeListener pcl);

    /**
     * Determines whether this node holds a data object with "staff only"
     * fields.  This is equivalent to calling getDataObject() and then checking
     * whether it implements {@link ISPStaffOnlyFieldProtected}, but without
     * the copy of the data object implied by getDataObject().
     */
    boolean hasStaffOnlyFields();

    /**
     * Returns (a copy of) the data object for this node.  This is a convenience
     * method that allows direct access to the "DataObject" client data.  It is
     * equivalent to getClientData("DataObject").
     *
     * @return the serializable data object for the node
     */
    ISPDataObject getDataObject();

    /**
     * Replaces the data object for this node.  This is a convenience method
     * that allows direct access to the "DataObject" client data.  It is
     * equivalent to setClientData("DataObject").
     *

     *
A property change event, using the name "ClientData:DataObject" is
     * fired by this method.
     *
     * @param dataObject a serializable object that contains the new
     *                   data for this node
     */
    PropagationId setDataObject(ISPDataObject dataObject);

    /**
     * Replaces the data object for this node and sets the version to match
     * the provided newVersion.  Usually the version is
     * automatically updated when the data object is changed and it is expected
     * that this method will be used only in very special cases where more
     * control over the resulting version vector is required.
     *
     * @param dataObject a serializable object that contains the new data for
     *                   this node
     * @param newVersion new version for this node.
     */
    PropagationId setDataObjectAndVersion(ISPDataObject dataObject, VersionVector<LifespanId, Integer> newVersion);

    /**
     * Gets the current version vector for this node.
     */
    VersionVector<LifespanId, Integer> getVersion();

    // --Commented out by Inspection (6/23/14 4:17 PM):void setVersion(VersionVector<LifespanId, Integer> version);

    /**
     * Replaces the data object for this node (firing a property change event
     * with name "ClientData:DataObject". If conflicts is
     * true, then the current version of the node's data object
     * is also stored in "ClientData:Conflicts".
     *
     * @param newValue new value for the data object
     * @param conflicts if true, store the current value in client
     *                  data
     */
    PropagationId setDataObject(ISPDataObject newValue, boolean conflicts);

    /**
     * Returns true if the node has a non-empty Conflicts client
     * data object.
     */
    boolean hasConflicts();

    /**
     * Gets the Conflicts object associated with this node, if any (returns
     * an empty Conflicts object if there are no conflicts)..
     * @return the client data keyed under ClientData:Conflicts, if
     * any; {@link Conflicts#EMPTY} otherwise
     */
    Conflicts getConflicts();

    void setConflicts(Conflicts c);

    /**
     * If this node has a {@link DataObjectConflict} stored in its client data,
     * it is updated to contain the current real data object value with the
     * opposite database perspective.  The current real data object is updated
     * to contain the value of the existing DataObjectConflict.
     *
     *
This method is called to select the opposite data object for viewing
     * or editing.

     */
    void swapDataObjectConflict();

    void addConflictNote(Conflict.Note cn);

    /**
     * Resolves a data object conflict.
     */
    void resolveDataObjectConflict();

    void resolveConflict(Conflict.Note cn);

    void resolveConflicts();

    /**
     * Returns a Set view of the names of client data owned by
     * this node.  The returned Set is not backed by internal
     * data, and may be modified freely by the client.
     *
     * @return Set of String keys for the client
     *         data
     */
    Set<String> getClientDataKeys();

    /**
     * Gets the named client data, if it exists.
     *
     * @return the named client data; null if the given name is
     *         not known
     */
    Object getClientData(String name);

    /**
     * Adds or updates the named client data.  Listeners are will be notified,
     * and the property name will be "ClientData:<name>" where <name> is the
     * name of the client data.
     *
     * @param name name of the client data that is being added or modified
     * @param obj  the new value of the client data
     */
    PropagationId putClientData(String name, Object obj);

    /**
     * Removes the named user object.  Listeners will be notified.
     *
     * @param name name of the client data that is being removed
     */
    void removeClientData(String name);

    /**
     * Adds or updates the specified transient client data. As its name suggests,
     * transient client data is not serialized. This facility is provided for short-
     * term caching.
     */
    void putTransientClientData(String key, Object value);

    /**
     * Returns the specified transient client data.
     *
     * @see #putTransientClientData(String, Object)
     */
    Object getTransientClientData(String key);

    /**
     * Removes the specified transient client data.
     *
     * @see #putTransientClientData(String, Object)
     */
    void removeTransientClientData(String key);

    void getProgramReadLock();
    void returnProgramReadLock();

    void getProgramWriteLock();
    void returnProgramWriteLock();
    boolean haveProgramWriteLock();

    void addTransientPropertyChangeListener(String propName, PropertyChangeListener pcl);

    void removeTransientPropertyChangeListener(String propName, PropertyChangeListener pcl);
}


text:
package org.w3c.domts.level2.core;

import org.w3c.dom.*;

import org.w3c.domts.DOMTestCase;
import org.w3c.domts.DOMTestDocumentBuilderFactory;

/**
 *     The "getElementsByTagNameNS(namespaceURI,localName)" method for a
 *    Document should return a new NodeList of all Elements that have a namespace
 *    when local name is specified as ' '.
 *
 *    Invoke method getElementsByTagNameNS(namespaceURI,localName) on this document
 *    with namespaceURI and localName as " ".
 *    Method should return a new NodeList of 37 elements.
* @author NIST
* @author Mary Brady
* @see http://www.w3.org/TR/DOM-Level-2-Core/core#ID-getElBTNNS
*/
public final class getElementsByTagNameNS01 extends DOMTestCase {

   /**
    * Constructor.
    * @param factory document factory, may not be null
    * @throws org.w3c.domts.DOMTestIncompatibleException Thrown if test is not compatible with parser configuration
    */
   public getElementsByTagNameNS01(final DOMTestDocumentBuilderFactory factory)  throws org.w3c.domts.DOMTestIncompatibleException {
      super(factory);

    //
    //   check if loaded documents are supported for content type
    //
    String contentType = getContentType();
    preload(contentType, "staffNS", false);
    }

   /**
    * Runs the test case.
    * @throws Throwable Any uncaught exception causes test to fail
    */
   public void runTest() throws Throwable {
      String namespaceURI = "*";
      String localName = "*";
      Document doc;
      NodeList newList;
      doc = (Document) load("staffNS", false);
      newList = doc.getElementsByTagNameNS(namespaceURI, localName);
      assertSize("throw_Size", 37, newList);
      }
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
   public String getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/getElementsByTagNameNS01";
   }
   /**
    * Runs this test from the command line.
    * @param args command line arguments
    */
   public static void main(final String[] args) {
        DOMTestCase.doMain(getElementsByTagNameNS01.class, args);
   }
}

redpajama_set_name: RedPajamaGithub


text:
checkstack
##########

checkstack is a tool for verifying `OpenStack`_
installations.

.. _`OpenStack` : http://www.openstack.org


text: never write user sign up code again, ever.


text:
package warrant

import (
	"crypto/x509"
	"encoding/pem"
	"errors"
	"fmt"
	"strings"

	"github.com/golang-jwt/jwt"
)

// Token is the representation of a token within UAA.
type Token struct {
	// Algorithm is the method used to sign the token.
	Algorithm string

	// KeyID is the ID of the signing key used to sign this token.
	KeyID string

	// ClientID is the value given in the "client_id" field of the token claims.
	// This is the unique identifier of the client to whom this token was granted.
	ClientID string `json:"client_id"`

	// UserID is the value given in the "user_id" field of the token claims.
	// This is the unique identifier for the user.
	UserID string `json:"user_id"`

	// Scopes are the values given in the "scope" field of the token claims.
	// These values indicate the level of access granted by the user to this token.
	Scopes []string `json:"scope"`

	// Issuer is the UAA endpoint that generated the token.
	Issuer string `json:"iss"`

	// Segments contains the raw token segment strings.
	Segments TokenSegments
}

// Verify will use the given signing keys to verify the authenticity of the
// token. Supports RSA and HMAC siging methods.
func (t Token) Verify(signingKeys []SigningKey) error {
	for _, signingKey := range signingKeys {
		if signingKey.KeyId == t.KeyID {
			signingString := strings.Join([]string{t.Segments.Header, t.Segments.Claims}, ".")

			switch t.Algorithm {
			case jwt.SigningMethodRS256.Alg(), jwt.SigningMethodRS384.Alg(), jwt.SigningMethodRS512.Alg():
				method := jwt.GetSigningMethod(t.Algorithm)

				var err error
				key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(signingKey.Value))
				if err != nil {
					block, rest := pem.Decode([]byte(signingKey.Value))
					if len(rest) > 0 {
						return errors.New("public key is not valid PEM encoding")
					}

					key, err = x509.ParsePKCS1PublicKey(block.Bytes)
					if err != nil {
						return err
					}
				}

				return method.Verify(signingString, t.Segments.Signature, key)

			case jwt.SigningMethodHS256.Alg(), jwt.SigningMethodHS384.Alg(), jwt.SigningMethodHS512.Alg():
				method := jwt.GetSigningMethod(t.Algorithm)
				key := []byte(signingKey.Value)
				return method.Verify(signingString, t.Segments.Signature, key)

			default:
				return fmt.Errorf("unsupported token signing method: %s", t.Algorithm)
			}
		}
	}

	return errors.New("token was not signed by a known key")
}

// TokenSegments is the encoded token segments split into their named parts.
type TokenSegments struct {
	// Header is the raw token header segment.
	Header string

	// Claims is the raw token claims segment.
	Claims string

	// Signature is the raw token signature segment.
	Signature string
}


text:
<!--
    Copyright 2011 The Kuali Foundation

    Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php

    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.
-->
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog/1.9"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog/1.9 http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-1.9.xsd">

	<changeSet author="KFS41" id="FIX_BAD_PARAMETER_VALUES">
		<comment>Blank out SUPPRESS_REJECT_REASON_CODES_ON_EIRT_APPROVAL parameter value which has a bad value.
		KFSMI-6533 Update parameter CAPITAL_OBJECT_ACQUISITION_CODES from data set
		</comment>
		<update tableName="KRNS_PARM_T">
			<column name="TXT" value="" />
			<where>NMSPC_CD='KFS-PURAP' AND
				PARM_NM='SUPPRESS_REJECT_REASON_CODES_ON_EIRT_APPROVAL' AND
				PARM_DTL_TYP_CD='ElectronicInvoiceReject' AND APPL_NMSPC_CD='KFS'
			</where>
		</update>
		<update tableName="KRNS_PARM_T">
			<column name="TXT" value="F;G;S;T" />
			<where>NMSPC_CD='KFS-CAM' and PARM_DTL_TYP_CD='AssetGlobal' and
				PARM_NM='CAPITAL_OBJECT_ACQUISITION_CODES'</where>
		</update>
	</changeSet>

	<changeSet author="KFS41" id="FIX_PARAMETER_DESCRIPTIONS">
		<comment>KFSMI-6443 - revise FEDERAL_ONLY_ROUTE_IND description </comment>
		<update tableName="KRNS_PARM_T">
			<column name="PARM_DESC_TXT"
				value="If the value of this parameter is N, the document routes to project directors for all accounts appearing on the document. If the parameter is set to Y, then only project directors associated with Federal accounts will receive the document." />
			<where>NMSPC_CD= 'KFS-EC' and PARM_DTL_TYP_CD='EffortCertification'
				and PARM_NM='FEDERAL_ONLY_ROUTE_IND'</where>
		</update>
	</changeSet>

	<changeSet author="KFS41" id="REMOVE_OBSELETE_PARAMETERS">
		<comment>KFSMI-6526 Remove parameter W9_OWNERSHIP_TYPES from data set.</comment>
		<delete tableName="KRNS_PARM_T">
			<where>NMSPC_CD="KFS-FP" AND PARM_DTL_TYP_CD="DisbursementVoucher"
				AND PARM_NM="W9_OWNERSHIP_TYPES"</where>
		</delete>
	</changeSet>

	<changeSet author="KFS41" id="NEW_ENDOWMENT_PARAMETERS">
		<comment>KFSMI-6408 Create new system parameters for Endowment Batch Job</comment>
		<insert tableName="KRNS_PARM_T">
			<column name="NMSPC_CD" value="KFS-ENDOW" />
			<column name="PARM_DTL_TYP_CD" value="GeneralLedgerInterfaceBatchProcessStep" />
			<column name="PARM_NM" value="COMBINE_ENDOWMENT_GL_ENTRIES_IND" />
			<column name="OBJ_ID" value="KFS681" />
			<column name="VER_NBR" valueNumeric="1" />
			<column name="PARM_TYP_CD" value="CONFG" />
			<column name="TXT" value="Y" />
			<column name="PARM_DESC_TXT"
				value="If this value is Y then all transactions of the same type to the same General Ledger will be entered as one total for the daily interface If this value is N,then entries will be made for each transaction as a unique general ledger line entry" />
			<column name="CONS_CD" value="A" />
			<column name="APPL_NMSPC_CD" value="KFS" />
		</insert>
		<insert tableName="KRNS_PARM_T">
			<column name="NMSPC_CD" value="KFS-ENDOW" />
			<column name="PARM_DTL_TYP_CD" value="GeneralLedgerInterfaceBatchProcessStep" />
			<column name="PARM_NM" value="CASH_SALE_GAIN_LOSS_OBJECT_CODE" />
			<column name="OBJ_ID" value="KFS682" />
			<column name="VER_NBR" valueNumeric="1" />
			<column name="PARM_TYP_CD" value="CONFG" />
			<column name="PARM_DESC_TXT"
				value="This value is used to generate the gain or loss general ledger entries that result from the cash sale of a KEM security These gains or losses are realized gains and losses for the KEMID" />
			<column name="CONS_CD" value="A" />
			<column name="APPL_NMSPC_CD" value="KFS" />
		</insert>
	</changeSet>

	<changeSet author="KFS41" id="NEW_ENDOWMENT_PARAMETERS">
		<comment>KFSMI-6443 Create System parameter for Effort Certification FEDERAL_SPONSOR_TYPE_CODE</comment>
		<insert tableName="KRNS_PARM_T">
			<column name="NMSPC_CD" value="KFS-EC" />
			<column name="PARM_DTL_TYP_CD" value="EffortCertification" />
			<column name="PARM_NM" value="FEDERAL_SPONSOR_TYPE_CODES" />
			<column name="OBJ_ID" value="KFS683" />
			<column name="VER_NBR" valueNumeric="1" />
			<column name="PARM_TYP_CD" value="CONFG" />
			<column name="PARM_DESC_TXT"
				value="This parameter defines the sponsor types that are considered Federal It is referenced along with the FEDERAL_ONLY_ROUTE_IND parameter to determine how ECD documents are routed" />
			<column name="CONS_CD" value="A" />
			<column name="APPL_NMSPC_CD" value="KFS" />
		</insert>
	</changeSet>
</databaseChangeLog>


text:
module TestEnsembleMethods

include(joinpath("..", "fixture_learners.jl"))
using .FixtureLearners
nfcp = NumericFeatureClassification()

using FactCheck

importall Orchestra.Transformers.EnsembleMethods
import Orchestra.Transformers.DecisionTreeWrapper: fit!, transform!
import Orchestra.Transformers.DecisionTreeWrapper: PrunedTree
import Orchestra.Transformers.DecisionTreeWrapper: RandomForest
import Orchestra.Transformers.DecisionTreeWrapper: DecisionStumpAdaboost

facts("Ensemble learners") do
  context("VoteEnsemble predicts according to majority") do
    always_a_options = { :label => "a" }
    always_b_options = { :label => "b" }
    learner = VoteEnsemble({
      :learners => [
        AlwaysSameLabelLearner(always_a_options),
        AlwaysSameLabelLearner(always_a_options),
        AlwaysSameLabelLearner(always_b_options)
      ]
    })
    fit!(learner, nfcp.train_instances, nfcp.train_labels)
    predictions = transform!(learner, nfcp.test_instances)
    expected_predictions = fill("a", size(nfcp.test_instances, 1))

    @fact predictions => expected_predictions
  end

  context("StackEnsemble predicts with combined learners") do
    # Fix random seed, due to stochasticity in stacker.
    srand(2)

    always_a_options = { :label => "a" }
    learner = StackEnsemble({
      :learners => [
        AlwaysSameLabelLearner(always_a_options),
        AlwaysSameLabelLearner(always_a_options),
        PerfectScoreLearner()
      ],
      :keep_original_features => true
    })
    fit!(learner, nfcp.train_instances, nfcp.train_labels)
    predictions = transform!(learner, nfcp.test_instances)
    unexpected_predictions = fill("a", size(nfcp.test_instances, 1))

    @fact predictions => not(unexpected_predictions)
  end

  context("BestLearner picks the best learner") do
    always_a_options = { :label => "a" }
    always_b_options = { :label => "b" }
    learner = BestLearner({
      :learners => [
        AlwaysSameLabelLearner(always_a_options),
        PerfectScoreLearner(),
        AlwaysSameLabelLearner(always_b_options)
      ]
    })
    fit!(learner, nfcp.train_instances, nfcp.train_labels)

    @fact learner.model[:best_learner_index] => 2
  end

  context("BestLearner conducts grid search") do
    learner = BestLearner({
      :learners => [PrunedTree(), DecisionStumpAdaboost(), RandomForest()],
      :learner_options_grid => [
        {
          :impl_options => {
            :purity_threshold => [0.5, 1.0]
          }
        },
        Dict(),
        {
          :impl_options => {
            :num_trees => [5, 10, 20],
            :partial_sampling => [0.5, 0.7]
          }
        }
      ]
    })
    fit!(learner, nfcp.train_instances, nfcp.train_labels)

    @fact length(learner.model[:learners]) => 8
  end
end

end # module


text:
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/tick.h>

#include <asm/pgtable.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/mmu.h>
#include <asm/cache.h>
#include <asm/pgalloc.h>

void (*powersave) (void) = NULL;

static inline void pm_idle(void)
{
	barrier();
}

void cpu_idle(void)
{
	set_thread_flag(TIF_POLLING_NRFLAG);

	/* endless idle loop with no priority at all */
	while (1) {
		tick_nohz_stop_sched_tick(1);

		while (!need_resched()) {
			check_pgt_cache();
			rmb();

			clear_thread_flag(TIF_POLLING_NRFLAG);

			local_irq_disable();
			/* Don't trace irqs off for idle */
			stop_critical_timings();
			if (!need_resched() && powersave != NULL)
				powersave();
			start_critical_timings();
			local_irq_enable();
			set_thread_flag(TIF_POLLING_NRFLAG);
		}

		tick_nohz_restart_sched_tick();
		preempt_enable_no_resched();
		schedule();
		preempt_disable();
	}
}


text:
title: AesiCompletionProcessor.getContextInformationAutoActivationCharacters - aesi-eclipse
---

[aesi-eclipse](../../index.html) / [com.virtlink.aesi.eclipse.codecompletion](../index.html) / [AesiCompletionProcessor](index.html) / [getContextInformationAutoActivationCharacters](.)

# getContextInformationAutoActivationCharacters

`open fun getContextInformationAutoActivationCharacters(): `[`CharArray`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-char-array/index.html)


text:
@implementation BBXDPasswordTextField

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.font = [UIFont systemFontOfSize:15];
        self.textColor = [UIColor colorWithRed:26/255.0 green:26/255.0 blue:26/255.0 alpha:1];  //#1a1a1a

        UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 38)];
        userNameLabel.font = [UIFont systemFontOfSize:15];
        userNameLabel.textColor = [UIColor colorWithRed:137/255.0 green:137/255.0 blue:137/255.0 alpha:1];  //#898989
        userNameLabel.text = NSLocalizedString(@"国家或地区", nil);
        userNameLabel.textAlignment = NSTextAlignmentLeft;
        self.leftView = userNameLabel;
        self.leftViewMode = UITextFieldViewModeAlways;
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    CGFloat bottomLineHeight = 0.5;
    CGRect bottomLineRect = CGRectMake(0, CGRectGetHeight(self.frame) - bottomLineHeight, CGRectGetWidth(self.frame), bottomLineHeight);

    UIColor *bottomLineColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];  //#ebebeb

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, bottomLineColor.CGColor);
    CGContextFillRect(context, bottomLineRect);
}

@end


text:
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.

// This file was modified by Oracle on 2013.
// Modifications copyright (c) 2013, Oracle and/or its affiliates.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_TEST_TOUCHES_HPP
#define BOOST_GEOMETRY_TEST_TOUCHES_HPP

#include <geometry_test_common.hpp>

#include <boost/geometry/core/ring_type.hpp>
#include <boost/geometry/algorithms/touches.hpp>
#include <boost/geometry/strategies/strategies.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/point_xy.hpp>

#include <boost/geometry/io/wkt/read.hpp>
#include <boost/variant/variant.hpp>

template <typename Geometry1, typename Geometry2>
void check_touches(Geometry1 const& geometry1,
                   Geometry2 const& geometry2,
                   std::string const& wkt1,
                   std::string const& wkt2,
                   bool expected)
{
    bool detected = bg::touches(geometry1, geometry2);

    BOOST_CHECK_MESSAGE(detected == expected,
        "touches: " << wkt1
        << " with " << wkt2
        << " -> Expected: " << expected
        << " detected: " << detected);

    detected = bg::touches(geometry2, geometry1);

    BOOST_CHECK_MESSAGE(detected == expected,
        "touches: " << wkt2
        << " with " << wkt1
        << " -> Expected: " << expected
        << " detected: " << detected);
}

template <typename Geometry1, typename Geometry2>
void test_touches(std::string const& wkt1,
        std::string const& wkt2, bool expected)
{
    Geometry1 geometry1;
    Geometry2 geometry2;

    bg::read_wkt(wkt1, geometry1);
    bg::read_wkt(wkt2, geometry2);

    boost::variant<Geometry1> v1(geometry1);
    boost::variant<Geometry2> v2(geometry2);

    check_touches(geometry1, geometry2, wkt1, wkt2, expected);
    check_touches(v1, geometry2, wkt1, wkt2, expected);
    check_touches(geometry1, v2, wkt1, wkt2, expected);
    check_touches(v1, v2, wkt1, wkt2, expected);
}

template <typename Geometry>
void check_self_touches(Geometry const& geometry,
                        std::string const& wkt,
                        bool expected)
{
    bool detected = bg::touches(geometry);

    BOOST_CHECK_MESSAGE(detected == expected,
        "touches: " << wkt
        << " -> Expected: " << expected
        << " detected: " << detected);
}

template <typename Geometry>
void test_self_touches(std::string const& wkt, bool expected)
{
    Geometry geometry;
    bg::read_wkt(wkt, geometry);
    boost::variant<Geometry> v(geometry);

    check_self_touches(geometry, wkt, expected);
    check_self_touches(v, wkt, expected);
}

#endif


text:
package com.rosendal.elevkarrosendal.fragments.feed.instagram;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.format.DateFormat;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.rosendal.elevkarrosendal.R;

import java.util.ArrayList;
import java.util.Calendar;

class InstaAdapter extends RecyclerView.Adapter<InstaAdapter.ViewHolder> {
    class ViewHolder extends RecyclerView.ViewHolder {
        TextView username, day, likes, caption;
        ImageView image;
        LinearLayout comments;
        String link;
        FrameLayout divider;

        public ViewHolder(View v) {
            super(v);

            username = (TextView) v.findViewById(R.id.username);
            day = (TextView) v.findViewById(R.id.date);
            likes = (TextView) v.findViewById(R.id.likes);
            caption = (TextView) v.findViewById(R.id.caption);
            comments = (LinearLayout) v.findViewById(R.id.llComments);
            image = (ImageView) v.findViewById(R.id.image);
            image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (link != null && !link.isEmpty()) {
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setData(Uri.parse(link));
                        c.startActivity(i);
                    }
                }
            });
            divider = (FrameLayout) v.findViewById(R.id.divider);
        }
    }

    private ArrayList<InstaPost> data;
    private Context c;

    public InstaAdapter(ArrayList<InstaPost> posts, Context context) {
        data = posts;
        c = context;
    }

    public void setData(ArrayList<InstaPost> list) {
        data = list;
        notifyDataSetChanged();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.insta_item, parent, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        InstaPost post = data.get(position);

        holder.likes.setText(post.likes + " likes");
        holder.day.setText(getTimeAgo(post.created, Calendar.getInstance().getTimeInMillis()));
        holder.username.setText(post.user);
        holder.link = post.link;
        holder.divider.setVisibility(post.comments.length > 0 ? View.VISIBLE : View.GONE);
        Glide.with(c).load(post.urlStandard).placeholder(R.drawable.loading).into(holder.image);

        if (post.caption != null && !post.caption.isEmpty()) {
            String caption = post.user + " " + post.caption;
            Spannable spannable = new SpannableString(caption);
            spannable.setSpan(new ForegroundColorSpan(ContextCompat.getColor(c, R.color.primary300)), 0, post.user.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.caption.setText(spannable, TextView.BufferType.SPANNABLE);
        }
        holder.comments.removeAllViews();
        for (Comment comment : post.comments) {
            holder.comments.addView(createCommentView(comment));
        }
    }

    private View createCommentView(Comment comment) {
        TextView view = new TextView(c);
        String text = comment.user + " " + comment.text;
        Spannable spannable = new SpannableString(text);
        spannable.setSpan(new ForegroundColorSpan(ContextCompat.getColor(c, R.color.primary300)), 0, comment.user.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        view.setText(spannable, TextView.BufferType.SPANNABLE);
        view.setPadding(0, 0, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, c.getResources().getDisplayMetrics()));
        return view;
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    private static final int SECOND_MILLIS = 1000;
    private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
    private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
    private static final int DAY_MILLIS = 24 * HOUR_MILLIS;

    public String getTimeAgo(long time, long time2) {
        if (time < 1000000000000L) {
            // if timestamp given in seconds, convert to millis
            time *= 1000;
        }

        if (time > time2 || time <= 0) {
            return null;
        }

        final long diff = time2 - time;
        if (diff < MINUTE_MILLIS) {
            return "just nu";
        } else if (diff < 50 * MINUTE_MILLIS) {
            return diff / MINUTE_MILLIS + "m";
        } else if (diff < 24 * HOUR_MILLIS) {
            return diff / HOUR_MILLIS + "h";
        } else if (diff < 6 * DAY_MILLIS) {
            return diff / DAY_MILLIS + "d";
        } else {
            java.text.DateFormat format = DateFormat.getDateFormat(c);
            return format.format(time);
        }
    }
}


text:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$this->title = 'Восстонавление пароля';
$this->params['breadcrumbs'][] = $this->title;
?>
Для восстановления пароля укажите свой Email.
<?= Html::beginForm(['forgot', 'id' => $id], 'post') ?>
<?= Html::input('text', 'email') ?>
<?= Html::submitButton('Отправить', ['class' => 'submit']) ?>
<?= Html::endForm() ?>


text:
import numpy
import sys

class BugPlacer(object):
    """
    Defines a dataset composed of a sequence of images of the
    specified dimensions (``gen.w`` by ``gen.h`` pixels). Each image
    contains a certain number of binary sprites or "bugs" scattered
    about. The ``gen`` parameter must be an iterator or an iterable
    such that:

       iter(gen) -> iterator of
           ((((x1, y1), bug1), ((x2, y2), bug2), ...), target)

    Where ``bugn`` is a :class:`Bug` object, ``0 <= xn < w``, ``0 <=
    yn < h``. ``BugPlacer`` will generate a scene where the top left
    pixel of the nth bug is positioned at ``(xn, yn)``
    coordinates. ``target`` is a tuple, list or vector of numbers
    representing the class(es) or target(s) associated to the
    scene. Additionally, ``gen`` must have the following attributes:

    - ``gen.w`` must be the width of the scene in pixels.

    - ``gen.h`` must be the height of the scene in pixels.

    - ``gen.nout`` must be the length of the target

    - ``gen.nclasses`` must be either ``None`` or a tuple, list or
      vectors of integers or ``None``, an integer at the nth position
      meaning that the nth target is a class identifier from 0 included
      to ``nclasses[n]`` excluded, ``None`` meaning that the nth target

    - ``gen.out_format`` must be 'array'

    - ``gen.out_dtype`` must be the dtype of the targets generated by
      iterating over ``iter(gen)`` (typically 'uint8', if the
      target(s) is(are) classes).

    The ``bugland.gen`` module contains generators corresponding to
    this interface.

    If ``collision_check`` is set to ``True``, no bugs' masks will
    overlap. This is done by rejection sampling: gen will be iterated
    over until it produces bugs at positions that do not lead to
    overlaps. For small images with large bugs or a lot of bugs, the
    rejection rate might be high. BugPlacer provides a method,
    ``self.rejection_rate()`` to have an estimate of the rejection
    rate for the samples generated up to the point the method is
    called. A warning will be issued during the generation of the very
    first sample if it takes more than 1000 tries, to help identify
    problems with placement.

    Another issue to be aware of with ``collision_check`` and
    rejection sampling is that the distribution of scenes might be
    biased as a result. For instance, if some bugs are larger than
    some others, scenes with them might be rejected at a greater
    frequency. Assymetrical bugs might be found more often at one side
    or corner than at the others, and so on. These biases might make
    learning easier. For the time being BugPlacer does not give
    feedback to the generator that might help it doing a counter-bias
    to guarantee certain important statistics. It is recommended to at
    least verify the distribution of classes.

    The dataset can be iterated over and yields (input, target) where
    input and target are vectors.
    """

    def __init__(self, gen, collision_check = False):
        self.gen = gen
        self.collision_check = collision_check

        self.w = gen.w
        self.h = gen.h
        self.nin = gen.w * gen.h
        assert gen.out_format == 'array'
        self.out_format = gen.out_format
        self.out_dtype = gen.out_dtype
        self.nout = gen.nout
        self.nclasses = gen.nclasses

        self.n_successes = 0
        self.n_rejections = 0

    def rejection_rate(self):
        """
        If collision_check is True, returns the rejection rate of the
        generator, which is the number of scenes that were rejected
        because of overlaps divided by the total number of scenes
        considered.
        """
        total = self.n_successes + self.n_rejections
        if total == 0:
            return None
        else:
            return float(self.n_rejections) / total

    def __iter__(self):

        gen = iter(self.gen)

        if self.collision_check:
            collider = numpy.zeros((self.h, self.w))

        while True:
            data = numpy.zeros((self.h, self.w))
            targets = numpy.zeros((self.nout,), dtype = self.out_dtype)
            if not self.collision_check:
                description, target = gen.next()
                for (x, y), bug in description:
                    data[y:y+bug.h, x:x+bug.w] = bug.patch
                targets[:] = target
                self.n_successes += 1

            else:
                ntrials = 0
                while True:
                    if self.n_successes == 0 and ntrials and ntrials % 1000 == 0:
                        print >> sys.stderr, "WARNING: Rejected %i candidates, could not yet fit a single scene together. You might want to generate larger images." % ntrials
                    ntrials += 1
                    description, target = gen.next()
                    collider.fill(0)

                    for (x, y), bug in description:
                        a, b = y-bug.marginh, y+bug.h+bug.marginh
                        c, d = x-bug.marginw, x+bug.w+bug.marginw

                        if a < 0 or b >= self.h or c < 0 or d >= self.w:

                            ba, bb = (a < 0)*-a, bug.mh - (b >= self.h)*(b-self.h+1)
                            bc, bd = (c < 0)*-c, bug.mw - (d >= self.w)*(d-self.w+1)

                            a, b = max(0, a), min(b, self.h-1)
                            c, d = max(0, c), min(d, self.w-1)

                            collider[a:b, c:d] += bug.mask[ba:bb, bc:bd]
                        else:
                            collider[a:b, c:d] += bug.mask

                    if numpy.any(collider>1):
                        self.n_rejections += 1
                        continue
                    else:
                        for (x, y), bug in description:
                            data[y:y+bug.h, x:x+bug.w] = bug.patch
                        targets[:] = target
                        self.n_successes += 1
                        break

            yield data.reshape(self.nin), targets


text:
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module:       $HEADER$
-- Description:  Type restricted variants of functions from Data.Function
--               module, and more.
-- Copyright:    (c) 2015, Peter Trško
-- License:      BSD3
--
-- Maintainer:   peter.trsko@gmail.com
-- Stability:    experimental
-- Portability:  NoImplicitPrelude
--
-- Type restricted variants of functions from "Data.Function" module, and more.
module Data.Proxy.Function
    (
    -- * Type Proxies For Functions
      aFunction
    , aFunction2
    , aFunction3

    -- * Restrict Functions Using Type Proxies
    , resultOf
    , hasResultOf
    , argumentOf
    , hasArgumentOf

    -- * Restricted Versions of Standard Functions
    , idOf
    , forget
    , thatForgotten
    )
  where

import Data.Function (const, flip, id)
import Data.Proxy (Proxy(Proxy))

-- | Type proxy for unary function. Note that @b@ may be a function too. All
-- this type proxy says is that it is at least unary function.
aFunction :: Proxy (a -> b)
aFunction = Proxy
{-# INLINE aFunction #-}

-- | Type proxy for binary function. Note that @b@ may be a function too. All
-- this type proxy says is that it is at least binary function.
aFunction2 :: Proxy (a -> b -> c)
aFunction2 = Proxy
{-# INLINE aFunction2 #-}

-- | Type proxy for ternary function. Note that @b@ may be a function too. All
-- this type proxy says is that it is at least ternary function.
aFunction3 :: Proxy (a -> b -> c -> d)
aFunction3 = Proxy
{-# INLINE aFunction3 #-}

-- | Restrict type of result of a function. Flipped version of 'resultOf'.
--
-- @
-- \\f -> f `hasResultOf` 'Data.Proxy.Either.anEitherOf' 'Data.Proxy.String.string' 'Data.Proxy.Int.int'
--     :: (a -> Either String Word64) -> a -> Either String Int
-- @
--
-- @
-- 'Data.Typeable.cast' `hasResultOf` 'Data.Proxy.Maybe.aMaybeOf' 'Data.Proxy.Int.int'
--     :: Typeable a => a -> Maybe Int
-- @
hasResultOf :: (a -> b) -> Proxy b -> a -> b
hasResultOf = const
{-# INLINE hasResultOf #-}

-- | Restrict type of result of a function. Flipped version of 'hasResultOf'.
--
-- @
-- 'resultOf' ('Data.Proxy.Either.anEitherOf' 'Data.Proxy.String.string' 'Data.Proxy.Int.int')
--     :: (a -> Either String Word64) -> a -> Either String Int
-- @
--
-- @
-- 'resultOf' ('Data.Proxy.Maybe.aMaybeOf' 'Data.Proxy.Int.int') 'Data.Typeable.cast'
--     :: Typeable a => a -> Maybe Int
-- @
resultOf :: Proxy b -> (a -> b) -> a -> b
resultOf Proxy = id
{-# INLINE resultOf #-}

-- | Restrict type of an argument of a function. Flipped variant of
-- 'hasArgumentOf'.
argumentOf :: Proxy a -> (a -> b) -> a -> b
argumentOf Proxy = id
{-# INLINE argumentOf #-}

-- | Restrict type of an argument of a function. Flipped variant of
-- 'argumentOf'.
hasArgumentOf :: (a -> b) -> Proxy a -> a -> b
hasArgumentOf = const
{-# INLINE hasArgumentOf #-}

-- | Type restricted identity function 'id' defined as:
--
-- @
-- 'idOf' = 'flip' 'asProxyTypeOf'
-- @
--
-- Examples:
--
-- @
-- 'idOf' 'Data.Proxy.Word.word16' :: 'Data.Word.Word16' -> 'Data.Word.Word16'
-- @
idOf :: Proxy a -> a -> a
idOf Proxy = id
{-# INLINE idOf #-}

-- | Type restricted variant of 'const'.
--
-- @
-- 'forget' 'Data.Proxy.Exception.ioException' (return Nothing)
--     :: 'Control.Exception.IOException' -> IO (Maybe a)
-- @
forget :: Proxy b -> a -> b -> a
forget Proxy = const -- \p -> argumentOf p . const
{-# INLINE forget #-}

-- | Type restricted version of @'flip' 'const'@.
--
-- @
-- 'Data.Proxy.Exception.ioException' `thatForgotten` return Nothing
--     :: 'Control.Exception.IOException' -> IO (Maybe a)
-- @
thatForgotten :: Proxy a -> a -> b -> b
thatForgotten Proxy = flip const -- \p -> `argumentOf` flip const
{-# INLINE thatForgotten #-}


text:
class QuestionsController < ApplicationController
  load_and_authorize_resource

  before_filter -> { flash.now[:notice] = flash[:notice].html_safe if flash[:html_safe] && flash[:notice] }

  # loads the page showing details for a single question so that a user
  #   can review the answer and specify whether he/she knew the answer
  def show
    @feedback_active = !!current_user
    @new_answer = @question.answers.new
  end

  # loads the new question page, allowing user to enter a new question/answer combo in a form
  # a GET request to this endpoint with the qset={qset_id} param will set the default qset
  # in the form; if that is not present, check if there is a default qset specified in the
  # session cookies (e.g. by a previously created question). If no valid default qset can be
  # determined, do not set the default qset to anything (make user choose from available qsets)
  def new
    @question.answers.build
    # user-accessible qsets (qsets in the user's org) that can store questions
    # (note that the root/org qset is explicitly not included / allowed)
    @qsets = current_user.org.descendants
    if params[:qset]
      # if the request param is valid, use it
      selected_qset = get_valid_qset(@qsets, params[:qset].to_i)
    else
      # if we have a cookie, use it
      # (the to_i call returns nil if it's not a valid integer)
      cookie_default_qset_id = cookies[:new_question_qset_id].to_i
      if cookie_default_qset_id
        selected_qset = get_valid_qset(@qsets, cookie_default_qset_id)
      else
        # we don't have a valid cookie value for the default qset, so remove the cookie
        # (the UI will not set a default for it to be reset by the client)and
        cookies.delete :new_question_qset_id
        selected_qset = nil
      end
    end

    if selected_qset
      @question.qset_id = selected_qset.id
      @qset_name = selected_qset.name
    end
  end

  # handles the request to save a new question (called from the new question page)
  def create
    question = current_user.questions.new(question_params)
    question.answers.first.creator = current_user
    question.save

    # users get one vote for their own questions by default
    # (so their karma/score improves as they create questions)
    current_user.vote_for(question)

    msg = %Q[Your question has been submitted! View it #{view_context.link_to("here", qset_path(question_params[:qset_id]))}].html_safe
    redirect_to new_question_path, notice: msg, flash: { html_safe: true }
  end

  # handles the request to update an existing question (called from the edit question page)
  # Note: when question or answer is modified (updated_at changes), the other one doesn't necessarily get modified.
  #   If we wanted to change both every time either changed, we could use PUT instead of PATCH. However, we might
  #   not want to update both, because it would be good to know when the question has changed so the answer is now
  #   out-of-date, for example.
  def update
    @question.user_id = current_user.id
    @question.update(question_params)
    redirect_to qset_path(@question.qset), notice: "Your question has been updated!"
  end

  def destroy
    @question.destroy
    redirect_to qset_path(@question.qset)
  end

  def feedback
    if ['no', 'yes', 'maybe'].include? params[:correct]
      analyzer.info {"User #{current_user.id} answered #{params[:correct]} for question #{params[:id]}"}
      respond_to do |format|
        format.js { render :nothing => true }
      end
    end
  end

  def upvote
    current_user.vote_for(@question)
    respond_to do |format|
      format.js { render json: @question.plusminus }
    end
  end

  def downvote
    current_user.vote_against(@question)
    respond_to do |format|
      format.js { render json: @question.plusminus}
    end
  end

  private
  def question_params
    # todo: we may need to validate answers_attribute :id so user cannot update someone else's answers
    params.require(:question).permit(:text, :qset_id, answers_attributes: [:id, :text, '_destroy'])
  end

  # helper method for checking if a Qset with a given id is a member of a list of Qsets
  # returns the matching Qset in an array (list) of Qsets (matches by id)
  # if no Qset is found for qset_id, returns nil
  def get_valid_qset(qset_list, qset_id)
    index = qset_list.find_index {|qset| qset.id == qset_id}
    if index
      qset_list[index]
    else
      nil
    end
  end
end


text:
package net.je2sh.spring;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import net.je2sh.spring.rest.JeeshRestOptions;
import net.je2sh.spring.rest.RestTerminalProvider;
import org.jline.terminal.Terminal;
import org.jline.terminal.impl.ExternalTerminal;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContextHolder;

@Configuration
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
@ConditionalOnWebApplication
@EnableConfigurationProperties(JeeshRestOptions.class)
@ComponentScan("net.je2sh.spring.rest")
public class JeeshRestAutoConfiguration {

    @Configuration
    @ConditionalOnClass(SecurityContextHolder.class)
    @Order(1001)
    public static class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().ignoringAntMatchers("/jeesh/**");
        }
    }

    @Bean
    @ConditionalOnMissingBean(RestTerminalProvider.class)
    public RestTerminalProvider terminalProvider() {
        return (InputStream in, OutputStream out) -> new ExternalTerminal("Je2sh Terminal", "TERM",
                                                                          in, out,
                                                                          StandardCharsets.UTF_8
                                                                                .name(),
                                                                          Terminal.SignalHandler.SIG_DFL);
    }

}


text:
package org.openeos.services.ui.form.abstractform;

import org.abstractform.binding.fluent.BFAbstractPresenter;
import org.openeos.services.ui.UIBean;
import org.openeos.services.ui.internal.UIBeanImpl;

/**
 * @author Fernando Rincon Martin <frm.rincon@gmail.com>
 *
 */
public class UIPresenter<S> extends BFAbstractPresenter<UIBean> {

	private Class<S> beanClass;
	private UIBean uiBean;

	public UIPresenter(Class<S> beanClass, UIBean uiBean) {
		super(uiBean);
		this.beanClass = beanClass;
		this.uiBean = uiBean;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.abstractform.binding.BPresenter#getPropertyValue(java.lang.String)
	 */
	@Override
	public Object getPropertyValue(String propertyName) {
		return uiBean == null ? null : uiBean.get(propertyName);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.abstractform.binding.BPresenter#setPropertyValue(java.lang.String,
	 * java.lang.Object)
	 */
	@Override
	public void setPropertyValue(String propertyName, Object value) {
		uiBean.set(propertyName, value);
	}

	public Class<?> getBeanClass() {
		return beanClass;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.abstractform.binding.BPresenter#fieldHasChanged(java.lang.String)
	 */
	@Override
	public void fieldHasChanged(String fieldId) {
		// Do nothing
	}

	public S getBeanWrapped() {
		return (S) ((UIBeanImpl) getModel()).getBeanWrapped();
	}

}


text:
define({
  "add": "Zum Hinzufügen hier klicken",
  "title": "Titel",
  "placeholderBookmarkName": "Lesezeichenname",
  "ok": "OK",
  "cancel": "Abbrechen",
  "warning": "Beenden Sie die Bearbeitung!",
  "edit": "Lesezeichen bearbeiten",
  "errorNameExist": "Lesezeichen ist vorhanden!",
  "errorNameNull": "Ungültiger Lesezeichenname!",
  "addBookmark": "Neue erstellen",
  "thumbnail": "Miniaturansicht",
  "thumbnailHint": "Zum Aktualisieren auf das Bild klicken",
  "displayBookmarksAs": "Lesezeichen anzeigen als",
  "cards": "Kacheln",
  "list": "Liste",
  "cardsTips": "Kachelansicht",
  "listTips": "Listenansicht",
  "makeAsDefault": "Als Standard festlegen",
  "default": "Standardeinstellung",
  "editable": "Das Hinzufügen von Lesezeichen im Widget zulassen",
  "alwaysSync": "Lesezeichen der Webkarte anzeigen",
  "configCustom": "Benutzerdefinierte Lesezeichen anzeigen",
  "import": "Importieren",
  "create": "Erstellen",
  "importTitle": "Lesezeichen importieren",
  "importFromWeb": "Lesezeichen aus der aktuellen Webkarte anzeigen",
  "selectAll": "Alles auswählen",
  "noBookmarkInConfig": "Klicken Sie auf "Importieren" oder "Neu erstellen", um Lesezeichen hinzuzufügen.",
  "noBookmarkInWebMap": "Auf der Karte ist kein Lesezeichen konfiguriert.",
  "extent": "Ausdehnung",
  "saveExtent": "Kartenausdehnung in diesem Lesezeichen speichern",
  "savelayers": "Layer-Sichtbarkeit speichern",
  "withVisibility": "Mit Layer-Sichtbarkeit",
  "bookmark": "Lesezeichen",
  "addBtn": "Hinzufügen",
  "deleteBtn": "Löschen",
  "editBtn": "Bearbeiten",
  "dragReorderTip": "Zur Neuanordnung halten und ziehen",
  "deleteBtnTip": "Das Lesezeichen löschen",
  "editBtnTip": "Das Lesezeichen bearbeiten"
});


text:
torquebox-zabbix-monitor
========================

monitors torquebox instance and pushes notification to zabbix

## Installation

    $ git clone https://github.com/lowang/torquebox-zabbix-monitor.git

Please change config/torquebox.yml to match your zabbix hostname, port and monitoring interval.

Then deploy it as:

    $ torquebox deploy torquebox-zabbix-monitor --env production

## Usage

Deploys to /monitoring context path, serves simple rack controller that present json data that are being monitored.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package org.springframework.boot.autoconfigure.couchbase;

import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseBucket;
import com.couchbase.client.java.cluster.ClusterInfo;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import org.junit.Rule;
import org.junit.Test;

import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

/**
 * Integration tests for {@link CouchbaseAutoConfiguration}.
 *
 * @author Stephane Nicoll
 */
public class CouchbaseAutoConfigurationIntegrationTests {

	private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
			.withConfiguration(
					AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
							CouchbaseAutoConfiguration.class));

	@Rule
	public final CouchbaseTestServer couchbase = new CouchbaseTestServer();

	@Test
	public void defaultConfiguration() {
		this.contextRunner.withPropertyValues("spring.couchbase.bootstrapHosts=localhost")
				.run((context) -> assertThat(context).hasSingleBean(Cluster.class)
						.hasSingleBean(ClusterInfo.class)
						.hasSingleBean(CouchbaseEnvironment.class)
						.hasSingleBean(Bucket.class));
	}

	@Test
	public void customConfiguration() {
		this.contextRunner.withUserConfiguration(CustomConfiguration.class)
				.withPropertyValues("spring.couchbase.bootstrapHosts=localhost")
				.run((context) -> {
					assertThat(context.getBeansOfType(Cluster.class)).hasSize(2);
					assertThat(context.getBeansOfType(ClusterInfo.class)).hasSize(1);
					assertThat(context.getBeansOfType(CouchbaseEnvironment.class))
							.hasSize(1);
					assertThat(context.getBeansOfType(Bucket.class)).hasSize(2);
				});
	}

	@Configuration
	static class CustomConfiguration {

		@Bean
		public Cluster myCustomCouchbaseCluster() {
			return mock(Cluster.class);
		}

		@Bean
		public Bucket myCustomCouchbaseClient() {
			return mock(CouchbaseBucket.class);
		}

	}

}


text:
class Devise::SessionsController < ApplicationController
  prepend_before_filter :require_no_authentication, :only => [ :new, :create ]
  prepend_before_filter :allow_params_authentication!, :only => :create
  prepend_before_filter :clear_locale, :only => [:create]
  prepend_before_filter :strip_whitespace, :only => [:create]
  include Devise::Controllers::InternalHelpers
  layout :select_layout

  # GET /resource/sign_in
  def new
    resource = build_resource
    clean_up_passwords(resource)
    if SystemConfiguration.isWebOPAC
      render :template => 'page/403', :status => 403
      return
    end
    if params[:opac]
      respond_with_navigational(resource, stub_options(resource)){render  :template => 'opac/devise/sessions/new'}
    else
      respond_with_navigational(resource, stub_options(resource)){ render_with_scope :new }
    end
  end

  # POST /resource/sign_in
  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)

    if params[:opac]
      respond_with resource, :location => opac_path
    else
      respond_with resource, :location => after_sign_in_path_for(resource)
    end
  end

  # DELETE /resource/sign_out
  def destroy
    signed_in = signed_in?(resource_name)
    if params[:opac]
      redirect_path = opac_path
    else
      redirect_path = after_sign_out_path_for(resource_name)
    end
    Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
    set_flash_message :notice, :signed_out if signed_in

    # We actually need to hardcode this as Rails default responder doesn't
    # support returning empty response on GET request
    respond_to do |format|
      format.any(*navigational_formats) { redirect_to redirect_path }
      format.all do
        method = "to_#{request_format}"
        text = {}.respond_to?(method) ? {}.send(method) : ""
        render :text => text, :status => :ok
      end
    end
  end

  def select_layout
    if params[:opac]
      "opac"
    else
      "application"
    end
  end

  def strip_whitespace
    if params[:user]
      params[:user][:username] = params[:user][:username].strip if params[:user][:username]
      params[:user][:password] = params[:user][:password].strip if params[:user][:password]
    end
  end

  protected

  def stub_options(resource)
    methods = resource_class.authentication_keys.dup
    methods = methods.keys if methods.is_a?(Hash)
    methods << :password if resource.respond_to?(:password)
    { :methods => methods, :only => [:password] }
  end

  private
  def clear_locale
    session[:locale] = nil
  end
end


text:
#include "SyRenSimplified.h"

SyRenSimplified::SyRenSimplified()
  : _port(SyRenTXPinSerial)
{

}

SyRenSimplified::SyRenSimplified(Print& port)
  : _port(port)
{

}

void SyRenSimplified::motor(int power)
{
  byte command;
  power = constrain(power, -126, 126);
  command = (power < 0 ? 127 : 128) + power;
  _port.write(command);
}

void SyRenSimplified::motor(byte motor_, int power)
{
  if (motor_ == 1) { motor(power); }
}

void SyRenSimplified::stop()
{
  motor(0);
}


text:
ANT_ERROR			="*** Error: ant not found or not on your PATH"
JAVA_ERROR			="*** Error: javac not found or not on your PATH"
JAVAC_ERROR			="*** Error: javac not found or not on your PATH"
JAVA_VERSION_ERROR	="*** Error: Wrong java version. Need >=1.6"

.PHONY: all configure build-check dist install clean

##
# Main Target:

all: dist

vlet: dist

vlet-all: dist-all

##
# Do some basic sanity checks, so user is informed at an early stage
# (this should be handled by ./configure)

build-check:
	@echo "=== VLET Makefile ==="
	@echo " This is a wrapper for the ant build files"
	@echo "===               ==="
	@which ant >/dev/null || (echo ${ANT_ERROR} ; exit 1)
	@which java >/dev/null || (echo ${JAVA_ERROR} ; exit 1)
	@which javac >/dev/null || (echo ${JAVAC_ERROR} ; exit 1)

#disabled:
#@[ `java -version 2>&1 | grep version | sed "s/[^0-9]*[0-9]\.\([0-9]\).*/\1/"` -ge 6 ] || (echo ${JAVA_VERSION_ERROR} && exit 1)

##
# Build distribution
# The default build will build the distribution in 'dist'
# The 'make install' command will copy this installation in the 'prefix-dir'.

dist: build-check
	ant -f build.xml dist-install

dist-all: build-check
	ant -f build.xml dist-install-all

##
# Optional configure (without, defaults will be assumed)

configure:
	ant -f build.xml bin-install

##
# Check/Test
#

check: test-dist

test: test-dist

test-dist:
	ant -f build.xml test-dist

##
# install (binary) distribution into prefix dir.
#
install:
	ant -Dproject.destdir=${DESTDIR} -Dproject.install.docdir=${docdir} -f build.xml bin-install

##
# clean targets

clean:
	ant -f build.xml  clean

dist-clean:
	ant -f build.xml  dist-clean


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

namespace Archimedes.Geometry.Primitives
{
    /// <summary>
    /// Collision parts of Arc implementation
    /// </summary>
    public partial class Arc
    {

        #region Rectangle2

        /// <summary>
        /// Checks if a Rectangle collides with the Arc.
        /// </summary>
        /// <param name="rect">Rectangle to check</param>
        /// <returns>On collision, true is returned, false otherwise</returns>
        private bool InterceptWithPolygon(Polygon2 polygon, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var borderLines = polygon.ToLines(); //get 4 borderlines from rect
            if (borderLines != null) {
                return InterceptLinesWith(borderLines, tolerance);
            }
            return false;
        }

        /// <summary>Checks if a Rectangle collides with the Arc.
        ///
        /// </summary>
        /// <param name="rect">Rectangle to check</param>
        /// <returns>On collision, a List of interception Points is returned</returns>
        private List<Vector2> InterceptPolygon(Polygon2 polygon, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var intersections = new List<Vector2>();
            var borderLines = polygon.ToLines(); //get 4 borderlines from rect
            if (borderLines != null) {
                intersections.AddRange(InterceptLines(borderLines, tolerance));
            }
            return intersections;
        }

        #endregion

        #region Arc - AARectangle

        /// <summary>
        /// Checks if a Rectangle collides with the Arc.
        /// </summary>
        /// <param name="rect">Rectangle to check</param>
        /// <returns>On collision, true is returned, false otherwise</returns>
        private bool InterceptRectWith(AARectangle rect, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {

            var borderLines = LineSegment2.FromRectangle(rect); //get 4 borderlines from rect
            if (borderLines != null) {
                return InterceptLinesWith(borderLines, tolerance);
            }
            return false;
        }

        /// <summary>Checks if a Rectangle collides with the Arc.
        ///
        /// </summary>
        /// <param name="rect">Rectangle to check</param>
        /// <returns>On collision, a List of interception Points is returned</returns>
        private List<Vector2> InterceptRect(AARectangle rect, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var intersections = new List<Vector2>();
            var borderLines = LineSegment2.FromRectangle(rect); //get 4 borderlines from rect
            if (borderLines != null) {
                intersections.AddRange(InterceptLines(borderLines, tolerance));
            }
            return intersections;
        }

        #endregion

        #region Arc - Line

        /// <summary>
        /// Arc-Line Interception
        /// </summary>
        /// <param name="uLine">Line to check</param>
        /// <param name="tolerance"></param>
        /// <returns>Returns the interception Point(s) if the Objects collide</returns>
        private List<Vector2> InterceptLine(LineSegment2 uLine, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var intersections = new List<Vector2>();

            // Stretch the line on both ends by tolerance
            // TODO Is this still necessary??
            var strechtedLine = (uLine.Clone() as LineSegment2);
            strechtedLine.Stretch(tolerance, Direction.LEFT);
            strechtedLine.Stretch(tolerance, Direction.RIGHT);
            uLine = strechtedLine;

            // Intersect with a circle and test inter points if they lie on our arc
            var circle = new Circle2(this.MiddlePoint, this.Radius);
            foreach (var possiblePnt in circle.Intersect(uLine, tolerance))
            {
                if (this.Contains(possiblePnt, tolerance))
                {
                    intersections.Add(possiblePnt);
                }
            }

            return intersections;
        }

        /// <summary>
        /// Arc - Line Collision
        /// </summary>
        /// <param name="uLine">Line to check</param>
        /// <returns>Returns true, if the objects collide, false otherwise</returns>
        private bool InterceptLineWith(LineSegment2 uLine, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            return InterceptLine(uLine, tolerance).Any();
        }

        private List<Vector2> InterceptLines(IEnumerable<LineSegment2> lines, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var intersections = new List<Vector2>();
            foreach (var border in lines)
            {
                intersections.AddRange(this.InterceptLine(border, tolerance));
            }
            return intersections;
        }

        private bool InterceptLinesWith(IEnumerable<LineSegment2> lines, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var intersections = new List<Vector2>();
            foreach (var border in lines)
            {
                if (this.InterceptLine(border, tolerance).Count != 0)
                {
                    return true;
                }
            }
            return false;
        }

        #endregion

        #region Arc - Circle

        private IEnumerable<Vector2> InterceptCircle(Circle2 circle, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var intersections = new List<Vector2>();

            var possibles = this.ToCircle().Intersect(circle, tolerance);
            foreach (var p in possibles)
            {
                if (this.Contains(p, tolerance))
                {
                    intersections.Add(p);
                }
            }

            return intersections;
        }

        private bool InterceptCircleWith(Circle2 circle, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var possibles = this.ToCircle().Intersect(circle, tolerance);
            foreach (var p in possibles)
            {
                if (this.Contains(p, tolerance)) return true;

            }
            return false;
        }

        #endregion

        #region Arc - Arc

        private IEnumerable<Vector2> InterceptArc(Arc arc, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var intersections = new List<Vector2>();
            var c1 = this.ToCircle();
            var c2 = arc.ToCircle();

            var possibles = c1.Intersect(c2, tolerance);

            foreach (var p in possibles)
            {
                if (this.Contains(p, tolerance) && arc.Contains(p, tolerance))
                    intersections.Add(p);
            }

            return intersections;
        }

        private bool InterceptArcWith(Arc arc, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var c1 = this.ToCircle();
            var c2 = arc.ToCircle();
            var possibles = c1.Intersect(c2, tolerance);

            foreach (var p in possibles)
            {
                if (this.Contains(p, tolerance) && arc.Contains(p, tolerance))
                    return true;
            }

            return false;
        }

        #endregion

        public bool HasCollision(IGeometry other, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            if (other is LineSegment2)
            {
                return this.InterceptLineWith(other as LineSegment2, tolerance);
            }
            else if (other is Circle2)
            {
                return this.InterceptCircleWith(other as Circle2, tolerance);
            }
            else if (other is Rectangle2)
            {
                return this.InterceptWithPolygon(((Rectangle2)other).ToPolygon2(), tolerance);
            }
            else if (other is Arc)
            {
                return this.InterceptArcWith(other as Arc, tolerance);
            }
            else
            {
                return other.HasCollision(this, tolerance);
            }
        }

        public IEnumerable<Vector2> Intersect(IGeometry other, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            var pnts = new List<Vector2>();

            if (other is LineSegment2)
            {
                pnts.AddRange(this.InterceptLine(other as LineSegment2, tolerance));
            }
            else if (other is Rectangle2)
            {
                pnts.AddRange(this.InterceptPolygon(((Rectangle2)other).ToPolygon2(), tolerance));
            }
            else if (other is Polygon2)
            {
                pnts.AddRange(this.InterceptPolygon(other as Polygon2, tolerance));
            }
            else if (other is Circle2)
            {
                pnts.AddRange(this.InterceptCircle(other as Circle2, tolerance));
            }
            else if (other is Arc)
            {
                pnts.AddRange(this.InterceptArc(other as Arc, tolerance));
            }
            else
            {
                if (other is IShape)
                    pnts.AddRange(((IShape)other).ToPolygon2().Intersect(this, tolerance));
            }
            return pnts;
        }

        /// <summary>
        /// Does a Point lie on the Arc line?
        /// </summary>
        /// <param name="point"></param>
        /// <param name="tolerance"></param>
        /// <returns></returns>
        public bool Contains(Vector2 point, double tolerance = GeometrySettings.DEFAULT_TOLERANCE)
        {
            bool conatins = false;

            // First, the distance from middlepoint to our Point must be equal to the radius:
            var distance = LineSegment2.CalcLenght(this.MiddlePoint, point);
            if (Math.Abs(distance - this.Radius) < tolerance)
            {
                // If this is true, we only need to check if we are in the arc angle

                var bowMiddle = this.GetPointOnArc(this.Angle/2);
                var l1 = new LineSegment2(this.Location, bowMiddle);
                var l2 = new LineSegment2(this.GetPointOnArc(this.Angle), bowMiddle);
                var intersection = new LineSegment2(this.MiddlePoint, point);

                conatins = intersection.IntersectLine(l1, tolerance).HasValue || intersection.IntersectLine(l2, tolerance).HasValue;

            }
            return conatins;
        }
    }
}


text:
@interface MUKContentLoggerMiddleware : NSObject <MUKContentMiddleware>
@end


text:
/* First, create two variables that will hold:
1. The different types of layers available to Mapbox and their respective
opacity attributes
2. The possible alignments which could be applied to the vignettes */

var layerTypes = {
    'fill': ['fill-opacity'],
    'line': ['line-opacity'],
    'circle': ['circle-opacity', 'circle-stroke-opacity'],
    'symbol': ['icon-opacity', 'text-opacity'],
    'raster': ['raster-opacity'],
    'fill-extrusion': ['fill-extrusion-opacity']
}
var alignments = {
    'left': 'lefty',
    'center': 'centered',
    'right': 'righty',
    'full':'fully'
}

/* These two functions help turn on and off individual layers (through their
opacity attributes):
The first one gets the type of layer (from a name specified on the config.js file)
The second one adjusts the layer's opacity */

function getLayerPaintType(layer) {
    var layerType = map.getLayer(layer).type;
    return layerTypes[layerType];
}
function setLayerOpacity(layer) {
    var paintProps = getLayerPaintType(layer.layer);
    paintProps.forEach(function (prop) {
        map.setPaintProperty(layer.layer, prop, layer.opacity);
    });
}

/* Next, these variables and functions create the story and vignette html
elements, and populate them with the content from the config.js file.
They also assign a css class to certain elements, also based on the
config.js file */

// Main 'story' and 'features' elements
var story = document.getElementById('story');
var features = document.createElement('div');
features.classList.add(alignments[config.alignment]);
features.setAttribute('id', 'features');

// Main 'header' element
var header = document.createElement('div');

// If the content exists, assign it to the 'header' element
if (config.toptitle) {
    var toptitle = document.createElement('h4');
    toptitle.innerText = config.toptitle;
    header.appendChild(toptitle);
}
if (config.title) {
    var titleText = document.createElement('h1');
    titleText.innerText = config.title;
    header.appendChild(titleText);
}
if (config.byline) {
    var bylineText = document.createElement('p');
    bylineText.classList.add("byline");
    bylineText.innerText = config.byline;
    header.appendChild(bylineText);
}
if (config.description) {
    var descriptionText = document.createElement('p');
    descriptionText.innerHTML = config.description;
    header.appendChild(descriptionText);
}

// If the header has anything in it, it gets appended to the story
if (header.innerText.length > 0) {
    header.classList.add(config.theme);
    header.setAttribute('id', 'header');
    story.appendChild(header);
}

/* After building the elements and assigning content to the header these
functions will loop through the chapters in the config.js file,
create the vignette elements and assign them their respective content */

config.chapters.forEach((record, idx) => {
    /* These first two variables will hold each vignette, the chapter
    element will go in the container element */
    var container = document.createElement('div');
    var chapter = document.createElement('div');

    // Creates the title for the vignettes
    if (record.title) {
        var title = document.createElement('h3');
        title.innerText = record.title;
        chapter.appendChild(title);
    }

    // Creates the image for the vignette
    if (record.image) {
        var image = new Image();
        image.src = record.image;
        chapter.appendChild(image);
    }

    // Creates the image credit for the vignette
    if (record.imageCredit) {
        var imageCredit = document.createElement('p');
        imageCredit.classList.add('imageCredit');
        imageCredit.innerHTML = 'Image credit: ' + record.imageCredit;
        chapter.appendChild(imageCredit);
    }
    // Creates the description for the vignette
    if (record.description) {
        var story = document.createElement('p');
        story.innerHTML = record.description;
        chapter.appendChild(story);
    }
    // Sets the id for the vignette and adds the step css attribute
    container.setAttribute('id', record.id);
    container.classList.add('step');
    if (idx === 0) {
        container.classList.add('active');
    }
    // Sets the overall theme to the chapter element
    chapter.classList.add(config.theme);
    /* Appends the chapter to the container element and the container
    element to the features element */
    container.appendChild(chapter);
    container.classList.add(alignments[record.alignment] || "lefty");
    features.appendChild(container);
});

// Appends the features element (with the vignettes) to the story element
story.appendChild(features);

/* Next, this section creates the footer element and assigns it
its content based on the config.js file */

var footer = document.createElement('div');
// This assigns all the content to the footer element
if (config.footer) {
    var footerText = document.createElement('p');
    footerText.innerHTML = config.footer + '<br>' + config.footerAttribution;
    footer.appendChild(footerText);
}
// If the footer element contains any content, add it to the story
if (footer.innerText.length > 0) {
    footer.classList.add(config.theme);
    footer.setAttribute('id', 'footer');
    story.appendChild(footer);
}

// Adds the Mapbox access token
mapboxgl.accessToken = config.accessToken;

// Honestly, don't know what this does
const transformRequest = (url) => {
    const hasQuery = url.indexOf("?") !== -1;
    const suffix = hasQuery ? "&pluginName=journalismScrollytelling" : "?pluginName=journalismScrollytelling";
    return {
        url: url + suffix
    }
}

/* This section creates the map element with the
attributes from the main section of the config.js file */

var map = new mapboxgl.Map({
    container: 'map',
    style: config.style,
    center: config.chapters[0].location.center,
    zoom: config.chapters[0].location.zoom,
    bearing: config.chapters[0].location.bearing,
    pitch: config.chapters[0].location.pitch,
    scrollZoom: false,
    transformRequest: transformRequest
});

// Instantiates the scrollama function
var scroller = scrollama();

/* Here we add the two extra layers we are using, just like in our previous
tutorial. At the end, however, we setup the functions that will tie the
scrolling to the chapters and move the map from one location to another
while changing the zoom level, pitch and bearing */

map.on("load", function () {
    // This is the function that finds the first symbol layer
    var layers = map.getStyle().layers;
    var firstSymbolId;
    for (var i = 0; i < layers.length; i++) {
        if (layers[i].type === 'symbol') {
            firstSymbolId = layers[i].id;
            break;
        }
    }

map.loadImage("./images/lineIcon.png", function (error, image){
    if (error) throw error;
    map.addImage("lineIcon", image);
  });

// Add NYC Buffalo layer
map.addLayer({
    'id': 'BuffaloPosition',
    'type': 'fill',
    'source': {
        'type': 'geojson',
        'data': 'data/01_Buffalo_NYC.geojson'
    },
    'paint': {
        'fill-color':  '#17b2ff',
    }
}, firstSymbolId);

// Add BuffaloOutline layer
    map.addLayer({
        'id': 'BuffaloOutline',
        'type': 'line',
        'source': {
            'type': 'geojson',
            'data': 'data/01_Buffalo_NYC.geojson'
        },
        'paint': {
            'line-color':  '#17b2ff',
            'line-width': 5
        }
    }, firstSymbolId);

// Add Erie Demographic layer
map.addLayer({
    'id': 'DemoMapofBuffalo1',
    'type': 'fill',
    'source': {
        'type': 'geojson',
        'data': 'data/ErieDemographic.geojson'
    },
    'paint': {
        'fill-color': ['step', ['get', 'Race White'],
        '#ffffff',
        1000,'#e7f2fe',
        2000,'#cee5fd',
        3000,'#b6d8fc',
        4000,'#9ecafa',
        5000,'#85bdf9',
        6000,'#6db0f8',
        7000,'#55a3f7',
        8000,'#3c96f6',
        9000,'#2489f5',
        10000,'#0b7cf4'],
        'fill-opacity': 0.2
    }
}, firstSymbolId);

map.addLayer({
    'id': 'DemoMapofBuffalo2',
    'type': 'fill',
    'source': {
        'type': 'geojson',
        'data': 'data/ErieDemographic.geojson'
    },
    'paint': {
        'fill-color': ['step', ['get', 'Race Asian'],
        '#ffffff',
        1000,'#e7f2fe',
        2000,'#cee5fd',
        3000,'#b6d8fc',
        4000,'#9ecafa',
        5000,'#85bdf9',
        6000,'#6db0f8',
        7000,'#55a3f7',
        8000,'#3c96f6',
        9000,'#2489f5',
        10000,'#0b7cf4'],
        'fill-opacity': 0.2
    }
}, firstSymbolId);

map.addLayer({
    'id': 'DemoMapofBuffalo3',
    'type': 'fill',
    'source': {
        'type': 'geojson',
        'data': 'data/ErieDemographic.geojson'
    },
    'paint': {
        'fill-color': ['step', ['get', 'Race Hispanic or Latino'],
        '#ffffff',
        1000,'#e7f2fe',
        2000,'#cee5fd',
        3000,'#b6d8fc',
        4000,'#9ecafa',
        5000,'#85bdf9',
        6000,'#6db0f8',
        7000,'#55a3f7',
        8000,'#3c96f6',
        9000,'#2489f5',
        10000,'#0b7cf4'],
        'fill-opacity': 0.2
    }
}, firstSymbolId);

map.addLayer({
    'id': 'DemoMapofBuffalo4',
    'type': 'fill',
    'source': {
        'type': 'geojson',
        'data': 'data/ErieDemographic.geojson'
    },
    'paint': {
        'fill-color': ['step', ['get', 'Race African American'],
        '#ffffff',
        1000,'#e7f2fe',
        2000,'#cee5fd',
        3000,'#b6d8fc',
        4000,'#9ecafa',
        5000,'#85bdf9',
        6000,'#6db0f8',
        7000,'#55a3f7',
        8000,'#3c96f6',
        9000,'#2489f5',
        10000,'#0b7cf4'],
        'fill-opacity': 0.2
    }
}, firstSymbolId);

// Add HighlightedNeighborhood layer
map.addLayer({
    'id': 'HighlightedNeighborhood',
    'type': 'circle',
    'source': {
        'type': 'geojson',
        'data': 'data/Three-Neighborhoods.geojson'
    },
    'paint': {
        'circle-color':  '#1ad1ff',
        'circle-stroke-color': '#ffffff',
        'circle-stroke-width': 0.5,
        'circle-radius': 8
    }
}, firstSymbolId);

// Add FivePoints layer

map.addLayer({
    id: "FivePointsLabel",
    type: "symbol",
    source: {
      type: "geojson",
      data: "data/Label1.geojson",
    },
    layout: {
      "icon-image": "lineIcon",
      "icon-size": 0.5,
      "icon-anchor": "bottom-left",
      "icon-offset": [5, 0],
      "text-field": [
        "format",
        ["upcase", ["get", "Company"]],
        {
          "font-scale":0.8,
        },
        "\n",
        {},
        ["get", "businessTy"],
        {
          "font-scale": 0.7,
        },
      ],
      "text-justify": "left",
      "text-anchor": "top-left",
      "text-offset": [0.7, -6],
      "text-font": ["literal", ["Oswald Regular"]],
      "text-padding": 1,
    },
    paint: {
      "text-color": "#e6f7ff",
      "text-halo-color": "#e6f7ff",
      "text-halo-width": 0.2,
      "icon-halo-color": "white",
      "icon-halo-width": 1,
    },
  },
  "state-label"
  );

  map.addLayer(
    {
      id: "FivePointsExtrusion",
      type: "fill-extrusion",
      source: {
        type: "geojson",
        data: "data/Label1.geojson",
      },
      paint: {
        "fill-extrusion-opacity": 0,
        "fill-extrusion-height": ["*", 0.002, ["get", "heightroof"]],
        "fill-extrusion-color": "#6db0f8",
      },
    },
  );

// Add Emerson layer

map.addLayer({
    id: "EmersonLabel",
    type: "symbol",
    source: {
      type: "geojson",
      data: "data/Label2.geojson",
    },
    layout: {
      "icon-image": "lineIcon",
      "icon-size": 0.5,
      "icon-anchor": "bottom-left",
      "icon-offset": [5, 0],
      "text-field": [
        "format",
        ["upcase", ["get", "Company"]],
        {
          "font-scale":0.8,
        },
        "\n",
        {},
        ["get", "businessTy"],
        {
          "font-scale": 0.7,
        },
      ],
      "text-justify": "left",
      "text-anchor": "top-left",
      "text-offset": [0.7, -6],
      "text-font": ["literal", ["Oswald Regular"]],
      "text-padding": 1,
    },
    paint: {
      "text-color": "#e6f7ff",
      "text-halo-color": "#e6f7ff",
      "text-halo-width": 0.2,
      "icon-halo-color": "white",
      "icon-halo-width": 1,
    },
  },
  "state-label"
  );

  map.addLayer(
    {
      id: "EmersonExtrusion",
      type: "fill-extrusion",
      source: {
        type: "geojson",
        data: "data/Label2.geojson",
      },
      paint: {
        "fill-extrusion-opacity": 0,
        "fill-extrusion-height": ["*", 0.002, ["get", "heightroof"]],
        "fill-extrusion-color": "#6db0f8",
      },
    },
  );

  // Add Broadway layer

map.addLayer({
    id: "BroadwayLabel",
    type: "symbol",
    source: {
      type: "geojson",
      data: "data/Label3.geojson",
    },
    layout: {
      "icon-image": "lineIcon",
      "icon-size": 0.5,
      "icon-anchor": "bottom-left",
      "icon-offset": [5, 0],
      "text-field": [
        "format",
        ["upcase", ["get", "Company"]],
        {
          "font-scale":0.8,
        },
        "\n",
        {},
        ["get", "businessTy"],
        {
          "font-scale": 0.7,
        },
      ],
      "text-justify": "left",
      "text-anchor": "top-left",
      "text-offset": [0.7, -6],
      "text-font": ["literal", ["Oswald Regular"]],
      "text-padding": 1,
    },
    paint: {
      "text-color": "#e6f7ff",
      "text-halo-color": "#e6f7ff",
      "text-halo-width": 0.2,
      "icon-halo-color": "white",
      "icon-halo-width": 1,
    },
  },
  "state-label"
  );

  map.addLayer(
    {
      id: "BroadwayExtrusion",
      type: "fill-extrusion",
      source: {
        type: "geojson",
        data: "data/Label3.geojson",
      },
      paint: {
        "fill-extrusion-opacity": 0,
        "fill-extrusion-height": ["*", 0.002, ["get", "heightroof"]],
        "fill-extrusion-color": "#6db0f8",
      },
    },
  );

  // Add Corridor layer

  map.addLayer({
    id: "CorridorLine",
    type: "line",
    source: {
      type: "geojson",
      data: "data/Corridor.geojson",
    },
    paint: {
        'line-color': '#ffff66',
        'line-width': 3
    },
  },firstSymbolId);

    // Setup the instance, pass callback functions
    scroller
        .setup({
            step: '.step',
            offset: 0.5,
            progress: true
        })
        .onStepEnter(response => {
            var chapter = config.chapters.find(chap => chap.id === response.element.id);
            response.element.classList.add('active');
            map.flyTo(chapter.location);
            if (config.showMarkers) {
                marker.setLngLat(chapter.location.center);
            }
            if (chapter.onChapterEnter.length > 0) {
                chapter.onChapterEnter.forEach(setLayerOpacity);
            }
        })
        .onStepExit(response => {
            var chapter = config.chapters.find(chap => chap.id === response.element.id);
            response.element.classList.remove('active');
            if (chapter.onChapterExit.length > 0) {
                chapter.onChapterExit.forEach(setLayerOpacity);
            }
        });

}
);

//Add popup - CAN BE FAULT
map.on('click', 'BuffaloPosition', function (e) {
    let Name = e.features[0].properties.name;
    new mapboxgl.Popup()
        .setLngLat(e.lngLat)
        .setHTML(Name)
        .addTo(map);
});
// Change the cursor to a pointer when the mouse is over the turnstileData layer.
map.on('mouseenter', 'BuffaloPosition', function () {
    map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'BuffaloPosition', function () {
    map.getCanvas().style.cursor = '';
});

/* Here we watch for any resizing of the screen to
adjust our scrolling setup */
window.addEventListener('resize', scroller.resize);


text:
package org.mdbda.codegen.helper;

import java.util.HashSet;

import org.mdbda.model.Task;
import org.mdbda.model.Workflow;
import org.mdbda.model.*;

public class MDBDAWorkflowHelper {

	private static HashSet<Task> addedPattern = new HashSet<>();

	public static void addPattern(Task p){
		addedPattern.add(p);
	}

	public static boolean containsPattern(Task p){
		return addedPattern.contains(p);
	}

	public static String getGeneratePackageName(Task p){
		String packageName = null;

		if(p instanceof Workflow){
			packageName = ((Workflow)p).getModelRoot().getName();
		}else if(p instanceof Task){
			packageName = p.getWorkflow().getModelRoot().getName();
		}
		return packageName;
	}

	public static String getGenerateClassName(Task p){
		String className = null;

		if(p instanceof Workflow){
			className = p.getName();
		}else if(p instanceof Task){
			className = p.getWorkflow().getName() + p.getName();
		}
		return className;
	}

}


text:
require 'spec_helper'
#copy from https://raw.github.com/radar/better_spree_paypal_express/master/spec/features/paypal_spec.rb
#http://sandbox.alipaydev.com/index.htm
#sandbox_areq22@aliyun.com
#http://openapi.alipaydev.com/gateway.do
describe "AlipayDualFun", js: true do
  let!(:product) { create(:product, :name => 'iPad') }

  before do
    @gateway = Spree::Gateway::AlipayDualfun.create!({
#      preferred_email: 'sandbox_areq22@aliyun.com',
      preferred_partner: '2088002627298374',
      preferred_sign: 'f4y25qc539qakg734vn2jpqq6gmybxoz',
      name: "Alipay",
      active: true,
# environment: Rails.env
    })
     create(:shipping_method)
  end

  def fill_in_address(kind = "bill")
    fill_in "First Name",              with: "John 99"
    fill_in "Last Name",               with: "Doe"
    fill_in "Street Address",          with: "100 first lane"
    fill_in "Street Address (cont'd)", with: "#101"
    fill_in "City",                    with: "Bethesda"
    fill_in "Zip",                     with: "20170"
    targetted_select2 "Alabama",       from: "#s2id_order_#{kind}_address_attributes_state_id"
    fill_in "Phone",                   with: "123-456-7890"
  end

  def switch_to_paypal_login
    # If you go through a payment once in the sandbox, it remembers your preferred setting.
    # It defaults to the *wrong* setting for the first time, so we need to have this method.
    unless page.has_selector?("#login_email")
      find("#loadLogin").click
    end
  end

  def add_to_cart(product)
    click_link product.name
    click_button 'Add To Cart'
  end

  it "pays for an order successfully" do
    visit spree.root_path
    expect(page).to have_content product.name
    add_to_cart product
    click_button 'Checkout'
    within("#guest_checkout") do
      fill_in "Email", :with => "test@example.com"
      click_button 'Continue'
    end
    fill_in_address
    click_button "Save and Continue"
    # Delivery step doesn't require any action
    click_button "Save and Continue"
    find("#paypal_button").click
    switch_to_paypal_login
    fill_in "login_email", :with => "pp@spreecommerce.com"
    fill_in "login_password", :with => "thequickbrownfox"
    click_button "Log In"
    find("#continue_abovefold").click   # Because there's TWO continue buttons.
    page.should have_content("Your order has been processed successfully")

    Spree::Payment.last.source.transaction_id.should_not be_blank
  end
=begin
  it "includes adjustments in PayPal summary" do
    visit spree.root_path
    click_link 'iPad'
    click_button 'Add To Cart'
    # TODO: Is there a better way to find this current order?
    order = Spree::Order.last
    order.adjustments.create!(:amount => -5, :label => "$5 off")
    order.adjustments.create!(:amount => 10, :label => "$10 on")
    visit '/cart'
    within("#cart_adjustments") do
      page.should have_content("$5 off")
      page.should have_content("$10 on")
    end
    click_button 'Checkout'
    within("#guest_checkout") do
      fill_in "Email", :with => "test@example.com"
      click_button 'Continue'
    end
    fill_in_billing
    click_button "Save and Continue"
    # Delivery step doesn't require any action
    click_button "Save and Continue"
    find("#paypal_button").click
    within("#miniCart") do
      page.should have_content("$5 off")
      page.should have_content("$10 on")
    end
  end

  # Regression test for #10
  context "will skip $0 items" do
    let!(:product2) { FactoryGirl.create(:product, :name => 'iPod') }

    specify do
      visit spree.root_path
      click_link 'iPad'
      click_button 'Add To Cart'

      visit spree.root_path
      click_link 'iPod'
      click_button 'Add To Cart'

      # TODO: Is there a better way to find this current order?
      order = Spree::Order.last
      order.line_items.last.update_attribute(:price, 0)
      click_button 'Checkout'
      within("#guest_checkout") do
        fill_in "Email", :with => "test@example.com"
        click_button 'Continue'
      end
      fill_in_billing
      click_button "Save and Continue"
      # Delivery step doesn't require any action
      click_button "Save and Continue"
      find("#paypal_button").click
      within("#miniCart") do
        page.should have_content('iPad')
        page.should_not have_content('iPod')
      end
    end
  end

  context "can process an order with $0 item total" do
    before do
      # If we didn't do this then the order would be free and skip payment altogether
      calculator = Spree::ShippingMethod.first.calculator
      calculator.preferred_amount = 10
      calculator.save
    end

    specify do
      visit spree.root_path
      click_link 'iPad'
      click_button 'Add To Cart'
      # TODO: Is there a better way to find this current order?
      order = Spree::Order.last
      order.adjustments.create!(:amount => -order.line_items.last.price, :label => "FREE iPad ZOMG!")
      click_button 'Checkout'
      within("#guest_checkout") do
        fill_in "Email", :with => "test@example.com"
        click_button 'Continue'
      end
      fill_in_billing
      click_button "Save and Continue"
      # Delivery step doesn't require any action
      click_button "Save and Continue"
      find("#paypal_button").click
      within("#miniCart") do
        page.should have_content('Current purchase')
      end
    end
  end

  context "cannot process a payment with invalid gateway details" do
    before do
      @gateway.preferred_login = nil
      @gateway.save
    end

    specify do
      visit spree.root_path
      click_link 'iPad'
      click_button 'Add To Cart'
      click_button 'Checkout'
      within("#guest_checkout") do
        fill_in "Email", :with => "test@example.com"
        click_button 'Continue'
      end
      fill_in_billing
      click_button "Save and Continue"
      # Delivery step doesn't require any action
      click_button "Save and Continue"
      find("#paypal_button").click
      page.should have_content("PayPal failed. Security header is not valid")
    end
  end

  context "as an admin" do
    stub_authorization!

    context "refunding payments" do
      before do
        visit spree.root_path
        click_link 'iPad'
        click_button 'Add To Cart'
        click_button 'Checkout'
        within("#guest_checkout") do
          fill_in "Email", :with => "test@example.com"
          click_button 'Continue'
        end
        fill_in_billing
        click_button "Save and Continue"
        # Delivery step doesn't require any action
        click_button "Save and Continue"
        find("#paypal_button").click
        switch_to_paypal_login
        fill_in "login_email", :with => "pp@spreecommerce.com"
        fill_in "login_password", :with => "thequickbrownfox"
        click_button "Log In"
        find("#continue_abovefold").click   # Because there's TWO continue buttons.
        page.should have_content("Your order has been processed successfully")

        visit '/admin'
        click_link Spree::Order.last.number
        click_link "Payments"
        click_link "PayPal"
        click_link "Refund"
      end

      it "can refund payments fully" do
        click_button "Refund"
        page.should have_content("PayPal refund successful")

        payment = Spree::Payment.last
        source = payment.source
        source.refund_transaction_id.should_not be_blank
        source.refunded_at.should_not be_blank
        source.state.should eql("refunded")
        source.refund_type.should eql("Full")
      end

      it "can refund payments partially" do
        payment = Spree::Payment.last
        # Take a dollar off, which should cause refund type to be...
        fill_in "Amount", :with => payment.amount - 1
        click_button "Refund"
        page.should have_content("PayPal refund successful")

        source = payment.source
        source.refund_transaction_id.should_not be_blank
        source.refunded_at.should_not be_blank
        source.state.should eql("refunded")
        # ... a partial refund
        source.refund_type.should eql("Partial")
      end

      it "errors when given an invalid refund amount" do
        fill_in "Amount", :with => "lol"
        click_button "Refund"
        page.should have_content("PayPal refund unsuccessful (The partial refund amount is not valid)")
      end
    end
  end
=end
end