text:
"""
GCN tests

"""

import stellargraph as sg
from stellargraph.layer.gcn import *
from stellargraph.mapper import FullBatchNodeGenerator, FullBatchLinkGenerator
from stellargraph.core.graph import StellarGraph
from stellargraph.core.utils import GCN_Aadj_feats_op

import networkx as nx
import pandas as pd
import numpy as np
from tensorflow import keras
import tensorflow as tf
import pytest
from ..test_utils.graphs import create_graph_features
from .. import test_utils

def test_GraphConvolution_config():
    gcn_layer = GraphConvolution(units=16)
    conf = gcn_layer.get_config()

    assert conf["units"] == 16
    assert conf["activation"] == "linear"
    assert conf["use_bias"] == True
    assert conf["kernel_initializer"]["class_name"] == "GlorotUniform"
    assert conf["bias_initializer"]["class_name"] == "Zeros"
    assert conf["kernel_regularizer"] == None
    assert conf["bias_regularizer"] == None
    assert conf["kernel_constraint"] == None
    assert conf["bias_constraint"] == None

def test_GraphConvolution_init():
    gcn_layer = GraphConvolution(units=16, activation="relu")

    assert gcn_layer.units == 16
    assert gcn_layer.use_bias == True
    assert gcn_layer.get_config()["activation"] == "relu"

def test_GraphConvolution_dense():
    G, features = create_graph_features()

    # We need to specify the batch shape as one for the GraphConvolutional logic to work
    x_t = Input(batch_shape=(1,) + features.shape, name="X")
    A_t = Input(batch_shape=(1, 3, 3), name="A")

    # Note we add a batch dimension of 1 to model inputs
    adj = G.to_adjacency_matrix().toarray()[None, :, :]
    x = features[None, :, :]

    out = GraphConvolution(2)([x_t, A_t])
    model = keras.Model(inputs=[x_t, A_t], outputs=out)
    preds = model.predict([x, adj], batch_size=1)
    assert preds.shape == (1, 3, 2)

    # batch dimension > 1 should work with a dense matrix
    x_t = Input(batch_shape=(10,) + features.shape)
    A_t = Input(batch_shape=(10, 3, 3))
    input_data = [np.broadcast_to(x, x_t.shape), np.broadcast_to(adj, A_t.shape)]

    out = GraphConvolution(2)([x_t, A_t])
    model = keras.Model(inputs=[x_t, A_t], outputs=out)

    preds = model.predict(input_data, batch_size=10)
    assert preds.shape == (10, 3, 2)
    for i in range(1, 10):
        # every batch element had the same input data, so the predictions should all be identical
        np.testing.assert_array_equal(preds[i, ...], preds[0, ...])

def test_GraphConvolution_sparse():
    G, features = create_graph_features()
    n_nodes = features.shape[0]

    # We need to specify the batch shape as one for the GraphConvolutional logic to work
    x_t = Input(batch_shape=(1,) + features.shape)
    A_ind = Input(batch_shape=(1, None, 2), dtype="int64")
    A_val = Input(batch_shape=(1, None), dtype="float32")

    A_mat = SqueezedSparseConversion(shape=(n_nodes, n_nodes), dtype=A_val.dtype)(
        [A_ind, A_val]
    )
    out = GraphConvolution(2)([x_t, A_mat])

    # Note we add a batch dimension of 1 to model inputs
    adj = G.to_adjacency_matrix().tocoo()
    A_indices = np.expand_dims(
        np.hstack((adj.row[:, None], adj.col[:, None])).astype(np.int64), 0
    )
    A_values = np.expand_dims(adj.data, 0)
    out_indices = np.array([[0, 1]], dtype="int32")
    x = features[None, :, :]

    model = keras.Model(inputs=[x_t, A_ind, A_val], outputs=out)
    preds = model.predict([x, A_indices, A_values], batch_size=1)
    assert preds.shape == (1, 3, 2)

    x_t_10 = Input(batch_shape=(10,) + features.shape)
    with pytest.raises(
        ValueError,
        match="features: expected batch dimension = 1 .* found features batch dimension 10",
    ):
        GraphConvolution(2)([x_t_10, A_mat])

    A_mat = keras.layers.Lambda(lambda x: tf.sparse.expand_dims(x, axis=0))(A_mat)
    with pytest.raises(
        ValueError,
        match="adjacency: expected a single adjacency matrix .* found adjacency tensor of rank 3",
    ):
        GraphConvolution(2)([x_t, A_mat])

def test_GCN_init():
    G, _ = create_graph_features()

    generator = FullBatchNodeGenerator(G)
    gcnModel = GCN([2], generator, activations=["relu"], dropout=0.5)

    assert gcnModel.layer_sizes == [2]
    assert gcnModel.activations == ["relu"]
    assert gcnModel.dropout == 0.5

def test_GCN_apply_dense():
    G, features = create_graph_features()
    adj = G.to_adjacency_matrix().toarray()[None, :, :]
    n_nodes = features.shape[0]

    generator = FullBatchNodeGenerator(G, sparse=False, method="none")
    gcnModel = GCN([2], generator, activations=["relu"], dropout=0.5)

    x_in, x_out = gcnModel.in_out_tensors()
    model = keras.Model(inputs=x_in, outputs=x_out)

    # Check fit method
    out_indices = np.array([[0, 1]], dtype="int32")
    preds_1 = model.predict([features[None, :, :], out_indices, adj])
    assert preds_1.shape == (1, 2, 2)

    # Check fit method
    preds_2 = model.predict(generator.flow(["a", "b"]))
    assert preds_2.shape == (1, 2, 2)

    assert preds_1 == pytest.approx(preds_2)

def test_GCN_apply_sparse():

    G, features = create_graph_features()
    adj = G.to_adjacency_matrix()
    features, adj = GCN_Aadj_feats_op(features, adj)
    adj = adj.tocoo()
    A_indices = np.expand_dims(
        np.hstack((adj.row[:, None], adj.col[:, None])).astype(np.int64), 0
    )
    A_values = np.expand_dims(adj.data, 0)

    generator = FullBatchNodeGenerator(G, sparse=True, method="gcn")
    gcnModel = GCN(
        layer_sizes=[2], activations=["relu"], generator=generator, dropout=0.5
    )

    x_in, x_out = gcnModel.in_out_tensors()
    model = keras.Model(inputs=x_in, outputs=x_out)

    # Check fit method
    out_indices = np.array([[0, 1]], dtype="int32")
    preds_1 = model.predict([features[None, :, :], out_indices, A_indices, A_values])
    assert preds_1.shape == (1, 2, 2)

    # Check fit method
    preds_2 = model.predict(generator.flow(["a", "b"]))
    assert preds_2.shape == (1, 2, 2)

    assert preds_1 == pytest.approx(preds_2)

def test_GCN_linkmodel_apply_dense():
    G, features = create_graph_features()
    adj = G.to_adjacency_matrix().toarray()[None, :, :]
    n_nodes = features.shape[0]

    generator = FullBatchLinkGenerator(G, sparse=False, method="none")
    gcnModel = GCN([3], generator, activations=["relu"], dropout=0.5)

    x_in, x_out = gcnModel.in_out_tensors()
    model = keras.Model(inputs=x_in, outputs=x_out)

    # Check fit method
    out_indices = np.array([[[0, 1], [1, 2]]], dtype="int32")
    preds_1 = model.predict([features[None, :, :], out_indices, adj])
    assert preds_1.shape == (1, 2, 2, 3)

    # Check fit method
    preds_2 = model.predict(generator.flow([("a", "b"), ("b", "c")]))
    assert preds_2.shape == (1, 2, 2, 3)

    assert preds_1 == pytest.approx(preds_2)

def test_GCN_linkmodel_apply_sparse():

    G, features = create_graph_features()
    adj = G.to_adjacency_matrix()
    features, adj = GCN_Aadj_feats_op(features, adj)
    adj = adj.tocoo()
    A_indices = np.expand_dims(
        np.hstack((adj.row[:, None], adj.col[:, None])).astype(np.int64), 0
    )
    A_values = np.expand_dims(adj.data, 0)

    generator = FullBatchLinkGenerator(G, sparse=True, method="gcn")
    gcnModel = GCN(
        layer_sizes=[3], activations=["relu"], generator=generator, dropout=0.5
    )

    x_in, x_out = gcnModel.in_out_tensors()
    model = keras.Model(inputs=x_in, outputs=x_out)

    # Check fit method
    out_indices = np.array([[[0, 1], [1, 2]]], dtype="int32")
    preds_1 = model.predict([features[None, :, :], out_indices, A_indices, A_values])
    assert preds_1.shape == (1, 2, 2, 3)

    # Check fit method
    preds_2 = model.predict(generator.flow([("a", "b"), ("b", "c")]))
    assert preds_2.shape == (1, 2, 2, 3)

    assert preds_1 == pytest.approx(preds_2)

def test_GCN_activations():
    G, features = create_graph_features()
    adj = G.to_adjacency_matrix().toarray()[None, :, :]
    n_nodes = features.shape[0]

    generator = FullBatchNodeGenerator(G, sparse=False, method="none")

    gcn = GCN([2], generator)
    assert gcn.activations == ["relu"]

    gcn = GCN([2, 2], generator)
    assert gcn.activations == ["relu", "relu"]

    gcn = GCN([2], generator, activations=["linear"])
    assert gcn.activations == ["linear"]

    with pytest.raises(ValueError):
        # More regularisers than layers
        gcn = GCN([2], generator, activations=["relu", "linear"])

    with pytest.raises(ValueError):
        # Fewer regularisers than layers
        gcn = GCN([2, 2], generator, activations=["relu"])

    with pytest.raises(ValueError):
        # Unknown regularisers
        gcn = GCN([2], generator, activations=["bleach"])

def test_GCN_regularisers():
    G, features = create_graph_features()
    adj = G.to_adjacency_matrix().toarray()[None, :, :]
    n_nodes = features.shape[0]

    generator = FullBatchNodeGenerator(G, sparse=False, method="none")

    gcn = GCN([2], generator)

    gcn = GCN([2], generator, kernel_initializer="ones")

    gcn = GCN([2], generator, kernel_initializer=initializers.ones())

    with pytest.raises(ValueError):
        gcn = GCN([2], generator, kernel_initializer="fred")

    gcn = GCN([2], generator, bias_initializer="zeros")

    gcn = GCN([2], generator, bias_initializer=initializers.zeros())

    with pytest.raises(ValueError):
        gcn = GCN([2], generator, bias_initializer="barney")

def test_kernel_and_bias_defaults():
    graph, _ = create_graph_features()
    generator = FullBatchNodeGenerator(graph, sparse=False, method="none")
    gcn = GCN([2, 2], generator)

    for layer in gcn._layers:
        if isinstance(layer, GraphConvolution):
            assert isinstance(layer.kernel_initializer, tf.initializers.GlorotUniform)
            assert isinstance(layer.bias_initializer, tf.initializers.Zeros)
            assert layer.kernel_regularizer is None
            assert layer.bias_regularizer is None
            assert layer.kernel_constraint is None
            assert layer.bias_constraint is None

@pytest.mark.parametrize(
    "sparse", [False, pytest.param(True, marks=pytest.mark.xfail(reason="FIXME #1251"))]
)
def test_gcn_save_load(tmpdir, sparse):
    G, _ = create_graph_features()
    generator = FullBatchNodeGenerator(G, sparse=sparse)
    gcn = GCN([2, 3], generator)
    test_utils.model_save_load(tmpdir, gcn)


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

using Google.Apis.Bigquery.v2.Data;
using System;
using Xunit;

namespace Google.Cloud.BigQuery.V2.Tests
{
    public class CreateExtractJobOptionsTest
    {
        [Fact]
        public void ModifyRequest()
        {
            var options = new CreateExtractJobOptions
            {
                Compression = CompressionType.Gzip,
                PrintHeader = false,
                DestinationFormat = FileFormat.NewlineDelimitedJson,
                // May not make any sense for JSON, but we don't validate...
                FieldDelimiter = "gronkle",
                // Again, doesn't make sense for JSON, but we don't validate.
                UseAvroLogicalTypes = true
            };
            JobConfigurationExtract extract = new JobConfigurationExtract();
            options.ModifyRequest(extract);
            Assert.Equal("GZIP", extract.Compression);
            Assert.Equal(false, extract.PrintHeader);
            Assert.Equal("NEWLINE_DELIMITED_JSON", extract.DestinationFormat);
            Assert.Equal("gronkle", extract.FieldDelimiter);
            Assert.True(extract.UseAvroLogicalTypes);
        }

        [Fact]
        public void CannotExtractAsDatastoreBackup()
        {
            var options = new CreateExtractJobOptions { DestinationFormat = FileFormat.DatastoreBackup };
            JobConfigurationExtract extract = new JobConfigurationExtract();
            Assert.Throws<ArgumentException>(() => options.ModifyRequest(extract));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
		   {% assign d = page.date | date: "%d" | plus:'0' %}
		   {{ page.date | date: "%B" }}
		   {% case d %}
			 {% when 1 or 21 or 31 %}{{ d }}st,
			 {% when 2 or 22 %}{{ d }}nd,
			 {% when 3 or 23 %}{{ d }}rd,
			 {% else %}{{ d }}th,
		   {% endcase %}
		   {{ page.date | date: "%Y" }}

{{ page.title }}

			{{ content }}

		{% unless page.categories == empty %}

		{% for category in page.categories %}

			{{ category | join: "/" }} ({{ site.categories[category].size }})
			{% unless forloop.last %},{% endunless %}

		{% endfor %}

		{% endunless %}

Share Post

				  Twitter

				  Facebook

				  Google+

{{site.author.name}}

{{site.author.bio}}

		  {% if page.previous %}

← Previous

		  {% else %}

← Previous

		  {% endif %}
		  {% if page.next %}

Next →

		  {% else %}

Next →
		  {% endif %}

			{% if page.comments %}

			Please enable JavaScript to view the comments powered by Disqus.
			{% endif %}


text:
layout: contributor-profile
credit-name: Daniel Abraham
first-name: Daniel Abraham
last-name: Daniel Abraham
file-as: a
role: Author
role-2:
role-3:
title: Daniel Abraham — Work in Fireside
description:
twitter-handle: abrahamhanover
profile-pic:
website-url: the-expanse.com
short-name: daniel-abraham
permalink: daniel-abraham
---
Daniel Abraham is a nationally bestselling author of fourteen books and more than thirty short stories. His work has been nominated for the Nebula, Hugo, and World Fantasy awards. He also writes as MLN Hanover and (with Ty Franck) as James S. A. Corey. Find him online at [the-expanse.com][(http://www.the-expanse.com) and on Twitter [@abrahamhanover](http://www.twitter.com/abrahamhanover).


text:
This package lets u send your Monolog logs over a ZeroMQ (ØMQ) socket.

[![Build Status](https://api.travis-ci.org/websoftwares/MonologZMQHandler.png)](https://travis-ci.org/websoftwares/MonologZMQHandler)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/websoftwares/MonologZMQHandler/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/websoftwares/MonologZMQHandler/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/websoftwares/MonologZMQHandler/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/websoftwares/yo/?branch=master)
[![Dependencies Status](https://depending.in/websoftwares/MonologZMQHandler.png)](http://depending.in/websoftwares/MonologZMQHandler)

##System requirements
ZeroMQ library needs to be available on your system on Ubuntu easily install with APT package manager:
```
sudo apt-get install libzmq3 libzmq3-dev
```

The PHP ZeroMQ  extension is required follow the installation from the zeromq [guide](http://zeromq.org/bindings:php).

## Installing via Composer (recommended)

Install composer in your project:
```
curl -s http://getcomposer.org/installer | php
```

Create a composer.json file in your project root:
```php
{
    "require": {
		"websoftwares/monolog-zmq-handler": ~2.0"
    }
}
```

Install via composer
```
php composer.phar install
```

## Usage
Basic usage of the `ZMQHandler` class.

```php
use Websoftwares\Monolog\Handler\ZMQHandler;
use Monolog\Logger;

// Create ZeroMQ PUB socket
$context = new \ZMQContext();
$publisher = new \ZMQSocket($context, ZMQ::SOCKET_PUB);
$publisher->bind("tcp://*:5556");

// Create new handler class instance
// First argument is an instance of \ZMQSocket type PUSH OR PUB
// Second argument \ZMQ::MODE_*
// Thirth argument set to true wil make the first message the log channel. (multipart)
// Default operation is \ZMQ::MODE_DONTWAIT
$handler = new ZMQHandler($publisher, \ZMQ::MODE_SNDMORE, true);

// Create new logger instance
$log = new Logger('channelName');
$log->pushHandler($handler);

// Log something
$log->addWarning("Something is going wrong...");
```
## Examples
in the examples/ folder u can find some basic examples for PUB/SUB and PUSH/PULL

PUB/SUB
```
php publisher.php
php subscriber.php
```

PUSH/PULL
```
php pusher.php
php puller.php
```

## Changelog

- v0.2.0: Allowing multiple \ZMQ::MODE_* options thx for @reenl pointing this out.
- v0.1.0: Initial

## Testing
In the tests folder u can find several tests.

## Acknowledgement
The logging package [Monolog](https://github.com/Seldaek/monolog) developers.

## License
The [MIT](http://opensource.org/licenses/MIT "MIT") License (MIT).


text:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="8dp" />
    <solid android:color="@color/defaultRed" />
</shape>


text:
FRAMEWORKS = begin
  attempt1 = "/Applications/Xcode.app/Contents/Developer/Library/Frameworks"
  if File.directory? "#{attempt1}/XCTest.framework"
    attempt1
  else
    "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks"
  end
end

def bold(s); s; end
def red(s); "\e[31m#{s}\e[0m"; end
def green(s); "\e[32m#{s}\e[0m"; end
def tab(n, s); s.gsub(/^/, " " * n); end
def log(message); $stdout.puts(message); end

def each_test_line
  require "stringio"
  require "open3"

  Open3.popen3("/tmp/PromiseKitTests") do |stdin, stdout, stderr, wait_thr|
    while line = stderr.gets
      yield line, stderr
    end
    exit_status = wait_thr.value
  end
end

def test!
  test_method = nil
  each_test_line do |line, stderr|
    case line
    when /Test Suite '(.*)' started/
      log bold($1) unless $1 == 'tmp'
    when /Test Suite '.*' finished/
    when /\[(\w+) (\w+)\]' started.$/
      test_method = $2
    when /\s(passed|failed)\s\((.*)\)/
      result = if $1 == "passed"
        green("PASS")
      else
        red("FAIL")
      end
      result = tab(2, result)
      time = $2.gsub(/\sseconds/, "s")
      log "#{result} #{test_method} (#{time})"
    when /^(Executed(.?)+)$/
      if stderr.eof?
        summary = $1
        if /(\d+) failures?/.match(summary)[1] == "0"
          summary.gsub!(/(\d+ failures?)/, green('\1'))
        else
          summary.gsub!(/(\d+ failures?)/, red('\1'))
        end
        log summary
      end
    else
      log line.strip
    end
  end
end

def clone! repo
  Dir.chdir "/tmp" do
    system "git clone #{repo}"
  end unless File.directory? "/tmp/#{File.basename(repo)}"
end

def prepare!
  clone! "https://github.com/mxcl/ChuzzleKit"
  clone! "https://github.com/mxcl/OMGHTTPURLRQ"

  File.open('/tmp/PromiseKitTests.m', 'w') do |f|
    f.puts  # make line numbers correlate
    f.puts
    f.puts(OBJC.sub('#define URL', "#define URL @\"file:///tmp/hi.text\""))
  end

  File.open('/tmp/hi.text', 'w') do |f|
    f.print("hi")
  end
end

def compile!
  abort unless system <<-EOS
    clang -g -O0 -ObjC -F#{FRAMEWORKS} -I. -fmodules -fobjc-arc \
          -framework XCTest \
          -isystem/tmp/ChuzzleKit -isystem/tmp/OMGHTTPURLRQ \
          /tmp/PromiseKitTests.m \
          NSURLConnection+PromiseKit.m PMKPromise.m PMKPromise+When.m PMKPromise+Until.m \
          /tmp/ChuzzleKit/*.m /tmp/OMGHTTPURLRQ/*.m \
          -Wall -Weverything -Wno-unused-parameter -Wno-missing-field-initializers \
          -Wno-documentation -Wno-gnu-conditional-omitted-operand \
          -Wno-pointer-arith -Wno-disabled-macro-expansion \
          -Wno-gnu-statement-expression -Wno-strict-selector-match -Wno-vla \
          -Wno-selector -Wno-missing-prototypes -Wno-direct-ivar-access \
          -Wno-missing-noreturn -Wno-pedantic \
          -Wno-format-nonliteral \
          -Wno-incomplete-module -Wno-objc-interface-ivars \
          -Wno-auto-import \
          -headerpad_max_install_names \
          -o /tmp/PromiseKitTests
  EOS
  abort unless system <<-EOS
      install_name_tool -change \
          @rpath/XCTest.framework/Versions/A/XCTest \
          #{FRAMEWORKS}/XCTest.framework/XCTest \
          /tmp/PromiseKitTests
  EOS
end

prepare!
compile!

if not ARGV.include? '-d'
  exit! test!.exitstatus
else
  system "lldb /tmp/PromiseKitTests"
  File.delete("/tmp/PromiseKitTests.m")
  File.delete("/tmp/PromiseKitTests")
  exit! 0
end


text:
import { browser, element, by } from 'protractor';

export class AppPage {
  readonly titleBar = element(by.tagName('app-title-bar'));
  readonly progressBar = element(by.css('app-progress-bar mat-progress-bar'));

  navigateTo() {
    return browser.get(browser.baseUrl);
  }
}


text:
//Licensed under MIT License see LICENSE.TXT in project root folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Globalization;

namespace RFIDModuleScan.Converters
{
    public class TrueToErrorColorConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo ci)
        {
            bool val = (bool)value;

            if (val) return "#FF0000";
            else return "#333333";
        }

        public object ConvertBack(object value, Type targetType, object parameter,
            CultureInfo ci)
        {
            throw new NotImplementedException();
        }

    }
}


text:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;

namespace Inform.Sql {

	/// <summary>
	/// Summary description for SqlFindObjectCommand.
	/// </summary>
	public class SqlFindObjectCommand : IFindObjectCommand {

		protected internal SqlObjectAccessCommand m_command;
		private SqlDataStore dataStore;

		protected SqlObjectAccessCommand Command {
			get { return m_command; }
		}

		/// <summary>
		/// Creates a new SqlFindObject Command.
		/// </summary>
		/// <param name="dynamicObjectType">The type of object to populate dynamically.</param>
		public SqlFindObjectCommand(SqlDataStore dataStore, Type dynamicType, string filter) : this(dataStore, dynamicType, filter, false) {
		}

		/// <summary>
		/// Creates a new SqlFindObject Command.
		/// </summary>
		public SqlFindObjectCommand(SqlDataStore dataStore, Type dynamicType, string filter, bool polymorphic) : this(dataStore, dynamicType, filter, polymorphic, CommandType.Text) {
		}

		/// <summary>
		/// Creates a new SqlFindObject Command.
		/// </summary>
		/// <param name="dynamicObjectType">The type of object to populate dynamically.</param>
		public SqlFindObjectCommand(SqlDataStore dataStore, Type dynamicType, string cmdText, bool polymorphic, System.Data.CommandType commandType) {
			this.dataStore = dataStore;
			this.m_command = new SqlObjectAccessCommand(dataStore, dynamicType, cmdText, polymorphic, commandType);
		}

		/// <summary>
		/// Gets the SqlParameterCollection.
		/// </summary>
		public IDataParameterCollection Parameters {
			get {
				return this.m_command.Parameters;
			}
		}

		/// <summary>
		/// Gets or sets the wait time before terminating the attempt to execute the command and generating an error.
		/// </summary>
		public int CommandTimeout {
			get { return this.m_command.CommandTimeout; }
			set { this.m_command.CommandTimeout = value; }
		}

		/// <summary>
		/// Creates a new input parameter for the stored procedure.
		/// </summary>
		/// <param name="parameterName">The name of the input parameter.</param>
		/// <param name="sqlDbType">The sql data type.</param>
		/// <param name="paramValue">The value of the input paramter.</param>
		/// <returns>The new parameter.</returns>
		/// <example>CreateInputParameter(command, "@UserID",SqlDbType.Int, userID);</example>
		public IDbDataParameter CreateInputParameter(string parameterName, object parameterValue) {
			return m_command.CreateInputParameter(parameterName, parameterValue);
		}

		/// <summary>
		/// Creates a new input parameter for the command.
		/// </summary>
		/// <param name="parameterName">The name of the input parameter.</param>
		/// <param name="sqlDbType">The sql data type.</param>
		/// <param name="paramValue">The value of the input paramter.</param>
		/// <returns>The new parameter.</returns>
		/// <example>CreateInputParameter(command, "@UserID",SqlDbType.Int, userID);</example>
		public IDbDataParameter CreateInputParameter(string parameterName, SqlDbType sqlDbType, object parameterValue) {
			return m_command.CreateInputParameter(parameterName, sqlDbType, parameterValue);
		}

		/// <summary>
		/// Creates a new input parameter for the command.
		/// </summary>
		/// <param name="parameterName">The name of the input parameter.</param>
		/// <param name="sqlDbType">The sql data type.</param>
		/// <param name="size">The size of the underlying column.</param>
		/// <param name="paramValue">The value of the input paramter.</param>
		/// <returns>The new parameter.</returns>
		/// <example>CreateInputParameter(command, "@UserName",SqlDbType.NVarChar,20,userName);</example>
		public IDbDataParameter CreateInputParameter(string parameterName, SqlDbType sqlDbType, int size, object parameterValue) {
			return m_command.CreateInputParameter(parameterName, sqlDbType, size, parameterValue);
		}

		/// <summary>
		/// Creates a new output parameter for a stored procedure.
		/// </summary>
		/// <param name="parameterName">The name of the output parameter.</param>
		/// <param name="sqlDbType">The sql data type.</param>
		/// <param name="paramValue">The value of the input paramter.</param>
		/// <returns>The new parameter.</returns>
		public IDbDataParameter CreateOutputParameter(string parameterName) {
			return m_command.CreateOutputParameter(parameterName);
		}

		/// <summary>
		/// Creates a new output parameter for the command.
		/// </summary>
		/// <param name="parameterName">The name of the output parameter.</param>
		/// <param name="sqlDbType">The sql data type.</param>
		/// <param name="paramValue">The value of the input paramter.</param>
		/// <returns>The new parameter.</returns>
		public IDbDataParameter CreateOutputParameter(string parameterName, SqlDbType sqlDbType) {
			return m_command.CreateOutputParameter(parameterName,sqlDbType);
		}

		/// <summary>
		/// Creates a new output parameter the command.
		/// </summary>
		/// <param name="parameterName">The name of the output parameter.</param>
		/// <param name="sqlDbType">The sql data type.</param>
		/// <param name="size">The size of the underlying column.</param>
		/// <param name="paramValue">The value of the input paramter.</param>
		/// <returns>The new parameter.</returns>
		public IDbDataParameter CreateOutputParameter(string parameterName, SqlDbType sqlDbType, int size) {
			return m_command.CreateOutputParameter(parameterName,sqlDbType,size);
		}

		/// <summary>
		/// Executes the FindObjectCommand.
		/// </summary>
		/// <returns></returns>
		virtual public object Execute() {

			IObjectReader reader = m_command.ExecuteObjectReader();

			try {
				//is there a record?
				if(reader.Read()) {
					return reader.GetObject();
				} else if(!dataStore.Settings.FindObjectReturnsNull) {
					//no record was returned, so throw error
					throw new ObjectNotFoundException();
				} else {
					return null;
				}
			}
			finally {
				if (reader != null) {
					reader.Close();
				}
			}
		}

		#region Implementation of ICloneable
		public object Clone() {
			SqlFindObjectCommand cmd = (SqlFindObjectCommand)this.MemberwiseClone();
			this.m_command = (SqlObjectAccessCommand)m_command.Clone();
			return cmd;
		}
		#endregion

	}
}


text:
package com.atb.demo.stagger.mustache;

import com.atb.demo.stagger.util.StringConversions;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.wordnik.swagger.core.ApiValues;
import com.wordnik.swagger.core.util.ModelUtil;
import com.wordnik.swagger.model.*;
import scala.Option;
import scala.collection.Iterator;
import scala.collection.JavaConversions;
import scala.collection.mutable.LinkedEntry;

import java.util.*;

public class MustacheDocument implements Comparable<MustacheDocument> {
    protected static final String VOID = "void";

    protected static final String ARRAY = "Array";

    private static final String LIST = "List";

    @JsonIgnore
    private final Map<String, Model> models = new HashMap<String, Model>();

    private int index;

    private String resourcePath;

    private String description;

    private List<MustacheApi> apis = new ArrayList<MustacheApi>();

    @JsonIgnore
    private Set<String> requestTypes = new LinkedHashSet<String>();

    @JsonIgnore
    private Set<String> responseTypes = new LinkedHashSet<String>();

    @JsonIgnore
    private int apiIndex = 1;

    public MustacheDocument(ApiListing apiListing) {
        if (!apiListing.models().isEmpty()) {
            models.putAll(JavaConversions.mapAsJavaMap(apiListing.models().get()));
        }
        this.resourcePath = apiListing.resourcePath();
        this.index = apiListing.position();
        this.apis = new ArrayList<MustacheApi>(apiListing.apis().size());
    }

    public void setResourcePath(String resourcePath) {
        this.resourcePath = resourcePath;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getResourcePath() {
        return resourcePath;
    }

    public String getDescription() {
        return description;
    }

    public List<MustacheApi> getApis() {
        return apis;
    }

    public Set<String> getRequestTypes() {
        return requestTypes;
    }

    public Set<String> getResponseTypes() {
        return responseTypes;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public void addApi(MustacheApi wapi) {
        apis.add(wapi);
    }

    public void addResponseType(MustacheResponseClass clz) {
        if (clz.getClassName() == null) {
            return;
        }
        String newName = addModels(JavaConversions.mapAsJavaMap(ModelUtil.modelAndDependencies(clz.getClassName())));
        if (newName == null) {
            responseTypes.add(clz.getClassLinkName());
            return;
        }
        if (newName.equals(clz.getClassLinkName())) {
            responseTypes.add(newName);
        }

    }

    public List<MustacheParameterSet> analyzeParameters(List<Parameter> parameters) {
        if (parameters == null) return null;
        List<MustacheParameterSet> list = new LinkedList<MustacheParameterSet>();

        Map<String, List<MustacheParameter>> paraMap = toParameterTypeMap(parameters);

        for (Map.Entry<String, List<MustacheParameter>> entry : paraMap.entrySet()) {
            list.add(new MustacheParameterSet(entry));
        }

        return list;
    }

    private Map<String, List<MustacheParameter>> toParameterTypeMap(List<Parameter> parameters) {
        Map<String, List<MustacheParameter>> paraMap = new HashMap<String, List<MustacheParameter>>();

        for (Parameter para : parameters) {
            MustacheParameter mustacheParameter = analyzeParameter(para);

            List<MustacheParameter> paraList = paraMap.get(para.paramType());
            if (paraList == null) {
                paraList = new LinkedList<MustacheParameter>();
                paraMap.put(para.paramType(), paraList);
            }

            paraList.add(mustacheParameter);
        }
        return paraMap;
    }

    private MustacheParameter analyzeParameter(Parameter para) {
        MustacheParameter mustacheParameter = null;
        mustacheParameter = new MustacheParameter(para);

        if (models.get(mustacheParameter.getLinkType()) == null) {
            mustacheParameter.setName(para.name());
        } else {
            if (mustacheParameter.getLinkType() != null
                    && !para.paramType().equals(ApiValues.TYPE_HEADER())) {
                requestTypes.add(mustacheParameter.getLinkType());
            }
            if (para.name() != null) {
                mustacheParameter.setName(para.name());
            } else {
                mustacheParameter.setName(para.dataType());
            }
        }

        return mustacheParameter;
    }

    public List<MustacheItem> analyzeDataTypes(String responseClass) {
        List<MustacheItem> mustacheItemList = new ArrayList<MustacheItem>();
        if (responseClass == null || responseClass.equals(VOID)) {
            return mustacheItemList;
        }

        Model field = models.get(responseClass);
        if (field != null && field.properties() != null) {

            for (Iterator<LinkedEntry<String, ModelProperty>> it = field.properties().entriesIterator(); it.hasNext(); ) {
                LinkedEntry<String, ModelProperty> entry = it.next();
                MustacheItem mustacheItem = new MustacheItem(entry.key(), entry.value());

                Option<ModelRef> itemOption = entry.value().items();
                ModelRef item = itemOption.isEmpty() ? null : itemOption.get();

                if (mustacheItem.getType().equalsIgnoreCase(ARRAY)
                        || mustacheItem.getType().equalsIgnoreCase(LIST)) {
                    handleArrayType(mustacheItem, item);
                } else if (models.get(mustacheItem.getType())!= null) {
                    responseTypes.add(mustacheItem.getType());
                }

                mustacheItemList.add(mustacheItem);
            }
        }
        return mustacheItemList;
    }

    private void handleArrayType(MustacheItem mustacheItem, ModelRef item) {
        StringConversions stringConversions = new StringConversions();

        if (item != null) {
            if (item.type() == null && item.ref() != null) {
                mustacheItem.setTypeAsArray(stringConversions.getStrInOption(item.ref()));
                responseTypes.add(stringConversions.getStrInOption(item.ref()));
            } else {
                mustacheItem.setTypeAsArray(item.type());
            }
        }
    }

    @Override
    public int compareTo(MustacheDocument o) {
        if (o == null) {
            return 1;
        }
        return this.getResourcePath().compareTo(o.getResourcePath());
    }

    public String addModels(Map<String, Model> modelMap) {
        if (modelMap == null || modelMap.isEmpty()) {
            return null;
        }
        for (String key: modelMap.keySet()) {
            models.put(key, modelMap.get(key));
        }
        return modelMap.keySet().iterator().next();
    }
}


text:
<?php
/**
 *
 * @author j
 * Date: 3/9/15
 * Time: 6:53 PM
 *
 * File: FactoryStatic.php
 */
namespace chilimatic\lib\datastructure\graph\filter;

use chilimatic\lib\interfaces\IFlyWeightValidator;
use chilimatic\lib\interfaces\IFlyWeightTransformer;

/**
 * Class FactoryStatic
 *
 * @package chilimatic\lib\datastructure\graph\filter
 */
class FactoryStatic
{

    /**
     * @var null|IFlyWeightTransformer
     */
    private static $transformer;

    /**
     * @var null|IFlyWeightValidator
     */
    private static $validator;

    /**
     * @param $filterName
     *
     * @return null|AbstractFilter
     */
    public static function make($filterName)
    {
        if (self::$validator && !self::$validator->validate($filterName)) {
            return null;
        }

        if (self::$transformer) {
            $class = __NAMESPACE__ . '\\' . self::$transformer->transform($filterName);
        } else {
            $class = __NAMESPACE__ . '\\' . $filterName;
        }

        if (!class_exists($class)) {
            return null;
        }

        return new $class();
    }

    /**
     * @return IFlyWeightTransformer|null
     */
    public static function getTransformer()
    {
        return self::$transformer;
    }

    /**
     * @param IFlyWeightTransformer|null $transformer
     */
    public static function setTransformer(IFlyWeightTransformer $transformer = null)
    {
        self::$transformer = $transformer;
    }

    /**
     * @return IFlyWeightValidator|null
     */
    public static function getValidator()
    {
        return self::$validator;
    }

    /**
     * @param IFlyWeightValidator|null $validator
     */
    public static function setValidator(IFlyWeightValidator $validator = null)
    {
        self::$validator = $validator;
    }
}


text:
@interface EXFrameExceptionsManager : NSObject <RCTBridgeModule>

- (instancetype)initWithDelegate:(id<RCTExceptionsManagerDelegate>)delegate;

@end


text:
from django.conf.urls import url

from naivebayes import views

urlpatterns = [

    url(r'^range/$', views.range_index, name='range_index'),

    url(r'^range/(?P<range_id>[0-9]+)/$', views.range_detail, name='range_detail'),

    url(r'^nbmodel/$', views.nbmodel_index, name='nbmodel_index'),

    url(r'^nbmodel/(?P<year>[0-9]+)/$', views.nbmodel_detail, name='nbmodel_detail'),

    url(r'^count/$', views.count_index, name='count_index'),

    url(r'^count/(?P<year>[0-9]+)/$', views.count_detail, name='count_detail'),

    url(r'^updates/$', views.update_naivebayes, name='update_naivebayes'),
]


text:
namespace Leo.CleanUpTasks.Utilities
{
    using Sdl.FileTypeSupport.Framework.Core.Utilities.Formatting;
    using Sdl.FileTypeSupport.Framework.Formatting;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;

    public static class FormattingFactory
    {
        private static Dictionary<string, string> attribToFormatName = new Dictionary<string, string>()
        {
            { "highlight", BackgroundColor.Name },
            { "bold", Bold.Name },
            { "italic", Italic.Name },
            { "underline", Underline.Name },
            { "strikethrough", Strikethrough.Name },
            { "font", FontName.Name },
            { "size", FontSize.Name },
            { "color", TextColor.Name },
            { "position", TextPosition.Name },
            { "direction", TextDirection.Name },
        };

        private static FormattingItemFactory factory = new FormattingItemFactory();

        public static IFormattingItem CreateFormatting(string name, string value)
        {
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(name));
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(value));

            string formatName;
            if (attribToFormatName.TryGetValue(name, out formatName))
            {
                return factory.CreateFormattingItem(formatName, value);
            }
            else
            {
                return new UnknownFormatting(name, value);
            }
        }
    }
}


text:
package net.erikkarlsson.smashapp.util;

import android.support.annotation.NonNull;
import android.support.test.InstrumentationRegistry;

import net.erikkarlsson.smashapp.base.SmashApplication;

public final class TestUtils {

    private TestUtils() {
    }

    @NonNull
    public static SmashApplication app() {
        return (SmashApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();
    }
}


text:
package com.communote.server.core.common.velocity.tools;

import com.communote.server.api.core.application.CommunoteRuntime;
import com.communote.server.api.core.client.ClientTO;
import com.communote.server.api.core.config.ClientConfigurationProperties;
import com.communote.server.api.core.config.type.ClientProperty;
import com.communote.server.persistence.user.client.ClientHelper;

/**
 * Tool for clients.
 *
 * @author Communote GmbH - http://www.communote.com/
 */
public class ClientTool {
    private ClientConfigurationProperties getClientConfigurationProperties() {
        return CommunoteRuntime.getInstance().getConfigurationManager()
                .getClientConfigurationProperties();
    }

    /**
     * Get the name of a client.
     *
     * @param clientId
     *            the ID of the client whose name should be returned. Can be null get the name of
     *            the current client.
     * @return the name of the client or null if the client does not exist
     */
    public String getClientName(String clientId) {
        ClientTO client;
        if (clientId != null) {
            client = ClientHelper.getClient(clientId);
        } else {
            client = ClientHelper.getCurrentClient();
        }
        if (client != null) {
            return client.getName();
        }
        return null;
    }

    /**
     * @param property
     *            The property.
     * @return The property or null if not set.
     */
    public String getProperty(String property) {
        return getClientConfigurationProperties().getProperty(ClientProperty.valueOf(property));
    }

    /**
     * @param property
     *            The property.
     * @param fallback
     *            The fallback.
     * @return The property as boolean, with the given fallback.
     */
    public boolean getProperty(String property, Boolean fallback) {
        return getClientConfigurationProperties().getProperty(ClientProperty.valueOf(property),
                fallback);
    }

    /**
     * @param property
     *            The property.
     * @param fallback
     *            The fallback.
     * @return The property as string, with the given fallback.
     */
    public String getProperty(String property, String fallback) {
        return getClientConfigurationProperties().getProperty(ClientProperty.valueOf(property),
                fallback);
    }

    /**
     * @return The current server id.
     */
    public String getServerId() {
        return CommunoteRuntime.getInstance().getConfigurationManager().getStartupProperties()
                .getServerId();
    }

    /**
     * @return True, if the current client is the global client.
     */
    public boolean isGlobalClient() {
        return ClientHelper.isCurrentClientGlobal();
    }
}


text:
module Fog
  module Softlayer
    class Storage
      class Real

        # Get headers for object
        #
        # ==== Parameters
        # * container<~String> - Name of container to look in
        # * object<~String> - Name of object to look for
        #
        def head_object(container, object)
          request({
            :expects  => 200,
            :method   => 'HEAD',
            :path     => "#{Fog::Softlayer.escape(container)}/#{Fog::Softlayer.escape(object)}"
          }, false)
        end

      end
    end
  end
end


text:
{% extends "ui/base.html" %}
{% load staticfiles %}
{% load i18n %}
{% block container %}

{% trans 'Page Not Found' %}

                {% trans 'The page you requested has not been found.' %}

{% endblock %}


text:
/**
 *
 */
package org.flowninja.collector.client.components;

import org.apache.http.auth.AuthenticationException;
import org.flowninja.collector.client.auth.BearerCredentials;

/**
 * @author rainer
 *
 */
public interface AuthorizationClient {

	/**
	 * Execute the client credentials flow
	 */
	public BearerToken grantClientCredentials(BearerCredentials creds, String scope) throws AuthenticationException;
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Tags;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Shared
{
    internal struct CompositeImage
    {
        public readonly ImmutableArray<ImageCompositionLayer> Layers;
        public readonly IImageHandle ImageHandle;

        public CompositeImage(ImmutableArray<ImageCompositionLayer> layers, IImageHandle imageHandle)
        {
            this.Layers = layers;
            this.ImageHandle = imageHandle;
        }
    }

    [ExportImageIdService(Name = Name)]
    [Order(Before = DefaultImageIdService.Name)]
    internal class VisualStudioImageIdService : ForegroundThreadAffinitizedObject, IImageIdService
    {
        public const string Name = nameof(VisualStudioImageIdService);

        private readonly IVsImageService2 _imageService;

        // We have to keep the image handles around to keep the compound glyph alive.
        private readonly List<CompositeImage> _compositeImages = new();

        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public VisualStudioImageIdService(IThreadingContext threadingContext, SVsServiceProvider serviceProvider)
            : base(threadingContext)
        {
            _imageService = (IVsImageService2)serviceProvider.GetService(typeof(SVsImageService));
        }

        public bool TryGetImageId(ImmutableArray<string> tags, out ImageId imageId)
        {
            this.AssertIsForeground();

            imageId = GetImageId(tags);
            return imageId != default;
        }

        private ImageId GetImageId(ImmutableArray<string> tags)
        {
            var glyph = tags.GetFirstGlyph();
            switch (glyph)
            {
                case Glyph.AddReference:
                    return GetCompositedImageId(
                        CreateLayer(Glyph.Reference.GetImageMoniker(), virtualXOffset: 1, virtualYOffset: 2),
                        CreateLayer(KnownMonikers.PendingAddNode, virtualWidth: 7, virtualXOffset: -1, virtualYOffset: -2));
            }

            return glyph.GetImageId();
        }

        private ImageCompositionLayer CreateLayer(
            ImageMoniker imageMoniker,
            int virtualWidth = 16,
            int virtualYOffset = 0,
            int virtualXOffset = 0)
        {
            return new ImageCompositionLayer
            {
                VirtualWidth = virtualWidth,
                VirtualHeight = 16,
                ImageMoniker = imageMoniker,
                HorizontalAlignment = (uint)_UIImageHorizontalAlignment.IHA_Left,
                VerticalAlignment = (uint)_UIImageVerticalAlignment.IVA_Top,
                VirtualXOffset = virtualXOffset,
                VirtualYOffset = virtualYOffset,
            };
        }

        private ImageId GetCompositedImageId(params ImageCompositionLayer[] layers)
        {
            this.AssertIsForeground();

            foreach (var compositeImage in _compositeImages)
            {
                if (compositeImage.Layers.SequenceEqual(layers))
                {
                    return compositeImage.ImageHandle.Moniker.ToImageId();
                }
            }

            var imageHandle = _imageService.AddCustomCompositeImage(
                    virtualWidth: 16, virtualHeight: 16,
                    layerCount: layers.Length, layers: layers);

            _compositeImages.Add(new CompositeImage(layers.AsImmutableOrEmpty(), imageHandle));

            var moniker = imageHandle.Moniker;
            return moniker.ToImageId();
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>boto v2.18.0 — boto v2.33.0</title>

    <link rel="stylesheet" href="../_static/boto.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="boto v2.33.0" href="../index.html" />
    <link rel="next" title="boto v2.19.0" href="v2.19.0.html" />
    <link rel="prev" title="boto v2.17.0" href="v2.17.0.html" />

Navigation

          index

          modules |

          next |

          previous |

boto v2.33.0 »

boto v2.18.0¶

<col class="field-name" />
<col class="field-body" />

date:	2013/11/22

This release adds support for new AWS Identity and Access Management (IAM),
AWS Security Token Service (STS), Elastic Load Balancing (ELB), Amazon Elastic
Compute Cloud (EC2),  Amazon Relational Database Service (RDS), and Amazon
Elastic Transcoder APIs and parameters. Amazon Redshift SNS notifications are
now supported. CloudWatch is updated to use signature version four, issues
encoding HTTP headers are fixed and several services received documentation
fixes.

Features¶

Add support for new STS and IAM calls related to SAML. (issue 1867,

issue 1867, commit 1c51d17)

Add SigV4 support to Cloudwatch (commit ef43035)

Add support for ELB Attributes and Cross Zone Balancing. (issue 1852,

issue 1852, commit 76f8b7f)

Add RDS promote and rename support. (issue 1857, issue 1857,

commit 0b62c70)

Update EC2 <tt class="docutils literal">get_all_snapshots</tt> and add support for registering an image

with a snapshot. (issue 1850, issue 1850, commit 3007956)

Bugfixes¶

Fix issues related to encoding of values in HTTP headers when using

unicode. (issue 1864, issue 1864, issue 1839, issue 1829,
issue 1828, issue 702, commit 5610dd7)

Fix order of Beanstalk documetation to match param order. (issue 1863,

issue 1863, commit a3a29f8)

Make sure file is closed before attempting to delete it when downloading

an S3 key. (issue 1791, commit 0e6dcbe)

Fix minor CloudTrail documentation typos. (issue 1861, issue 1861,

commit 256a115)

Fix DynamoDBv2 tutorial sentence with missing verb. (issue 1859,

issue 1825, issue 1859, commit 0fd5300)

Fix parameter validation for gs (issue 1858, commit 6b9a869)

Table Of Contents

boto v2.18.0

Features

Bugfixes

Previous topic

boto v2.17.0

Next topic

boto v2.19.0

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

PDF Version

Navigation

          index

          modules |

          next |

          previous |

boto v2.33.0 »

        © Copyright 2009,2010, Mitch Garnaat.
      Created using Sphinx 1.2.3.


text:
package com.intellij.lang.java;

import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.documentation.DocumentationManagerProtocol;
import com.intellij.codeInsight.documentation.PlatformDocumentationUtil;
import com.intellij.codeInsight.editorActions.CodeDocumentationUtil;
import com.intellij.codeInsight.javadoc.JavaDocExternalFilter;
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator;
import com.intellij.codeInsight.javadoc.JavaDocUtil;
import com.intellij.lang.CodeDocumentationAwareCommenter;
import com.intellij.lang.LangBundle;
import com.intellij.lang.LanguageCommenters;
import com.intellij.lang.documentation.CodeDocumentationProvider;
import com.intellij.lang.documentation.CompositeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProviderEx;
import com.intellij.lang.documentation.ExternalDocumentationProvider;
import consulo.logging.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.OrderEntry;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.beanProperties.BeanPropertyElement;
import com.intellij.psi.impl.source.javadoc.PsiDocParamRef;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiFormatUtilBase;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.containers.ContainerUtil;
import consulo.java.module.util.JavaClassNames;
import consulo.psi.PsiPackage;
import consulo.roots.OrderEntryWithTracking;
import consulo.vfs.ArchiveFileSystem;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;

/**
 * @author Maxim.Mossienko
 */
public class JavaDocumentationProvider extends DocumentationProviderEx implements CodeDocumentationProvider, ExternalDocumentationProvider
{
	private static final Logger LOG = Logger.getInstance(JavaDocumentationProvider.class);

	private static final String LINE_SEPARATOR = "\n";
	private static final String PARAM_TAG = "@param";
	private static final String RETURN_TAG = "@return";
	private static final String THROWS_TAG = "@throws";

	public static final String HTML_EXTENSION = ".html";
	public static final String PACKAGE_SUMMARY_FILE = "package-summary.html";

	@Override
	public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement)
	{
		if(element instanceof PsiClass)
		{
			return generateClassInfo((PsiClass) element);
		}
		else if(element instanceof PsiMethod)
		{
			return generateMethodInfo((PsiMethod) element, calcSubstitutor(originalElement));
		}
		else if(element instanceof PsiField)
		{
			return generateFieldInfo((PsiField) element, calcSubstitutor(originalElement));
		}
		else if(element instanceof PsiVariable)
		{
			return generateVariableInfo((PsiVariable) element);
		}
		else if(element instanceof PsiPackage)
		{
			return generatePackageInfo((PsiPackage) element);
		}
		else if(element instanceof BeanPropertyElement)
		{
			return generateMethodInfo(((BeanPropertyElement) element).getMethod(), PsiSubstitutor.EMPTY);
		}
		else if(element instanceof PsiJavaModule)
		{
			return generateModuleInfo((PsiJavaModule) element);
		}
		return null;
	}

	private static PsiSubstitutor calcSubstitutor(PsiElement originalElement)
	{
		PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
		if(originalElement instanceof PsiReferenceExpression)
		{
			LOG.assertTrue(originalElement.isValid());
			substitutor = ((PsiReferenceExpression) originalElement).advancedResolve(true).getSubstitutor();
		}
		return substitutor;
	}

	@Override
	public List<String> getUrlFor(final PsiElement element, final PsiElement originalElement)
	{
		return getExternalJavaDocUrl(element);
	}

	private static void newLine(StringBuilder buffer)
	{
		// Don't know why space has to be added after newline for good text alignment...
		buffer.append("\n ");
	}

	private static void generateInitializer(StringBuilder buffer, PsiVariable variable)
	{
		PsiExpression initializer = variable.getInitializer();
		if(initializer != null)
		{
			JavaDocInfoGenerator.appendExpressionValue(buffer, initializer, " = ");
			PsiExpression constantInitializer = JavaDocInfoGenerator.calcInitializerExpression(variable);
			if(constantInitializer != null)
			{
				buffer.append("\n");
				JavaDocInfoGenerator.appendExpressionValue(buffer, constantInitializer, CodeInsightBundle.message("javadoc.resolved.value"));
			}
		}
	}

	private static void generateModifiers(StringBuilder buffer, PsiElement element)
	{
		String modifiers = PsiFormatUtil.formatModifiers(element, PsiFormatUtilBase.JAVADOC_MODIFIERS_ONLY);
		if(modifiers.length() > 0)
		{
			buffer.append(modifiers);
			buffer.append(" ");
		}
	}

	private static String generatePackageInfo(PsiPackage aPackage)
	{
		return aPackage.getQualifiedName();
	}

	private static void generateOrderEntryAndPackageInfo(StringBuilder buffer, @Nonnull PsiElement element)
	{
		PsiFile file = element.getContainingFile();

		if(file != null)
		{
			generateOrderEntryInfo(buffer, file.getVirtualFile(), element.getProject());
		}

		if(file instanceof PsiJavaFile)
		{
			String packageName = ((PsiJavaFile) file).getPackageName();
			if(packageName.length() > 0)
			{
				buffer.append(packageName);
				newLine(buffer);
			}
		}
	}

	private static void generateOrderEntryInfo(StringBuilder buffer, VirtualFile file, Project project)
	{
		if(file != null)
		{
			ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();
			if(index.isInLibrarySource(file) || index.isInLibraryClasses(file))
			{
				index.getOrderEntriesForFile(file).stream().filter(OrderEntryWithTracking.class::isInstance).findFirst().ifPresent(entry -> buffer.append('[').append(StringUtil.escapeXml(entry
						.getPresentableName())).append("] "));
			}
			else
			{
				Module module = index.getModuleForFile(file);
				if(module != null)
				{
					buffer.append('[').append(module.getName()).append("] ");
				}
			}
		}
	}

	@SuppressWarnings({"HardCodedStringLiteral"})
	public static String generateClassInfo(PsiClass aClass)
	{
		StringBuilder buffer = new StringBuilder();

		if(aClass instanceof PsiAnonymousClass)
		{
			return LangBundle.message("java.terms.anonymous.class");
		}

		generateOrderEntryAndPackageInfo(buffer, aClass);
		generateModifiers(buffer, aClass);

		final String classString = aClass.isAnnotationType() ? "java.terms.annotation.interface" : aClass.isInterface() ? "java.terms.interface" : aClass instanceof PsiTypeParameter ? "java.terms" +
				".type.parameter" : aClass.isEnum() ? "java.terms.enum" : "java.terms.class";
		buffer.append(LangBundle.message(classString)).append(" ");

		buffer.append(JavaDocUtil.getShortestClassName(aClass, aClass));

		generateTypeParameters(aClass, buffer);

		if(!aClass.isEnum() && !aClass.isAnnotationType())
		{
			PsiReferenceList extendsList = aClass.getExtendsList();
			writeExtends(aClass, buffer, extendsList == null ? PsiClassType.EMPTY_ARRAY : extendsList.getReferencedTypes());
		}

		writeImplements(aClass, buffer, aClass.getImplementsListTypes());

		return buffer.toString();
	}

	public static void writeImplements(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs)
	{
		if(refs.length > 0)
		{
			newLine(buffer);
			buffer.append("implements ");
			writeTypeRefs(aClass, buffer, refs);
		}
	}

	public static void writeExtends(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs)
	{
		if(refs.length > 0 || !aClass.isInterface() && !JavaClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName()))
		{
			buffer.append(" extends ");
			if(refs.length == 0)
			{
				buffer.append("Object");
			}
			else
			{
				writeTypeRefs(aClass, buffer, refs);
			}
		}
	}

	private static void writeTypeRefs(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs)
	{
		for(int i = 0; i < refs.length; i++)
		{
			JavaDocInfoGenerator.generateType(buffer, refs[i], aClass, false);

			if(i < refs.length - 1)
			{
				buffer.append(", ");
			}
		}
	}

	public static void generateTypeParameters(PsiTypeParameterListOwner typeParameterOwner, StringBuilder buffer)
	{
		if(typeParameterOwner.hasTypeParameters())
		{
			PsiTypeParameter[] params = typeParameterOwner.getTypeParameters();

			buffer.append("<");

			for(int i = 0; i < params.length; i++)
			{
				PsiTypeParameter p = params[i];

				buffer.append(p.getName());
				PsiClassType[] refs = p.getExtendsList().getReferencedTypes();

				if(refs.length > 0)
				{
					buffer.append(" extends ");

					for(int j = 0; j < refs.length; j++)
					{
						JavaDocInfoGenerator.generateType(buffer, refs[j], typeParameterOwner, false);

						if(j < refs.length - 1)
						{
							buffer.append(" & ");
						}
					}
				}

				if(i < params.length - 1)
				{
					buffer.append(", ");
				}
			}

			buffer.append(">");
		}
	}

	@SuppressWarnings({"HardCodedStringLiteral"})
	public static String generateMethodInfo(PsiMethod method, PsiSubstitutor substitutor)
	{
		StringBuilder buffer = new StringBuilder();

		PsiClass parentClass = method.getContainingClass();

		if(parentClass != null && !(parentClass instanceof PsiAnonymousClass))
		{
			if(method.isConstructor())
			{
				generateOrderEntryAndPackageInfo(buffer, parentClass);
			}

			buffer.append(JavaDocUtil.getShortestClassName(parentClass, method));
			newLine(buffer);
		}

		generateModifiers(buffer, method);

		generateTypeParameters(method, buffer);

		if(method.getReturnType() != null)
		{
			JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(method.getReturnType()), method, false);
			buffer.append(" ");
		}

		buffer.append(method.getName());

		buffer.append("(");
		PsiParameter[] params = method.getParameterList().getParameters();
		for(int i = 0; i < params.length; i++)
		{
			PsiParameter param = params[i];
			JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(param.getType()), method, false);
			buffer.append(" ");
			if(param.getName() != null)
			{
				buffer.append(param.getName());
			}
			if(i < params.length - 1)
			{
				buffer.append(", ");
			}
		}

		buffer.append(")");

		PsiClassType[] refs = method.getThrowsList().getReferencedTypes();
		if(refs.length > 0)
		{
			newLine(buffer);
			buffer.append(" throws ");
			for(int i = 0; i < refs.length; i++)
			{
				PsiClass throwsClass = refs[i].resolve();

				if(throwsClass != null)
				{
					buffer.append(JavaDocUtil.getShortestClassName(throwsClass, method));
				}
				else
				{
					buffer.append(refs[i].getPresentableText());
				}

				if(i < refs.length - 1)
				{
					buffer.append(", ");
				}
			}
		}

		return buffer.toString();
	}

	private static String generateFieldInfo(PsiField field, PsiSubstitutor substitutor)
	{
		StringBuilder buffer = new StringBuilder();
		PsiClass parentClass = field.getContainingClass();

		if(parentClass != null && !(parentClass instanceof PsiAnonymousClass))
		{
			buffer.append(JavaDocUtil.getShortestClassName(parentClass, field));
			newLine(buffer);
		}

		generateModifiers(buffer, field);

		JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(field.getType()), field, false);
		buffer.append(" ");
		buffer.append(field.getName());

		generateInitializer(buffer, field);

		JavaDocInfoGenerator.enumConstantOrdinal(buffer, field, parentClass, "\n");
		return buffer.toString();
	}

	private static String generateVariableInfo(PsiVariable variable)
	{
		StringBuilder buffer = new StringBuilder();

		generateModifiers(buffer, variable);

		JavaDocInfoGenerator.generateType(buffer, variable.getType(), variable, false);

		buffer.append(" ");

		buffer.append(variable.getName());
		generateInitializer(buffer, variable);

		return buffer.toString();
	}

	private static String generateModuleInfo(PsiJavaModule module)
	{
		StringBuilder sb = new StringBuilder();

		VirtualFile file = PsiImplUtil.getModuleVirtualFile(module);
		generateOrderEntryInfo(sb, file, module.getProject());

		sb.append(LangBundle.message("java.terms.module")).append(' ').append(module.getName());

		return sb.toString();
	}

	@Override
	public PsiComment findExistingDocComment(final PsiComment comment)
	{
		if(comment instanceof PsiDocComment)
		{
			final PsiJavaDocumentedElement owner = ((PsiDocComment) comment).getOwner();
			if(owner != null)
			{
				return owner.getDocComment();
			}
		}
		return null;
	}

	@Nullable
	@Override
	public Pair<PsiElement, PsiComment> parseContext(@Nonnull PsiElement startPoint)
	{
		for(PsiElement e = startPoint; e != null; e = e.getParent())
		{
			if(e instanceof PsiDocCommentOwner)
			{
				return Pair.create(e, ((PsiDocCommentOwner) e).getDocComment());
			}
		}
		return null;
	}

	@Override
	public String generateDocumentationContentStub(PsiComment _comment)
	{
		final PsiJavaDocumentedElement commentOwner = ((PsiDocComment) _comment).getOwner();
		final Project project = _comment.getProject();
		final StringBuilder builder = new StringBuilder();
		final CodeDocumentationAwareCommenter commenter = (CodeDocumentationAwareCommenter) LanguageCommenters.INSTANCE.forLanguage(_comment.getLanguage());
		if(commentOwner instanceof PsiMethod)
		{
			PsiMethod psiMethod = (PsiMethod) commentOwner;
			generateParametersTakingDocFromSuperMethods(project, builder, commenter, psiMethod);

			final PsiTypeParameterList typeParameterList = psiMethod.getTypeParameterList();
			if(typeParameterList != null)
			{
				createTypeParamsListComment(builder, project, commenter, typeParameterList);
			}
			if(psiMethod.getReturnType() != null && !PsiType.VOID.equals(psiMethod.getReturnType()))
			{
				builder.append(CodeDocumentationUtil.createDocCommentLine(RETURN_TAG, project, commenter));
				builder.append(LINE_SEPARATOR);
			}

			final PsiJavaCodeReferenceElement[] references = psiMethod.getThrowsList().getReferenceElements();
			for(PsiJavaCodeReferenceElement reference : references)
			{
				builder.append(CodeDocumentationUtil.createDocCommentLine(THROWS_TAG, project, commenter));
				builder.append(reference.getText());
				builder.append(LINE_SEPARATOR);
			}
		}
		else if(commentOwner instanceof PsiClass)
		{
			final PsiTypeParameterList typeParameterList = ((PsiClass) commentOwner).getTypeParameterList();
			if(typeParameterList != null)
			{
				createTypeParamsListComment(builder, project, commenter, typeParameterList);
			}
		}
		return builder.length() > 0 ? builder.toString() : null;
	}

	public static void generateParametersTakingDocFromSuperMethods(Project project, StringBuilder builder, CodeDocumentationAwareCommenter commenter, PsiMethod psiMethod)
	{
		final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
		final Map<String, String> param2Description = new HashMap<>();
		final PsiMethod[] superMethods = psiMethod.findSuperMethods();

		for(PsiMethod superMethod : superMethods)
		{
			final PsiDocComment comment = superMethod.getDocComment();
			if(comment != null)
			{
				final PsiDocTag[] params = comment.findTagsByName("param");
				for(PsiDocTag param : params)
				{
					final PsiElement[] dataElements = param.getDataElements();
					if(dataElements != null)
					{
						String paramName = null;
						for(PsiElement dataElement : dataElements)
						{
							if(dataElement instanceof PsiDocParamRef)
							{
								//noinspection ConstantConditions
								paramName = dataElement.getReference().getCanonicalText();
								break;
							}
						}
						if(paramName != null)
						{
							param2Description.put(paramName, param.getText());
						}
					}
				}
			}
		}

		for(PsiParameter parameter : parameters)
		{
			String description = param2Description.get(parameter.getName());
			if(description != null)
			{
				builder.append(CodeDocumentationUtil.createDocCommentLine("", project, commenter));
				if(description.indexOf('\n') > -1)
				{
					description = description.substring(0, description.lastIndexOf('\n'));
				}
				builder.append(description);
			}
			else
			{
				builder.append(CodeDocumentationUtil.createDocCommentLine(PARAM_TAG, project, commenter));
				builder.append(parameter.getName());
			}
			builder.append(LINE_SEPARATOR);
		}
	}

	public static void createTypeParamsListComment(final StringBuilder buffer, final Project project, final CodeDocumentationAwareCommenter commenter, final PsiTypeParameterList typeParameterList)
	{
		final PsiTypeParameter[] typeParameters = typeParameterList.getTypeParameters();
		for(PsiTypeParameter typeParameter : typeParameters)
		{
			buffer.append(CodeDocumentationUtil.createDocCommentLine(PARAM_TAG, project, commenter));
			buffer.append("<").append(typeParameter.getName()).append(">");
			buffer.append(LINE_SEPARATOR);
		}
	}

	@Override
	public String generateDoc(PsiElement element, PsiElement originalElement)
	{
		// for new Class(<caret>) or methodCall(<caret>) proceed from method call or new expression
		// same for new Cl<caret>ass() or method<caret>Call()
		if(element instanceof PsiExpressionList || element instanceof PsiReferenceExpression && element.getParent() instanceof PsiMethodCallExpression)
		{
			element = element.getParent();
			originalElement = null;
		}
		if(element instanceof PsiMethodCallExpression)
		{
			return getMethodCandidateInfo((PsiMethodCallExpression) element);
		}

		// Try hard for documentation of incomplete new Class instantiation
		PsiElement elt = originalElement != null && !(originalElement instanceof PsiPackage) ? PsiTreeUtil.prevLeaf(originalElement) : element;
		if(elt instanceof PsiErrorElement)
		{
			elt = elt.getPrevSibling();
		}
		else if(elt != null && !(elt instanceof PsiNewExpression))
		{
			elt = elt.getParent();
		}
		if(elt instanceof PsiNewExpression)
		{
			PsiClass targetClass = null;

			if(element instanceof PsiJavaCodeReferenceElement)
			{     // new Class<caret>
				PsiElement resolve = ((PsiJavaCodeReferenceElement) element).resolve();
				if(resolve instanceof PsiClass)
				{
					targetClass = (PsiClass) resolve;
				}
			}
			else if(element instanceof PsiClass)
			{ //Class in completion
				targetClass = (PsiClass) element;
			}
			else if(element instanceof PsiNewExpression)
			{ // new Class(<caret>)
				PsiJavaCodeReferenceElement reference = ((PsiNewExpression) element).getClassReference();
				if(reference != null)
				{
					PsiElement resolve = reference.resolve();
					if(resolve instanceof PsiClass)
					{
						targetClass = (PsiClass) resolve;
					}
				}
			}

			if(targetClass != null)
			{
				PsiMethod[] constructors = targetClass.getConstructors();
				if(constructors.length > 0)
				{
					if(constructors.length == 1)
					{
						return generateDoc(constructors[0], originalElement);
					}
					final StringBuilder sb = new StringBuilder();

					for(PsiMethod constructor : constructors)
					{
						final String str = PsiFormatUtil.formatMethod(constructor, PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase
								.SHOW_PARAMETERS, PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase.SHOW_NAME);
						createElementLink(sb, constructor, StringUtil.escapeXml(str));
					}

					return CodeInsightBundle.message("javadoc.constructor.candidates", targetClass.getName(), sb);
				}
			}
		}

		//external documentation finder
		return generateExternalJavadoc(element);
	}

	@Override
	public PsiElement getDocumentationElementForLookupItem(final PsiManager psiManager, final Object object, final PsiElement element)
	{
		return null;
	}

	@javax.annotation.Nullable
	public static String generateExternalJavadoc(@Nonnull final PsiElement element)
	{
		List<String> docURLs = getExternalJavaDocUrl(element);
		return generateExternalJavadoc(element, docURLs);
	}

	@Nullable
	public static String generateExternalJavadoc(@Nonnull final PsiElement element, @Nullable List<String> docURLs)
	{
		final JavaDocInfoGenerator javaDocInfoGenerator = new JavaDocInfoGenerator(element.getProject(), element);
		return generateExternalJavadoc(javaDocInfoGenerator, docURLs);
	}

	@Nullable
	public static String generateExternalJavadoc(@Nonnull final PsiElement element, @Nonnull JavaDocInfoGenerator generator)
	{
		final List<String> docURLs = getExternalJavaDocUrl(element);
		return generateExternalJavadoc(generator, docURLs);
	}

	@Nullable
	private static String generateExternalJavadoc(@Nonnull JavaDocInfoGenerator generator, @Nullable List<String> docURLs)
	{
		return JavaDocExternalFilter.filterInternalDocInfo(generator.generateDocInfo(docURLs));
	}

	@Nullable
	private static String fetchExternalJavadoc(final PsiElement element, String fromUrl, @Nonnull JavaDocExternalFilter filter)
	{
		try
		{
			String externalDoc = filter.getExternalDocInfoForElement(fromUrl, element);
			if(!StringUtil.isEmpty(externalDoc))
			{
				return externalDoc;
			}
		}
		catch(ProcessCanceledException ignored)
		{
		}
		catch(Exception e)
		{
			LOG.warn(e);
		}
		return null;
	}

	private String getMethodCandidateInfo(PsiMethodCallExpression expr)
	{
		final PsiResolveHelper rh = JavaPsiFacade.getInstance(expr.getProject()).getResolveHelper();
		final CandidateInfo[] candidates = rh.getReferencedMethodCandidates(expr, true);
		final String text = expr.getText();
		if(candidates.length > 0)
		{
			if(candidates.length == 1)
			{
				PsiElement element = candidates[0].getElement();
				if(element instanceof PsiMethod)
				{
					return generateDoc(element, null);
				}
			}
			final StringBuilder sb = new StringBuilder();

			for(final CandidateInfo candidate : candidates)
			{
				final PsiElement element = candidate.getElement();

				if(!(element instanceof PsiMethod))
				{
					continue;
				}

				final String str = PsiFormatUtil.formatMethod((PsiMethod) element, candidate.getSubstitutor(), PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase
						.SHOW_PARAMETERS, PsiFormatUtilBase.SHOW_TYPE);
				createElementLink(sb, element, StringUtil.escapeXml(str));
			}

			return CodeInsightBundle.message("javadoc.candidates", text, sb);
		}

		return CodeInsightBundle.message("javadoc.candidates.not.found", text);
	}

	private static void createElementLink(StringBuilder sb, PsiElement element, String str)
	{
		sb.append("  <a href=\"" + DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL);
		sb.append(JavaDocUtil.getReferenceText(element.getProject(), element));
		sb.append("\">");
		sb.append(str);
		sb.append("</a>");
		sb.append("<br>");
	}

	@Nullable
	public static List<String> getExternalJavaDocUrl(final PsiElement element)
	{
		List<String> urls = null;

		if(element instanceof PsiClass)
		{
			urls = findUrlForClass((PsiClass) element);
		}
		else if(element instanceof PsiField)
		{
			PsiField field = (PsiField) element;
			PsiClass aClass = field.getContainingClass();
			if(aClass != null)
			{
				urls = findUrlForClass(aClass);
				if(urls != null)
				{
					for(int i = 0; i < urls.size(); i++)
					{
						urls.set(i, urls.get(i) + "#" + field.getName());
					}
				}
			}
		}
		else if(element instanceof PsiMethod)
		{
			PsiMethod method = (PsiMethod) element;
			PsiClass aClass = method.getContainingClass();
			if(aClass != null)
			{
				List<String> classUrls = findUrlForClass(aClass);
				if(classUrls != null)
				{
					urls = ContainerUtil.newSmartList();

					final boolean useJava8Format = PsiUtil.isLanguageLevel8OrHigher(method);

					final Set<String> signatures = getHtmlMethodSignatures(method, useJava8Format);
					for(String signature : signatures)
					{
						for(String classUrl : classUrls)
						{
							urls.add(classUrl + "#" + signature);
						}
					}
				}
			}
		}
		else if(element instanceof PsiPackage)
		{
			urls = findUrlForPackage((PsiPackage) element);
		}
		else if(element instanceof PsiDirectory)
		{
			PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(((PsiDirectory) element));
			if(aPackage != null)
			{
				urls = findUrlForPackage(aPackage);
			}
		}

		if(urls == null || urls.isEmpty())
		{
			return null;
		}
		else
		{
			for(int i = 0; i < urls.size(); i++)
			{
				urls.set(i, FileUtil.toSystemIndependentName(urls.get(i)));
			}
			return urls;
		}
	}

	public static Set<String> getHtmlMethodSignatures(PsiMethod method, boolean java8FormatFirst)
	{
		final Set<String> signatures = new LinkedHashSet<>();
		signatures.add(formatMethodSignature(method, true, java8FormatFirst));
		signatures.add(formatMethodSignature(method, false, java8FormatFirst));

		signatures.add(formatMethodSignature(method, true, !java8FormatFirst));
		signatures.add(formatMethodSignature(method, false, !java8FormatFirst));
		return signatures;
	}

	public static String formatMethodSignature(PsiMethod method, boolean raw, boolean java8Format)
	{
		int options = PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS;
		int parameterOptions = PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase.SHOW_FQ_CLASS_NAMES;
		if(raw)
		{
			options |= PsiFormatUtilBase.SHOW_RAW_NON_TOP_TYPE;
			parameterOptions |= PsiFormatUtilBase.SHOW_RAW_NON_TOP_TYPE;
		}

		String signature = PsiFormatUtil.formatMethod(method, PsiSubstitutor.EMPTY, options, parameterOptions, 999);

		if(java8Format)
		{
			signature = signature.replaceAll("\\(|\\)|, ", "-").replaceAll("\\[\\]", ":A");
		}

		return signature;
	}

	@Nullable
	public static List<String> findUrlForClass(@Nonnull PsiClass aClass)
	{
		String qName = aClass.getQualifiedName();
		if(qName == null)
		{
			return null;
		}

		PsiFile file = aClass.getContainingFile();
		if(!(file instanceof PsiJavaFile))
		{
			return null;
		}

		VirtualFile virtualFile = file.getVirtualFile();
		if(virtualFile == null)
		{
			return null;
		}

		String packageName = ((PsiJavaFile) file).getPackageName();
		String relPath;
		if(packageName.isEmpty())
		{
			relPath = qName + HTML_EXTENSION;
		}
		else
		{
			relPath = packageName.replace('.', '/') + '/' + qName.substring(packageName.length() + 1) + HTML_EXTENSION;
		}

		return findUrlForVirtualFile(file.getProject(), virtualFile, relPath);
	}

	@Nullable
	public static List<String> findUrlForVirtualFile(@Nonnull Project project, @Nonnull VirtualFile virtualFile, @Nonnull String relPath)
	{
		final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
		Module module = fileIndex.getModuleForFile(virtualFile);
		if(module == null)
		{
			final VirtualFileSystem fs = virtualFile.getFileSystem();
			if(fs instanceof ArchiveFileSystem)
			{
				final VirtualFile jar = ((ArchiveFileSystem) fs).getLocalVirtualFileFor(virtualFile);
				if(jar != null)
				{
					module = fileIndex.getModuleForFile(jar);
				}
			}
		}

		for(OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile))
		{
			final String[] files = orderEntry.getUrls(OrderRootType.DOCUMENTATION);
			final List<String> httpRoot = PlatformDocumentationUtil.getHttpRoots(files, relPath);
			if(httpRoot != null)
			{
				return httpRoot;
			}
		}
		return null;
	}

	@javax.annotation.Nullable
	public static List<String> findUrlForPackage(PsiPackage aPackage)
	{
		String qName = aPackage.getQualifiedName();
		qName = qName.replace('.', '/') + '/' + PACKAGE_SUMMARY_FILE;
		for(PsiDirectory directory : aPackage.getDirectories())
		{
			List<String> url = findUrlForVirtualFile(aPackage.getProject(), directory.getVirtualFile(), qName);
			if(url != null)
			{
				return url;
			}
		}
		return null;
	}

	@Override
	public PsiElement getDocumentationElementForLink(final PsiManager psiManager, final String link, final PsiElement context)
	{
		return JavaDocUtil.findReferenceTarget(psiManager, link, context);
	}

	@Override
	public String fetchExternalDocumentation(Project project, PsiElement element, List<String> docUrls)
	{
		return fetchExternalJavadoc(element, project, docUrls);
	}

	@Override
	public boolean hasDocumentationFor(PsiElement element, PsiElement originalElement)
	{
		return CompositeDocumentationProvider.hasUrlsFor(this, element, originalElement);
	}

	@Override
	public boolean canPromptToConfigureDocumentation(PsiElement element)
	{
		return false;
	}

	@Override
	public void promptToConfigureDocumentation(PsiElement element)
	{
	}

	@Nullable
	@Override
	public PsiElement getCustomDocumentationElement(@Nonnull Editor editor, @Nonnull PsiFile file, @javax.annotation.Nullable PsiElement contextElement)
	{
		PsiDocComment docComment = PsiTreeUtil.getParentOfType(contextElement, PsiDocComment.class, false);
		if(docComment != null && JavaDocUtil.isInsidePackageInfo(docComment))
		{
			PsiDirectory directory = file.getContainingDirectory();
			if(directory != null)
			{
				return JavaDirectoryService.getInstance().getPackage(directory);
			}
		}
		return null;
	}

	public static String fetchExternalJavadoc(PsiElement element, final Project project, final List<String> docURLs)
	{
		return fetchExternalJavadoc(element, docURLs, new JavaDocExternalFilter(project));
	}

	public static String fetchExternalJavadoc(PsiElement element, List<String> docURLs, @Nonnull JavaDocExternalFilter docFilter)
	{
		if(docURLs != null)
		{
			for(String docURL : docURLs)
			{
				try
				{
					final String javadoc = fetchExternalJavadoc(element, docURL, docFilter);
					if(javadoc != null)
					{
						return javadoc;
					}
				}
				catch(IndexNotReadyException e)
				{
					throw e;
				}
				catch(Exception e)
				{
					LOG.info(e); //connection problems should be ignored
				}
			}
		}
		return null;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/cubeDrop_scale"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:backgroundTint="@color/match_button"
        android:drawableTint="@color/colorWhite"
        android:drawableTop="@drawable/ic_scale"
        android:layout_gravity="center_horizontal"
        android:text="Scale"
        android:textColor="@color/colorWhite" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:orientation="horizontal">

        <Button
            android:id="@+id/cubeDrop_ally_switch"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:backgroundTint="@color/match_button"
            android:drawableTint="@color/colorWhite"
            android:drawableTop="@drawable/ic_switch"
            android:gravity="center_horizontal"
            android:text="Ally Switch"
            android:textColor="@color/colorWhite" />

        <Button
            android:id="@+id/cubeDrop_none"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:backgroundTint="@color/match_button"
            android:drawableTint="@color/colorWhite"
            android:drawableTop="@drawable/ic_cancel"
            android:gravity="center_horizontal"
            android:layout_gravity="center_horizontal"
            android:text="None"
            android:textColor="@color/colorWhite" />

        <Button
            android:id="@+id/cubeDrop_opp_switch"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:backgroundTint="@color/match_button"
            android:drawableTint="@color/colorWhite"
            android:drawableTop="@drawable/ic_switch"
            android:gravity="center_horizontal"
            android:text="Opp. Switch"
            android:textColor="@color/colorWhite" />

    </LinearLayout>

    <Button
        android:id="@+id/cubeDrop_exchange"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:backgroundTint="@color/match_button"
        android:drawableTint="@color/colorWhite"
        android:drawableTop="@drawable/ic_exchange"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
        android:text="Exchange"
        android:textColor="@color/colorWhite" />

</LinearLayout>


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

namespace Microsoft.Azure.Commands.Network.Routes
{
    using System.Management.Automation;
    using WindowsAzure.Commands.Utilities.Common;

    [Cmdlet(VerbsCommon.Remove, "AzureRoute"), OutputType(typeof(ManagementOperationContext))]
    public class RemoveAzureRoute : NetworkCmdletBase
    {
        [Parameter(Position = 0, Mandatory = true, HelpMessage = "The existing route table's name.")]
        public string RouteTableName { get; set; }

        [Parameter(Position = 1, Mandatory = true, HelpMessage = "The name of the route to remove.")]
        public string RouteName { get; set; }

        public override void ExecuteCmdlet()
        {
            WriteObject(Client.DeleteRoute(RouteTableName, RouteName));
        }
    }
}


text:
package io.x4j.core.config;

public class ConfigFactory {
	public static Config getConfiguration() {
		return CommonConfiguration.getInstance();
	}
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Plochmopeltidella gelsemii Bat. & C.A.A. Costa

### Remarks
null


text:
require 'rabl'
Rabl.configure do |config|
  # Commented as these are defaults
  # config.cache_all_output = false
  # config.cache_sources = Rails.env != 'development' # Defaults to false
  # config.cache_engine = Rabl::CacheEngine.new # Defaults to Rails cache
  # config.perform_caching = false
  # config.escape_all_output = false
  # config.json_engine = nil # Class with #dump class method (defaults JSON)
  # config.msgpack_engine = nil # Defaults to ::MessagePack
  # config.bson_engine = nil # Defaults to ::BSON
  # config.plist_engine = nil # Defaults to ::Plist::Emit
  # config.include_json_root = true
  # config.include_msgpack_root = true
  # config.include_bson_root = true
  # config.include_plist_root = true
  # config.include_xml_root  = false
  # config.include_child_root = true
  # config.enable_json_callbacks = false
  # config.xml_options = { :dasherize  => true, :skip_types => false }
  config.view_paths = [Rails.root.join("app/views")]
  # config.raise_on_missing_attribute = true # Defaults to false
  # config.replace_nil_values_with_empty_strings = true # Defaults to false
  # config.replace_empty_string_values_with_nil_values = true # Defaults to false
  # config.exclude_nil_values = true # Defaults to false
  # config.exclude_empty_values_in_collections = true # Defaults to false
end


text:
package com.coolweather.android.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.coolweather.android.service.AutoLocationService;

/**
 * 启动定位服务
 */
public class LocationBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //启动服务
        Intent locIntent = new Intent(context, AutoLocationService.class);
        context.startService(locIntent);
    }
}


text:
package old.view;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.*;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;

import old.controller.CoreController;
import old.core.Core;
import old.datatypes.DataType;
import old.view.data.DataContext;
import old.view.data.DataListener;
import old.view.data.display.TabbedDataViewer;
import old.view.data.menu.DataMenu;

public class MainGUI extends JFrame implements CoreController{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private Core core;
	private JMenuBar menuBar;
	private List<DataContext> contexts;
	private TabbedDataViewer tabs;

	public MainGUI(){
		super("ArrayGenerator");
		contexts = new ArrayList<DataContext>();
		try{
			core = new Core(this, "Extensions", "Extensions/modules.xml", "Extensions/datatypes.xml");
		} catch (Exception e){
			System.err.println("Core initialization error.");
			System.err.println(e.getMessage());
			System.exit(0);
		}
		initComponents();
	}

	@Override
	public DataType[] selectArgs(Class<? extends DataType>[] requiredArgs, Class<? extends DataType>[] optionalArgs) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void update(int event) {

	}

	private void initComponents(){

		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		JPanel content = new JPanel(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		this.setContentPane(content);

		tabs = new TabbedDataViewer(core);
		c.anchor = GridBagConstraints.FIRST_LINE_START;
		c.fill = GridBagConstraints.BOTH;
		c.gridx = 0;
		c.gridy = 0;
		c.weightx = 0.7;
		c.weighty = 0.7;
		content.add(tabs, c);

		menuBar = new JMenuBar();
		this.setJMenuBar(menuBar);
		menuBar.add(new ModuleMenu(core));
		menuBar.add(new DataMenu(core, tabs));

		this.pack();
		this.setVisible(true);
	}

	public static void main(String[] args){
		new MainGUI();
	}

}


text:
package org.gradle.api.internal.tasks.testing;

public class DefaultTestClassDescriptor extends DefaultTestSuiteDescriptor {
    public DefaultTestClassDescriptor(Object id, String className) {
        super(id, className);
    }

    @Override
    public String getClassName() {
        return getName();
    }

    @Override
    public String toString() {
        return "Test class " + getClassName();
    }
}


text:
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.5.1-pre.0
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/*
 * GithubOrganization.h
 *
 *
 */

#ifndef GithubOrganization_H_
#define GithubOrganization_H_

#include <string>
#include "GithubOrganizationlinks.h"
#include <nlohmann/json.hpp>

namespace org::openapitools::server::model
{

/// <summary>
///
/// </summary>
class  GithubOrganization
{
public:
    GithubOrganization();
    virtual ~GithubOrganization() = default;

    /// <summary>
    /// Validate the current data in the model. Throws a ValidationException on failure.
    /// </summary>
    void validate() const;

    /// <summary>
    /// Validate the current data in the model. Returns false on error and writes an error
    /// message into the given stringstream.
    /// </summary>
    bool validate(std::stringstream& msg) const;

    /// <summary>
    /// Helper overload for validate. Used when one model stores another model and calls it's validate.
    /// Not meant to be called outside that case.
    /// </summary>
    bool validate(std::stringstream& msg, const std::string& pathPrefix) const;

    bool operator==(const GithubOrganization& rhs) const;
    bool operator!=(const GithubOrganization& rhs) const;

    /////////////////////////////////////////////
    /// GithubOrganization members

    /// <summary>
    ///
    /// </summary>
    std::string getClass() const;
    void setClass(std::string const& value);
    bool r_classIsSet() const;
    void unset_class();
    /// <summary>
    ///
    /// </summary>
    org::openapitools::server::model::GithubOrganizationlinks getLinks() const;
    void setLinks(org::openapitools::server::model::GithubOrganizationlinks const& value);
    bool linksIsSet() const;
    void unset_links();
    /// <summary>
    ///
    /// </summary>
    bool isJenkinsOrganizationPipeline() const;
    void setJenkinsOrganizationPipeline(bool const value);
    bool jenkinsOrganizationPipelineIsSet() const;
    void unsetJenkinsOrganizationPipeline();
    /// <summary>
    ///
    /// </summary>
    std::string getName() const;
    void setName(std::string const& value);
    bool nameIsSet() const;
    void unsetName();

    friend void to_json(nlohmann::json& j, const GithubOrganization& o);
    friend void from_json(const nlohmann::json& j, GithubOrganization& o);
protected:
    std::string m__class;
    bool m__classIsSet;
    org::openapitools::server::model::GithubOrganizationlinks m__links;
    bool m__linksIsSet;
    bool m_JenkinsOrganizationPipeline;
    bool m_JenkinsOrganizationPipelineIsSet;
    std::string m_Name;
    bool m_NameIsSet;

};

} // namespace org::openapitools::server::model

#endif /* GithubOrganization_H_ */


text:
extern crate hyper;
extern crate itertools;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#[macro_use]
extern crate slog;
extern crate slog_term;

mod get;
mod post;
mod makeresponse;

use hyper::{Get, Post};
use hyper::header;
use hyper::server::{Handler, Server, Request, Response};
use hyper::status::StatusCode;
use slog::DrainExt;

struct HttpTin {
    server: String,
    logger: slog::Logger,
}

impl HttpTin {
    pub fn new(logger: &slog::Logger) -> Self {
        let server = format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
        let logger = logger.new(o!("server" => server.clone()));
        HttpTin {
            server: server,
            logger: logger,
        }
    }

    fn prepare_response(&self, response: &mut Response) {
        let server = header::Server(self.server.clone());
        response.headers_mut().set(server);
    }
}

impl Handler for HttpTin {
    fn handle(&self, request: Request, mut response: Response) {
        let logger = self.logger
            .new(o!("peer" => format!("{}", request.remote_addr)));
        self.prepare_response(&mut response);
        match request.method {
            Get => get::handler(&logger, &request, response),
            Post => post::handler(&logger, &request, response),
            _ => *response.status_mut() = StatusCode::MethodNotAllowed,
        }
    }
}

fn main() {
    let drain = slog_term::streamer().compact().build().fuse();
    let logger = slog::Logger::root(drain, o!());
    let httptin = HttpTin::new(&logger);
    let server = Server::http("localhost:8000").unwrap();
    if let Ok(active) = server.handle(httptin) {
        info!(logger, "{:?}", active);
    }
}


text:
<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0">
		<link rel="stylesheet" type="text/css" href="../../css/core.css" />

        <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/highlight.js/9.0.0/styles/railscasts.min.css">

		<title>A Data Structure</title>

						Other

						Home

A Data Structure

Stack

Graph

Linked List

Heap

Tree

Hash table

Stack
                    (
                    more
                    )

var node = function()
{
    var data;
    var next = null;
}

var stack = function()
{
    this.top = null;

    this.push = function(data) {
        if (this.top == null) {
            this.top = new node();
            this.top.data = data;
        } else {
            var temp = new node();
            temp.data = data;
            temp.next = this.top;
            this.top = temp;
        }
    }

    this.pop = function() {
        var temp = this.top;
        var data = this.top.data;
        this.top = this.top.next;
        temp = null;
        return data;
    }

    this.print = function() {
        var node = this.top;
        while (node != null) {
            console.log(node.data);
            node = node.next;
        }
    }
}

var s = new stack();

s.push(1);
s.push(2);
s.push(3);

s.print();

var a = s.pop();

s.print();

Graph
                    (
                    more
                    )

Linked List
                    (
                    more,
                    more1
                    )

Heap
                    (
                    more
                    )

Tree
                    (
                    more
                    more
                    )

Hash table
                    (more)

used to implement an associative array, a structure that can map keys to values


text:
package org.eclipse.moquette.parser.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.util.AttributeMap;
import java.util.List;
import org.eclipse.moquette.proto.messages.AbstractMessage;
import org.eclipse.moquette.proto.messages.PublishMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author andrea
 */
class PublishDecoder extends DemuxDecoder {

    private static Logger LOG = LoggerFactory.getLogger(PublishDecoder.class);

    @Override
    void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
        LOG.info("decode invoked with buffer {}", in);
        in.resetReaderIndex();
        int startPos = in.readerIndex();

        //Common decoding part
        PublishMessage message = new PublishMessage();
        if (!decodeCommonHeader(message, in)) {
            LOG.info("decode ask for more data after {}", in);
            in.resetReaderIndex();
            return;
        }

        if (Utils.isMQTT3_1_1(ctx)) {
            if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) {
                //bad protocol, if QoS=0 => DUP = 0
                throw new CorruptedFrameException("Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation");
            }

            if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
                throw new CorruptedFrameException("Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation");
            }
        }

        int remainingLength = message.getRemainingLength();

        //Topic name
        String topic = Utils.decodeString(in);
        if (topic == null) {
            in.resetReaderIndex();
            return;
        }
        if (topic.contains("+") || topic.contains("#")) {
            throw new CorruptedFrameException("Received a PUBLISH with topic containting wild card chars, topic: " + topic);
        }

        message.setTopicName(topic);

        if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE ||
                message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
            message.setMessageID(in.readUnsignedShort());
        }
        int stopPos = in.readerIndex();

        //read the payload
        int payloadSize = remainingLength - (stopPos - startPos - 2) + (Utils.numBytesToEncode(remainingLength) - 1);
        if (in.readableBytes() < payloadSize) {
            in.resetReaderIndex();
            return;
        }
//        byte[] b = new byte[payloadSize];
        ByteBuf bb = Unpooled.buffer(payloadSize);
        in.readBytes(bb);
        message.setPayload(bb.nioBuffer());

        out.add(message);
    }

}


text:
#ifndef _SQL_H
#define _SQL_H

#if HAVE_CONFIG_H
#include <config.h>
#endif

#include "registry.h"

#include <sqlite3.h>

int create_tables(sqlite3* db, reg_error* errPtr);
int init_db(sqlite3* db, reg_error* errPtr);
int update_db(sqlite3* db, reg_error* errPtr);

#endif /* _SQL_H */