text:
title: Utilitaires
---

## Random Tokens

In many situations, we need to generate tokens and then verify them. If your tokens are tied to a state (for example, a user ID), you should refer to the [sessions tokens](../authentication/session-tokens.md) page. If not, the token generators below may be useful.

### Unsigned Tokens

The `generateToken` function generates a cryptographically secure random token encoded in base64url (128 bits).

```typescript
import { generateToken } from '@foal/core';

const token = await generateToken();
```

### Signed Tokens

You can also generate a token using a secret. The secret is used to *sign* the token to provide extra security. It must be encoded in base64. You can generate one with the following command:

```
foal createsecret
```

**Generate a signed token**
```typescript
import { generateSignedToken } from '@foal/core';

const token = await generateSignedToken(secret);
```

**Verify and read a signed token**
```typescript
import { verifySignedToken } from '@foal/core';

const signedTokenToVerify = 'xxx.yyy';
const result = await verifySignedToken(signedTokenToVerify, secret);
if (result === false) {
  console.log('incorrect signature');
} else {
  console.log('The token is ', result);
}
```

## String Encoding

### Base64 to Base64URL

This function converts a base64-encoded string into a base64URL-encoded string.

It replaces the characters `+` and `/` with `-` and `_` and omits the `=` sign.

```typescript
import { convertBase64ToBase64url } from '@foal/core';

const foo = convertBase64ToBase64url('bar');
```

### Base64URL to Base64

This function converts a base64URL-encoded string into a base64-encoded string.

It replaces the characters `-` and `_` with `+` and `/` and adds the `=` padding character(s) if any.

```typescript
import { convertBase64urlToBase64 } from '@foal/core';

const foo = convertBase64urlToBase64('bar');
```

## Buffers & Streams

### Stream to Buffer

This function converts a stream of buffers into a concatenated buffer. It returns a promise.

If the stream emits an error, the promise is rejected with the emitted error.

```typescript
import { streamToBuffer } from '@foal/core';

const buffer = await streamToBuffer(stream);
```


text:
import Association from './association';
import { capitalize } from 'ember-cli-mirage/utils/inflector';

class BelongsTo extends Association {

  /*
    The belongsTo association adds a fk to the owner of the association
  */
  getForeignKeyArray() {
    return [this.owner, `${this.target}Id`];
  }

  getForeignKey() {
    return `${this.target}Id`;
  }

  addMethodsToModelClass(ModelClass, key, schema) {
    let modelPrototype = ModelClass.prototype;
    var association = this;
    var foreignKey = this.getForeignKey();

    var associationHash = {};
    associationHash[key] = this;
    modelPrototype.belongsToAssociations = _.assign(modelPrototype.belongsToAssociations, associationHash);
    modelPrototype.associationKeys.push(key);
    modelPrototype.associationIdKeys.push(foreignKey);

    Object.defineProperty(modelPrototype, this.getForeignKey(), {

      /*
        object.parentId
          - returns the associated parent's id
      */
      get: function() {
        return this.attrs[foreignKey];
      },

      /*
        object.parentId = (parentId)
          - sets the associated parent (via id)
      */
      set: function(id) {
        if (id && !schema[association.target].find(id)) {
          throw 'Couldn\'t find ' + association.target + ' with id = ' + id;
        }

        this.attrs[foreignKey] = id;
        return this;
      }
    });

    Object.defineProperty(modelPrototype, key, {
      /*
        object.parent
          - returns the associated parent
      */
      get: function() {
        var foreignKeyId = this[foreignKey];
        if (foreignKeyId) {
          association._tempParent = null;
          return schema[association.target].find(foreignKeyId);

        } else if (association._tempParent) {
          return association._tempParent;
        } else {
          return null;
        }
      },

      /*
        object.parent = (parentModel)
          - sets the associated parent (via model)
      */
      set: function(newModel) {
        if (newModel && newModel.isNew()) {
          this[foreignKey] = null;
          association._tempParent = newModel;
        } else if (newModel) {
          association._tempParent = null;
          this[foreignKey] = newModel.id;
        } else {
          association._tempParent = null;
          this[foreignKey] = null;
        }
      }
    });

    /*
      object.newParent
        - creates a new unsaved associated parent
    */
    modelPrototype['new' + capitalize(key)] = function(attrs) {
      var parent = schema[key].new(attrs);

      this[key] = parent;

      return parent;
    };

    /*
      object.createParent
        - creates an associated parent, persists directly to db,
          and updates the owner's foreign key
    */
    modelPrototype['create' + capitalize(key)] = function(attrs) {
      var parent = schema[key].create(attrs);

      this[foreignKey] = parent.id;

      return parent;
    };
  }

}

export default BelongsTo;

redpajama_set_name: RedPajamaGithub


text:
C
C
*+ synch_setsp

       subroutine synch_setsp(injection_index_E,spectral_type,status)
C      --------------------------------------------------------------
C
C Set-up the theoretical spectrum for later use with defined properties
C
C Input:
C    injection index of electron population == GAMMA
       real*4         injection_index_E
C    spectra type code
       integer        spectral_type
C Returned:
C    status
       integer        status
C
C The electron spectrum is assumed to be of the form:
C      N(E)dE = N0 E**-GAMMA dE
C The spectral type is a code as follows:
C      1      ==     KP spectrum aged angle averaged
C      2      ==     KP spectrum aged not angle averaged
C      3      ==     KP spectrum continuous injection angle averaged
C      4      ==     KP spectrum continuous injection not angle averaged
C      5      ==     JP spectrum
C
C The theoretical spectrum appropriate to these values is defined.  If
C a suitable spectrum is not on file then the spectrum is calculated.
C Note that the injection index is assumed accurate to only two places
C of decimals.
C
*-
       include '../include/anmap_sys_pars.inc'
       include '../include/synch_defn.inc'
C
       integer     local_igamma, ifile, istat, iword
       integer     header_record(220), nrec
       logical     spectrum_not_found
       character   name*80

       if (status.ne.0) return

C define integer value of gamma to use in search
       local_igamma = injection_index_E*100.0
C test current spectrum
       if (local_igamma.eq.igamma .and. spectral_type.eq.iflag) return
C open file and search for a suitable spectrum
       istat = 0
       call io_namfil(synch_sys_file,name,0,istat)
       if (istat.ne.0) then
C .. create spectral file
         istat = 0
         call io_operan(ifile,synch_sys_file,'WRITE',880,0,status)
         header_record(1) = 0
         call io_wrfile(ifile,1,header_record,220,status)
         if (status.ne.0) goto 999
         spectrum_not_found = .true.
       else
         call io_operan(ifile,synch_sys_file,'WRITE',880,0,status)
         iword = 220
         call io_rdfile(ifile,1,header_record,iword,status)
         nrec = 2
         if (status.ne.0) goto 999
         spectrum_not_found = .true.
         do while ( spectrum_not_found .and.
     *              nrec.le.(header_record(1)+1) )
           iword = 220
           call io_rdfile(ifile,nrec,synch_curr_sp,iword,status)
           nrec = nrec + 1
           if (igamma.eq.local_igamma .and.
     *         spectral_type.eq.iflag) then
             spectrum_not_found = .false.
           end if
         end do
       end if
100    continue
       if (spectrum_not_found) then
         iflag  = spectral_type
         igamma = local_igamma
         gamma  = injection_index_E
         call io_wrout(' ')
         call io_wrout('.. constructing spectrum please be patient')
         call synch_makesp(status)
         if (status.ne.0) goto 999
         call io_wrout('.. spectrum constructed successfully')
         call io_wrout(' ')
         header_record(1) = header_record(1) + 1
         call io_wrfile(ifile,1,header_record,220,status)
         nrec = header_record(1) + 1
         call io_wrfile(ifile,nrec,synch_curr_sp,220,status)
       end if

999    close (ifile)
       call iocmd_err(status,'SYNCH_GETSP','Failed')

       end


text:
package com.vaadin.tests.components.orderedlayout;

import com.vaadin.tests.components.AbstractOrderedLayoutTest;
import com.vaadin.ui.VerticalLayout;

public class VerticalLayoutTest extends
        AbstractOrderedLayoutTest<VerticalLayout> {

    @Override
    protected Class<VerticalLayout> getTestClass() {
        return VerticalLayout.class;
    }

}


text:
.. _how_to_dump_heap_profile_of_envoy:

How to dump heap profile of Envoy?
===================================

If Envoy binary that build with ``gperftools`` is used, please check `PPROF.md <https://github.com/envoyproxy/envoy/blob/main/bazel/PPROF.md>`_
for how to generate Envoy heap profiles.

For any Envoy binary that build with normal ``tcmalloc``, the :ref:`/heap_dump <operations_admin_interface_heap_dump>` endpoint
is supported to dump current heap profile of Envoy.

Use following Envoy process as a specific example:

.. code-block:: bash

    $ /path/to/envoy -c /path/to/config.yaml --concurrency 2

You can get a heap profile of Envoy by the following command:

.. code-block:: bash

    $ curl <Envoy IP>:<Envoy Admin Port>/dump_heap -o /heap/output/envoy.heap

And then you can analyze the outputed heap profile with pprof:

.. code-block:: bash

    $ pprof -http:localhost:9999 /heap/output/envoy.heap

.. note::
    If you dump the heap profile in the production environment and analyze it in the local environment, please ensure
    there is a Envoy binary in your local environment and the local's binary has same path with the production's one.
    And please ensure that the Envoy binary that used to analyze heap profile is a binary with function symbol
    (no stripped binary).

You can also get heap diff from two different heap profiles:

.. code-block:: bash

    $ pprof -http:localhost:9999 /heap/output/envoy_1.heap
    $ sleep 30
    $ pprof -http:localhost:9999 /heap/output/envoy_2.heap
    $ pprof -http:localhost:9999 -base /heap/output/envoy_1.heap /heap/output/envoy_2.heap


text:
package org.jitsi.turnserver.listeners;

import java.io.UnsupportedEncodingException;

import org.ice4j.TransportAddress;
import org.ice4j.attribute.Attribute;
import org.ice4j.attribute.DataAttribute;
import org.ice4j.attribute.XorPeerAddressAttribute;
import org.ice4j.message.Indication;
import org.ice4j.message.Message;
import org.jitsi.turnserver.IndicationListener;
import org.jitsi.turnserver.stack.Allocation;
import org.jitsi.turnserver.stack.TurnStack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class to handle the incoming Data indications.
 *
 * @author Aakash Garg
 *
 */
public class DataIndicationListener extends IndicationListener {
    /**
     * The <tt>Logger</tt> used by the <tt>DataIndicationListener</tt> class and its instances for
     * logging output.
     */
    private static final Logger logger =
            LoggerFactory.getLogger(DataIndicationListener.class.getName());

    /**
     * parametrised constructor.
     *
     * @param turnStack the turnStack to set for this class.
     */
    public DataIndicationListener(TurnStack turnStack) {
        super(turnStack);
    }

    /**
     * Handles the incoming data indication.
     *
     * @param ind the indication to handle.
     * @param alloc the allocation associated with message.
     */
    @Override
    public void handleIndication(Indication ind, Allocation alloc) {
        if (ind.getMessageType() == Message.DATA_INDICATION) {
            logger.trace("Received a Data Indication message.");
            byte[] tran = ind.getTransactionID();

            XorPeerAddressAttribute xorPeerAddress =
                    (XorPeerAddressAttribute) ind.getAttribute(Attribute.XOR_PEER_ADDRESS);
            xorPeerAddress.setAddress(xorPeerAddress.getAddress(), tran);
            DataAttribute data = (DataAttribute) ind.getAttribute(Attribute.DATA);

            TransportAddress peerAddr = xorPeerAddress.getAddress();
            try {
                String line = new String(data.getData(), "UTF-8");
                // System.out.println(line);
                logger.trace("Data Indiaction message from  " + peerAddr + " is " + line);
                /*
                 * System.out.println("Received a Data indiction from " + peerAddr + ", message : "
                 * + line);
                 */ } catch (UnsupportedEncodingException e) {
                logger.warn("Unable to convert to String!");
            }
        }
    }

}


text:
package display

import (
	"fmt"
	"testing"

	"github.com/insionng/yougam/libraries/x/text/internal/testtext"
)

func TestLinking(t *testing.T) {
	base := getSize(t, `display.Tags(language.English).Name(language.English)`)
	compact := getSize(t, `display.English.Languages().Name(language.English)`)

	if d := base - compact; d < 1.5*1024*1024 {
		t.Errorf("size(base)-size(compact) was %d; want > 1.5MB", base, compact)
	}
}

func getSize(t *testing.T, main string) int {
	size, err := testtext.CodeSize(fmt.Sprintf(body, main))
	if err != nil {
		t.Skipf("skipping link size test; binary size could not be determined: %v", err)
	}
	return size
}

const body = `package main
import (
	"github.com/insionng/yougam/libraries/x/text/language"
	"github.com/insionng/yougam/libraries/x/text/language/display"
)
func main() {
	%s
}
`


text:
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2013, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
// Algorithms for combining (i.e. merging and chaining) seeds.
// ==========================================================================

// TODO(holtgrew): All the Nothing()'s should not be part of the public interface.

#ifndef SEQAN_SEEDS_SEEDS_COMBINATION_H_
#define SEQAN_SEEDS_SEEDS_COMBINATION_H_

namespace seqan {

// ===========================================================================
// Enums, Tags, Classes, Specializations
// ===========================================================================

// TODO(holtgrew): Stream-line tags to Merge, ChaosChain, SimpleChain?
/**
.Tag.Local Chaining
..cat:Seed Handling
..summary:The local chaining algorithms to use when adding a seed to a @Class.SeedSet@.
..see:Class.SeedSet
..see:Function.SeedSet#addSeed
..tag.Merge:Merge with existing seed.
..tag.Chaos:CHAOS chaining.
..tag.SimpleChain:Simple chaining.
..tag.Single:Add single seed without merging and chaining.
..include:seqan/seeds.h
*/
struct Merge_;
typedef Tag<Merge_> Merge;

struct Chaos_;
typedef Tag<Chaos_> Chaos;

struct SimpleChain_;
typedef Tag<SimpleChain_> SimpleChain;

struct Single_;
typedef Tag<Single_> Single;

// ===========================================================================
// Metafunctions
// ===========================================================================

// ===========================================================================
// Functions
// ===========================================================================

// Returns true iff b can be merged into a where a is the one to the
// upper left, b the one to the lower right.
template <typename TSeedSpec, typename TSeedConfig, typename TThreshold, typename TBandwidth>
inline bool
_seedsCombineable(Seed<TSeedSpec, TSeedConfig> const & seedA,
                  Seed<TSeedSpec, TSeedConfig> const & seedB,
                  TThreshold const & maxDiagonalDistance,
                  TBandwidth const & /*maxBandwidth*/,
                  Merge const &)
{
    // TODO(holtgrew): TThreshold could be Position<TSeed>::Type.
    // b has to be right of a for the two seeds to be mergeable.
    if (beginPositionH(seedB) < beginPositionH(seedA) || beginPositionV(seedB) < beginPositionV(seedA))
        return false;
    // If the two seeds do not overlap, they cannot be merged.
    if (beginPositionH(seedB) > endPositionH(seedA) || beginPositionV(seedB) > endPositionV(seedA))
        return false;
    // If the distance between the diagonals exceeds the threshold
    // then the seeds cannot be merged.
    typedef typename MakeUnsigned_<TThreshold>::Type TUnsignedThreshold;
    if (static_cast<TUnsignedThreshold>(_abs(endDiagonal(seedA) - beginDiagonal(seedB))) > static_cast<TUnsignedThreshold>(maxDiagonalDistance))
        return false;
    // Otherwise, the seeds can be merged.
    return true;
}

// Returns true iff b can be simple-chained to a where a is the one to
// the upper left, b the one to the lower right.
template <typename TSeedSpec, typename TSeedConfig, typename TThreshold, typename TBandwidth>
inline bool
_seedsCombineable(Seed<TSeedSpec, TSeedConfig> const & seedA,
                  Seed<TSeedSpec, TSeedConfig> const & seedB,
                  TThreshold const & maxGapSize,
                  TBandwidth const & /*maxBandwidth*/,
                  SimpleChain const &)
{
    // TODO(holtgrew): We should be able to configure whether we want to have Manhattan, euclidean, minimal edit distance, for seeds.
    // TODO(holtgrew): TThreshold could be Position<TSeed>::Type.

    // b has to be right of a for the two seeds to be chainable.
    if (beginPositionH(seedB) < endPositionH(seedA) || beginPositionV(seedB) < endPositionV(seedA))
        return false;

    // Distance is maximal distance, this corresponds to going the
    // distacen in the smaller distance with matches/mismatches and
    // the rest with indels.
    TThreshold distance = _max(beginPositionH(seedB) - endPositionH(seedA), beginPositionV(seedB) - endPositionV(seedA));
    // Compare distance with threshold.
    return distance <= maxGapSize;
}

// Returns true iff b can be Chaos chained to a where a is the one to
// the upper left, b the one to the lower right.
//
// TODO(holtgrew): Replace bandwidth with diagonalDistance.
template <typename TSeedSpec, typename TSeedConfig, typename TDistanceThreshold, typename TBandwidthThreshold>
inline bool
_seedsCombineable(Seed<TSeedSpec, TSeedConfig> const & seedA,
                  Seed<TSeedSpec, TSeedConfig> const & seedB,
                  TDistanceThreshold const & maxGapSize,
                  TBandwidthThreshold const & bandwidth,
                  Chaos const &)
{
    // b has to be right of a for the two seeds to be chainable.
    if (beginPositionH(seedB) < endPositionH(seedA) || beginPositionV(seedB) < endPositionV(seedA))
        return false;

    // The diagonal distance has to be smaller than the bandwidth.
    // TODO(holtgrew): s/beginDiagonal/getBeginDiagonal/
    TBandwidthThreshold diagonalDistance = _abs(endDiagonal(seedB) - beginDiagonal(seedA));
    if (diagonalDistance > bandwidth)
        return false;

    // Distance is maximal distance, this corresponds to going the
    // distance in the smaller distance with matches/mismatches and
    // the rest with indels.
    TDistanceThreshold distance = _max(beginPositionH(seedB) - endPositionH(seedA), beginPositionV(seedB) - endPositionV(seedA));
    // Compare distance with threshold.
    return distance <= maxGapSize;
}

// Updating the coordinates of seeds is the same for merging and
// simple chaining.  Only the score computation differs.
template <typename TSeedConfig>
inline void
_updateSeedsCoordinatesMergeOrSimpleChain(
        Seed<Simple, TSeedConfig> & seed,
        Seed<Simple, TSeedConfig> const & other)
{
    setBeginPositionH(seed, std::min(beginPositionH(seed), beginPositionH(other)));
    setBeginPositionV(seed, std::min(beginPositionV(seed), beginPositionV(other)));
    setEndPositionH(seed, std::max(endPositionH(seed), endPositionH(other)));
    setEndPositionV(seed, std::max(endPositionV(seed), endPositionV(other)));
    setLowerDiagonal(seed, std::min(lowerDiagonal(seed), lowerDiagonal(other)));
    setUpperDiagonal(seed, std::max(upperDiagonal(seed), upperDiagonal(other)));
}

template <typename TSeedConfig, typename TScoreValue, typename TSequence0, typename TSequence1>
inline void
_combineSeeds(Seed<Simple, TSeedConfig> & seed,
              Seed<Simple, TSeedConfig> const & other,
              Score<TScoreValue, Simple> const & /*scoringScheme*/,
              TSequence0 const & /*sequence0*/,
              TSequence1 const & /*sequence1*/,
              Merge const &)
{
    _updateSeedsScoreMerge(seed, other);
    _updateSeedsCoordinatesMergeOrSimpleChain(seed, other);
}

template <typename TSeedConfig, typename TScoreValue, typename TSequence0, typename TSequence1>
inline void
_combineSeeds(Seed<Simple, TSeedConfig> & seed,
              Seed<Simple, TSeedConfig> const & other,
              Score<TScoreValue, Simple> const & scoringScheme,
              TSequence0 const & /*sequence0*/,
              TSequence1 const & /*sequence1*/,
              SimpleChain const &)
{
    _updateSeedsScoreSimpleChain(seed, other, scoringScheme);
    _updateSeedsCoordinatesMergeOrSimpleChain(seed, other);
}

template <typename TSeedConfig, typename TScoreValue, typename TSequence0, typename TSequence1>
inline void
_combineSeeds(Seed<Simple, TSeedConfig> & seed,
              Seed<Simple, TSeedConfig> const & other,
              Score<TScoreValue, Simple> const & scoringScheme,
              TSequence0 const & sequence0,
              TSequence1 const & sequence1,
              Chaos const &)
{
    typedef Seed<Simple, TSeedConfig> TSeed;
    typedef typename Position<TSeed>::Type TPosition;

    // TODO(holtgrew): Assert seed left of other.

    // Compute gaps in both dimensions, the remaining gap is the
    // vertical/horizontal distance we will not fill with CHAOS
    // chaining.
    //
    // TODO(holtgrew): We need + 1 here, do we need it anywhere else?
    TPosition gapDim0 = beginPositionH(other) - endPositionH(seed);
    TPosition gapDim1 = beginPositionV(other) - endPositionV(seed);
    TPosition minGap = _min(gapDim0, gapDim1);
    TPosition maxGap = _max(gapDim0, gapDim1);
    TPosition remainingGap = maxGap - minGap;

    // Compute new score using the CHAOS method.
    //
    // First, compute the score when force-aligning from seed.
    TPosition posLeft0 = endPositionH(seed);
    TPosition posLeft1 = endPositionV(seed);
    TScoreValue tmpScore = 0;
    // TODO(holtgrew): Probably better use iterators on sequences!
    for (TPosition i = 0; i < minGap; ++i)
        tmpScore += score(scoringScheme, sequence0[posLeft0 + i], sequence1[posLeft1 + i]);

    SEQAN_ASSERT_GT(beginPositionH(other), static_cast<TPosition>(0));
    SEQAN_ASSERT_GT(beginPositionV(other), static_cast<TPosition>(0));
    TPosition posRight0 = beginPositionH(other);
    TPosition posRight1 = beginPositionV(other);

    // Now, try to put the gap at each position and get the position
    // with the highest score.  If there are two such positions, the
    // first one found is returned which is the one that is furthest
    // away from seed.
    // TPosition bestGapPos = 0;  // delta to lowermost position  // TODO(holtgrew): Set but not used;  Remove?
    TScoreValue bestScore = tmpScore;
    for (TPosition i = 1; i < minGap; ++i) {
        tmpScore -= score(scoringScheme, sequence0[posLeft0 + minGap - i], sequence1[posLeft1 + minGap - i]);
        tmpScore += score(scoringScheme, sequence0[posRight0 - i], sequence1[posRight1 - i]);
        if (tmpScore > bestScore) {
            // Found a better score.
            bestScore = tmpScore;
            // bestGapPos = i;  // TODO(holtgrew): Set but not used;  Remove?
        }
    }

    // Now, the best gap is when extending the lower right seed
    // (other) by bestGapPos to the upper right.  However, this is
    // ignored for simple seeds: We simply update the score and are
    // done.
    _updateSeedsScoreChaos(seed, other, bestScore + remainingGap * scoreGap(scoringScheme));

    // For simple seeds, the coordinate computation is the same as for
    // merge/simple chain.
    //
    // TODO(holtgrew): Adjust the name of updateSeedsCoordinatesMergeOrSimpleChain to reflect this.
    _updateSeedsCoordinatesMergeOrSimpleChain(seed, other);
}

template <typename TSeedConfig, typename TScoreValue, typename TSequence0, typename TSequence1>
inline void
_combineSeeds(Seed<ChainedSeed, TSeedConfig> & seed,
              Seed<ChainedSeed, TSeedConfig> const & other,
              Score<TScoreValue, Simple> const & /*scoringScheme*/,
              TSequence0 const & /*sequence0*/,
              TSequence1 const & /*sequence1*/,
              Merge const &)
{
    // For chained seeds, we first remove all diagonals from seed
    // until the last diagonal of seed starts truly before other.
    // Then, we possibly shorten the last diagonal.  Finally, we copy
    // over all diagonals from other.

    // std::cout << "Merging chained seeds " << seed << " and " << other << std::endl;
    SEQAN_ASSERT_LEQ_MSG(beginPositionH(seed), beginPositionH(other), "Monotony in both dimensions required for merging.");
    SEQAN_ASSERT_LEQ_MSG(beginPositionV(seed), beginPositionV(other), "Monotony in both dimensions required for merging.");

    _updateSeedsScoreMerge(seed, other);

    // Remove diagonals.
    typedef Seed<ChainedSeed, TSeedConfig> TSeed;
    typedef typename Iterator<TSeed, Standard>::Type TIterator;
    TIterator it;
    // TODO(holtgrew): Could use back() instead of lastKept.
    TIterator lastKept = begin(seed);
    for (it = begin(seed); it != end(seed); ++it) {
        if (it->beginPositionH >= beginPositionH(other) && it->beginPositionV >= beginPositionV(other))
            break;
        lastKept = it;
    }
    if (it != end(seed))
        truncateDiagonals(seed, it);
    // std::cout << "Seed after truncating diagonals: " << seed << std::endl;

    // Shorten last diagonal if necessary.
    if (lastKept->beginPositionH + lastKept->length > beginPositionH(other) && lastKept->beginPositionV + lastKept->length > beginPositionV(other)) {
        lastKept->length = _min(beginPositionH(other) - lastKept->beginPositionH, beginPositionV(other) - lastKept->beginPositionV);
    } else if (lastKept->beginPositionH + lastKept->length > beginPositionH(other)) {
        lastKept->length = beginPositionH(other) - lastKept->beginPositionH;
    } else if (lastKept->beginPositionV + lastKept->length > beginPositionV(other)) {
        lastKept->length = beginPositionV(other) - lastKept->beginPositionV;
    }

    // Maybe remove shortened diagonal if its length is 0.
    if (back(seed).length == 0) {
        // TODO(holtgrew): Do not use dot method.
        seed._seedDiagonals.pop_back();
    }

    // Copy over other diagonals.
    typedef typename Iterator<TSeed const, Standard>::Type TConstIterator;
    for (TConstIterator it = begin(other, Standard()); it != end(other, Standard()); ++it)
        appendDiagonal(seed, *it);

    // std::cout << "Chained seed after merging: " << seed << std::endl;

    // TODO(holtgrew): Update lower and upper diagonals!
}

template <typename TSeedConfig, typename TScoreValue, typename TSequence0, typename TSequence1>
inline void
_combineSeeds(Seed<ChainedSeed, TSeedConfig> & seed,
              Seed<ChainedSeed, TSeedConfig> const & other,
              Score<TScoreValue, Simple> const & scoringScheme,
              TSequence0 const & /*sequence0*/,
              TSequence1 const & /*sequence1*/,
              SimpleChain const &)
{
    // Simply copy over the diagonals of the seed (other) into the
    // left one (seed) after updating the score.

    _updateSeedsScoreSimpleChain(seed, other, scoringScheme);

    // Copy over other diagonals.
    typedef Seed<ChainedSeed, TSeedConfig> TSeed;
    typedef typename Iterator<TSeed const, Standard>::Type TConstIterator;
    for (TConstIterator it = begin(other, Standard()); it != end(other, Standard()); ++it)
        appendDiagonal(seed, *it);
}

template <typename TSeedConfig, typename TScoreValue, typename TSequence0, typename TSequence1>
inline void
_combineSeeds(Seed<ChainedSeed, TSeedConfig> & seed,
              Seed<ChainedSeed, TSeedConfig> const & other,
              Score<TScoreValue, Simple> const & scoringScheme,
              TSequence0 const & sequence0,
              TSequence1 const & sequence1,
              Chaos const &)
{
    typedef Seed<ChainedSeed, TSeedConfig> TSeed;
    typedef typename Position<TSeed>::Type TPosition;
    typedef typename Iterator<TSeed const, Standard>::Type TConstIterator;

    // TODO(holtgrew): Assert seed left of other.

    // Compute gaps in both dimensions, the remaining gap is the
    // vertical/horizontal distance we will not fill with CHAOS
    // chaining.
    //
    // TODO(holtgrew): We need + 1 here, do we need it anywhere else?
    TPosition gapDim0 = beginPositionH(other) - endPositionH(seed);
    TPosition gapDim1 = beginPositionV(other) - endPositionV(seed);
    TPosition minGap = _min(gapDim0, gapDim1);
    TPosition maxGap = _max(gapDim0, gapDim1);
    TPosition remainingGap = maxGap - minGap;

    // Compute new score using the CHAOS method.
    //
    // First, compute the score when force-aligning from seed.
    TPosition posLeft0 = endPositionH(seed);
    TPosition posLeft1 = endPositionV(seed);
    TScoreValue tmpScore = 0;
    // TODO(holtgrew): Probably better use iterators on sequences!
    for (TPosition i = 0; i < minGap; ++i)
        tmpScore += score(scoringScheme, sequence0[posLeft0 + i], sequence1[posLeft1 + i]);

    SEQAN_ASSERT_GT(beginPositionH(other), static_cast<TPosition>(0));
    SEQAN_ASSERT_GT(beginPositionV(other), static_cast<TPosition>(0));
    TPosition posRight0 = beginPositionH(other);
    TPosition posRight1 = beginPositionV(other);

    // Now, try to put the gap at each position and get the position
    // with the highest score.  If there are two such positions, the
    // first one found is returned which is the one that is furthest
    // away from seed.
    TPosition bestGapPos = 0;  // delta to lowermost position
    TScoreValue bestScore = tmpScore;
    for (TPosition i = 1; i < minGap; ++i) {
        tmpScore -= score(scoringScheme, sequence0[posLeft0 + minGap - i], sequence1[posLeft1 + minGap - i]);
        tmpScore += score(scoringScheme, sequence0[posRight0 - i], sequence1[posRight1 - i]);
        if (tmpScore > bestScore) {
            // Found a better score.
            bestScore = tmpScore;
            bestGapPos = i;
        }
    }

    // Now, the best gap is when extending the lower right seed
    // (other) by bestGapPos to the upper right.  The upper left seed
    // is extended by (minGap - bestGapPos).
    //
    // Adjust last diagonal of seed.
    back(seed).length += minGap - bestGapPos;
    // Copy over the first diagonal of other and adjust diagonal.
    appendDiagonal(seed, front(other));
    back(seed).beginPositionH -= bestGapPos;
    back(seed).beginPositionV -= bestGapPos;
    back(seed).length += bestGapPos;
    // Copy over all other diagonals.
    TConstIterator it = begin(other, Standard());
    TConstIterator itEnd = end(other, Standard());
    // TODO(holtgrew): value(it) does not work here, the adaption around std::list needs more work!
    for (++it; it != itEnd; ++it)
        appendDiagonal(seed, *it);

    // Finally, we update the score and are done.
    _updateSeedsScoreChaos(seed, other, bestScore + remainingGap * scoreGap(scoringScheme));
}

}  // namespace seqan

#endif  // #ifndef SEQAN_SEEDS_SEEDS_COMBINATION_UNORDERED_H_


text:
package dht

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"time"

	"github.com/hashicorp/consul/api"
	"github.com/stvp/rendezvous"
)

const (
	checkInterval = 5 * time.Second
	pollWait      = time.Second
)

func newCheckListenerAndServer() (listener net.Listener, server *http.Server, err error) {
	listener, err = net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return listener, nil, err
	}

	server = &http.Server{
		ReadTimeout:  time.Second,
		WriteTimeout: time.Second,
		Handler: http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
			fmt.Fprintf(resp, "OK")
		}),
	}

	// When the listener is closed, this goroutine returns.
	go server.Serve(listener)

	return listener, server, err
}

// Node is a single node in a distributed hash table, coordinated using
// services registered in Consul. Key membership is determined using rendezvous
// hashing to ensure even distribution of keys and minimal key membership
// changes when a Node fails or otherwise leaves the hash table.
//
// Errors encountered when making blocking GET requests to the Consul agent API
// are logged using the log package.
type Node struct {
	// Consul
	serviceName string
	serviceID   string
	consul      *api.Client

	// HTTP health check server
	checkURL      string
	checkListener net.Listener
	checkServer   *http.Server

	// Hash table
	hashTable *rendezvous.Table
	waitIndex uint64

	// Graceful shutdown
	stop chan bool
}

// Join creates a new Node and adds it to the distributed hash table specified
// by the given name. The given id should be unique among all Nodes in the hash
// table.
func Join(name, id string) (node *Node, err error) {
	node = &Node{
		serviceName: name,
		serviceID:   id,
		stop:        make(chan bool),
	}

	node.consul, err = api.NewClient(api.DefaultConfig())
	if err != nil {
		return nil, fmt.Errorf("dht: can't create Consul API client: %s", err)
	}

	node.checkListener, node.checkServer, err = newCheckListenerAndServer()
	if err != nil {
		return nil, fmt.Errorf("dht: can't start HTTP server: %s", err)
	}

	err = node.register()
	if err != nil {
		return nil, fmt.Errorf("dht: can't register %s service: %s", node.serviceName, err)
	}

	err = node.update()
	if err != nil {
		return nil, fmt.Errorf("dht: can't fetch %s services list: %s", node.serviceName, err)
	}

	go node.poll()

	return node, nil
}

func (n *Node) register() (err error) {
	err = n.consul.Agent().ServiceRegister(&api.AgentServiceRegistration{
		Name: n.serviceName,
		ID:   n.serviceID,
		Check: &api.AgentServiceCheck{
			HTTP:     fmt.Sprintf("http://%s", n.checkListener.Addr().String()),
			Interval: checkInterval.String(),
		},
	})
	return err
}

func (n *Node) poll() {
	var err error

	for {
		select {
		case <-n.stop:
			return
		case <-time.After(pollWait):
			err = n.update()
			if err != nil {
				log.Printf("[dht %s %s] error: %s", n.serviceName, n.serviceID, err)
			}
		}
	}
}

// update blocks until the service list changes or until the Consul agent's
// timeout is reached (10 minutes by default).
func (n *Node) update() (err error) {
	opts := &api.QueryOptions{WaitIndex: n.waitIndex}
	serviceEntries, meta, err := n.consul.Health().Service(n.serviceName, "", true, opts)
	if err != nil {
		return err
	}

	ids := make([]string, len(serviceEntries))
	for i, entry := range serviceEntries {
		ids[i] = entry.Service.ID
	}

	n.hashTable = rendezvous.New(ids)
	n.waitIndex = meta.LastIndex

	return nil
}

// Member returns true if the given key belongs to this Node in the distributed
// hash table.
func (n *Node) Member(key string) bool {
	return n.hashTable.Get(key) == n.serviceID
}

// Leave removes the Node from the distributed hash table by de-registering it
// from Consul. Once Leave is called, the Node should be discarded. An error is
// returned if the Node is unable to successfully deregister itself from
// Consul. In that case, Consul's health check for the Node will fail and
// require manual cleanup.
func (n *Node) Leave() (err error) {
	close(n.stop) // stop polling for state
	err = n.consul.Agent().ServiceDeregister(n.serviceID)
	n.checkListener.Close() // stop the health check http server
	return err
}


text:
package org.zalando.problem.spring.web.advice.network;

import org.apiguardian.api.API;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.zalando.problem.Problem;
import org.zalando.problem.Status;
import org.zalando.problem.spring.web.advice.AdviceTrait;

import java.net.SocketTimeoutException;

import static org.apiguardian.api.API.Status.EXPERIMENTAL;
import static org.apiguardian.api.API.Status.INTERNAL;

@API(status = EXPERIMENTAL)
public interface SocketTimeoutAdviceTrait extends AdviceTrait {

    @API(status = INTERNAL)
    @ExceptionHandler
    default ResponseEntity<Problem> handleSocketTimeout(
            final SocketTimeoutException exception,
            final NativeWebRequest request) {
        return create(Status.GATEWAY_TIMEOUT, exception, request);
    }

}


text: <input type="checkbox" data-field="show-badge" checked />


text:
package org.onepf.opfpush;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import org.onepf.opfpush.backoff.InfinityExponentialBackoffManager;
import org.onepf.opfpush.backoff.RetryManager;
import org.onepf.opfpush.configuration.Configuration;
import org.onepf.opfpush.listener.EventListener;
import org.onepf.opfpush.model.AvailabilityResult;
import org.onepf.opfpush.model.Message;
import org.onepf.opfpush.model.PushError;
import org.onepf.opfpush.model.State;
import org.onepf.opfpush.model.UnrecoverablePushError;
import org.onepf.opfpush.notification.NotificationMaker;
import org.onepf.opfpush.pushprovider.PushProvider;
import org.onepf.opfutils.OPFChecks;
import org.onepf.opfutils.OPFLog;
import org.onepf.opfutils.OPFUtils;
import org.onepf.opfutils.exception.InitException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

import static android.provider.Settings.Secure;
import static android.provider.Settings.Secure.ANDROID_ID;
import static org.onepf.opfpush.OPFConstants.ACTION_NO_AVAILABLE_PROVIDER;
import static org.onepf.opfpush.OPFConstants.ACTION_RECEIVE;
import static org.onepf.opfpush.OPFConstants.ACTION_REGISTRATION;
import static org.onepf.opfpush.OPFConstants.ACTION_UNREGISTRATION;
import static org.onepf.opfpush.model.Operation.REGISTER;
import static org.onepf.opfpush.model.Operation.UNREGISTER;
import static org.onepf.opfpush.model.State.REGISTERED;
import static org.onepf.opfpush.model.State.REGISTERING;
import static org.onepf.opfpush.model.State.UNREGISTERED;
import static org.onepf.opfpush.model.UnrecoverablePushError.Type.AVAILABILITY_ERROR;

/**
 * The helper class to manage push providers.
 *

 * Use {@link #register()} to start a registration and {@link #unregister()} for start an unregistration.
 * The registration and unregistration operations are asynchronous. You can handle results of these operations
 * via the implementation of the {@link org.onepf.opfpush.listener.EventListener} interface or the extension of
 * the {@link org.onepf.opfpush.receiver.OPFPushReceiver} class.
 *

 * You must initialize the {@link org.onepf.opfpush.OPFPush} class before start using the {@code OPFPushHelper}.
 *
 * @author Kirill Rozov
 * @author Roman Savin
 * @since 04.09.2014
 */
@SuppressWarnings({"PMD.GodClass", "PMD.TooManyMethods"})
final class OPFPushHelperImpl extends OPFPushHelper {

    @SuppressWarnings("NullableProblems")
    @NonNull
    private EventListener eventListenerWrapper;

    @NonNull
    private final Context appContext;

    @Nullable
    private PushProvider currentProvider;

    @SuppressWarnings("NullableProblems")
    @NonNull
    private List<PushProvider> sortedProvidersList;

    @NonNull
    private final Map<String, UnrecoverablePushError> registerProviderErrors = new HashMap<>();

    @NonNull
    private final Map<String, String> providersByHostApps = new HashMap<>();

    private volatile Configuration configuration;

    @NonNull
    private final ReceivedMessageHandler receivedMessageHandler = new ReceivedMessageHandlerImpl();

    @NonNull
    private final Settings settings;

    @SuppressWarnings("NullableProblems")
    @NonNull
    private RetryManager retryManager;

    @NonNull
    private final Object registrationLock = new Object();

    @NonNull
    private final Object initLock = new Object();

    OPFPushHelperImpl(@NonNull final Context context) {
        super();
        appContext = context.getApplicationContext();
        settings = Settings.getInstance(context);
    }

    /**
     * If the {@code OPFPushHelper} is unregistered, it chooses a push provider with
     * the highest priority and starts the registration. Does nothing in another case.
     * The registration result can be handled via the implementation of the {@link org.onepf.opfpush.listener.EventListener}
     * interface or the extension of the {@link org.onepf.opfpush.receiver.OPFPushReceiver} class.
     *

     * The priority of providers corresponds to the order in which they was added to the
     * {@link org.onepf.opfpush.configuration.Configuration} before the initialization.
     * If you set {@code true} as an argument of {@link org.onepf.opfpush.configuration.Configuration.Builder#setSelectSystemPreferred(boolean)}
     * method, the system push provider will get the highest priority.
     *
     * @throws java.lang.IllegalStateException If {@code OPFPush} haven't been initialized.
     */
    @Override
    public void register() {
        OPFLog.logMethod();

        checkInit(true);
        synchronized (registrationLock) {
            final State state = settings.getState();
            OPFLog.d("Register state : " + state.toString());
            switch (state) {
                case REGISTERED:
                case REGISTERING:
                    break;
                case UNREGISTERED:
                    registerFirstAvailableProvider();
                    break;
            }
        }
    }

    /**
     * If the {@code OPFPushHelper} is registered or registration is in process,
     * starts the asynchronous unregistration of the current push provider. Does nothing
     * if the {@code OPFPushHelper} has already been unregistered.
     *

     * You should rarely (if ever) need to call this method. Not only is it expensive in terms of resources,
     * but it invalidates your registration ID, which you should never change unnecessarily.
     * A better approach is to simply have your server stop sending messages.
     * Only use unregister if you want to change your sender ID.
     *
     * @throws java.lang.IllegalStateException If {@code OPFPush} haven't been initialized.
     */
    @Override
    public void unregister() {
        OPFLog.logMethod();

        checkInit(true);
        synchronized (registrationLock) {
            final State state = settings.getState();
            OPFLog.d("Registration state = " + state.toString());
            if (currentProvider == null) {
                OPFLog.w("Current provider null");
                return;
            }
            final String providerName = currentProvider.getName();
            final boolean isCurrentProviderRegistered = currentProvider.isRegistered();

            if (state == REGISTERING || state == REGISTERED || isCurrentProviderRegistered) {
                retryManager.cancelRetryUnregister(providerName);

                final String oldRegistrationId = currentProvider.getRegistrationId();
                unregister(currentProvider.getName());
                fakeOnUnregistered(providerName, oldRegistrationId);
            } else {
                OPFLog.w("Unregistration wasn't performed because already unregistered.");
            }
        }
    }

    @SuppressWarnings({"UnusedDeclaration", "PMD.UnusedPrivateMethod"})
    private boolean canSendMessages() {
        throw new UnsupportedOperationException("Not supported in current version");
    }

    @SuppressWarnings({"UnusedDeclaration", "PMD.UnusedPrivateMethod", "PMD.UnusedFormalParameter"})
    private void sendMessage(@NonNull final Message message) {
        throw new UnsupportedOperationException("Not supported in current version");
    }

    /**
     * Returns the registration ID if there's the registered push provider, null otherwise.
     *
     * @return The registration ID if there's the registered push provider, null otherwise.
     */
    @Nullable
    @Override
    public String getRegistrationId() {
        if (currentProvider != null) {
            return currentProvider.getRegistrationId();
        }

        return null;
    }

    /**
     * Returns the current provider name if there's the registered push provider, null otherwise.
     *
     * @return The current provider name if there's the registered push provider, null otherwise.
     */
    @Nullable
    @Override
    public String getProviderName() {
        if (currentProvider != null) {
            return currentProvider.getName();
        }

        return null;
    }

    /**
     * Returns the registered push provider.
     *
     * @return The registered push provider. Can be null.
     */
    @Nullable
    @Override
    public PushProvider getCurrentProvider() {
        return currentProvider;
    }

    /**
     * Returns the {@link org.onepf.opfpush.OPFPushHelper.ReceivedMessageHandler} instance.
     * Intended for the internal use, should never be called directly.
     *
     * @return The {@link org.onepf.opfpush.OPFPushHelper.ReceivedMessageHandler} instance.
     */
    @NonNull
    @Override
    public ReceivedMessageHandler getReceivedMessageHandler() {
        checkInit(true);
        return receivedMessageHandler;
    }

    /**
     * Returns {@code true} if the {@code OPFPushHelper} is registered, false otherwise.
     *
     * @return {@code true} if the {@code OPFPushHelper} is registered, false otherwise.
     */
    @Override
    public boolean isRegistered() {
        return settings.getState() == REGISTERED;
    }

    /**
     * Returns {@code true} if the registration operation is being performed at the moment.
     *
     * @return {@code true} if the registration operation is being performed at the moment.
     */
    @Override
    public boolean isRegistering() {
        return settings.getState() == REGISTERING;
    }

    @Override
    public void onNeedRetryRegistration() {
        OPFLog.logMethod();
        OPFLog.d("Current provider : " + currentProvider);
        settings.clear();
        if (currentProvider != null) {
            currentProvider.onRegistrationInvalid();
            currentProvider = null;
        }
        register();
    }

    @NonNull
    @Override
    public String toString() {
        return "OPFPushHelper{"
                + "options="
                + configuration
                + ", currentProvider="
                + currentProvider
                + ", initDone="
                + isInitDone()
                + ", registered="
                + isRegistered()
                + '}';
    }

    @SuppressFBWarnings({"DC_DOUBLECHECK", "DC_DOUBLECHECK"})
    @Override
    void init(@NonNull final Configuration initialConfiguration) {
        OPFLog.logMethod(initialConfiguration);

        if (this.configuration == null) {
            synchronized (initLock) {
                if (this.configuration == null) {
                    this.configuration = initialConfiguration;
                }
            }
        }

        final List<PushProvider> providers = configuration.getProviders();
        for (PushProvider provider : providers) {
            provider.checkManifest(configuration.getCheckManifestHandler());
            providersByHostApps.put(provider.getHostAppPackage(), provider.getName());
        }

        retryManager = RetryManager.init(appContext, InfinityExponentialBackoffManager.getInstance());

        final EventListener eventListener = configuration.getEventListener();
        final boolean isOPFReceiverRegistered = isOPFReceiverRegistered();

        OPFLog.d("isOPFReceiverRegistered == " + isOPFReceiverRegistered
                + "; eventListenerWrapper == " + eventListener);
        if (isOPFReceiverRegistered && eventListener != null) {
            throw new IllegalStateException("You can't register OPFReceiver and set event listener");
        } else if (!isOPFReceiverRegistered && eventListener == null) {
            throw new IllegalStateException("You must register OPFReceiver or set event listener");
        }

        initSortedProviderList();
        this.eventListenerWrapper = EventListenerWrapperCreator
                .getEventListenerWrapper(eventListener);
        restoreLastProvider();
        OPFLog.i("Init done.");
    }

    @Override
    boolean isInitDone() {
        synchronized (initLock) {
            return configuration != null;
        }
    }

    @Override
    void restartRegisterOnBoot() {
        OPFLog.logMethod();

        checkInit(true);
        settings.clear();
        register();
    }

    @Override
    void register(@NonNull final String providerName) {
        synchronized (registrationLock) {
            register(getProviderWithException(providerName));
        }
    }

    @Override
    void unregister(@NonNull final String providerName) {
        synchronized (registrationLock) {
            unregister(getProviderWithException(providerName));
        }
    }

    @SuppressWarnings("PMD.OneDeclarationPerLine")
    @Override
    void registerNextAvailableProvider(@Nullable final String prevProviderName) {
        synchronized (registrationLock) {
            OPFLog.logMethod(prevProviderName);

            final int providersCount = sortedProvidersList.size();
            final int prevProviderPosition = getProviderPosition(sortedProvidersList, prevProviderName);

            for (int i = (prevProviderPosition + 1) % providersCount, j = 0;
                 j < providersCount;
                 i = (i + 1) % providersCount, j++) {

                final PushProvider provider = sortedProvidersList.get(i);
                final String providerName = provider.getName();
                OPFLog.d("Provider name : " + providerName);

                final AvailabilityResult providerAvailability = provider.getAvailabilityResult();
                if (!providerAvailability.isAvailable()) {
                    final Integer availabilityErrorCode = providerAvailability.getErrorCode();
                    OPFLog.d("Provider isn't available. Error code : " + availabilityErrorCode);
                    if (availabilityErrorCode != null) {
                        registerProviderErrors.put(
                                providerName,
                                new UnrecoverablePushError(
                                        AVAILABILITY_ERROR,
                                        providerName,
                                        availabilityErrorCode
                                )
                        );
                    }
                } else if (!registerProviderErrors.containsKey(providerName)) {
                    OPFLog.d("Provider is available.");
                    retryManager.cancelRetryRegister(providerName);
                    register(provider);
                    return;
                }
            }

            settings.saveState(UNREGISTERED);
            OPFLog.w("No more available providers.");
            eventListenerWrapper.onNoAvailableProvider(appContext, registerProviderErrors);
        }
    }

    @Nullable
    @Override
    String getProviderNameByHostApp(@Nullable final String appPackage) {
        OPFLog.logMethod(appPackage);
        return providersByHostApps.get(appPackage);
    }

    private void cancelAllOperationsForProvider(@NonNull final String providerName) {
        OPFLog.logMethod(providerName);
        retryManager.cancelRetryAllOperations(providerName);
    }

    private void checkInit(final boolean needInit) {
        final boolean isInit = isInitDone();
        if (needInit != isInit) {
            throw new InitException(isInit);
        }
    }

    private void onProviderUnavailable(@NonNull final PushProvider provider) {
        OPFLog.logMethod(provider);
        final String providerName = provider.getName();

        cancelAllOperationsForProvider(providerName);
        settings.removeRegisteringProvider(providerName);
        settings.removeUnregisteringProvider(providerName);
        provider.onUnavailable();
    }

    private void restoreLastProvider() {
        OPFLog.logMethod();

        final PushProvider lastProvider = getLastProvider();
        if (lastProvider == null) {
            OPFLog.i("No last provider.");
            return;
        }

        OPFLog.d("Try restore last provider '%s'.", lastProvider);

        if (lastProvider.getAvailabilityResult().isAvailable() && lastProvider.isRegistered()) {
            OPFLog.i("Last provider is available and registered");
            currentProvider = lastProvider;
            settings.saveState(REGISTERED);
        } else {
            OPFLog.i("Last provider is unavailable or unregistered");
            settings.clear();
            currentProvider = null;
            onProviderUnavailable(lastProvider);
        }
    }

    /**
     * Registers a first available provider.
     */
    private void registerFirstAvailableProvider() {
        OPFLog.logMethod();
        registerNextAvailableProvider(null);
    }

    private int getProviderPosition(@NonNull final List<PushProvider> providers,
                                    @Nullable final String providerName) {
        OPFLog.logMethod(providers, providerName);

        final int providersCount = providers.size();
        if (providerName != null) {
            for (int i = 0; i < providersCount; i++) {
                if (providerName.equals(providers.get(i).getName())) {
                    return i;
                }
            }
        }

        return providersCount - 1;
    }

    /**
     * Starts register the provider.
     *
     * @param provider Provider for registration.
     */
    private void register(@NonNull final PushProvider provider) {
        OPFLog.logMethod(provider);

        final String regId = provider.getRegistrationId();
        final String providerName = provider.getName();
        if (settings.isProviderUnregistrationPerforming(providerName)) {
            OPFLog.i("Unregistration is being performed for provider %s", provider);

            //reset retrying backoff
            retryManager.cancelRetryUnregister(providerName);
            unregister(providerName);

            settings.savePendingRegistrationProvider(providerName);
        } else if (provider.isRegistered() && !TextUtils.isEmpty(regId) && !isRegistering()) {
            OPFLog.i("Provider %s as already registered", provider);

            settings.removePendingRegistrationProvider();
            receivedMessageHandler.onRegistered(provider.getName(), regId);
        } else if (provider.getAvailabilityResult().isAvailable()) {
            OPFLog.i("Provider %s is available", provider);

            settings.saveState(REGISTERING);
            settings.removePendingRegistrationProvider();
            settings.saveRegisteringProvider(providerName);
            RegisteringTimeoutController.setTimeout(appContext, providerName);
            provider.register();
        } else {
            OPFLog.i("Provider %s is no available", provider);

            settings.removePendingRegistrationProvider();
            onProviderUnavailable(provider);
            register();
        }
    }

    private void unregister(@NonNull final PushProvider provider) {
        OPFLog.logMethod(provider);

        final String providerName = provider.getName();
        if (settings.isProviderRegistrationPerforming(providerName)) {
            OPFLog.i("Registration is being performed for provider %s", provider);

            //reset retrying backoff
            retryManager.cancelRetryRegister(providerName);
            register(providerName);

            settings.savePendingUnregistrationProvider(providerName);
        } else if (!provider.isRegistered()) {
            OPFLog.i("Provider %s as already unregistered", provider);

            settings.removePendingUnregistrationProvider();
            receivedMessageHandler.onUnregistered(providerName, provider.getRegistrationId());
        } else if (provider.getAvailabilityResult().isAvailable()) {
            OPFLog.i("Provider %s is available", provider);

            settings.removePendingUnregistrationProvider();
            settings.saveUnregisteringProvider(providerName);
            provider.unregister();
        } else {
            OPFLog.i("Provider %s is no available", provider);

            final String pendingRegistrationProvider = settings.getPendingRegistrationProvider();
            settings.removePendingUnregistrationProvider();
            onProviderUnavailable(provider);
            if (providerName.equals(pendingRegistrationProvider)) {
                registerNextAvailableProvider(providerName);
            }
        }
    }

    @Nullable
    private PushProvider getProvider(@NonNull final String providerName) {
        OPFLog.logMethod(providerName);

        for (PushProvider provider : sortedProvidersList) {
            if (providerName.equals(provider.getName())) {
                return provider;
            }
        }

        OPFLog.w("There isn't provider with name \"" + providerName + "\"");
        return null;
    }

    @NonNull
    private PushProvider getProviderWithException(@NonNull final String providerName) {
        OPFLog.logMethod(providerName);

        final PushProvider provider = getProvider(providerName);
        if (provider == null) {
            throw new IllegalStateException(String.format(
                    Locale.US,
                    "Provider with name '%s' not found.",
                    providerName
            ));
        }
        return provider;
    }

    @Nullable
    private PushProvider getLastProvider() {
        OPFLog.logMethod();

        final String storedProviderName = settings.getLastProviderName();
        if (!TextUtils.isEmpty(storedProviderName)) {
            final PushProvider provider = getProvider(storedProviderName);
            if (provider != null) {
                return provider;
            }

            settings.saveLastProvider(null);
        }

        OPFLog.i("There isn't a stored provider");
        return null;
    }

    private void initSortedProviderList() {
        OPFLog.logMethod();
        sortedProvidersList = new ArrayList<>(configuration.getProviders());
        if (!configuration.isSelectSystemPreferred()) {
            OPFLog.d("No system preferred");
            return;
        }

        Collections.sort(sortedProvidersList, new Comparator<PushProvider>() {
            @Override
            public int compare(PushProvider leftProvider, PushProvider rightProvider) {
                final String leftHostAppPackage = leftProvider.getHostAppPackage();
                final String rightHostAppPackage = rightProvider.getHostAppPackage();

                boolean isLeftProviderSystem = false;
                boolean isRightProviderSystem = false;
                if (leftHostAppPackage != null) {
                    isLeftProviderSystem = OPFUtils.isSystemApp(appContext, leftHostAppPackage);
                }
                if (rightHostAppPackage != null) {
                    isRightProviderSystem = OPFUtils.isSystemApp(appContext, rightHostAppPackage);
                }

                if (isLeftProviderSystem == isRightProviderSystem) {
                    return 0;
                } else if (isLeftProviderSystem) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });
    }

    private void fakeOnUnregistered(@NonNull final String providerName,
                                    @Nullable final String registrationId) {
        OPFLog.logMethod(providerName, registrationId);
        currentProvider = null;
        settings.saveState(UNREGISTERED);
        settings.saveLastProvider(null);
        registerProviderErrors.clear();
        eventListenerWrapper.onUnregistered(appContext, providerName, registrationId);
    }

    @SuppressWarnings("PMD.AvoidCatchingGenericException")
    private boolean isOPFReceiverRegistered() {
        OPFLog.logMethod();
        final Intent intentBroadcastReceive = new Intent(ACTION_RECEIVE);
        final Intent intentBroadcastRegistration = new Intent(ACTION_REGISTRATION);
        final Intent intentBroadcastUnregistration = new Intent(ACTION_UNREGISTRATION);
        final Intent intentBroadcastNoAvailableProvider = new Intent(ACTION_NO_AVAILABLE_PROVIDER);

        try {
            OPFChecks.checkReceiver(appContext, intentBroadcastReceive);
            OPFChecks.checkReceiver(appContext, intentBroadcastRegistration);
            OPFChecks.checkReceiver(appContext, intentBroadcastUnregistration);
            OPFChecks.checkReceiver(appContext, intentBroadcastNoAvailableProvider);
        } catch (RuntimeException e) {
            return false;
        }
        return true;
    }

    /**
     * Handles messages that were received by a push provider receiver.
     */
    @SuppressWarnings("UnusedDeclaration")
    private final class ReceivedMessageHandlerImpl implements ReceivedMessageHandler {

        private final Handler handler = new Handler(Looper.getMainLooper());

        /**
         * A push provider calls this method when a new message is received.
         *
         * @param providerName The name of the provider which has received the message.
         * @param extras       The message extras.
         */
        @Override
        public void onMessage(@NonNull final String providerName,
                              @Nullable final Bundle extras) {
            OPFLog.logMethod(providerName);
            if (currentProvider != null && providerName.equals(currentProvider.getName())) {
                settings.saveState(REGISTERED);

                //noinspection InnerClassTooDeeplyNested
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //All operations with NotificationMaker should are performed in the main thread.
                        //It saves users from having to make thread safe NotificationMaker.
                        final NotificationMaker notificationMaker = currentProvider.getNotificationMaker();
                        if (extras != null && notificationMaker.needShowNotification(extras)) {
                            notificationMaker.showNotification(appContext, extras);
                        } else {
                            eventListenerWrapper.onMessage(appContext, providerName, extras);
                        }
                    }
                });
            } else {
                OPFLog.w("Ignore onMessage from provider " + providerName
                        + ". Current provider is " + currentProvider);
            }
        }

        /**
         * A push provider calls this method when the server have deleted some pending messages
         * because they were collapsible.
         *
         * @param providerName  The name of the provider which has received the message.
         * @param messagesCount Deleted messages count. If the messages count is unknown, than
         *                      the {@link org.onepf.opfpush.OPFConstants#MESSAGES_COUNT_UNKNOWN} value
         *                      is passed as an argument.
         */
        @Override
        public void onDeletedMessages(@NonNull final String providerName,
                                      final int messagesCount) {
            OPFLog.logMethod(providerName, messagesCount);
            if (currentProvider != null && providerName.equals(currentProvider.getName())) {
                settings.saveState(REGISTERED);
                eventListenerWrapper.onDeletedMessages(appContext, providerName, messagesCount);
            } else {
                OPFLog.w("Ignore onDeletedMessages from provider " + providerName
                        + ". Current provider is " + currentProvider);
            }
        }

        /**
         * A push provider calls this method when the message about successful registration is received.
         *
         * @param providerName   The name of the provider which has been registered for pushes.
         * @param registrationId The new registration ID for the instance of your app.
         */
        @Override
        public void onRegistered(@NonNull final String providerName,
                                 @NonNull final String registrationId) {
            synchronized (registrationLock) {
                OPFLog.logMethod(providerName, registrationId);
                cancelAllOperationsForProvider(providerName);
                settings.removeRegisteringProvider(providerName);

                if (isRegistered()) {
                    OPFLog.d("Registration state is REGISTERED");
                    return;
                }

                OPFLog.i("Successfully register provider '%s'.", providerName);
                settings.saveState(REGISTERED);
                settings.saveLastAndroidId(
                        Secure.getString(appContext.getContentResolver(), ANDROID_ID)
                );
                currentProvider = getProviderWithException(providerName);
                settings.saveLastProvider(currentProvider);
                registerProviderErrors.clear();

                eventListenerWrapper.onRegistered(appContext, providerName, registrationId);

                if (providerName.equals(settings.getPendingUnregistrationProvider())) {
                    unregister(providerName);
                }
            }
        }

        /**
         * A push provider calls this method when the message about successful unregistration is received.
         *
         * @param providerName      The name of the provider which has been unregistered for pushes.
         * @param oldRegistrationId The registration ID for the instance of your app that is now unregistered.
         */
        @Override
        public void onUnregistered(@NonNull final String providerName,
                                   @Nullable final String oldRegistrationId) {
            synchronized (registrationLock) {
                OPFLog.logMethod(providerName, oldRegistrationId);
                OPFLog.i("Successfully unregister provider '%s'.", providerName);
                settings.removeUnregisteringProvider(providerName);
                if (providerName.equals(settings.getPendingRegistrationProvider())) {
                    register(providerName);
                }
            }
        }

        /**
         * A push providers calls this method when a registration error is received.
         *
         * @param providerName The name of the provider which has received the registration error.
         * @param error        The instance of the occurred error.
         */
        @Override
        public void onRegistrationError(@NonNull final String providerName,
                                        @NonNull final PushError error) {
            synchronized (registrationLock) {
                OPFLog.logMethod(providerName, error);

                if (isRegistered()) {
                    OPFLog.d("Registration state is REGISTERED");
                    return;
                }

                OPFLog.i("Registration error has been received : " + error);
                settings.saveState(UNREGISTERED);
                if (error.isRecoverable()
                        && retryManager.hasTries(providerName, REGISTER)) {
                    retryManager.postRetryRegister(providerName);
                } else {
                    registerProviderErrors.put(providerName, (UnrecoverablePushError) error);
                    retryManager.reset(providerName, REGISTER);
                    settings.removeRegisteringProvider(providerName);
                    if (providerName.equals(settings.getPendingUnregistrationProvider())) {
                        unregister(providerName);
                    }

                    registerNextAvailableProvider(providerName);
                }
            }
        }

        /**
         * A push provider calls this method when an unregistration error is received.
         *
         * @param providerName The name of the provider which has received the unregistration error.
         * @param error        The instance of the occurred error.
         */
        @Override
        public void onUnregistrationError(@NonNull final String providerName,
                                          @NonNull final PushError error) {
            synchronized (registrationLock) {
                OPFLog.logMethod(providerName, error);

                final PushProvider provider = getProviderWithException(providerName);
                if (!provider.isRegistered()) {
                    OPFLog.i("Provider already unregistered.");
                    return;
                }

                if (error.isRecoverable()
                        && retryManager.hasTries(providerName, UNREGISTER)) {
                    OPFLog.i("Error while unregister provider %1$s : %2$s. Unregistration will be retried",
                            providerName, error);
                    retryManager.postRetryUnregister(providerName);
                } else {
                    OPFLog.w("Error while unregister provider %1$s : %2$s",
                            providerName, error);
                    settings.removeUnregisteringProvider(providerName);
                    if (providerName.equals(settings.getPendingRegistrationProvider())) {
                        register(providerName);
                    }
                }
            }
        }

        /**
         * A push provider calls this method when an error of unknown operation is received.
         * The right callback method is chosen depends on the current {@code OPFPushHelper} state.
         *
         * @param providerName The name of the provider which has received the error.
         * @param error        The instance of the occurred error.
         */
        @Override
        public void onError(@NonNull final String providerName, @NonNull final PushError error) {
            synchronized (registrationLock) {
                OPFLog.logMethod(providerName, error);

                final State state = settings.getState();
                final boolean isProviderRegistered = getProviderWithException(providerName).isRegistered();
                OPFLog.i("Error occurred. Registration state : "
                        + state + " Provider.isRegistered == " + isProviderRegistered);
                if (state == REGISTERING || !isProviderRegistered) {
                    onRegistrationError(providerName, error);
                } else {
                    onUnregistrationError(providerName, error);
                }
            }
        }
    }
}


text:
package powercrystals.minefactoryreloaded.api;

import net.minecraft.item.ItemStack;
import net.minecraft.world.World;

/**
 * @author PowerCrystals
 *
 * Defines a plantable object for use in the Planter.
 */
public interface IFactoryPlantable
{
	/**
	 * @return The block or item ID this plantable is managing.
	 */
	public int getSeedId();

	/**
	 * @param world The world instance this block or item will be placed into.
	 * @param x The destination X coordinate.
	 * @param y The destination Y coordinate.
	 * @param z The destination Z coordinate.
	 * @param stack The stack being planted.
	 * @return The block ID that will be placed into the world.
	 */
	public int getPlantedBlockId(World world, int x, int y, int z, ItemStack stack);

	/**
	 * @param world The world instance this block or item will be placed into.
	 * @param x The destination X coordinate.
	 * @param y The destination Y coordinate.
	 * @param z The destination Z coordinate.
	 * @param stack The stack being planted.
	 * @return The block metadata that will be placed into the world.
	 */
	public int getPlantedBlockMetadata(World world, int x, int y, int z, ItemStack stack);

	/**
	 * @param world The world instance this block or item will be placed into.
	 * @param x The destination X coordinate.
	 * @param y The destination Y coordinate.
	 * @param z The destination Z coordinate.
	 * @param stack The stack being planted.
	 * @return True if this plantable can be placed at the provided coordinates.
	 */
	public boolean canBePlantedHere(World world, int x, int y, int z, ItemStack stack);

	/**
	 * Called before planting is performed. Used to till soil, for example.
	 * @param world The world instance this block or item will be placed into.
	 * @param x The destination X coordinate.
	 * @param y The destination Y coordinate.
	 * @param z The destination Z coordinate.
	 * @param stack The stack being planted.
	 */
	public void prePlant(World world, int x, int y, int z, ItemStack stack);

	/**
	 * Called after planting is performed. Usually empty.
	 * @param world The world instance this block or item will be placed into.
	 * @param x The destination X coordinate.
	 * @param y The destination Y coordinate.
	 * @param z The destination Z coordinate.
	 * @param stack The stack being planted.
	 */
	public void postPlant(World world, int x, int y, int z, ItemStack stack);
}


text:
import { Corner24 } from "../../";

export = Corner24;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of map</title>
  <meta name="keywords" content="map">
  <meta name="description" content="MAP Map ImageGroup coordinate to a new representation">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html v1.5 © 2003-2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../../../../m2html.css">

Home >  .. > SMASHtoolbox > +SMASH > +ImageAnalysis > @ImageGroup > map.m

map

PURPOSE

MAP Map ImageGroup coordinate to a new representation

SYNOPSIS

function object=map(object,coordinate,method,argument)

DESCRIPTION

MAP Map ImageGroup coordinate to a new representation

 This method applies a mapping function to one or both coordinate
 arrays in ImageGroup object.  It is intended for advanced users only.
 For simple transformations, use the shift and scale methods.  Many data
 transformations can be performed directly.
    >> object=2*object+1; % Data is multipied by 2 and added by one

 If the above solutions are insufficient, this method should be called
 with the following syntax.
    >> object=map(object,coordinate,method,argument);

 Valid coordinate choices are 'Grid1', 'Grid2', and 'Data'.  Three mapping
 methods--'polynomial','table', and 'custom'--are supported.  The final
 input depends on the method. Polynomial mapping requires a N+1 length for
 a N-th order polynomial. Table mapping requires two-column table of input
 and output values used for interpolation.  Custom mapping requires a
 handle to a function that accepts and returns a single array; note that
 this array may have one or two columns, depending on the coordinate
 choice.

 see also ImageGroup

CROSS-REFERENCE INFORMATION

This function calls:

map	MAP Map ImageGroup coordinate to a new representation

split	SPLIT Divide ImageGroup into Image objects

This function is called by:

map	MAP Map ImageGroup coordinate to a new representation

SOURCE CODE

0001 %MAP Map ImageGroup coordinate to a new representation
0002 %
0003 % This method applies a mapping function to one or both coordinate
0004 % arrays in ImageGroup object.  It is intended for advanced users only.
0005 % For simple transformations, use the shift and scale methods.  Many data
0006 % transformations can be performed directly.
0007 %    >> object=2*object+1; % Data is multipied by 2 and added by one
0008 %
0009 % If the above solutions are insufficient, this method should be called
0010 % with the following syntax.
0011 %    >> object=map(object,coordinate,method,argument);
0012 %
0013 % Valid coordinate choices are 'Grid1', 'Grid2', and 'Data'.  Three mapping
0014 % methods--'polynomial','table', and 'custom'--are supported.  The final
0015 % input depends on the method. Polynomial mapping requires a N+1 length for
0016 % a N-th order polynomial. Table mapping requires two-column table of input
0017 % and output values used for interpolation.  Custom mapping requires a
0018 % handle to a function that accepts and returns a single array; note that
0019 % this array may have one or two columns, depending on the coordinate
0020 % choice.
0021 %
0022 % see also ImageGroup
0023
0024 % created January 29, 2016 by Sean Grant (Sandia National Laboratories/UT)
0025
0026 % Note: as of making this, the Image function will work on ImageGroups
0027 % directly without this.
0028 function object=map(object,coordinate,method,argument)
0029
0030 % split up ImageGroup
0031 temp=cell(object.NumberImages,1);
0032 tempObj=cell(object.NumberImages,1);
0033
0034 % Perform function on each image individually
0035 [temp{:}]=split(object);
0036 for n=1:object.NumberImages
0037     tempObj{n}=map(temp{n},coordinate,method,argument);
0038 end
0039
0040 % remake ImageGroup
0041 object=SMASH.ImageAnalysis.ImageGroup(tempObj{:});
0042
0043
0044 end
0045

<address>Generated on Tue 10-Nov-2020 17:53:50 by m2html © 2005</address>


text:
Validate open external URL in browser support

## Spec Link

https://crosswalk-project.org/jira/browse/XWALK-3690


text: strong, b { font-weight: bold; }


text:
.debug {
    background-color: pink;
}


text:
package com.clearlyspam23.GLE;

import java.awt.Component;
import java.util.List;

public abstract class PropertyTemplate<T extends Component, E> implements Nameable{

	@SuppressWarnings("rawtypes")
	private PropertyDefinition definition;

	private String name;

	protected PropertyTemplate(){

	}

	@SuppressWarnings("rawtypes")
	public PropertyTemplate(PropertyDefinition def){
		this.definition = def;
	}

	public final String getName(){
		return name;
	}

	public final void setName(String name){
		this.name = name;
	}

	@SuppressWarnings("rawtypes")
	public final PropertyDefinition getDefinition(){
		return definition;
	}

	@SuppressWarnings("rawtypes")
	public final void setDefinition(PropertyDefinition def){
		definition = def;
	}

//	public final void setToProperty(T component, Property<E> value){
//		setToValue(component, value.getValue());
//	}
//
//	public final Property<E> getPropertyFrom(T component){
//		return new Property<E>(definition.getName(), getValueFrom(component));
//	}
//
//	public final Property<E> getDefaultProperty(){
//		return new Property<E>(definition.getName(), getDefaultValue());
//	}

	public abstract T getEditorComponent();

	public abstract void setToValue(T component, E value);

	public abstract E getValueFrom(T component);

	public abstract E getDefaultValue();

	public List<String> checkValidity(){
		return null;
	}

}


text:
module Main where

import HW01Tests

main :: IO ()
main = do
  putStrLn "hello eric"


text:
{% extends "templates/docs/layout.njk" %}
{% set page_title ="Dividers" %}
{% set active_accordion ="elements" %}
{% set active_page ="dividers" %}

{% block main %}

    {% include "templates/docs/dividers/text_dividers.njk" %}
    <hr class="light" />
    {% include "templates/docs/dividers/hr_dividers.njk" %}

{% endblock %}


text:
import Ember from 'ember';
import Suggester from '../utils/suggester';

export default Ember.View.extend({
  classNames: ["story"],

  templateName: function() {
    if (this.get('content.model.isDeleted')) {
      return "story/deleted";
    }
    return "story/" + this.get('content.model.type');
  }.property('content.model.type', 'content.model.isDeleted'),

  rerenderOnDeletion: function() {
    this.rerender();
  }.observes('content.model.isDeleted'),

  truncateLongComments: function() {
    var commentEl = this.$(".comment-text")[0];
    if (commentEl && commentEl.offsetHeight < commentEl.scrollHeight - 1) {
      this.get('controller').set('overflowing', true);
    }
  },

  hideSpoilers: function() {
    if (this.get('content.model.type') === "comment") {
      Ember.run.scheduleOnce('afterRender', this, function() {
        this.$(".spoiler").spoilerAlert();
      });
    }
  }.on('didInsertElement').observes('content.showAll', 'content.loadingAll'),

  didInsertElement: function() {
    var storyType = this.get('content.model.type');
    if (storyType === "comment") {
      this.truncateLongComments();
      this.$("img").load(() => {
        this.truncateLongComments();
      });

      Suggester(this.$('textarea'));
    }
  }
});


text:
package org.pa.library.ui.console.ctrl.functionCtrl;

import java.util.ArrayList;
import java.util.List;
import org.pa.library.logic.SearchOperation;
import org.pa.library.model.Book;
import org.pa.library.model.Library;
import org.pa.library.ui.console.viewer.functionViewers.BookListViewer;
import org.pa.library.ui.console.viewer.functionViewers.BookManageViewer;
import org.pa.library.ui.console.viewer.functionViewers.BookManageViewer;
import org.pa.library.ui.console.viewer.functionViewers.SearchMenuViewer;
public class SearchCtrl {
    private SearchOperation searchOperation   = new SearchOperation();
    private BookManageViewer bookManageViewer = new BookManageViewer();
    private SearchMenuViewer searchMenuViewer = new SearchMenuViewer();
    private BookListViewer bookListViewer     = new BookListViewer();
    // put library in constructor.

    public List<Book> searchBook(Library library, Book request) {// don't know how to extract this method to search Operation leaving out the requestFail exception.

        List<Book> foundBooks = new ArrayList<Book>();
        List<Book> booksByTitle = new ArrayList<Book>();
        List<Book> booksByLanguage = new ArrayList<Book>();
        List<Book> booksByYearOfIssuing = new ArrayList<Book>();
        List<Book> booksByAuthor = new ArrayList<Book>();
        boolean emptyTitle = request.getTitle() == null;
        boolean emptyLanguage = request.getLanguage() == null;
        boolean emptyYearOfIssuing = request.getYearOfIssuing() == null;
        boolean emptyAuthor = request.getAuthors().size() == 0;

        List<ArrayList<Book>> list = new ArrayList<ArrayList<Book>>();

        if(!emptyTitle) {
        booksByTitle = searchOperation.searchTitle(library, request.getTitle());
        }
        if(!emptyLanguage) {
        booksByLanguage = searchOperation.searchLanguage(library, request.getLanguage());
        }
        if(!emptyYearOfIssuing) {
        booksByYearOfIssuing = searchOperation.searchYearOfIssuing(library, request.getYearOfIssuing());
        }
        if(!emptyAuthor) {
        booksByAuthor = searchOperation.searchAuthor(library, request.getAuthors());
        }
        // make a list of non-empty lists
        if (booksByTitle.size() != 0) {
            list.add((ArrayList<Book>) booksByTitle);
        }
        if (booksByLanguage.size() != 0) {
            list.add((ArrayList<Book>) booksByLanguage);
        }
        if (booksByYearOfIssuing.size() != 0) {
            list.add((ArrayList<Book>) booksByYearOfIssuing);
        }
        if (booksByAuthor.size() != 0) {
            list.add((ArrayList<Book>) booksByAuthor);
        }
          // pick the first list in the list<List>, call retainAll from this list on all of the lists
        for(ArrayList<Book> arrayList : list) {
        list.get(0).retainAll(arrayList);
        }
      //filter out the common items from the 4 lists
          foundBooks = list.get(0);

        if (emptyTitle && emptyLanguage && emptyYearOfIssuing && emptyAuthor) {
            bookManageViewer.answerBookRequestFail();
            searchMenuViewer.makeSearchMenu();
        }
        return foundBooks;

    }

   public void showFoundBooks(Library library, List<Book> foundBooks) {

        if (foundBooks.size() == 0) {
                bookManageViewer.answerBookSearchFail();
            }
           else bookListViewer.listFoundBooks(foundBooks);

        }
}


text:
package net.sf.mmm.persistence.base.jpa;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import javax.persistence.Version;

import net.sf.mmm.util.entity.api.PersistenceEntity;
import net.sf.mmm.util.entity.base.AbstractRevisionedEntity;

/**
 * This is the abstract base-implementation of a {@link net.sf.mmm.util.entity.api.GenericEntity} using the
 * {@link javax.persistence JPA} (Java Persistence API).

 *
 * @param <ID> is the type of the {@link #getId() primary key}.
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 1.0.0
 */
@MappedSuperclass
public abstract class AbstractJpaEntity<ID> extends AbstractRevisionedEntity<ID> implements PersistenceEntity<ID> {

  /** UID for serialization. */
  private static final long serialVersionUID = 3256209723131574786L;

  /**
   * The constructor.
   */
  public AbstractJpaEntity() {

    super();
  }

  /**
   * ATTENTION:

   * If your ID is not {@link GeneratedValue generated}, you need to override this method. In this case you
   * can also override {@link #setId(Object)} to change the visibility to public.

   *

   *
   * {@inheritDoc}
   */
  @Override
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  public ID getId() {

    return super.getId();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  @Version
  @Column(name = "version")
  public int getModificationCounter() {

    return super.getModificationCounter();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  @Transient
  public Number getRevision() {

    return super.getRevision();
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="100dp"
              android:background="#bbaacc"
              android:orientation="vertical"
              android:gravity="center"
              android:padding="8dp"
    >

    <TextView
        android:id="@+id/type_c_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        tools:text="type name"
        />

    <TextView
        android:id="@+id/type_c_age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:textSize="16sp"
        tools:text="18"
        />

</LinearLayout>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>What Input?</title>

    <link rel="stylesheet" href="styles/index.css">

What Input?

        A global utility for tracking the current input method (mouse, keyboard, or touch), as well as the current intent (mouse, keyboard, or touch).

        Tab, click or tap the links and form controls to see how What Input allows them to be styled differently.

Cras justo odio

                Dapibus ac facilisis in

Morbi leo risus

                Porta ac consectetur ac

                Vestibulum at eros

              <button data-module="alert" data-message="This button is not inside a form.">Do Something</button>

          <form class="well-column">

              Example Text Input
              <input type="email" id="exampleInput" name="exampleInput">

              Selection
              <select id="exampleSelect" name="exampleSelect">
                <option value="" disabled selected>Select an Option</option>
                <option>Option 1</option>
                <option>Option 2</option>
                <option>Option 3</option>
              </select>

              Example Textarea
              <textarea id="exampleTextarea" name="exampleTextarea"></textarea>

              <input type="checkbox"> Check me out

              <button type="submit" data-module="alert" data-message="This button is inside a form.">Form Submit</button>

          </form>

          Made with ♥ at
          Viget.

          Check out the project
          on GitHub.


text:
package org.apache.ftpserver.usermanager.impl;

import java.io.File;

import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.test.TestUtil;
import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor;
import org.apache.ftpserver.usermanager.DbUserManagerFactory;
import org.apache.ftpserver.usermanager.UserManagerFactory;

/**
*
* @author Apache MINA Project
*
*/
public class ClearTextDbUserManagerTest extends DbUserManagerTest {

    @Override
    protected File getInitSqlScript() {
        return new File(TestUtil.getBaseDir(),
            "src/test/resources/dbusermanagertest-cleartext-hsql.sql");
    }

    @Override
    protected UserManagerFactory createUserManagerFactory() throws FtpException {
        DbUserManagerFactory manager = (DbUserManagerFactory) super.createUserManagerFactory();
        manager.setPasswordEncryptor(new ClearTextPasswordEncryptor());
        return manager;

    }
}


text:
module Api
  module V1
    class AuthenticatedApiController < ActionController::API
      include Pundit
      # protect_from_forgery with: :null_session

      #doorkeeper_for :all
      before_action :doorkeeper_authorize!

      after_action :verify_authorized
      after_action :verify_policy_scoped, :only => :index

      rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

      around_filter :set_current_user

      respond_to :json

      def set_current_user
        User.current_user = current_user
        yield
      ensure
        # to address the thread variable leak issues in Puma/Thin webserver
        User.current_user = nil
      end

      def pundit_user
        user = current_user
        scopes = doorkeeper_token.scopes unless doorkeeper_token.nil?
        [user,scopes]
      end

      # GET /me.json
      def me
        render json:  current_resource_owner
      end

      private
      def user_not_authorized
        head :unauthorized
      end

      # Find the user that owns the access token
      def current_resource_owner
        User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
      end
      def current_user
        User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
      end

    end
  end
end


text:
<!DOCTYPE html>
<html lang="en">
<head>

	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title></title>
	<meta name="description" content="">
	<link rel=canonical href="http://yourwebsite.com/">

	<!-- Stylesheets -->
	<link rel="stylesheet" href="css/main.min.css">

	<!-- Favicons -->
	<link rel="shortcut icon" sizes="16x16 32x32 48x48 64x64" href=http://domain.com/favicon.ico>
	<link rel=apple-touch-icon-precomposed sizes=57x57 href=/img/icons/favicon-57.png>
	<link rel=apple-touch-icon sizes=72x72 href=/img/icons/favicon-72.png>
	<link rel=apple-touch-icon sizes=114x114 href=/img/icons/favicon-114.png>
	<link rel=apple-touch-icon sizes=120x120 href=/img/icons/favicon-120.png>
	<link rel=apple-touch-icon sizes=144x144 href=/img/icons/favicon-144.png>
	<link rel=apple-touch-icon sizes=152x152 href=/img/icons/favicon-152.png>
	<meta name=application-name content=yourappname>
	<meta name=msapplication-TileImage content=/img/icons/favicon-144.png>
	<meta name=msapplication-TileColor content=#FFFFFF>

	<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
	<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
	<!--[if lt IE 9]>
	  <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
	  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
	<![endif]-->

</head>

<body>

</body>
</html>


text:
Smith_Network
=============

2014 NHN NEXT NETWORK


text: You should do that...