text:
import java.util.*;
import java.util.stream.Stream;

class FilterFindIsPresent {
  public static void test(List<String> list) {
    if(list.stream().anyMatch(l -> !l.isEmpty())) {
      System.out.println("oops");
    }
  }
}


text:
LockerRoom.configure do |c|
  c.app_name = 'dummy'
end

redpajama_set_name: RedPajamaGithub


text:
'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var pkg = require( './../package.json' ).name;
var endsWith = require( './../lib/polyfill.js' );

// MAIN //

bench( pkg+'::polyfill', function benchmark( b ) {
	var values;
	var bool;
	var str;
	var i;

	str = 'To be, or not to be, that is the question.';
	values = [
		'.',
		'z',
		'questions'
	];

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		bool = endsWith( str, values[ i%values.length ], str.length );
		if ( typeof bool !== 'boolean' ) {
			b.fail( 'should return a boolean' );
		}
	}
	b.toc();
	if ( !isBoolean( bool ) ) {
		b.fail( 'should return a boolean' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});


text:
.class final Landroid/net/nsd/NsdServiceInfo$1;
.super Ljava/lang/Object;
.source "NsdServiceInfo.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/nsd/NsdServiceInfo;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Landroid/net/nsd/NsdServiceInfo;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 263
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/net/nsd/NsdServiceInfo;
    .locals 8
    .param p1, "in"    # Landroid/os/Parcel;

    .prologue
    const/4 v7, 0x1

    .line 265
    new-instance v1, Landroid/net/nsd/NsdServiceInfo;

    invoke-direct {v1}, Landroid/net/nsd/NsdServiceInfo;-><init>()V

    .line 266
    .local v1, "info":Landroid/net/nsd/NsdServiceInfo;
    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v5

    # setter for: Landroid/net/nsd/NsdServiceInfo;->mServiceName:Ljava/lang/String;
    invoke-static {v1, v5}, Landroid/net/nsd/NsdServiceInfo;->access$002(Landroid/net/nsd/NsdServiceInfo;Ljava/lang/String;)Ljava/lang/String;

    .line 267
    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v5

    # setter for: Landroid/net/nsd/NsdServiceInfo;->mServiceType:Ljava/lang/String;
    invoke-static {v1, v5}, Landroid/net/nsd/NsdServiceInfo;->access$102(Landroid/net/nsd/NsdServiceInfo;Ljava/lang/String;)Ljava/lang/String;

    .line 269
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v5

    if-ne v5, v7, :cond_0

    .line 271
    :try_start_0
    invoke-virtual {p1}, Landroid/os/Parcel;->createByteArray()[B

    move-result-object v5

    invoke-static {v5}, Ljava/net/InetAddress;->getByAddress([B)Ljava/net/InetAddress;

    move-result-object v5

    # setter for: Landroid/net/nsd/NsdServiceInfo;->mHost:Ljava/net/InetAddress;
    invoke-static {v1, v5}, Landroid/net/nsd/NsdServiceInfo;->access$202(Landroid/net/nsd/NsdServiceInfo;Ljava/net/InetAddress;)Ljava/net/InetAddress;
    :try_end_0
    .catch Ljava/net/UnknownHostException; {:try_start_0 .. :try_end_0} :catch_0

    .line 275
    :cond_0
    :goto_0
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v5

    # setter for: Landroid/net/nsd/NsdServiceInfo;->mPort:I
    invoke-static {v1, v5}, Landroid/net/nsd/NsdServiceInfo;->access$302(Landroid/net/nsd/NsdServiceInfo;I)I

    .line 278
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v2

    .line 279
    .local v2, "recordCount":I
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_1
    if-ge v0, v2, :cond_2

    .line 280
    const/4 v3, 0x0

    .line 281
    .local v3, "valueArray":[B
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v5

    if-ne v5, v7, :cond_1

    .line 282
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v4

    .line 283
    .local v4, "valueLength":I
    new-array v3, v4, [B

    .line 284
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->readByteArray([B)V

    .line 286
    .end local v4    # "valueLength":I
    :cond_1
    # getter for: Landroid/net/nsd/NsdServiceInfo;->mTxtRecord:Landroid/util/ArrayMap;
    invoke-static {v1}, Landroid/net/nsd/NsdServiceInfo;->access$400(Landroid/net/nsd/NsdServiceInfo;)Landroid/util/ArrayMap;

    move-result-object v5

    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v6

    invoke-virtual {v5, v6, v3}, Landroid/util/ArrayMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 279
    add-int/lit8 v0, v0, 0x1

    goto :goto_1

    .line 288
    .end local v3    # "valueArray":[B
    :cond_2
    return-object v1

    .line 272
    .end local v0    # "i":I
    .end local v2    # "recordCount":I
    :catch_0
    move-exception v5

    goto :goto_0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1
    .param p1, "x0"    # Landroid/os/Parcel;

    .prologue
    .line 263
    invoke-virtual {p0, p1}, Landroid/net/nsd/NsdServiceInfo$1;->createFromParcel(Landroid/os/Parcel;)Landroid/net/nsd/NsdServiceInfo;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Landroid/net/nsd/NsdServiceInfo;
    .locals 1
    .param p1, "size"    # I

    .prologue
    .line 292
    new-array v0, p1, [Landroid/net/nsd/NsdServiceInfo;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1
    .param p1, "x0"    # I

    .prologue
    .line 263
    invoke-virtual {p0, p1}, Landroid/net/nsd/NsdServiceInfo$1;->newArray(I)[Landroid/net/nsd/NsdServiceInfo;

    move-result-object v0

    return-object v0
.end method


text:
.. _example5:

Example 5: Literal values
-------------------------

The next example illustrates some variations on what we have seen so
far. The example creates and asserts plain, data-typed, and
language-tagged literals, and then conducts searches for them in three
ways:

   - :meth:`getStatements` search, which is an efficient way to match a
     single triple pattern.
   - SPARQL direct match, for efficient multi-pattern search.
   - SPARQL filter match, for sophisticated filtering such as
     performing range matches.

The :meth:`getStatements` and SPARQL direct searches return exactly
the datatype you ask for. The SPARQL filter queries can sometimes
return multiple datatypes. This behavior will be one focus of this
section.

If you are not explicit about the datatype of a value, either when
asserting the triple or when writing a search pattern, AllegroGraph
will deduce an appropriate datatype and use it. This is another focus
of this section. This helpful behavior can sometimes surprise you with
unanticipated results.

Setup
~~~~~

We begin by obtaining a connection object and remvoing all existing data
from the repository

.. literalinclude:: doctest_setup.py
   :language: python_rdf
   :start-after: BEGIN-CONNECT
   :end-before: END-CONNECT

For the sake of coding efficiency, it is good practice to create variables
for namespace strings. We'll use this namespace again and again in the
following example. We have made the URIs in this example very short to
keep the result displays compact.

.. testcode:: example5

   exns = "ex://"
   conn.setNamespace('ex', exns)

Namespace handling, including the :meth:`setNamespace` method, is
described in :ref:`example11`.

The example will use an artificial data set consisting of eight
statements, each illustrating a different kind of literal. The subject
will describe the nature of the literal used as the object, while the
predicate will always be ``<ex://p>``. The example shows how to enter
a full URI string, or alternately how to combine a namespace with a
local resource name.

.. testcode:: example5

   ex_integer = conn.createURI("ex://integer")
   ex_double = conn.createURI("ex://double")
   ex_int = conn.createURI("ex://int")
   ex_long = conn.createURI(
       namespace=exns, localname="long")
   ex_float = conn.createURI(
       namespace=exns, localname="float")
   ex_decimal = conn.createURI(
       namespace=exns, localname="decimal")
   ex_string = conn.createURI(
       namespace=exns, localname="string")
   ex_plain = conn.createURI(
       namespace=exns, localname="plain")

The predicate for all our statements will be the same.

.. testcode:: example5

   pred = conn.createURI(namespace=exns, localname="p")

Now we construct the objects, illustrating various kinds of RDF
literals.

.. testcode:: example5

   from franz.openrdf.vocabulary.xmlschema import XMLSchema

   # Type will be XMLSchema.INTEGER
   forty_two = conn.createLiteral(42)
   # Type will be XMLSchema.DOUBLE
   forty_two_double = conn.createLiteral(42.0)
   forty_two_int = conn.createLiteral(
       '42', datatype=XMLSchema.INT)
   forty_two_long = conn.createLiteral(
       '42', datatype=XMLSchema.LONG)
   forty_two_float = conn.createLiteral(
       '42', datatype=XMLSchema.FLOAT)
   forty_two_decimal = conn.createLiteral(
       '42', datatype=XMLSchema.DECIMAL)
   forty_two_string = conn.createLiteral(
       '42', datatype=XMLSchema.STRING)
   # Creates a plain (untyped) literal.
   forty_two_plain = conn.createLiteral('42')

In four of these statements, we explicitly identified the datatype of
the value in order to create an INT, a LONG, a FLOAT and a
STRING. This is the best practice.

In three other statements, we just handed AllegroGraph numeric-looking
values to see what it would do with them. As we will see in a moment,
``42`` creates an INTEGER, ``42.0`` becomes a DOUBLE, and ``'42'``
becomes a "plain" (untyped) literal value.

.. warning:: Note that plain literals are not *quite* the same thing
             as typed literal strings. A search for a plain literal
             will not always match a typed string, and *vice versa*.)

Now we will now assemble the URIs and values into :class:`statements
<.Statement>` (which are client-side triples):

.. testcode:: example5

   stmt1 = conn.createStatement(ex_integer, pred, forty_two)
   stmt2 = conn.createStatement(ex_double, pred, forty_two_double)
   stmt3 = conn.createStatement(ex_int, pred, forty_two_int)
   stmt4 = conn.createStatement(ex_long, pred, forty_two_long)
   stmt5 = conn.createStatement(ex_float, pred, forty_two_float)
   stmt6 = conn.createStatement(ex_decimal, pred, forty_two_decimal)
   stmt7 = conn.createStatement(ex_string, pred, forty_two_string)
   stmt8 = conn.createStatement(ex_plain, pred, forty_two_plain)

And then add the statements to the triple store on the AllegroGraph
server. We can use either :meth:`add` or :meth:`addStatement` for this
purpose.

.. testcode:: example5

   conn.add(stmt1)
   conn.add(stmt2)
   conn.add(stmt3)
   conn.addStatement(stmt4)
   conn.addStatement(stmt5)
   conn.addStatement(stmt6)
   conn.addStatement(stmt7)
   conn.addStatement(stmt8)

Now we'll complete the round trip to see what triples we get back from
these assertions. This is where we use :meth:`getStatements` in this
example to retrieve and display triples for us:

.. testcode:: example5

   print("Showing all triples using getStatements(). Eight matches.")
   conn.getStatements(None, pred, None, output=True,)

This code prints out all triples from the store. The ``output``
parameter causes the result to be printed on ``stdout`` (it is also
possible to pass a file name or a file-like object as the value of
this parameter to print to other destinations). Without ``output`` the
result would have been returned as a |RepositoryResult| object.

Note that the retrieved literals are of eight types: an int (a 32-bit
integer), an integer (arbitrary precision), a decimal, a long, a
float, a double, a string, and a "plain literal."

.. testoutput:: example5
   :options: +SORT +NORMALIZE_WHITESPACE

   Showing all triples using getStatements(). Eight matches.
   <ex://plain> <ex://p> "42" .
   <ex://string> <ex://p> "42"^^<http://www.w3.org/2001/XMLSchema#string> .
   <ex://decimal> <ex://p> "42.0"^^<http://www.w3.org/2001/XMLSchema#decimal> .
   <ex://float> <ex://p> "4.2E1"^^<http://www.w3.org/2001/XMLSchema#float> .
   <ex://long> <ex://p> "42"^^<http://www.w3.org/2001/XMLSchema#long> .
   <ex://int> <ex://p> "42"^^<http://www.w3.org/2001/XMLSchema#int> .
   <ex://double> <ex://p> "4.2E1"^^<http://www.w3.org/2001/XMLSchema#double> .
   <ex://integer> <ex://p> "42"^^<http://www.w3.org/2001/XMLSchema#integer> .

If you ask for a specific datatype, you will get it. If you leave the
decision up to AllegroGraph, you might get something unexpected such as
a plain literal value.

Numeric literal values
~~~~~~~~~~~~~~~~~~~~~~

Matching 42 without explicit type
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This section explores :meth:`getStatements` and SPARQL matches against
numeric triples. We ask AllegroGraph to find an untyped number,
``42``.

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, pred, 42, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s ?p 42 .}',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery(
       'SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = 42)}',
       output=True)
   print()

We use the :meth:`executeQuery` method to retrieve the result of a
SPARQL query. Like :meth:`getStatements`, it accepts an ``output``
parameter that causes the result to be printed (instead of being
returned as a |TupleQueryResult| object).  Here is what the query
methods discussed in this example would return:

.. Format of decimals has changed in 6.3.0, we need the doctests
   to work with both versions.

.. condtestoutput:: example5
   :options: +SORT +NORMALIZE_WHITESPACE
   :if: ag_version >= (6, 3, 0)

   getStatements():
   <ex://integer> <ex://p> "42"^^<http://www.w3.org/2001/XMLSchema#integer> .

   SPARQL direct match
   --------------
   | s          |
   ==============
   | ex:integer |
   --------------

   SPARQL filter match
   -----------------------------
   | s          | p    | o     |
   =============================
   | ex:integer | ex:p | 42    |
   | ex:double  | ex:p | 4.2E1 |
   | ex:int     | ex:p | 42    |
   | ex:long    | ex:p | 42    |
   | ex:float   | ex:p | 4.2E1 |
   | ex:decimal | ex:p | 42.0  |
   -----------------------------

.. condtestoutput:: example5
   :options: +SORT +NORMALIZE_WHITESPACE
   :if: ag_version < (6, 3, 0)

   getStatements():
   <ex://integer> <ex://p> "42"^^<http://www.w3.org/2001/XMLSchema#integer> .

   SPARQL direct match
   --------------
   | s          |
   ==============
   | ex:integer |
   --------------

   SPARQL filter match
   ------------------------------
   | s          | p    | o      |
   ==============================
   | ex:decimal | ex:p | 42.0   |
   | ex:integer | ex:p | 42     |
   | ex:float   | ex:p | 42.0   |
   | ex:double  | ex:p | 42.0d0 |
   | ex:long    | ex:p | 42     |
   | ex:int     | ex:p | 42     |
   ------------------------------

The :meth:`getStatements` query returned triples containing longs
only. The SPARQL direct match treated the numeric literal as if it had
the type of ``<http://www.w3.org/2001/XMLSchema#integer>`` (see the
SPARQL `specification
<https://www.w3.org/TR/sparql11-query/#QSynLiterals>`__ for
information on how literals are parsed in queries) and returned only
triples with exactly the same type. The SPARQL filter match, however,
opened the doors to matches of multiple numeric types, and returned
ints, floats, longs and doubles.

Matching 42.0 without explicit type
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Now we will try the same queries using ``42.0``.

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, pred, 42.0, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s <ex://p> 42.0 .}',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery(
       'SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = 42.0)}',
       output=True)
   print()

Here is what the query methods discussed in this example would
return:

.. condtestoutput:: example5
   :if: ag_version >= (6, 3, 0)
   :options: +SORT +NORMALIZE_WHITESPACE

   getStatements():
   <ex://double> <ex://p> "4.2E1"^^<http://www.w3.org/2001/XMLSchema#double> .

   SPARQL direct match
   --------------
   | s          |
   ==============
   | ex:decimal |
   --------------

   SPARQL filter match
   -----------------------------
   | s          | p    | o     |
   =============================
   | ex:integer | ex:p | 42    |
   | ex:double  | ex:p | 4.2E1 |
   | ex:int     | ex:p | 42    |
   | ex:long    | ex:p | 42    |
   | ex:float   | ex:p | 4.2E1 |
   | ex:decimal | ex:p | 42.0  |
   -----------------------------

.. condtestoutput:: example5
   :if: ag_version < (6, 3, 0)
   :options: +SORT +NORMALIZE_WHITESPACE

   getStatements():
   <ex://double> <ex://p> "4.2E1"^^<http://www.w3.org/2001/XMLSchema#double> .

   SPARQL direct match
   --------------
   | s          |
   ==============
   | ex:decimal |
   --------------

   SPARQL filter match
   ------------------------------
   | s          | p    | o      |
   ==============================
   | ex:decimal | ex:p | 42.0   |
   | ex:integer | ex:p | 42     |
   | ex:float   | ex:p | 42.0   |
   | ex:double  | ex:p | 42.0d0 |
   | ex:long    | ex:p | 42     |
   | ex:int     | ex:p | 42     |
   ------------------------------

The :meth:`getStatements` search returned a double but not the similar
float. Direct SPARQL match treated ``42.0`` as a decimal (in
accordance with the SPARQL specification). The filter match returned
all numeric types that were equal to 42.0.

Matching "42"^^xsd:int
^^^^^^^^^^^^^^^^^^^^^^

The next section shows the results obtained when querying for a
literal with explicitly specified type. Note that doing this with
:meth:`getStatements` requires passing in a :class:`.Literal` object,
not a raw value.

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, pred, forty_two_int, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s ?p "42"^^xsd:int .}',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery('''
       SELECT ?s ?p ?o WHERE {
          ?s ?p ?o .
          filter (?o = "42"^^xsd:int)
       }''',
       output=True)
   print()

Here is what the query methods discussed in this example would
return:

.. condtestoutput:: example5
   :if: ag_version >= (6, 3, 0)
   :options: +SORT +NORMALIZE_WHITESPACE

   getStatements():
   <ex://int> <ex://p> "42"^^<http://www.w3.org/2001/XMLSchema#int> .

   SPARQL direct match
   ----------
   | s      |
   ==========
   | ex:int |
   ----------

   SPARQL filter match
   -----------------------------
   | s          | p    | o     |
   =============================
   | ex:integer | ex:p | 42    |
   | ex:double  | ex:p | 4.2E1 |
   | ex:int     | ex:p | 42    |
   | ex:long    | ex:p | 42    |
   | ex:float   | ex:p | 4.2E1 |
   | ex:decimal | ex:p | 42.0  |
   -----------------------------

.. condtestoutput:: example5
   :if: ag_version < (6, 3, 0)
   :options: +SORT +NORMALIZE_WHITESPACE

   getStatements():
   <ex://int> <ex://p> "42"^^<http://www.w3.org/2001/XMLSchema#int> .

   SPARQL direct match
   ----------
   | s      |
   ==========
   | ex:int |
   ----------

   SPARQL filter match
   ------------------------------
   | s          | p    | o      |
   ==============================
   | ex:decimal | ex:p | 42.0   |
   | ex:integer | ex:p | 42     |
   | ex:float   | ex:p | 42.0   |
   | ex:double  | ex:p | 42.0d0 |
   | ex:long    | ex:p | 42     |
   | ex:int     | ex:p | 42     |
   ------------------------------

We would get similar results when asking for any other typed literal
(``forty_two_long``, ``forty_two_float``, ...).

Numeric strings and plain literals
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

At this point we are transitioning from tests of numeric matches to
tests of string matches, but there is a gray zone to be explored
first. What do we find if we search for strings that contain numbers?
In particular, what about "plain literal" values that are almost, but
not quite, strings?

Matching "42" as a typed string
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Let's start with a typed string literal.

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, pred, forty_two_string, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s ?p "42"^^xsd:string .}',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery('''
       SELECT ?s ?p ?o WHERE {
          ?s ?p ?o .
          filter (?o = "42"^^xsd:string)
       }''',
       output=True)
   print()

Here are the results:

.. testoutput:: example5
   :options: +SORT +NORMALIZE_WHITESPACE

    getStatements():
    <ex://string> <ex://p> "42"^^<http://www.w3.org/2001/XMLSchema#string> .

    SPARQL direct match
    -------------
    | s         |
    =============
    | ex:plain  |
    | ex:string |
    -------------

    SPARQL filter match
    ------------------------------------------------------------------
    | s         | p    | o                                           |
    ==================================================================
    | ex:string | ex:p | 42^^http://www.w3.org/2001/XMLSchema#string |
    | ex:plain  | ex:p | 42                                          |
    ------------------------------------------------------------------

SPARQL matched both plain and literal strings, but a
:meth:`getStatements` search returned only typed matches. In both
cases numeric literals were ignored.

Matching "42" as a plain literal
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If we try to match a plain (untyped) string value

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, pred, forty_two_plain, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s ?p "42" .}',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery('''
       SELECT ?s ?p ?o WHERE {
          ?s ?p ?o .
          filter (?o = "42")
       }''',
       output=True)
   print()

We will get results consistent with that we saw in the typed case:

.. testoutput:: example5
   :options: +SORT +NORMALIZE_WHITESPACE

    getStatements():
    <ex://plain> <ex://p> "42" .

    SPARQL direct match
    -------------
    | s         |
    =============
    | ex:plain  |
    | ex:string |
    -------------

    SPARQL filter match
    ------------------------------------------------------------------
    | s         | p    | o                                           |
    ==================================================================
    | ex:string | ex:p | 42^^http://www.w3.org/2001/XMLSchema#string |
    | ex:plain  | ex:p | 42                                          |
    ------------------------------------------------------------------

In SPARQL both kinds of string literals were matched, while
:meth:`getStatements` returned only direct matches.

Matching strings
~~~~~~~~~~~~~~~~

In this section we'll set up a variety of string triples and
experiment with matching them using :meth:`getStatements` and SPARQL.

.. note:: :ref:`example12` is a different topic. In this section we're
          doing simple matches of whole strings.

Sample data
^^^^^^^^^^^

For these examples we will use a different data set.

.. testcode:: example5

   name = conn.createURI('ex://name')
   upper_g = conn.createLiteral('Galadriel')
   lower_g = conn.createLiteral('galadriel')
   typed_g = conn.createLiteral('Galadriel', XMLSchema.STRING)
   lang_g = conn.createLiteral('Galadriel', language='sjn')
   upper_a = conn.createLiteral('Artanis')
   lower_a = conn.createLiteral('artanis')
   typed_a = conn.createLiteral('Artanis', XMLSchema.STRING)
   lang_a = conn.createLiteral('Artanis', language='qya')
   conn.addTriple('<ex://upper_g>', name, upper_g)
   conn.addTriple('<ex://lower_g>', name, lower_g)
   conn.addTriple('<ex://typed_g>', name, typed_g)
   conn.addTriple('<ex://lang_g>', name, lang_g)
   conn.addTriple('<ex://upper_a>', name, upper_a)
   conn.addTriple('<ex://lower_a>', name, lower_a)
   conn.addTriple('<ex://typed_a>', name, typed_a)
   conn.addTriple('<ex://lang_a>', name, lang_a)

We have two literals, each in four variants:

   - Upper case (plain literal)
   - Lower case (plain literal)
   - Typed
   - Tagged with a `BCP47`_ language tag appropriate for its language
     (Quenya or Sindarin) according to the the `registry`_

Matching a plain string
^^^^^^^^^^^^^^^^^^^^^^^

We've seen a similar case when looking at matches for ``"42"``, but
this time we have more similar literals in the store.

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, name, upper_g, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s <ex://name> "Galadriel" .}',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery('''
       SELECT ?s ?o WHERE {
          ?s <ex://name> ?o .
          filter (?o = "Galadriel")
       }''',
       output=True)
   print()

Here's the result:

.. testoutput:: example5
   :options: +SORT +NORMALIZE_WHITESPACE

   getStatements():
   <ex://upper_g> <ex://name> "Galadriel" .

   SPARQL direct match
   --------------
   | s          |
   ==============
   | ex:typed_g |
   | ex:upper_g |
   --------------

   SPARQL filter match
   -------------------------------------------------------------------
   | s          | o                                                  |
   ===================================================================
   | ex:typed_g | Galadriel^^http://www.w3.org/2001/XMLSchema#string |
   | ex:upper_g | Galadriel                                          |
   -------------------------------------------------------------------

We can see that the match is case-sensitive and ignores the
language-tagged literal in all cases. As usual :meth:`getStatements`
matches only the exact kind of literal that we've provided, while
SPARQL is more liberal.

Matching a language-tagged string
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To retrieve the language-tagged variant we can ask for it explicitly:

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, name, lang_g, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s <ex://name> "Galadriel"@sjn .}',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery('''
       SELECT ?s ?o WHERE {
          ?s <ex://name> ?o .
          filter (?o = "Galadriel"@sjn)
       }''',
       output=True)
   print()

Unsurprisingly we get exactly what we have asked for

.. testoutput:: example5
   :options: +SORT +NORMALIZE_WHITESPACE

   getStatements():
   <ex://lang_g> <ex://name> "Galadriel"@sjn .

   SPARQL direct match
   -------------
   | s         |
   =============
   | ex:lang_g |
   -------------

   SPARQL filter match
   -----------------------------
   | s         | o             |
   =============================
   | ex:lang_g | Galadriel@sjn |
   -----------------------------

You may be wondering how to perform a string match where language and
capitalization don't matter. You can do that with a SPARQL filter
query using the ``str()`` function, which strips out the string
portion of a literal, leaving behind the datatype or language
tag. Then the ``fn:lower-case()`` function eliminates case issues:

.. testcode:: example5

   conn.executeTupleQuery('''
       SELECT ?s ?o WHERE {
          ?s <ex://name> ?o .
          filter (fn:lower-case(str(?o)) = "artanis")
       }''',
       output=True)

This query returns all variants of the selected literal

.. testoutput:: example5
   :options: +SORT +NORMALIZE_WHITESPACE

   -----------------------------------------------------------------
   | s          | o                                                |
   =================================================================
   | ex:lang_a  | Artanis@qya                                      |
   | ex:typed_a | Artanis^^http://www.w3.org/2001/XMLSchema#string |
   | ex:lower_a | artanis                                          |
   | ex:upper_a | Artanis                                          |
   -----------------------------------------------------------------

Remember that the SPARQL ``filter`` queries are powerful, but they are
also the slowest queries. SPARQL direct queries and getStatements()
queries are faster.

Booleans
~~~~~~~~

Boolean values in SPARQL are represented by literals of type
``<http://www.w3.org/2001/XMLSchema#boolean>``. There are two ways to
create such literals in Python:

   1. From corresponding Python boolean values (``True`` and ``FAlse``):

      .. testcode:: example5

         true1 = conn.createLiteral(True)
         false1 = conn.createLiteral(False)

   2. By creating a typed literal with the value of ``"true"`` or
      ``"false"``. The type must be ``xsd:boolean``:

      .. testcode:: example5

         true2 = conn.createLiteral("true", datatype=XMLSchema.BOOLEAN)
         false2 = conn.createLiteral("false", datatype=XMLSchema.BOOLEAN)

Both ways of creating boolean literals produce equivalent results:

.. testcode:: example5

   print(true1)
   print(true2)

As we can see the literals are identical.

.. testoutput:: example5

   "true"^^<http://www.w3.org/2001/XMLSchema#boolean>
   "true"^^<http://www.w3.org/2001/XMLSchema#boolean>

Let us add some boolean data to the store:

.. testcode:: example5

   conn.addData("""
       <ex://f> <ex://p>
           "false"^^<http://www.w3.org/2001/XMLSchema#boolean> .
       # In Turtle 'true' is the same as '"true"^^xsd:boolean"'
       <ex://t> <ex://p> true .
   """)

When querying for boolean values using SPARQL one can use the literals
``true`` and ``false`` as a shorthand for
``"true"^^<http://www.w3.org/2001/XMLSchema#boolean>`` and
``"false"^^<http://www.w3.org/2001/XMLSchema#boolean>``. The code
below illustrates various ways of querying for boolean values:

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, None, true1, output=True)
   print()

   print('SPARQL direct match (true)')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s ?p true.}',
       output=True)
   print()

   print('SPARQL direct match ("false"^^xsd:boolean)')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s ?p "false"^^xsd:boolean .}',
       output=True)
   print()

   print('SPARQL filter match ("false"^^xsd:boolean)')
   conn.executeTupleQuery('''
       SELECT ?s ?o WHERE {
          ?s ?p ?o .
          filter (?o = "false"^^xsd:boolean)
       }''',
       output=True)
   print()

Here's the output from that script:

.. testoutput:: example5

   getStatements():
   <ex://t> <ex://p> "true"^^<http://www.w3.org/2001/XMLSchema#boolean> .

   SPARQL direct match (true)
   --------
   | s    |
   ========
   | ex:t |
   --------

   SPARQL direct match ("false"^^xsd:boolean)
   --------
   | s    |
   ========
   | ex:f |
   --------

   SPARQL filter match ("false"^^xsd:boolean)
   ----------------
   | s    | o     |
   ================
   | ex:f | false |
   ----------------

Dates and times
~~~~~~~~~~~~~~~

SPARQL represents dates and times using three literal types:
``xsd:date``, ``xsd:time`` and ``xsd:dateTime``. These can be created
either explicitly from strings in the `ISO 8601`_ format or from
Python ``datetime.date``, ``datetime.time`` and ``datetime.datetime``
values.

Let's create a few sample literals:

.. testcode:: example5

   from datetime import date, time, datetime
   import iso8601

   d = conn.createLiteral(date(1944, 8, 1))
   t = conn.createLiteral(time(15, 0, 0))
   dt = conn.createLiteral('1944-08-01T17:00:00+02:00',
                           datatype=XMLSchema.DATETIME)

Creating ``time`` and ``datetime`` literals from Python values can
yield somewhat unexpected results if time zones are involved:

.. testcode:: example5

   surprise = conn.createLiteral(iso8601.parse_date(
       '1944-08-01T17:00:00+02:00'))
   # Should be the same...
   print(dt)
   print(surprise)

The output is

.. testoutput:: example5

   "1944-08-01T17:00:00+02:00"^^<http://www.w3.org/2001/XMLSchema#dateTime>
   "1944-08-01T15:00:00Z"^^<http://www.w3.org/2001/XMLSchema#dateTime>

The time has been converted to UTC. While both ``dt`` and ``surprise``
refer to the same moment in time, this conversion might still lead to
problems if the user is not aware that it takes place.

We will now add the newly created literals to the store:

.. testcode:: example5

   conn.addTriple('<ex://d>', '<ex://p>', d)
   conn.addTriple('<ex://t>', '<ex://p>', t)
   conn.addTriple('<ex://dt>', '<ex://p>', dt)

The following sections illustrate how date and time values behave
during queries.

Matching dates
^^^^^^^^^^^^^^
Let's try the usual mix of query methods and see what is returned:

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, None, d, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s ?p "1944-08-01"^^xsd:date .}',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery('''
       SELECT ?s ?o WHERE {
          ?s ?p ?o .
          filter (?o = "1944-08-01"^^xsd:date)
       }''',
       output=True)
   print()

The result is not surprising. It is worth noting that the ``datetime``
value has not been returned, even though it refers to the same date.

.. testoutput:: example5
   :options: +NORMALIZE_WHITESPACE

    getStatements():
    <ex://d> <ex://p> "1944-08-01"^^<http://www.w3.org/2001/XMLSchema#date> .

    SPARQL direct match
    --------
    | s    |
    ========
    | ex:d |
    --------

    SPARQL filter match
    ---------------------
    | s    | o          |
    =====================
    | ex:d | 1944-08-01 |
    ---------------------

Matching times
^^^^^^^^^^^^^^

Times can be queried in a similar fashion.

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, None, t, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery(
       'SELECT ?s WHERE {?s ?p "15:00:00Z"^^xsd:time .}',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery('''
       SELECT ?s ?o WHERE {
          ?s ?p ?o .
          filter (?o = "15:00:00Z"^^xsd:time)
       }''',
       output=True)
   print()

Again, only the value of the appropriate type is returned.

.. testoutput:: example5

   getStatements():
   <ex://t> <ex://p> "15:00:00Z"^^<http://www.w3.org/2001/XMLSchema#time> .

   SPARQL direct match
   --------
   | s    |
   ========
   | ex:t |
   --------

   SPARQL filter match
   --------------------
   | s    | o         |
   ====================
   | ex:t | 15:00:00Z |
   --------------------

Matching datetimes
^^^^^^^^^^^^^^^^^^

Datetimes work just like times and dates:

.. testcode:: example5

   print('getStatements():')
   conn.getStatements(None, None, dt, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery('''
       SELECT ?s WHERE {
          ?s ?p "1944-08-01T17:00:00+02:00"^^xsd:dateTime .
       }''',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery('''
       SELECT ?s ?o WHERE {
          ?s ?p ?o .
          filter (?o = "1944-08-01T17:00:00+02:00"^^xsd:dateTime)
       }''',
       output=True)
   print()

The result:

.. testoutput:: example5

   getStatements():
   <ex://dt> <ex://p> "1944-08-01T17:00:00+02:00"^^<http://www.w3.org/2001/XMLSchema#dateTime> .

   SPARQL direct match
   ---------
   | s     |
   =========
   | ex:dt |
   ---------

   SPARQL filter match
   -------------------------------------
   | s     | o                         |
   =====================================
   | ex:dt | 1944-08-01T17:00:00+02:00 |
   -------------------------------------

Matching datetimes with offsets
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

We saw that times created from Python values are converted to UTC. So
what happens when we query for Zulu time, while the value in the store
is still in CEST?

.. testcode:: example5

   zulu = conn.createLiteral("1944-08-01T15:00:00Z",
                             datatype=XMLSchema.DATETIME)
   print('getStatements():')
   conn.getStatements(None, None, zulu, output=True)
   print()

   print('SPARQL direct match')
   conn.executeTupleQuery('''
       SELECT ?s WHERE {
          ?s ?p "1944-08-01T15:00:00Z"^^xsd:dateTime .
       }''',
       output=True)
   print()

   print('SPARQL filter match')
   conn.executeTupleQuery('''
       SELECT ?s ?o WHERE {
          ?s ?p ?o .
          filter (?o = "1944-08-01T15:00:00Z"^^xsd:dateTime)
       }''',
       output=True)
   print()

AllegroGraph still finds our value when using SPARQL

.. testoutput:: example5

   getStatements():

   SPARQL direct match
   ---------
   | s     |
   =========
   | ex:dt |
   ---------

   SPARQL filter match
   -------------------------------------
   | s     | o                         |
   =====================================
   | ex:dt | 1944-08-01T17:00:00+02:00 |
   -------------------------------------

When evaluating SPARQL queries AllegroGraph treats ``datetime``
objects that refer to the same point in time as equivalent, regardless
of the timezone used in their representation. :meth:`getStatements`
performs exact matching, so will not return a value with different
timezone.

.. _BCP47: https://tools.ietf.org/html/bcp47
.. _registry: https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
.. _ISO 8601: https://en.wikipedia.org/wiki/ISO_8601


text:
package akka.kafka.scaladsl

import java.util.concurrent.ConcurrentLinkedQueue

import akka.Done
import akka.kafka._
import akka.kafka.testkit.KafkaTestkitTestcontainersSettings
import akka.kafka.testkit.scaladsl.TestcontainersKafkaPerClassLike
import akka.stream.scaladsl.Keep
import akka.stream.testkit.scaladsl.StreamTestKit.assertAllStagesStopped
import akka.stream.testkit.scaladsl.TestSink

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.jdk.CollectionConverters._

class RetentionPeriodSpec extends SpecBase with TestcontainersKafkaPerClassLike {

  override val testcontainersSettings = KafkaTestkitTestcontainersSettings(system)
  // The bug commit refreshing circumvents was fixed in Kafka 2.1.0
  // https://issues.apache.org/jira/browse/KAFKA-4682
  // Confluent Platform 5.0.0 bundles Kafka 2.0.0
  // https://docs.confluent.io/current/installation/versions-interoperability.html
    .withConfluentPlatformVersion("5.0.0")
    .withInternalTopicsReplicationFactor(1)
    .withConfigureKafka { brokerContainers =>
      brokerContainers.foreach {
        _.withEnv("KAFKA_AUTO_CREATE_TOPICS_ENABLE", "false")
          .withEnv("KAFKA_OFFSETS_RETENTION_MINUTES", "1")
          .withEnv("KAFKA_OFFSETS_RETENTION_CHECK_INTERVAL_MS", "100")
      }
    }

  "After retention period (1 min) consumer" must {

    "resume from committed offset" in assertAllStagesStopped {
      val topic1 = createTopic()
      val group1 = createGroupId()

      produce(topic1, 1 to 100)

      val committedElements = new ConcurrentLinkedQueue[Int]()

      val consumerSettings = consumerDefaults.withGroupId(group1).withCommitRefreshInterval(5.seconds)

      val (control, probe1) = Consumer
        .committableSource(consumerSettings, Subscriptions.topics(topic1))
        .mapAsync(10) { elem =>
          elem.committableOffset.commitInternal().map { _ =>
            committedElements.add(elem.record.value.toInt)
            Done
          }
        }
        .toMat(TestSink.probe)(Keep.both)
        .run()

      probe1
        .request(25)
        .expectNextN(25)
        .toSet should be(Set(Done))

      val longerThanRetentionPeriod = 70.seconds
      sleep(longerThanRetentionPeriod, "Waiting for retention to expire for probe1")

      probe1.cancel()
      Await.result(control.isShutdown, remainingOrDefault)

      val probe2 = Consumer
        .committableSource(consumerSettings, Subscriptions.topics(topic1))
        .map(_.record.value)
        .runWith(TestSink.probe)

      // Note that due to buffers and mapAsync(10) the committed offset is more
      // than 26, and that is not wrong

      // some concurrent publish
      produce(topic1, 101 to 200)

      val expectedElements = ((committedElements.asScala.max + 1) to 100).map(_.toString)
      probe2
        .request(100)
        .expectNextN(expectedElements)

      sleep(longerThanRetentionPeriod, "Waiting for retention to expire for probe2")

      probe2.cancel()

      val probe3 = Consumer
        .committableSource(consumerSettings, Subscriptions.topics(topic1))
        .map(_.record.value)
        .runWith(TestSink.probe)

      probe3
        .request(100)
        .expectNextN(expectedElements)

      probe3.cancel()
    }
  }
}


text:
import test from 'ava';
import { isMutable, modify } from '@collectable/core';
import { SortedSetStructure as SortedSet, size, union } from '../../src';
import { fromStringArray, snapshot } from '../test-utils';

const mainValues = ['A', 'C', 'B', 'D', 'E'];
const otherValues = ['F', 'D', 'E', 'G'];
const expectedValues = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
let main: SortedSet<string>, result: SortedSet<string>;
let other: SortedSet<string>, otherSnapshot: object;

test.beforeEach(() => {
  other = fromStringArray(otherValues);
  otherSnapshot = snapshot(other);
  main = modify(fromStringArray(mainValues));
  result = union(other, main);
});

test('the main set is returned', t => {
  t.is(result, main);
});

test('the main set is still mutable', t => {
  t.true(isMutable(result));
});

test('the other input set is not modified', t => {
  t.deepEqual(snapshot(other), otherSnapshot);
});

test('the main set includes all items from both inputs', t => {
  t.deepEqual(Array.from(result), expectedValues);
  t.is(size(result), expectedValues.length);
});


text:
package com.hazelcast.config;

import com.hazelcast.internal.eviction.EvictionConfiguration;
import com.hazelcast.internal.eviction.EvictionPolicyComparator;
import com.hazelcast.internal.eviction.EvictionPolicyType;
import com.hazelcast.internal.eviction.EvictionStrategyType;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.DataSerializable;
import com.hazelcast.nio.serialization.impl.BinaryInterface;

import java.io.IOException;
import java.io.Serializable;

import static com.hazelcast.util.Preconditions.checkNotNull;
import static com.hazelcast.util.Preconditions.checkPositive;

/**
 * Configuration for eviction.
 * You can set a limit for number of entries or total memory cost of entries.
 */
@BinaryInterface
public class EvictionConfig implements EvictionConfiguration, DataSerializable, Serializable {

    /**
     * Default maximum entry count.
     */
    public static final int DEFAULT_MAX_ENTRY_COUNT = 10000;

    /**
     * Default maximum entry count for Map on-heap Near Caches.
     */
    public static final int DEFAULT_MAX_ENTRY_COUNT_FOR_ON_HEAP_MAP = Integer.MAX_VALUE;

    /**
     * Default Max-Size Policy.
     */
    public static final MaxSizePolicy DEFAULT_MAX_SIZE_POLICY = MaxSizePolicy.ENTRY_COUNT;

    /**
     * Default Eviction Policy.
     */
    public static final EvictionPolicy DEFAULT_EVICTION_POLICY = EvictionPolicy.LRU;

    protected int size = DEFAULT_MAX_ENTRY_COUNT;
    protected MaxSizePolicy maxSizePolicy = DEFAULT_MAX_SIZE_POLICY;
    protected EvictionPolicy evictionPolicy = DEFAULT_EVICTION_POLICY;
    protected String comparatorClassName;
    protected EvictionPolicyComparator comparator;

    protected EvictionConfig readOnly;

    /**
     * Used by the {@link NearCacheConfigAccessor} to initialize the proper default value for on-heap maps.
     */
    boolean sizeConfigured;

    public EvictionConfig() {
    }

    public EvictionConfig(int size, MaxSizePolicy maxSizePolicy, EvictionPolicy evictionPolicy) {
        /**
         * ===== NOTE =====
         *
         * Do not use setters, because they are overridden in the readonly version of this config and
         * they cause an "UnsupportedOperationException". Just set directly if the value is valid.
         */

        this.sizeConfigured = true;
        this.size = checkPositive(size, "Size must be positive number!");
        this.maxSizePolicy = checkNotNull(maxSizePolicy, "Max-Size policy cannot be null!");
        this.evictionPolicy = checkNotNull(evictionPolicy, "Eviction policy cannot be null!");
    }

    public EvictionConfig(int size, MaxSizePolicy maxSizePolicy, String comparatorClassName) {
        /**
         * ===== NOTE =====
         *
         * Do not use setters, because they are overridden in the readonly version of this config and
         * they cause an "UnsupportedOperationException". Just set directly if the value is valid.
         */

        this.sizeConfigured = true;
        this.size = checkPositive(size, "Size must be positive number!");
        this.maxSizePolicy = checkNotNull(maxSizePolicy, "Max-Size policy cannot be null!");
        this.comparatorClassName = checkNotNull(comparatorClassName, "Comparator classname cannot be null!");
    }

    public EvictionConfig(int size, MaxSizePolicy maxSizePolicy, EvictionPolicyComparator comparator) {
        /**
         * ===== NOTE =====
         *
         * Do not use setters, because they are overridden in the readonly version of this config and
         * they cause an "UnsupportedOperationException". Just set directly if the value is valid.
         */

        this.sizeConfigured = true;
        this.size = checkPositive(size, "Size must be positive number!");
        this.maxSizePolicy = checkNotNull(maxSizePolicy, "Max-Size policy cannot be null!");
        this.comparator = checkNotNull(comparator, "Comparator cannot be null!");
    }

    public EvictionConfig(EvictionConfig config) {
        /**
         * ===== NOTE =====
         *
         * Do not use setters, because they are overridden in readonly version of this config and
         * cause "UnsupportedOperationException". So just set directly if value is valid.
         */

        this.sizeConfigured = true;
        this.size = checkPositive(config.size, "Size must be positive number!");
        this.maxSizePolicy = checkNotNull(config.maxSizePolicy, "Max-Size policy cannot be null!");
        if (config.evictionPolicy != null) {
            this.evictionPolicy = config.evictionPolicy;
        }
        // Eviction policy comparator class name is not allowed to be null
        if (config.comparatorClassName != null) {
            this.comparatorClassName = config.comparatorClassName;
        }
        // Eviction policy comparator is not allowed to be null
        if (config.comparator != null) {
            this.comparator = config.comparator;
        }
    }

    /**
     * Maximum Size Policy
     */
    public enum MaxSizePolicy {
        /**
         * Policy based on maximum number of entries stored per data structure (map, cache etc)
         */
        ENTRY_COUNT,
        /**
         * Policy based on maximum used native memory in megabytes per data structure (map, cache etc)
         * on each Hazelcast instance
         */
        USED_NATIVE_MEMORY_SIZE,
        /**
         * Policy based on maximum used native memory percentage per data structure (map, cache etc)
         * on each Hazelcast instance
         */
        USED_NATIVE_MEMORY_PERCENTAGE,
        /**
         * Policy based on minimum free native memory in megabytes per Hazelcast instance
         */
        FREE_NATIVE_MEMORY_SIZE,
        /**
         * Policy based on minimum free native memory percentage per Hazelcast instance
         */
        FREE_NATIVE_MEMORY_PERCENTAGE
    }

    /**
     * Gets immutable version of this configuration.
     *
     * @return Immutable version of this configuration.
     * @deprecated this method will be removed in 4.0; it is meant for internal usage only.
     */
    public EvictionConfig getAsReadOnly() {
        if (readOnly == null) {
            readOnly = new EvictionConfigReadOnly(this);
        }
        return readOnly;
    }

    public int getSize() {
        return size;
    }

    public EvictionConfig setSize(int size) {
        this.sizeConfigured = true;
        this.size = checkPositive(size, "Size must be positive number!");
        return this;
    }

    public MaxSizePolicy getMaximumSizePolicy() {
        return maxSizePolicy;
    }

    public EvictionConfig setMaximumSizePolicy(MaxSizePolicy maxSizePolicy) {
        this.maxSizePolicy = checkNotNull(maxSizePolicy, "Max-Size policy cannot be null!");
        return this;
    }

    public EvictionPolicy getEvictionPolicy() {
        return evictionPolicy;
    }

    public EvictionConfig setEvictionPolicy(EvictionPolicy evictionPolicy) {
        this.evictionPolicy = checkNotNull(evictionPolicy, "Eviction policy cannot be null!");
        return this;
    }

    @Override
    public String getComparatorClassName() {
        return comparatorClassName;
    }

    public EvictionConfig setComparatorClassName(String comparatorClassName) {
        this.comparatorClassName = checkNotNull(comparatorClassName, "Eviction policy comparator class name cannot be null!");
        return this;
    }

    @Override
    public EvictionPolicyComparator getComparator() {
        return comparator;
    }

    public EvictionConfig setComparator(EvictionPolicyComparator comparator) {
        this.comparator = checkNotNull(comparator, "Eviction policy comparator cannot be null!");
        return this;
    }

    @Override
    public EvictionStrategyType getEvictionStrategyType() {
        return EvictionStrategyType.DEFAULT_EVICTION_STRATEGY;
    }

    @Override
    public EvictionPolicyType getEvictionPolicyType() {
        if (evictionPolicy == EvictionPolicy.LFU) {
            return EvictionPolicyType.LFU;
        } else if (evictionPolicy == EvictionPolicy.LRU) {
            return EvictionPolicyType.LRU;
        } else if (evictionPolicy == EvictionPolicy.RANDOM) {
            return EvictionPolicyType.RANDOM;
        } else if (evictionPolicy == EvictionPolicy.NONE) {
            return EvictionPolicyType.NONE;
        } else {
            return null;
        }
    }

    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        out.writeInt(size);
        out.writeUTF(maxSizePolicy.toString());
        out.writeUTF(evictionPolicy.toString());
        out.writeUTF(comparatorClassName);
        out.writeObject(comparator);
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        size = in.readInt();
        maxSizePolicy = MaxSizePolicy.valueOf(in.readUTF());
        evictionPolicy = EvictionPolicy.valueOf(in.readUTF());
        comparatorClassName = in.readUTF();
        comparator = in.readObject();
    }

    @Override
    public String toString() {
        return "EvictionConfig{"
                + "size=" + size
                + ", maxSizePolicy=" + maxSizePolicy
                + ", evictionPolicy=" + evictionPolicy
                + ", comparatorClassName=" + comparatorClassName
                + ", comparator=" + comparator
                + '}';
    }
}


text:
package org.redisson;

import java.util.Iterator;

import org.redisson.client.codec.Codec;
import org.redisson.command.CommandAsyncExecutor;

public class RedissonSetMultimapIterator<K, V, M> extends RedissonMultiMapIterator<K, V, M> {

    public RedissonSetMultimapIterator(RedissonMultimap<K, V> map, CommandAsyncExecutor commandExecutor, Codec codec) {
        super(map, commandExecutor, codec);
    }

    @Override
    protected Iterator<V> getIterator(String name) {
        RedissonSet<V> set = new RedissonSet<V>(codec, commandExecutor, map.getValuesName(name), null);
        return set.iterator();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/next_video_plugin_poster_margin"
    android:layout_gravity="bottom">

        <ImageView
            android:id="@+id/video_poster"
            android:layout_width="@dimen/next_video_plugin_poster_width"
            android:layout_height="@dimen/next_video_plugin_poster_height"
            android:padding="@dimen/next_video_plugin_poster_padding"
            android:background="@color/next_video_plugin_border_color" />

        <ImageView
            android:src="@drawable/icon_play"
            android:layout_width="@dimen/next_video_plugin_icon_play_width"
            android:layout_height="@dimen/next_video_plugin_icon_play_height"
            android:layout_centerInParent="true" />

</RelativeLayout>


text:
package com.bya.springmvc4.interceptor;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by bao on 2017/6/18.
 * 实现HanlderInteceptor 或者继承 handlerInterceptorAdapter
 */
public class DemoInterceptor extends HandlerInterceptorAdapter{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        long startTime=System.currentTimeMillis();
        request.setAttribute("startTime",startTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Long startTime= (Long) request.getAttribute("startTime");
        request.removeAttribute("startTime");
        long endTime=System.currentTimeMillis();
        System.out.println("本次请求处理的时间是"+new Long(endTime-startTime)+"ms");
    }
}


text:
package com.uber.tchannel.channels;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public enum ConnectionState {

    UNCONNECTED("unconnected"),
    CONNECTED("connected"),
    IDENTIFIED("identified"),
    DESTROYED("destroyed");

    private final @NotNull String state;

    ConnectionState(@NotNull String state) {
        this.state = state;
    }

    public static @Nullable ConnectionState toState(@Nullable String state) {
        if (state == null) {
            return null;
        }

        switch (state) {
            case "unconnected":
                return UNCONNECTED;
            case "connected":
                return CONNECTED;
            case "identified":
                return IDENTIFIED;
            case "destroyed":
                return DESTROYED;
            default:
                return null;
        }
    }

    public static boolean isConnected(ConnectionState state) {
        return state == IDENTIFIED || state == CONNECTED;
    }

    public static boolean isConnected(@Nullable Connection conn) {
        return conn != null && isConnected(conn.state);

    }

    public @NotNull String getState() {
        return state;
    }

}


text:
module.exports = {
  module: 'vs',
  childRoutes: [
    {
      path: '/vs/requests',
      component: require('./src/content/vs-request/VsRequests'),
      access: [ { type: 'HAS_ANY_AUTHORITY', authorities: ['VSREQUEST_READ'] } ]
    },
    {
      path: '/vs/systems',
      component: require('./src/content/vs-system/VsSystems'),
      access: [ { type: 'HAS_ANY_AUTHORITY', authorities: ['VSREQUEST_READ'] } ]
    },
    {
      path: 'vs/request/:entityId/detail',
      component: require('./src/content/vs-request/VsRequestContent'),
      access: [ { type: 'HAS_ANY_AUTHORITY', authorities: ['VSREQUEST_READ'] } ]
    },
    {
      path: 'vs/request/:entityId/new',
      component: require('./src/content/vs-request/VsRequestContent'),
      access: [ { type: 'HAS_ANY_AUTHORITY', authorities: ['VSREQUEST_CREATE'] } ]
    }
  ]
};


text:
package pl.touk.sputnik.processor.pylint;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import pl.touk.sputnik.exec.ExternalProcess;

import java.util.List;

@Slf4j
class PylintExecutor {
    private static final String PYLINT_EXECUTABLE = "pylint";
    private static final String PYLINT_OUTPUT_FORMAT = "--output-format=json";
    private static final String PYLINT_RCFILE_NAME = "--rcfile=";

    private String rcfileName;

    PylintExecutor(@Nullable String rcfileName) {
        this.rcfileName = rcfileName;
    }

    String runOnFile(String filePath) {
        log.info("Review on file: " + filePath);
        return new ExternalProcess().executeCommand(buildParams(filePath));
    }

    @NotNull
    private String[] buildParams(String filePath) {
        List<String> basicPylintArgs = ImmutableList.of(
                PYLINT_EXECUTABLE,
                PYLINT_OUTPUT_FORMAT);
        List<String> rcfileNameArg = getRcfileNameAsList();
        List<String> filePathArg = ImmutableList.of(filePath);
        List<String> allArgs = Lists.newArrayList(Iterables.concat(basicPylintArgs, rcfileNameArg, filePathArg));
        return allArgs.toArray(new String[allArgs.size()]);
    }

    private List<String> getRcfileNameAsList() {
        if (rcfileName == null) {
            return ImmutableList.of();
        }
        return ImmutableList.of(PYLINT_RCFILE_NAME + rcfileName);
    }
}


text:
package ru.org.linux.gallery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import ru.org.linux.boxlets.AbstractBoxlet;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class GalleryBoxlet extends AbstractBoxlet {
  private static final int COUNT_ITEMS = 3;

  @Autowired
  private ImageService imageService;

  @Override
  @RequestMapping("/gallery.boxlet")
  protected ModelAndView getData(HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("boxlets/gallery");
    List<PreparedGalleryItem> list = imageService.prepareGalleryItem(imageService.getGalleryItems(COUNT_ITEMS));
    mav.addObject("items", list);
    return mav;
  }
}


text:
namespace http {
namespace server {

connection_manager::connection_manager() {}

void connection_manager::start(connection_ptr c)
{
	connections_.insert(c);
	c->start();
}

void connection_manager::stop(connection_ptr c)
{
	connections_.erase(c);
	c->stop();
}

void connection_manager::stop_all()
{
	std::for_each(connections_.begin(), connections_.end(), [=](const connection_ptr& ptr) {
        stop(ptr);
    });
	connections_.clear();
}

} // namespace server
} // namespace http


text:
A web app that can control the Amazon FireTV (/ Stick). Just start app.js, fill in your device's IP address and use your web browser as a remote.
Be sure to enable ADB on the FireTV.

# Setup
```bash
$ git clone https://github.com/ZaneH/FireTVRemote-Node.git
$ cd FireTVRemote-Node
$ node app.js
```

## Keyboard bindings
|Keyboard Button|Remote Button|
|:-------------:|:-----------:|
|↑              |↑            |
|↓              |↓            |
|←              |←            |
|→              |→            |
|Enter          |Select       |
|Spacebar       |Select       |
|Escape         |Back         |

All alphanumeric keys are also mapped to the keyboard so you can simply type on your keyboard and recieve feedback from your FireTV.

*Not all traffic is guaranteed to be sequential if you're a fast typer.*


text:
const { Toolkit } = require("actions-toolkit")
const tools = new Toolkit()
const fetch = require("./fetch.js")
const { processData, report } = require("./process-data.js")
const { filter } = require("./filter.js")

const teams = [
  {
    id: `MDQ6VGVhbTI5MzQzMzQ=`,
    name: `core`,
    channelId: process.env.SLACK_CORE_CHANNEL_ID,
  },
  {
    id: `MDQ6VGVhbTMzMDc4MzY=`,
    name: `learning`,
    channelId: process.env.SLACK_LEARNING_CHANNEL_ID,
  },
]

const start = async function () {
  const data = await fetch()
  if (data) {
    const queues = processData(data)
    await Promise.all(
      teams.map(team => {
        if (team.name === `core`) {
          // send report of all PRs (without filtering) to Core
          tools.log.info(`-> Reporting for ${team.name} team`)
          return report({ queues, channelId: team.channelId })
        } else {
          // send filtered reports to respective teams
          tools.log.info(`-> Reporting for ${team.name} team`)
          return report(filter(queues, team))
        }
      })
    )
  }
}

start()


text:
describe Joybox::UI::Label do
  behaves_like Joybox::UI::Label

  describe "Initialization" do
    it "should initialize with text" do
      color = "#FFFFFF".to_color
      label = Label.new text: 'Label',
                        position: [100, 100],
                        color: color

      label.should.not == nil
      label.text.should == 'Label'
      label.position.should == CGPointMake(100, 100)
      label.color.should.not == nil
    end
  end

end


text:
using FluentAssertions;
using Xunit;

namespace OnlineWallet.Web.Common.Helpers
{
    [Trait(nameof(StringExtensions), nameof(StringExtensions.FillWith))]
    public class StringExtensionsFillWith
    {
        [Fact(DisplayName = nameof(Fills_the_text_with_given_char_between_every_char_and_at_the_begin_and_end))]
        public void Fills_the_text_with_given_char_between_every_char_and_at_the_begin_and_end()
        {
            var result = "gamma".FillWith('%');

            result.Should().Be("%g%a%m%m%a%");
        }
    }
}


text:
package io.undertow.server.handlers.encoding;

import io.undertow.UndertowLogger;
import io.undertow.conduits.DeflatingStreamSinkConduit;
import io.undertow.conduits.GzipStreamSinkConduit;
import io.undertow.server.ConduitWrapper;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.ConduitFactory;
import io.undertow.util.ObjectPool;
import org.xnio.conduits.StreamSinkConduit;

import java.util.zip.Deflater;

/**
 * Content coding for 'deflate'
 *
 * @author Stuart Douglas
 */
public class GzipEncodingProvider implements ContentEncodingProvider {

    private final ObjectPool<Deflater> deflaterPool;

    public GzipEncodingProvider() {
        this(Deflater.DEFAULT_COMPRESSION);
    }

    public GzipEncodingProvider(int deflateLevel) {
        this(DeflatingStreamSinkConduit.newInstanceDeflaterPool(deflateLevel));
    }

    public GzipEncodingProvider(ObjectPool<Deflater> deflaterPool) {
        this.deflaterPool = deflaterPool;
    }

    @Override
    public ConduitWrapper<StreamSinkConduit> getResponseWrapper() {
        return new ConduitWrapper<StreamSinkConduit>() {
            @Override
            public StreamSinkConduit wrap(final ConduitFactory<StreamSinkConduit> factory, final HttpServerExchange exchange) {
                UndertowLogger.REQUEST_LOGGER.tracef("Created GZIP response conduit for %s", exchange);
                return new GzipStreamSinkConduit(factory, exchange, deflaterPool);
            }
        };
    }
}


text:
require 'irb'
require 'csv'
require 'date'
require 'optparse'
require 'optparse/date'
require 'pathname'
require 'strscan'
require 'fileutils'
require 'yaml'
require 'highline/import'

module Ldgr
  # Parses configuration options.
  #
  #
  # Examples
  #
  #   Ldgr::Parser.parse
  #   # => some file action
  #
  # Returns nothing on success.
  class Parser
    FILEBASE = Dir.home + '/.config/ledger/'
    VERSION = Ldgr::VERSION
    PROGRAM_NAME = 'ldgr'
    MATCH = /(?=(\n\d\d\d\d-\d\d-\d\d)(=\d\d\d\d-\d\d-\d\d)*)|\z/
    OTHER_MATCH = /(?=(\d\d\d\d-\d\d-\d\d)(=\d\d\d\d-\d\d-\d\d)*)/
    COMMANDS = %w(add sort tag clear open).freeze

    attr_accessor :transactions_file, :config

    # Public: Creates a new Parser object
    #
    # config  - A hash of config options
    #
    # Examples
    #
    #   new(config: {currency: '¥'})
    #   # => <ParserObject>
    #
    # Returns a Parser object.
    def initialize(config: {})
      @transactions_file = defaults.fetch(:transactions_file)
      @config = defaults.merge(user_config).merge(config)
    end

    # Public: Kicks off the CLI
    #
    # Examples
    #
    #   parse
    #
    # Returns nothing.
    def parse
      setup

      cli = OptionParser.new do |o|
        o.banner = "Usage #{PROGRAM_NAME} [add|sort|tag|clear|open]"
        o.program_name = PROGRAM_NAME
        o.version = VERSION

        o.define '-C', '--currency=CURRENCY', String, 'the currency of the transaction'
        o.define '-E', '--effective=EFFECTIVE_DATE', Date, 'the effective date of the transaction'
        o.define '-a', '--account=ACCOUNT', String, 'the account of the transaction'
        o.define '-c', '--cleared', TrueClass, 'clear the transaction'
        o.define '-d', '--date=DATE', Date, 'the date of the transaction'
        o.define '-e', '--equity=EQUITY', String, 'the equity of the transaction'
        o.define '-f', '--file=FILE', String, 'a file of transactions'
        o.define '-A', '--amount=AMOUNT', String, 'the amount of the transaction'
        o.define '-p', '--payee=PAYEE', String, 'the payee of the transaction'
      end

      command = String(cli.parse(ARGV, into: config)[0])
      send(command) if COMMANDS.include? command
    end

    # Public: Adds a transaction to the transactions_file.
    #
    # Examples
    #
    #   add
    #
    # Returns nothing.
    def add
      error_policy = ->(key) { fail "You need to provide a value for #{key.to_s}." }

      transaction = Transaction.new do |t|
        date = String(config.fetch(:date) { |key| error_policy.call(key) })
        effective = String(config.fetch(:effective) { |key| error_policy.call(key) })

        t.payee    = config.fetch(:payee) { |key| error_policy.call(key) }
        t.account  = config.fetch(:account) { |key| error_policy.call(key) }
        t.amount   = config.fetch(:amount) { |key| error_policy.call(key) }
        t.currency = config.fetch(:currency) { config.fetch(:currency) }
        t.equity   = config.fetch(:equity) { config.fetch(:equity) }
        t.cleared  = config[:cleared] ? '* ' : ''
        t.date     = date == effective ? date : date << '=' << effective
      end

      File.open(transactions_file, 'a') { |file| file.puts transaction }
    end

    # Public: Runs through all uncleared transactions that are passed
    # their effective date and offers to clear them.
    #
    # Examples
    #
    #   clear
    #
    # Returns nothing.
    def clear
      output = ''
      pattern = /((^\d{,4}-\d{,2}-\d{,2})(=\d{,4}-\d{,2}-\d{,2})?) ([^\*]+)/
      count = 0

      File.open(transactions_file, 'r') do |transactions|
        transactions.each_line do |transaction|
          match = pattern.match(transaction)
          if match && match[3]
            effective_date = Date.parse(match[3])
          else
            effective_date = Date.today
          end
          if match && Date.today >= effective_date
            count += 1
            front = match[1]
            back = match[4]
            puts transaction
            question = ask('Do you want to clear this?  ') do |q|
              q.default = 'No'
            end
            transaction.gsub!(pattern, "#{front} * #{back}") if question.match?(/y/i)
          end
          output << transaction
        end
      end
      IO.write(transactions_file, output)
    end

    # Public: Runs through all transactions with only Expenses set as the account and lets you enter an account name.
    #
    # Examples
    #
    #   tag
    #
    # Returns nothing.
    def tag
      output = ''
      pattern = /(^\s+Expenses[^:])\s*(¥.+)/
      count = 0
      previous = ''

      File.open(transactions_file, 'r') do |transactions|
        transactions.each_line do |transaction|
          match = pattern.match(transaction)
          if match
            count += 1
            puts "\n#{previous} #{match[2]}"
            question = ask('What account does this belong to?  ') { |q| q.default = 'None' }
            transaction.gsub!(match[1], "  #{question.capitalize}  ") if question != 'None'
          end
          previous = transaction.chomp
          output << transaction
        end
      end
      IO.write(transactions_file, output)
    end

    # Public: Sorts all transactions by date.
    #
    # Examples
    #
    #   sort
    #
    # Returns nothing.
    def sort
      text = File.read(transactions_file).gsub(/\n+|\r+/, "\n").squeeze("\n").strip
      scanner = StringScanner.new(text)
      results = []

      until scanner.eos?
        results << scanner.scan_until(MATCH)
        scanner.skip_until(OTHER_MATCH)
      end

      File.open(transactions_file, 'w') do |file|
        file.puts results.sort
      end
    end

    private
    # Private: User-specified config options
    #
    # Examples
    #
    #   user_config
    #   # => {all the config options from the user's YAML file}
    #
    # Returns a hash of user-specified config options.
    def user_config
      path = Pathname(FILEBASE + 'ldgr.yaml')
      path.exist? ? YAML.load_file(path).to_h : {}
    end

    # Private: Opens a settings file from ~/.config/ledger
    #
    # Examples
    #
    #   open accounts
    #   # => accounts file opens in $EDITOR
    #
    # Returns nothing.
    def open
      def open_file(file_to_open)
        checked_file = "#{FILEBASE}#{file_to_open}.dat"
        fail "#{checked_file} doesn't exist." unless Pathname(checked_file).exist?
        system(ENV['EDITOR'], checked_file)
      end

      open_file(ARGV[1])
    end

    # Private: ldgr's default configuration options
    #
    # Examples
    #
    #   defaults
    #   # => {all the configuration options}
    #
    # Returns a hash of default configuration options.
    def defaults
      {
        currency: '$',
        equity: 'Cash',
        effective: Date.today,
        date: Date.today,
        cleared: false,
        transactions_file: FILEBASE + 'transactions.dat'
      }
    end

    # Private: Prepares users' file system for ldgr.
    #
    # Returns nothing.
    def setup
      setup_files = %w(transactions.dat accounts.dat budgets.dat aliases.dat commodities.dat setup.dat ledger.dat)
      FileUtils.mkdir_p(FILEBASE)
      setup_files.each do |file|
        FileUtils.touch("#{FILEBASE}#{file}")
      end
    end
  end
end


text:
package serial

import (
	"fmt"
	"log"
	"os"
	"syscall"
	"time"
	"unsafe"
)

var baudRates = map[int]uint32{
	50:      syscall.B50,
	75:      syscall.B75,
	110:     syscall.B110,
	134:     syscall.B134,
	150:     syscall.B150,
	200:     syscall.B200,
	300:     syscall.B300,
	600:     syscall.B600,
	1200:    syscall.B1200,
	1800:    syscall.B1800,
	2400:    syscall.B2400,
	4800:    syscall.B4800,
	9600:    syscall.B9600,
	19200:   syscall.B19200,
	38400:   syscall.B38400,
	57600:   syscall.B57600,
	115200:  syscall.B115200,
	230400:  syscall.B230400,
	460800:  syscall.B460800,
	500000:  syscall.B500000,
	576000:  syscall.B576000,
	921600:  syscall.B921600,
	1000000: syscall.B1000000,
	1152000: syscall.B1152000,
	1500000: syscall.B1500000,
	2000000: syscall.B2000000,
	2500000: syscall.B2500000,
	3000000: syscall.B3000000,
	3500000: syscall.B3500000,
	4000000: syscall.B4000000,
}

var charSizes = map[int]uint32{
	5: syscall.CS5,
	6: syscall.CS6,
	7: syscall.CS7,
	8: syscall.CS8,
}

// port implements Port interface.
type port struct {
	// Should use fd directly by using syscall.Open() ?
	file       *os.File
	oldTermios *syscall.Termios

	timeout time.Duration
}

// New allocates and returns a new serial port controller.
func New() Port {
	return &port{}
}

// Open connects to the given serial port.
func (p *port) Open(c *Config) (err error) {
	termios, err := newTermios(c)
	if err != nil {
		return
	}
	// See man termios(3).
	// O_NOCTTY: no controlling terminal.
	// O_NDELAY: no data carrier detect.
	p.file, err = os.OpenFile(c.Address, syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NDELAY, os.FileMode(0666))
	if err != nil {
		return
	}
	// Backup current termios to restore on closing.
	p.backupTermios()
	if err = p.setTermios(termios); err != nil {
		p.file.Close()
		p.file = nil
		p.oldTermios = nil
		return
	}
	p.timeout = c.Timeout
	return
}

func (p *port) Close() (err error) {
	if p.file == nil {
		return
	}
	p.restoreTermios()
	err = p.file.Close()
	p.file = nil
	p.oldTermios = nil
	return
}

// Read reads from serial port. Port must be opened before calling this method.
// It is blocked until all data received or timeout after p.timeout.
func (p *port) Read(b []byte) (n int, err error) {
	var rfds syscall.FdSet

	fd := int(p.file.Fd())
	fdSet(fd, &rfds)

	var tv *syscall.Timeval
	if p.timeout > 0 {
		timeout := syscall.NsecToTimeval(p.timeout.Nanoseconds())
		tv = &timeout
	}
	if _, err = syscall.Select(fd+1, &rfds, nil, nil, tv); err != nil {
		err = fmt.Errorf("serial: could not select: %v", err)
		return
	}
	if !fdIsSet(fd, &rfds) {
		// Timeout
		err = ErrTimeout
		return
	}
	n, err = p.file.Read(b)
	return
}

// Write writes data to the serial port.
func (p *port) Write(b []byte) (n int, err error) {
	n, err = p.file.Write(b)
	return
}

func (p *port) setTermios(termios *syscall.Termios) (err error) {
	if err = tcsetattr(int(p.file.Fd()), termios); err != nil {
		err = fmt.Errorf("serial: could not set setting: %v", err)
	}
	return
}

// backupTermios saves current termios setting.
// Make sure that device file has been opened before calling this function.
func (p *port) backupTermios() {
	oldTermios := &syscall.Termios{}
	if err := tcgetattr(int(p.file.Fd()), oldTermios); err != nil {
		// Warning only.
		log.Printf("serial: could not get setting: %v\n", err)
		return
	}
	// Will be reloaded when closing.
	p.oldTermios = oldTermios
}

// restoreTermios restores backed up termios setting.
// Make sure that device file has been opened before calling this function.
func (p *port) restoreTermios() {
	if p.oldTermios == nil {
		return
	}
	if err := tcsetattr(int(p.file.Fd()), p.oldTermios); err != nil {
		// Warning only.
		log.Printf("serial: could not restore setting: %v\n", err)
		return
	}
	p.oldTermios = nil
}

// Helpers for termios

func newTermios(c *Config) (termios *syscall.Termios, err error) {
	termios = &syscall.Termios{}
	var flag uint32
	// Baud rate
	if c.BaudRate == 0 {
		// 19200 is the required default.
		flag = syscall.B19200
	} else {
		flag = baudRates[c.BaudRate]
		if flag == 0 {
			err = fmt.Errorf("serial: unsupported baud rate %v", c.BaudRate)
			return
		}
	}
	// Input baud.
	termios.Ispeed = flag
	// Output baud.
	termios.Ospeed = flag
	// Character size.
	if c.DataBits == 0 {
		flag = syscall.CS8
	} else {
		flag = charSizes[c.DataBits]
		if flag == 0 {
			err = fmt.Errorf("serial: unsupported character size %v", c.DataBits)
			return
		}
	}
	termios.Cflag |= flag
	// Stop bits
	switch c.StopBits {
	case 0, 1:
		// Default is one stop bit.
		// noop
	case 2:
		// CSTOPB: Set two stop bits.
		termios.Cflag |= syscall.CSTOPB
	default:
		err = fmt.Errorf("serial: unsupported stop bits %v", c.StopBits)
		return
	}
	switch c.Parity {
	case "N":
		// noop
	case "O":
		// PARODD: Parity is odd.
		termios.Cflag |= syscall.PARODD
		fallthrough
	case "", "E":
		// As mentioned in the modbus spec, the default parity mode must be Even parity
		// PARENB: Enable parity generation on output.
		termios.Cflag |= syscall.PARENB
		// INPCK: Enable input parity checking.
		termios.Iflag |= syscall.INPCK
	default:
		err = fmt.Errorf("serial: unsupported parity %v", c.Parity)
		return
	}
	// Control modes.
	// CREAD: Enable receiver.
	// CLOCAL: Ignore control lines.
	termios.Cflag |= syscall.CREAD | syscall.CLOCAL
	// Special characters.
	// VMIN: Minimum number of characters for noncanonical read.
	// VTIME: Time in deciseconds for noncanonical read.
	// Both are unused as NDELAY is we utilized when opening device.
	return
}

// tcsetattr sets terminal file descriptor parameters.
// See man tcsetattr(3).
func tcsetattr(fd int, termios *syscall.Termios) (err error) {
	r, _, errno := syscall.Syscall(uintptr(syscall.SYS_IOCTL),
		uintptr(fd), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(termios)))
	if errno != 0 {
		err = errno
		return
	}
	if r != 0 {
		err = fmt.Errorf("tcsetattr failed %v", r)
	}
	return
}

// tcgetattr gets terminal file descriptor parameters.
// See man tcgetattr(3).
func tcgetattr(fd int, termios *syscall.Termios) (err error) {
	r, _, errno := syscall.Syscall(uintptr(syscall.SYS_IOCTL),
		uintptr(fd), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(termios)))
	if errno != 0 {
		err = errno
		return
	}
	if r != 0 {
		err = fmt.Errorf("tcgetattr failed %v", r)
		return
	}
	return
}

// fdGet returns index and offset of fd in fds.
func fdGet(fd int, fds *syscall.FdSet) (index, offset int) {
	index = fd / (syscall.FD_SETSIZE / len(fds.Bits)) % len(fds.Bits)
	offset = fd % (syscall.FD_SETSIZE / len(fds.Bits))
	return
}

// fdSet implements FD_SET macro.
func fdSet(fd int, fds *syscall.FdSet) {
	idx, pos := fdGet(fd, fds)
	fds.Bits[idx] = 1 << uint(pos)
}

// fdIsSet implements FD_ISSET macro.
func fdIsSet(fd int, fds *syscall.FdSet) bool {
	idx, pos := fdGet(fd, fds)
	return fds.Bits[idx]&(1<<uint(pos)) != 0
}


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

<title>Uses of Class org.hibernate.jpa.event.internal.jpa.CallbackRegistryImpl (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.hibernate.jpa.event.internal.jpa.CallbackRegistryImpl

Packages that use CallbackRegistryImpl

Package
Description

org.hibernate.jpa.event.internal.jpa

Uses of CallbackRegistryImpl in org.hibernate.jpa.event.internal.jpa

Methods in org.hibernate.jpa.event.internal.jpa with parameters of type CallbackRegistryImpl

Modifier and Type
Method and Description

void
LegacyCallbackProcessor.processCallbacksForEntity(Object entityObject,
                         CallbackRegistryImpl callbackRegistry)

void
CallbackProcessorImpl.processCallbacksForEntity(Object entityObject,
                         CallbackRegistryImpl callbackRegistry)

void
CallbackProcessor.processCallbacksForEntity(Object entityObject,
                         CallbackRegistryImpl registry)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System.Collections.Generic;

namespace IdentityServer4.Configuration
{
    /// <summary>
    /// Options class to configure discovery endpoint
    /// </summary>
    public class DiscoveryOptions
    {
        /// <summary>
        /// Show endpoints
        /// </summary>
        public bool ShowEndpoints { get; set; } = true;

        /// <summary>
        /// Show signing keys
        /// </summary>
        public bool ShowKeySet { get; set; } = true;

        /// <summary>
        /// Show identity scopes
        /// </summary>
        public bool ShowIdentityScopes { get; set; } = true;

        /// <summary>
        /// Show API scopes
        /// </summary>
        public bool ShowApiScopes { get; set; } = true;

        /// <summary>
        /// Show identity claims
        /// </summary>
        public bool ShowClaims { get; set; } = true;

        /// <summary>
        /// Show response types
        /// </summary>
        public bool ShowResponseTypes { get; set; } = true;

        /// <summary>
        /// Show response modes
        /// </summary>
        public bool ShowResponseModes { get; set; } = true;

        /// <summary>
        /// Show standard grant types
        /// </summary>
        public bool ShowGrantTypes { get; set; } = true;

        /// <summary>
        /// Show custom grant types
        /// </summary>
        public bool ShowExtensionGrantTypes { get; set; } = true;

        /// <summary>
        /// Show token endpoint authentication methods
        /// </summary>
        public bool ShowTokenEndpointAuthenticationMethods { get; set; } = true;

        /// <summary>
        /// Adds custom entries to the discovery document
        /// </summary>
        public Dictionary<string, object> CustomEntries { get; set; } = new Dictionary<string, object>();
    }
}


text:
import db from './db';

function findOrCreateByFacebookId(profile) {
  return db.search('users', `value.facebook.id = ${profile.id}`)
    .then((res) => {
      if (res.body.count === 0) {
        const { id, name, email } = profile;
        return create({
          email,
          facebook: {
            id,
            name,
            email
          }
        });
      } else {
        return Object.assign({}, { key: res.body.results[0].path.key }, res.body.results[0].value );
      }
    })
}

function findByKey(key) {

}

function create(user) {
  return db.post('users', user)
    .then((res) => {
      return Object.assign({}, { key: res.path.key }, user);
    })
}

function deleteUserByKey(userId) {

}

export {
  findOrCreateByFacebookId,
  findByKey,
  create,
}


text:
'''The Random interface for random byte generators'''
from details.MJRCTRDRBG import CTRDRBG
from details.MJRAES import AES
from time import time
from os import urandom
from os import getpid, getppid

class Random(object):
    '''The interface for random byte generator'''

    def __init__(self, seed=None, keysize=32, cipher=AES):
        '''Constructor
        seed = seed (will auto-generate if not specified)
        keysize = keysize of underlying block cipher (default = 32 bytes)
        cipher = Class for block cipher (default: AES)
        '''
        self.__drbg = CTRDRBG(cipher, keysize)
        if (seed is None) or (len(seed) == 0):
            seed = Random.__generate_seed(1024)

        microseconds = round(time() * 1000000)
        nonce = microseconds.to_bytes(12, byteorder='big')
        personalization = b'MJR CTR-DRBG'
        self.__drbg._Instantiate(seed, nonce, personalization)
        # To detect a later fork
        self.__pid = getpid()

    @staticmethod
    def __generate_seed(numbytes):
        '''Generates a default seed
        Uses urandom because otherwise @tqbf will
        complain'''
        return urandom(numbytes)

    def get_bytes(self, numbytes):
        if (self.__pid != getpid()):
            # fork() happened -- reseed
            self.__drbg._Reseed(self.__generate_seed(1024), None)
            self.__pid = getpid()
        try:
            rand = self.__drbg._Generate(numbytes, None)
        except AssertionError:
            # resseed required
            self.__drbg._Reseed(self.__generate_seed(1024), None)
            rand = self.__drbg._Generate(numbytes, None)
        return rand


text:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),

    url(r'^clouds/$', views.cloudmesh_clouds, name='cloudmesh_clouds'),
    url(r'^cloud/(?P<cloud>\w+)/$', views.cloudmesh_cloud, name='cloudmesh_cloud'),
    url(r'^default/$', views.cloudmesh_defaults, name='cloudmesh_default'),
    url(r'^refresh/(?P<action>\w+)/(?P<cloud>\w+)/$', views.cloudmesh_refresh, name='cloudmesh_refresh'),
    url(r'^image/refresh/$', views.cloudmesh_refresh_db, name='cloudmesh_refresh_db'),
    url(r'^flavor/refresh/$', views.cloudmesh_refresh_db, name='cloudmesh_refresh_db'),
    url(r'^vm/refresh/$', views.cloudmesh_refresh_vm, name='cloudmesh_refresh_vm'),
    url(r'^vm/vm_action/$', views.cloudmesh_vm_action, name='cloudmesh_vm_action'),
    url(r'^image/$', views.cloudmesh_images, name='cloudmesh_image'),
    url(r'^image/(?P<cloud>\w+)/$', views.cloudmesh_images, name='cloudmesh_image'),
    url(r'^flavor/$', views.cloudmesh_flavors, name='cloudmesh_flavor'),
    url(r'^flavor/(?P<cloud>\w+)/$', views.cloudmesh_flavors, name='cloudmesh_flavor'),
    url(r'^vm/$', views.cloudmesh_vms, name='cloudmesh_vm'),
    url(r'^vm/(?P<cloud>\w+)/$', views.cloudmesh_vms, name='cloudmesh_vm'),

    #    url(r'^vcluster/$', views.cloudmesh_vclusters, name='cloudmesh_vcluster'),
]


text:
import Ember from 'ember';
import FormRouteMixin from 'ember-form-object/mixins/form-route';

export default Ember.Route.extend(FormRouteMixin, {
  formName: 'login',

  actions: {
    save() {
      window.alert(`Will save: ${this.get('form.email')} - ${this.get('form.password')}`);
      this.get('form').save().then(res => {
        window.alert(`Result: ${res}`);
      });
    }
  }
});


text:
import {SET_CHANNELS, SELECT_CHANNEL} from './actions/channels';
import {Channel} from './classes/Channel';

export function channels(state = [], action = null) {
	switch (action.type) {
		case SET_CHANNELS:
			return action.channels;
		default:
			return state;
	}
}

export function channel(state = new Channel(), action = null) {
	switch (action.type) {
		case SELECT_CHANNEL:
			return action.channel;
		default:
			return state;
	}
}


text:
tasync
======

A small utility program to export, sync and import whole Azure Table Storage accounts.


text:
'use strict';

import {TPromise} from 'vs/base/common/winjs.base';
import {IDisposable} from 'vs/base/common/lifecycle';
import {IModel, EventType, IModelContentChangedEvent} from 'vs/editor/common/editorCommon';
import {ICompatWorkerService, ICompatMode} from 'vs/editor/common/services/compatWorkerService';
import {DefaultWorkerFactory} from 'vs/base/worker/defaultWorkerFactory';
import {WorkerClient} from 'vs/base/common/worker/workerClient';
import {IModelService} from 'vs/editor/common/services/modelService';
import {ModesRegistry} from 'vs/editor/common/modes/modesRegistry';

export class MainThreadCompatWorkerService implements ICompatWorkerService {
	public _serviceBrand: any;
	public isInMainThread = true;

	private _workerFactory: DefaultWorkerFactory;
	private _worker: WorkerClient;
	private _workerCreatedPromise: TPromise<void>;
	private _triggerWorkersCreatedPromise: (value: void) => void;

	private _modelListeners: { [uri: string]: IDisposable };

	constructor(
		@IModelService modelService: IModelService
	) {
		this._workerFactory = new DefaultWorkerFactory(true);
		this._worker = null;
		this._workerCreatedPromise = new TPromise<void>((c, e, p) => {
			this._triggerWorkersCreatedPromise = c;
		}, () => {
			// Not cancelable
		});

		this._modelListeners = Object.create(null);

		const isInterestingModel = (model:IModel) => {
			if (model.isTooLargeForHavingARichMode()) {
				return false;
			}

			let modeId = model.getModeId();

			let compatModes = ModesRegistry.getCompatModes();
			for (let i = 0; i < compatModes.length; i++) {
				if (compatModes[i].id === modeId) {
					return true;
				}
			}

			return false;
		};

		const onModelAdded = (model:IModel) => {
			if (!isInterestingModel(model)) {
				return;
			}

			this._modelListeners[model.uri.toString()] = model.addBulkListener((events) => {
				let contentChangedEvents = (
					events
					.filter(e => e.getType() === EventType.ModelRawContentChanged)
					.map(e => <IModelContentChangedEvent>e.getData())
				);
				if (contentChangedEvents.length === 0) {
					return;
				}

				this._call('$', 'acceptModelEvents', [model.uri, { contentChanged: contentChangedEvents }]);
			});

			this._call('$', 'acceptNewModel', [{
				url: model.uri,
				versionId: model.getVersionId(),
				value: model.toRawText(),
				modeId: model.getMode().getId()
			}]);
		};

		const onModelRemoved = (model:IModel) => {
			if (this._modelListeners[model.uri.toString()]) {
				this._modelListeners[model.uri.toString()].dispose();
				delete this._modelListeners[model.uri.toString()];

				this._call('$', 'acceptDidDisposeModel', [model.uri]);
			}
		};

		modelService.onModelAdded(onModelAdded);
		modelService.onModelRemoved(onModelRemoved);
		modelService.onModelModeChanged(event => {
			onModelRemoved(event.model);
			onModelAdded(event.model);
		});
	}

	public registerCompatMode(compatMode:ICompatMode): void {
		this._call('$', 'instantiateCompatMode', [compatMode.getId()]);
	}

	public CompatWorker(obj: ICompatMode, methodName: string, target: Function, param: any[]): TPromise<any> {
		return this._call(obj.getId(), methodName, param);
	}

	private _ensureWorkers(): void {
		if (this._triggerWorkersCreatedPromise) {
			// Workers not created yet

			this._createWorker();

			let complete = this._triggerWorkersCreatedPromise;
			this._triggerWorkersCreatedPromise = null;
			complete(null);
		}
	}

	private _afterWorkers(): TPromise<void> {
		this._ensureWorkers();

		let shouldCancelPromise = false;

		return new TPromise<void>((c, e, p) => {

			// hide the initialize promise inside this
			// promise so that it won't be canceled by accident
			this._workerCreatedPromise.then(() => {
				if (!shouldCancelPromise) {
					c(null);
				}
			}, e, p);

		}, () => {
			// mark that this promise is canceled
			shouldCancelPromise = true;
		});
	}

	private _createWorker(isRetry:boolean = false): void {
		this._worker = new WorkerClient(
			this._workerFactory,
			'vs/editor/common/worker/editorWorkerServer'
		);
		this._worker.onModuleLoaded = this._worker.request('initialize', {
			modesRegistryData: {
				compatModes: ModesRegistry.getCompatModes(),
				languages: ModesRegistry.getLanguages()
			}
		}).then(() => {
			ModesRegistry.onDidAddCompatModes((m) => this._call('$', 'acceptCompatModes', [m]));
			ModesRegistry.onDidAddLanguages((m) => this._call('$', 'acceptLanguages', [m]));
		}, (err) => {
			this._worker.dispose();
			this._worker = null;
			if (isRetry) {
				console.warn('Creating the web worker already failed twice. Giving up!');
			} else {
				this._createWorker(true);
			}
		});
	}

	private _call(rpcId: string, methodName: string, args:any[]): TPromise<any> {
		return this._afterWorkers().then(_ => {
			if (this._worker === null) {
				throw new Error('Cannot fulfill request...');
			}
			return this._worker.request('request', {
				target: rpcId,
				methodName: methodName,
				args: args
			});
		});
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="Animation">
        <item>Alpha</item>
        <item>Scale </item>
        <item>Left</item>
        <item>Right</item>
        <item>Bottom</item>
    </string-array>

    <string-array name="DiffData">
        <item>Data1</item>
        <item>Data2</item>
        <item>Data3</item>
        <item>Same</item>
    </string-array>
</resources>


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yiic message' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE, this file must be saved in UTF-8 encoding.
 */
return array (
  'Basic settings' => '',
  'E.g. http://example.com/humhub' => '',
  'New users will automatically added to these space(s).' => '',
  'Save' => '',
);


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* PHP_Beautifier_Batch_Files
* Handle the batch process for multiple php files to one directory
*
* PHP version 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt.  If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
* @category   PHP
* @package PHP_Beautifier
* @subpackage Batch
* @author Claudio Bustos <cdx@users.sourceforge.com>
* @copyright  2004-2010 Claudio Bustos
* @link     http://pear.php.net/package/PHP_Beautifier
* @link     http://beautifyphp.sourceforge.net
* @license    http://www.php.net/license/3_0.txt  PHP License 3.0
* @version    CVS: $Id:$
*/
/**
* PHP_Beautifier_Batch_Files
* Handle the batch process for multiple php files to one directory
*
* @category   PHP
* @package PHP_Beautifier
* @author Claudio Bustos <cdx@users.sourceforge.com>
* @copyright  2004-2010 Claudio Bustos
* @link     http://pear.php.net/package/PHP_Beautifier
* @link     http://beautifyphp.sourceforge.net
* @license    http://www.php.net/license/3_0.txt  PHP License 3.0
* @version    Release: 0.1.15
*/
class PHP_Beautifier_Batch_Output_Directory extends PHP_Beautifier_Batch_Output {
    public function save()
    {
        $aInputFiles = $this->oBatch->getInputFiles();
        $sOutputPath = $this->oBatch->getOutputPath();
        $aOutputFiles = PHP_Beautifier_Common::getSavePath($aInputFiles, $sOutputPath);
        $oLog = PHP_Beautifier_Common::getLog();
        for ($x = 0;$x<count($aInputFiles);$x++) {
            try {
                $this->beautifierSetInputFile($aInputFiles[$x]);
                $this->beautifierProcess();
                PHP_Beautifier_Common::createDir($aOutputFiles[$x]);
                $this->beautifierSave($aOutputFiles[$x]);
            }
            catch(Exception $oExp) {
                $oLog->log($oExp->getMessage() , PEAR_LOG_ERR);
            }
        }
        return true;
    }
    /**
    * Send the output of the files, one after another
    * With a little header
    * @return string
    */
    public function get()
    {
        $aInputFiles = $this->oBatch->getInputFiles();
        $sText = '';
        foreach($aInputFiles as $sFile) {
            $this->beautifierSetInputFile($sFile);
            $this->beautifierProcess();
            $sText.= $this->beautifierGet()."\n";
        }
        return $sText;
    }
}
?>