text:
/*!
 * 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.
 */

@charset "utf-8";

/* Admin styles for the Warehouse project (PyPI) */

.table td,
.table th {
  max-width: 30em;
}

redpajama_set_name: RedPajamaGithub


text:
#include "extensions/filters/http/grpc_json_transcoder/json_transcoder_filter.h"

#include "envoy/common/exception.h"
#include "envoy/http/filter.h"

#include "common/common/assert.h"
#include "common/common/enum_to_int.h"
#include "common/common/utility.h"
#include "common/filesystem/filesystem_impl.h"
#include "common/grpc/common.h"
#include "common/http/headers.h"
#include "common/http/utility.h"
#include "common/protobuf/protobuf.h"

#include "google/api/annotations.pb.h"
#include "google/api/http.pb.h"
#include "grpc_transcoding/json_request_translator.h"
#include "grpc_transcoding/path_matcher_utility.h"
#include "grpc_transcoding/response_to_json_translator.h"

using Envoy::Protobuf::DescriptorPool;
using Envoy::Protobuf::FileDescriptor;
using Envoy::Protobuf::FileDescriptorSet;
using Envoy::Protobuf::io::ZeroCopyInputStream;
using Envoy::ProtobufUtil::Status;
using Envoy::ProtobufUtil::error::Code;
using google::grpc::transcoding::JsonRequestTranslator;
using google::grpc::transcoding::PathMatcherBuilder;
using google::grpc::transcoding::PathMatcherUtility;
using google::grpc::transcoding::RequestInfo;
using google::grpc::transcoding::ResponseToJsonTranslator;
using google::grpc::transcoding::Transcoder;
using google::grpc::transcoding::TranscoderInputStream;

namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace GrpcJsonTranscoder {

namespace {

// Transcoder:
// https://github.com/grpc-ecosystem/grpc-httpjson-transcoding/blob/master/src/include/grpc_transcoding/transcoder.h
// implementation based on JsonRequestTranslator & ResponseToJsonTranslator
class TranscoderImpl : public Transcoder {
public:
  /**
   * Construct a transcoder implementation
   * @param request_translator a JsonRequestTranslator that does the request translation
   * @param response_translator a ResponseToJsonTranslator that does the response translation
   */
  TranscoderImpl(std::unique_ptr<JsonRequestTranslator> request_translator,
                 std::unique_ptr<ResponseToJsonTranslator> response_translator)
      : request_translator_(std::move(request_translator)),
        response_translator_(std::move(response_translator)),
        request_stream_(request_translator_->Output().CreateInputStream()),
        response_stream_(response_translator_->CreateInputStream()) {}

  // Transcoder
  ::google::grpc::transcoding::TranscoderInputStream* RequestOutput() override {
    return request_stream_.get();
  }
  ProtobufUtil::Status RequestStatus() override { return request_translator_->Output().Status(); }

  ZeroCopyInputStream* ResponseOutput() override { return response_stream_.get(); }
  ProtobufUtil::Status ResponseStatus() override { return response_translator_->Status(); }

private:
  std::unique_ptr<JsonRequestTranslator> request_translator_;
  std::unique_ptr<ResponseToJsonTranslator> response_translator_;
  std::unique_ptr<TranscoderInputStream> request_stream_;
  std::unique_ptr<TranscoderInputStream> response_stream_;
};

} // namespace

JsonTranscoderConfig::JsonTranscoderConfig(
    const envoy::config::filter::http::transcoder::v2::GrpcJsonTranscoder& proto_config) {
  FileDescriptorSet descriptor_set;

  switch (proto_config.descriptor_set_case()) {
  case envoy::config::filter::http::transcoder::v2::GrpcJsonTranscoder::kProtoDescriptor:
    if (!descriptor_set.ParseFromString(
            Filesystem::fileReadToEnd(proto_config.proto_descriptor()))) {
      throw EnvoyException("transcoding_filter: Unable to parse proto descriptor");
    }
    break;
  case envoy::config::filter::http::transcoder::v2::GrpcJsonTranscoder::kProtoDescriptorBin:
    if (!descriptor_set.ParseFromString(proto_config.proto_descriptor_bin())) {
      throw EnvoyException("transcoding_filter: Unable to parse proto descriptor");
    }
    break;
  default:
    NOT_REACHED;
  }

  for (const auto& file : descriptor_set.file()) {
    if (descriptor_pool_.BuildFile(file) == nullptr) {
      throw EnvoyException("transcoding_filter: Unable to build proto descriptor pool");
    }
  }

  PathMatcherBuilder<const Protobuf::MethodDescriptor*> pmb;

  for (const auto& service_name : proto_config.services()) {
    auto service = descriptor_pool_.FindServiceByName(service_name);
    if (service == nullptr) {
      throw EnvoyException("transcoding_filter: Could not find '" + service_name +
                           "' in the proto descriptor");
    }
    for (int i = 0; i < service->method_count(); ++i) {
      auto method = service->method(i);
      if (!PathMatcherUtility::RegisterByHttpRule(
              pmb, method->options().GetExtension(google::api::http), method)) {
        throw EnvoyException("transcoding_filter: Cannot register '" + method->full_name() +
                             "' to path matcher");
      }
    }
  }

  path_matcher_ = pmb.Build();

  type_helper_.reset(
      new google::grpc::transcoding::TypeHelper(Protobuf::util::NewTypeResolverForDescriptorPool(
          Grpc::Common::typeUrlPrefix(), &descriptor_pool_)));

  const auto print_config = proto_config.print_options();
  print_options_.add_whitespace = print_config.add_whitespace();
  print_options_.always_print_primitive_fields = print_config.always_print_primitive_fields();
  print_options_.always_print_enums_as_ints = print_config.always_print_enums_as_ints();
  print_options_.preserve_proto_field_names = print_config.preserve_proto_field_names();

  match_incoming_request_route_ = proto_config.match_incoming_request_route();
}

bool JsonTranscoderConfig::matchIncomingRequestInfo() const {
  return match_incoming_request_route_;
}

ProtobufUtil::Status JsonTranscoderConfig::createTranscoder(
    const Http::HeaderMap& headers, ZeroCopyInputStream& request_input,
    google::grpc::transcoding::TranscoderInputStream& response_input,
    std::unique_ptr<Transcoder>& transcoder, const Protobuf::MethodDescriptor*& method_descriptor) {
  const ProtobufTypes::String method = headers.Method()->value().c_str();
  ProtobufTypes::String path = headers.Path()->value().c_str();
  ProtobufTypes::String args;

  const size_t pos = path.find('?');
  if (pos != std::string::npos) {
    args = path.substr(pos + 1);
    path = path.substr(0, pos);
  }

  struct RequestInfo request_info;
  std::vector<VariableBinding> variable_bindings;
  method_descriptor =
      path_matcher_->Lookup(method, path, args, &variable_bindings, &request_info.body_field_path);
  if (!method_descriptor) {
    return ProtobufUtil::Status(Code::NOT_FOUND, "Could not resolve " + path + " to a method");
  }

  auto status = methodToRequestInfo(method_descriptor, &request_info);
  if (!status.ok()) {
    return status;
  }

  for (const auto& binding : variable_bindings) {
    google::grpc::transcoding::RequestWeaver::BindingInfo resolved_binding;
    status = type_helper_->ResolveFieldPath(*request_info.message_type, binding.field_path,
                                            &resolved_binding.field_path);
    if (!status.ok()) {
      return status;
    }

    resolved_binding.value = binding.value;

    request_info.variable_bindings.emplace_back(std::move(resolved_binding));
  }

  std::unique_ptr<JsonRequestTranslator> request_translator{
      new JsonRequestTranslator(type_helper_->Resolver(), &request_input, request_info,
                                method_descriptor->client_streaming(), true)};

  const auto response_type_url =
      Grpc::Common::typeUrl(method_descriptor->output_type()->full_name());
  std::unique_ptr<ResponseToJsonTranslator> response_translator{new ResponseToJsonTranslator(
      type_helper_->Resolver(), response_type_url, method_descriptor->server_streaming(),
      &response_input, print_options_)};

  transcoder.reset(
      new TranscoderImpl(std::move(request_translator), std::move(response_translator)));
  return ProtobufUtil::Status();
}

ProtobufUtil::Status
JsonTranscoderConfig::methodToRequestInfo(const Protobuf::MethodDescriptor* method,
                                          google::grpc::transcoding::RequestInfo* info) {
  auto request_type_url = Grpc::Common::typeUrl(method->input_type()->full_name());
  info->message_type = type_helper_->Info()->GetTypeByTypeUrl(request_type_url);
  if (info->message_type == nullptr) {
    ENVOY_LOG(debug, "Cannot resolve input-type: {}", method->input_type()->full_name());
    return ProtobufUtil::Status(Code::NOT_FOUND,
                                "Could not resolve type: " + method->input_type()->full_name());
  }

  return ProtobufUtil::Status();
}

JsonTranscoderFilter::JsonTranscoderFilter(JsonTranscoderConfig& config) : config_(config) {}

Http::FilterHeadersStatus JsonTranscoderFilter::decodeHeaders(Http::HeaderMap& headers,
                                                              bool end_stream) {
  const auto status =
      config_.createTranscoder(headers, request_in_, response_in_, transcoder_, method_);

  if (!status.ok()) {
    // If transcoder couldn't be created, it might be a normal gRPC request, so the filter will
    // just pass-through the request to upstream.
    return Http::FilterHeadersStatus::Continue;
  }

  headers.removeContentLength();
  headers.insertContentType().value().setReference(Http::Headers::get().ContentTypeValues.Grpc);
  headers.insertEnvoyOriginalPath().value(*headers.Path());
  headers.insertPath().value("/" + method_->service()->full_name() + "/" + method_->name());
  headers.insertMethod().value().setReference(Http::Headers::get().MethodValues.Post);
  headers.insertTE().value().setReference(Http::Headers::get().TEValues.Trailers);

  if (!config_.matchIncomingRequestInfo()) {
    decoder_callbacks_->clearRouteCache();
  }

  if (end_stream) {
    request_in_.finish();

    const auto& request_status = transcoder_->RequestStatus();
    if (!request_status.ok()) {
      ENVOY_LOG(debug, "Transcoding request error {}", request_status.ToString());
      error_ = true;
      decoder_callbacks_->sendLocalReply(Http::Code::BadRequest, request_status.error_message(),
                                         nullptr);

      return Http::FilterHeadersStatus::StopIteration;
    }

    Buffer::OwnedImpl data;
    readToBuffer(*transcoder_->RequestOutput(), data);

    if (data.length() > 0) {
      decoder_callbacks_->addDecodedData(data, true);
    }
  }
  return Http::FilterHeadersStatus::Continue;
}

Http::FilterDataStatus JsonTranscoderFilter::decodeData(Buffer::Instance& data, bool end_stream) {
  ASSERT(!error_);

  if (!transcoder_) {
    return Http::FilterDataStatus::Continue;
  }

  request_in_.move(data);

  if (end_stream) {
    request_in_.finish();
  }

  readToBuffer(*transcoder_->RequestOutput(), data);

  const auto& request_status = transcoder_->RequestStatus();

  if (!request_status.ok()) {
    ENVOY_LOG(debug, "Transcoding request error {}", request_status.ToString());
    error_ = true;
    decoder_callbacks_->sendLocalReply(Http::Code::BadRequest, request_status.error_message(),
                                       nullptr);

    return Http::FilterDataStatus::StopIterationNoBuffer;
  }
  return Http::FilterDataStatus::Continue;
}

Http::FilterTrailersStatus JsonTranscoderFilter::decodeTrailers(Http::HeaderMap&) {
  ASSERT(!error_);

  if (!transcoder_) {
    return Http::FilterTrailersStatus::Continue;
  }

  request_in_.finish();

  Buffer::OwnedImpl data;
  readToBuffer(*transcoder_->RequestOutput(), data);

  if (data.length()) {
    decoder_callbacks_->addDecodedData(data, true);
  }
  return Http::FilterTrailersStatus::Continue;
}

void JsonTranscoderFilter::setDecoderFilterCallbacks(
    Http::StreamDecoderFilterCallbacks& callbacks) {
  decoder_callbacks_ = &callbacks;
}

Http::FilterHeadersStatus JsonTranscoderFilter::encodeHeaders(Http::HeaderMap& headers,
                                                              bool end_stream) {
  if (!Grpc::Common::isGrpcResponseHeader(headers, end_stream)) {
    error_ = true;
  }

  if (error_ || !transcoder_) {
    return Http::FilterHeadersStatus::Continue;
  }

  response_headers_ = &headers;

  if (end_stream) {
    // In gRPC wire protocol, headers frame with end_stream is a trailers-only response.
    // The return value from encodeTrailers is ignored since it is always continue.
    encodeTrailers(headers);
    return Http::FilterHeadersStatus::Continue;
  }

  headers.insertContentType().value().setReference(Http::Headers::get().ContentTypeValues.Json);
  if (!method_->server_streaming()) {
    return Http::FilterHeadersStatus::StopIteration;
  }

  return Http::FilterHeadersStatus::Continue;
}

Http::FilterDataStatus JsonTranscoderFilter::encodeData(Buffer::Instance& data, bool end_stream) {
  if (error_ || !transcoder_) {
    return Http::FilterDataStatus::Continue;
  }

  response_in_.move(data);

  if (end_stream) {
    response_in_.finish();
  }

  readToBuffer(*transcoder_->ResponseOutput(), data);

  if (!method_->server_streaming() && !end_stream) {
    // Buffer until the response is complete.
    return Http::FilterDataStatus::StopIterationAndBuffer;
  }
  // TODO(lizan): Check ResponseStatus

  return Http::FilterDataStatus::Continue;
}

Http::FilterTrailersStatus JsonTranscoderFilter::encodeTrailers(Http::HeaderMap& trailers) {
  if (error_ || !transcoder_) {
    return Http::FilterTrailersStatus::Continue;
  }

  response_in_.finish();

  Buffer::OwnedImpl data;
  readToBuffer(*transcoder_->ResponseOutput(), data);

  if (data.length()) {
    encoder_callbacks_->addEncodedData(data, true);
  }

  if (method_->server_streaming()) {
    // For streaming case, the headers are already sent, so just continue here.
    return Http::FilterTrailersStatus::Continue;
  }

  const absl::optional<Grpc::Status::GrpcStatus> grpc_status =
      Grpc::Common::getGrpcStatus(trailers);
  if (!grpc_status || grpc_status.value() == Grpc::Status::GrpcStatus::InvalidCode) {
    response_headers_->Status()->value(enumToInt(Http::Code::ServiceUnavailable));
  } else {
    response_headers_->Status()->value(Grpc::Utility::grpcToHttpStatus(grpc_status.value()));
    response_headers_->insertGrpcStatus().value(enumToInt(grpc_status.value()));
  }

  const Http::HeaderEntry* grpc_message_header = trailers.GrpcMessage();
  if (grpc_message_header) {
    response_headers_->insertGrpcMessage().value(*grpc_message_header);
  }

  response_headers_->insertContentLength().value(
      encoder_callbacks_->encodingBuffer() ? encoder_callbacks_->encodingBuffer()->length() : 0);
  return Http::FilterTrailersStatus::Continue;
}

void JsonTranscoderFilter::setEncoderFilterCallbacks(
    Http::StreamEncoderFilterCallbacks& callbacks) {
  encoder_callbacks_ = &callbacks;
}

// TODO(lizan): Incorporate watermarks to bound buffer sizes
bool JsonTranscoderFilter::readToBuffer(Protobuf::io::ZeroCopyInputStream& stream,
                                        Buffer::Instance& data) {
  const void* out;
  int size;
  while (stream.Next(&out, &size)) {
    data.add(out, size);

    if (size == 0) {
      return true;
    }
  }
  return false;
}

} // namespace GrpcJsonTranscoder
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>All Classes (twitter4j-stream 3.0.3 API)</title>
<meta name="date" content="2012-12-23">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

ControlStreamInfo

FilterQuery

RawStreamListener

SiteStreamsAdapter

SiteStreamsListener

StallWarning

StatusAdapter

StatusListener

StatusStream

StreamController

TwitterStream

TwitterStreamFactory

UserStream

UserStreamAdapter

UserStreamListener

VersionStream


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.

Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata

Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests

    Public Class WithBlockSemanticModelTests
        Inherits FlowTestBase

#Region "Symbol / Type Info"

        <Fact>
        Public Sub WithAliasedStaticField()
            Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
    <file name="a.vb">
Imports Alias1 = ClassWithField
Class ClassWithField
    Public Shared field1 As String = "a"
End Class
Module WithAliasedStaticField
    Sub Main()
        With Alias1.field1 'BIND:"Alias1.field1"
            Dim newString = .Replace("a", "b")
        End With
    End Sub
End Module
    </file>
</compilation>)
            Dim tree = compilation.SyntaxTrees.Single()
            Dim model = compilation.GetSemanticModel(tree)
            Dim withExpression = DirectCast(tree.GetCompilationUnitRoot().DescendantNodes().Where(Function(n) n.Kind = SyntaxKind.SimpleMemberAccessExpression).First(), MemberAccessExpressionSyntax)

            Assert.Equal("Alias1", model.GetAliasInfo(DirectCast(withExpression.Expression, IdentifierNameSyntax)).ToDisplayString())
            Assert.False(model.GetConstantValue(withExpression).HasValue)
            Dim typeInfo = model.GetTypeInfo(withExpression)
            Assert.Equal("String", typeInfo.Type.ToDisplayString())
            Assert.Equal("String", typeInfo.ConvertedType.ToDisplayString())
            Dim conv = model.GetConversion(withExpression)
            Assert.Equal(ConversionKind.Identity, conv.Kind)
            Dim symbolInfo = model.GetSymbolInfo(withExpression)
            Assert.Equal("Public Shared field1 As String", symbolInfo.Symbol.ToDisplayString())
            Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind)
            Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
            Assert.Equal(0, model.GetMemberGroup(withExpression).Length)
        End Sub

        <Fact>
        Public Sub WithDeclaresAnonymousLocalSymbolAndTypeInfo()
            Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
    <file name="a.vb">
Module WithDeclaresAnonymousLocalSymbolAndTypeInfo
    Sub Main()
        With New With {.A = 1, .B = "2"} 'BIND:"New With {.A = 1, .B = "2"}"
            .A = .B
        End With
    End Sub
End Module
    </file>
</compilation>)
            Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of AnonymousObjectCreationExpressionSyntax)(compilation, "a.vb")

            Assert.Null(semanticInfo.Alias)
            Assert.False(semanticInfo.ConstantValue.HasValue)
            Assert.Equal("<anonymous type: A As Integer, B As String>", semanticInfo.Type.ToDisplayString())
            Assert.Equal("<anonymous type: A As Integer, B As String>", semanticInfo.ConvertedType.ToDisplayString())
            Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
            Assert.Equal("Public Sub New(A As Integer, B As String)", semanticInfo.Symbol.ToDisplayString()) ' should get constructor for anonymous type
            Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
            Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
            Assert.Equal(0, semanticInfo.MemberGroup.Length)
        End Sub

        <Fact(), WorkItem(544083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544083")>
        Public Sub WithSpeculativeSymbolInfo()
            Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
    <file name="a.vb">
Class C1
    Property Property1 As Integer
    Property Property2 As String
End Class
Module Module1
    Sub Main()
        Dim x As New C1()
        With x
            Dim f = Function() .Property1 'BINDHERE
        End With
    End Sub
End Module
    </file>
</compilation>)
            Dim semanticModel = GetSemanticModel(compilation, "a.vb")
            Dim position = compilation.SyntaxTrees.Single().ToString().IndexOf("'BINDHERE", StringComparison.Ordinal)

            Dim expr = SyntaxFactory.ParseExpression(".property2")
            Dim speculativeTypeInfo = semanticModel.GetSpeculativeTypeInfo(position, expr, SpeculativeBindingOption.BindAsExpression)
            Assert.Equal("String", speculativeTypeInfo.ConvertedType.ToDisplayString())
            Dim conv = semanticModel.GetSpeculativeConversion(position, expr, SpeculativeBindingOption.BindAsExpression)
            Assert.Equal(ConversionKind.Identity, conv.Kind)
            Assert.Equal("String", speculativeTypeInfo.Type.ToDisplayString())

            Dim speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(position, SyntaxFactory.ParseExpression(".property2"), SpeculativeBindingOption.BindAsExpression)
            Assert.Equal("Public Property Property2 As String", speculativeSymbolInfo.Symbol.ToDisplayString())
            Assert.Equal(SymbolKind.Property, speculativeSymbolInfo.Symbol.Kind)
        End Sub

#End Region

#Region "FlowAnalysis"

        <Fact>
        Public Sub UseWithVariableInNestedLambda()
            Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
    <file name="a.vb">
Class C1
    Property Property1 As Integer
End Class
Module Module1
    Sub Main()
        Dim x As New C1()
        With x
            Dim f = Function()
                        [|Return .Property1|]
                    End Function
        End With
    End Sub
End Module
    </file>
</compilation>)
            Dim controlFlowResults = analysis.Item1
            Dim dataFlowResults = analysis.Item2

            Assert.Empty(dataFlowResults.VariablesDeclared)
            Assert.Empty(dataFlowResults.AlwaysAssigned)
            Assert.Empty(dataFlowResults.DataFlowsIn)
            Assert.Empty(dataFlowResults.DataFlowsOut)
            Assert.Empty(dataFlowResults.ReadInside)
            Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside))
            Assert.Empty(dataFlowResults.WrittenInside)
            Assert.Equal("x, f", GetSymbolNamesJoined(dataFlowResults.WrittenOutside))

            Assert.Empty(controlFlowResults.EntryPoints)
            Assert.False(controlFlowResults.EndPointIsReachable)
            Assert.True(controlFlowResults.StartPointIsReachable)
            Assert.Equal(1, controlFlowResults.ExitPoints.Count)
        End Sub

        <Fact>
        Public Sub WithDeclaresAnonymousLocalDataFlow()
            Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
    <file name="a.vb">
Module WithDeclaresAnonymousLocal
    Sub Main()
        With New With {.A = 1, .B = "2"}
            [|.A = .B|]
        End With
    End Sub
End Module
    </file>
</compilation>)
            Dim controlFlowResults = analysis.Item1
            Dim dataFlowResults = analysis.Item2

            Assert.Empty(dataFlowResults.VariablesDeclared)
            Assert.Empty(dataFlowResults.AlwaysAssigned)
            Assert.Empty(dataFlowResults.DataFlowsIn) ' assume anonymous locals don't show
            Assert.Empty(dataFlowResults.DataFlowsOut)
            Assert.Empty(dataFlowResults.ReadInside) ' assume anonymous locals don't show
            Assert.Empty(dataFlowResults.ReadOutside)
            Assert.Empty(dataFlowResults.WrittenInside)
            Assert.Empty(dataFlowResults.WrittenOutside) ' assume anonymous locals don't show

            Assert.Empty(controlFlowResults.ExitPoints)
            Assert.Empty(controlFlowResults.EntryPoints)
            Assert.True(controlFlowResults.EndPointIsReachable)
            Assert.True(controlFlowResults.StartPointIsReachable)
        End Sub

        <Fact>
        Public Sub EmptyWith()
            Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
    <file name="a.vb">
Module Module1
    Sub Main()
        Dim x As Object()
        [|With x
        End With|]
    End Sub
End Module
    </file>
</compilation>)
            Dim controlFlowResults = analysis.Item1
            Dim dataFlowResults = analysis.Item2

            Assert.Empty(dataFlowResults.VariablesDeclared)
            Assert.Empty(dataFlowResults.AlwaysAssigned)
            Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn))
            Assert.Empty(dataFlowResults.DataFlowsOut)
            Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside))
            Assert.Empty(dataFlowResults.ReadOutside)
            Assert.Empty(dataFlowResults.WrittenInside)
            Assert.Empty(dataFlowResults.WrittenOutside)

            Assert.Empty(controlFlowResults.ExitPoints)
            Assert.Empty(controlFlowResults.EntryPoints)
            Assert.True(controlFlowResults.EndPointIsReachable)
            Assert.True(controlFlowResults.StartPointIsReachable)
        End Sub

#End Region

        <Fact, WorkItem(2662, "https://github.com/dotnet/roslyn/issues/2662")>
        Public Sub Issue2662()
            Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
    <file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.CompilerServices

Module Program
    Sub Main(args As String())

    End Sub
    Private Sub AddCustomer()
        Dim theCustomer As New Customer

        With theCustomer
            .Name = "Abc"
            .URL = "http://www.microsoft.com/"
            .City = "Redmond"
            .Print(.Name)
        End With
    End Sub

    <Extension()>
    Public Sub Print(ByVal cust As Customer, str As String)
        Console.WriteLine(str)
    End Sub

    Public Class Customer
        Public Property Name As String
        Public Property City As String
        Public Property URL As String

        Public Property Comments As New List(Of String)
    End Class
End Module
    ]]></file>
</compilation>, {Net40.SystemCore})

            compilation.AssertNoDiagnostics()

            Dim tree = compilation.SyntaxTrees.Single()
            Dim model = compilation.GetSemanticModel(tree)
            Dim withBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of WithBlockSyntax)().Single()

            Dim name = withBlock.Statements(3).DescendantNodes().OfType(Of IdentifierNameSyntax).Where(Function(i) i.Identifier.ValueText = "Name").Single()
            model.GetAliasInfo(name)

            Dim result2 = model.AnalyzeDataFlow(withBlock, withBlock)
            Assert.True(result2.Succeeded)

            model = compilation.GetSemanticModel(tree)
            model.GetAliasInfo(name)

            Assert.Equal("theCustomer As Program.Customer", model.GetSymbolInfo(withBlock.WithStatement.Expression).Symbol.ToTestDisplayString())
        End Sub

        <Fact>
        <WorkItem(187910, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=187910&_a=edit")>
        Public Sub Bug187910()
            Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
    <file name="a.vb">
Class ClassWithField
    Public field1 As String = "a"
End Class
Class WithAliasedStaticField
    Sub Test(parameter as ClassWithField)
        With parameter
            System.Console.WriteLine(.field1)
        End With
    End Sub
End Class
    </file>
</compilation>)

            Dim compilationB = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
    <file name="b.vb">
Class WithAliasedStaticField1
    Sub Test(parameter as ClassWithField)
        With parameter
            System.Console.WriteLine(.field1)
        End With
    End Sub
End Class
    </file>
</compilation>)

            compilation.AssertTheseDiagnostics()

            Dim treeA = compilation.SyntaxTrees.Single()
            Dim modelA = compilation.GetSemanticModel(treeA)
            Dim parameter = treeA.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "parameter").First()

            Assert.Equal("Sub WithAliasedStaticField.Test(parameter As ClassWithField)", modelA.GetEnclosingSymbol(parameter.SpanStart).ToTestDisplayString())

            Dim treeB = compilationB.SyntaxTrees.Single()
            Dim withBlockB = treeB.GetCompilationUnitRoot().DescendantNodes().OfType(Of WithBlockSyntax)().Single()

            Dim modelAB As SemanticModel = Nothing
            Assert.True(modelA.TryGetSpeculativeSemanticModel(parameter.Parent.Parent.SpanStart, withBlockB, modelAB))

            Assert.Equal("Sub WithAliasedStaticField.Test(parameter As ClassWithField)", modelAB.GetEnclosingSymbol(withBlockB.WithStatement.Expression.SpanStart).ToTestDisplayString())
        End Sub

        <Fact>
        <WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
        Public Sub WithTargetAsArgument_01()
            Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
    <file name="a.vb">
Class Base
End Class

Class Derived
    Inherits Base

    Public Function Contains(node As Base) As Boolean
        Return True
    End Function
End Class

Module Ext
    Sub M(vbNode As Derived)
        With vbNode
            If .Contains(vbNode) Then
            End If
        End With
    End Sub
End Module
    </file>
</compilation>)

            compilation.AssertTheseDiagnostics()

            Dim tree = compilation.SyntaxTrees.Single()
            Dim model = compilation.GetSemanticModel(tree)
            Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()

            Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
            Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
            Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind)

            Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
            Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
            Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind)

            Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
        End Sub

        <Fact>
        <WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
        Public Sub WithTargetAsArgument_02()
            Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
    <file name="a.vb"><![CDATA[
Class Base
End Class

Class Derived
    Inherits Base
End Class

Module Ext
    <System.Runtime.CompilerServices.Extension()>
    Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode
        Return Nothing
    End Function

    Sub M(vbNode As Derived)
        With vbNode
            If .GetCurrent(vbNode) Is Nothing Then
            End If
        End With
    End Sub
End Module
    ]]></file>
</compilation>, additionalRefs:={Net40.SystemCore})

            compilation.AssertTheseDiagnostics()

            Dim tree = compilation.SyntaxTrees.Single()
            Dim model = compilation.GetSemanticModel(tree)
            Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()

            Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
            Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
            Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind)

            Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
            Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
            Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind)

            Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
        End Sub

        <Fact>
        <WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
        Public Sub WithTargetAsArgument_03()
            Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
    <file name="a.vb"><![CDATA[
Class Base
End Class

Class Derived
    Inherits Base

    Public Function Contains(node As Base) As Boolean
        Return True
    End Function
End Class

Module Ext
    <System.Runtime.CompilerServices.Extension()>
    Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode
        Return Nothing
    End Function

    Sub M(vbNode As Derived)
        With vbNode
            If .GetCurrent(vbNode) Is Nothing Then
            End If
            If .Contains(vbNode) Then
            End If
        End With
    End Sub
End Module
    ]]></file>
</compilation>, additionalRefs:={Net40.SystemCore})

            compilation.AssertTheseDiagnostics()

            Dim tree = compilation.SyntaxTrees.Single()
            Dim model = compilation.GetSemanticModel(tree)
            Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()

            Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
            Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
            Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind)

            Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
            Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
            Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind)

            Dim symbolInfo3 = model.GetSymbolInfo(nodes(2))
            Assert.Equal("vbNode As Derived", symbolInfo3.Symbol.ToTestDisplayString())
            Assert.Equal(SymbolKind.Parameter, symbolInfo3.Symbol.Kind)

            Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
            Assert.Same(symbolInfo1.Symbol, symbolInfo3.Symbol)
        End Sub

        <Fact>
        <WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
        Public Sub WithTargetAsArgument_04()
            Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
    <file name="a.vb"><![CDATA[
Class Base
End Class

Class Derived
    Inherits Base
End Class

Module Ext
    <System.Runtime.CompilerServices.Extension()>
    Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode
        Return Nothing
    End Function

    readonly property vbNode As Derived
        Get
            return nothing
        End Get
    End Property

    Sub M()
        With vbNode
            If .GetCurrent(vbNode) Is Nothing Then
            End If
        End With
    End Sub
End Module
    ]]></file>
</compilation>, additionalRefs:={Net40.SystemCore})

            compilation.AssertTheseDiagnostics()

            Dim tree = compilation.SyntaxTrees.Single()
            Dim model = compilation.GetSemanticModel(tree)
            Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()

            Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
            Assert.Equal("ReadOnly Property Ext.vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
            Assert.Equal(SymbolKind.Property, symbolInfo1.Symbol.Kind)

            Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
            Assert.Equal("ReadOnly Property Ext.vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
            Assert.Equal(SymbolKind.Property, symbolInfo2.Symbol.Kind)

            Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
        End Sub

    End Class

End Namespace


text:
package net.anotheria.moskito.webui.shared.action;

import net.anotheria.maf.action.AbortExecutionException;
import net.anotheria.maf.action.ActionMapping;
import net.anotheria.maf.bean.FormBean;
import net.anotheria.maf.json.JSONResponse;
import org.json.JSONException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Save nav menu state action.
 *
 * @author Vasyl Zarva
 */
public class SaveNavMenuStateAction extends BaseAJAXMoskitoUIAction {

	/**
	 * Request param: indication if menu navigation is collapsed or not.
	 */
	public static final String PARAM_IS_NAV_MENU_COLLAPSED = "isNavMenuCollapsed";

	/**
	 * Attribute name: indication if menu navigation is collapsed or not.
	 */
	public static final String ATTR_IS_NAV_MENU_COLLAPSED = "isNavMenuCollapsed";

	@Override
	protected void invokeExecute(ActionMapping mapping, FormBean bean, HttpServletRequest req, HttpServletResponse res, JSONResponse jsonResponse) throws AbortExecutionException, IOException, JSONException {
		final String navMenuCollapseStateParam = req.getParameter(PARAM_IS_NAV_MENU_COLLAPSED);

		req.getSession().setAttribute(ATTR_IS_NAV_MENU_COLLAPSED, Boolean.valueOf(navMenuCollapseStateParam));
	}
}


text:
from oslo_config import cfg

from magnum.i18n import _

docker_registry_group = cfg.OptGroup(name='docker_registry',
                                     title='Options for Docker Registry')

docker_registry_opts = [
    cfg.StrOpt('swift_region',
               help=_('Region name of Swift')),
    cfg.StrOpt('swift_registry_container',
               default='docker_registry',
               help=_('Name of the container in Swift which docker registry '
                      'stores images in'))
]

def register_opts(conf):
    conf.register_group(docker_registry_group)
    conf.register_opts(docker_registry_opts, group=docker_registry_group)

def list_opts():
    return {
        docker_registry_group: docker_registry_opts
    }


text:
<template name="xray">
    <div class="xray-toolbar">
        <button class="xray-toggle">{{label}}</button>
    </div>
</template>


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('diary', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='diary',
            name='user',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
        ),
    ]


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Source: stacked-bar.js</title>

            <meta name="description" content="Britecharts is a client-side reusable Charting Library based on D3.js v4 that allows easy and intuitive use of charts and components that can be composed together creating amazing visualizations." />

                <meta name="keywords" content="Britecharts, D3.js" />

        <meta name="msapplication-tap-highlight" content="no">
        <meta name="msapplication-config" content="img/icons/browserconfig.xml">

        <link rel="manifest" href="manifest.json">

        <meta name="mobile-web-app-capable" content="yes">
        <meta name="application-name" content="Britecharts">
        <link rel="icon" sizes="192x192" href="img/icons/chrome-touch-icon-192x192.png">

        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="#009FA1">
        <meta name="apple-mobile-web-app-title" content="Britecharts">
        <link rel="apple-touch-icon" sizes="180x180" href="img/icons/apple-touch-icon.png">

        <link rel="mask-icon" href="img/icons/safari-pinned-tab.svg" color="#5bbad5">

        <meta name="theme-color" content="#ffffff">

        <link rel="shortcut icon" href="img/icons/favicon.ico">
        <link rel="icon" type="image/png" href="img/icons/favicon-32x32.png" sizes="32x32">
        <link rel="icon" type="image/png" href="img/icons/favicon-16x16.png" sizes="16x16">

            <meta property="og:title" content="Britecharts, a D3.js based charting library of reusable components"/>
            <meta property="og:type" content="website"/>
            <meta property="og:image" content="https://eventbrite.github.io/britecharts/img/logo-stripes-small.png"/>
            <meta property="og:site_name" content="Britecharts"/>
            <meta property="og:url" content=""/>

            <meta name="twitter:card" content="summary" />
            <meta name="twitter:site" content="@britecharts" />
            <meta name="twitter:description" content="Britecharts is a client-side reusable Charting Library based on D3.js v4 that allows easy and intuitive use of charts and components that can be composed together creating amazing visualizations." />

        <link type="text/css" rel="stylesheet" href="styles/custom.css">
        <link type="text/css" rel="stylesheet" href="styles/demos.css">
        <link type="text/css" rel="stylesheet" href="styles/prism.css"  />
        <link type="text/css" rel="stylesheet" href="styles/britecharts.css" />

            		<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">

                    </button>

            				Getting started

            				Demos

Bar Chart

Brush Chart

Donut Chart

Kitchen Sink

Line Chart

Sparkline Chart

Stacked Area Chart

Stacked Bar Chart

Step Chart

            				API

Bar

Brush

Donut

Legend

Line

Mini-tooltip

Sparkline

Stacked-area

Stacked-bar

Step

Tooltip

Types

                            Github

                        <form class="navbar-form" role="search">

                                <input type="text" class="form-control pull-left" placeholder="Search" name="q" id="search-input">

                                    <button class="btn btn-default" id="search-submit">

                                    </button>

                        </form>

Source: stacked-bar.js

define(function(require){
    'use strict';

    const d3Array = require('d3-array');
    const d3Axis = require('d3-axis');
    const d3Color = require('d3-color');
    const d3Collection = require('d3-collection');
    const d3Dispatch = require('d3-dispatch');
    const d3Ease = require('d3-ease');
    const d3Interpolate = require('d3-interpolate');
    const d3Scale = require('d3-scale');
    const d3Shape = require('d3-shape');
    const d3Selection = require('d3-selection');
    const assign = require('lodash.assign');

    const {exportChart} = require('./helpers/exportChart');
    const colorHelper = require('./helpers/colors');
    const NUMBER_FORMAT = ',f';
    const uniq = (arrArg) => arrArg.filter((elem, pos, arr) => arr.indexOf(elem) == pos);

    /**
     * @typdef D3Layout
     * @type function
     */

    /**
     * @typedef stackedBarData
     * @type {Object}
     * @property {Object[]} data       All data entries
     * @property {String} name         Name of the entry
     * @property {String} stack        Stack of the entry
     * @property {Number} value        Value of the entry
     *
     * @example
     * {
     *     'data': [
     *         {
     *             "name": "2011-01",
     *             "stack": "Direct",
     *             "value": 0
     *         }
     *     ]
     * }
     */

    /**
     * Stacked Area Chart reusable API module that allows us
     * rendering a multi area and configurable chart.
     *
     * @module Stacked-bar
     * @tutorial stacked-bar
     * @requires d3-array, d3-axis, d3-color, d3-collection, d3-dispatch, d3-ease,
     *  d3-interpolate, d3-scale, d3-shape, d3-selection, lodash assign
     *
     * @example
     * let stackedBar = stackedBar();
     *
     * stackedBar
     *     .width(containerWidth);
     *
     * d3Selection.select('.css-selector')
     *     .datum(dataset.data)
     *     .call(stackedBar);
     *
     */
    return function module() {

        let margin = {
            top: 40,
            right: 30,
            bottom: 60,
            left: 70
            },
            width = 960,
            height = 500,

            xScale,
            xAxis,
            yScale,
            yAxis,

            aspectRatio = null,

            verticalTicks = 5,
            yTickTextYOffset = -8,
            yTickTextXOffset = -20,

            numOfVerticalTicks = 5,
            numOfHorizontalTicks = 5,
            percentageAxisToMaxRatio = 1,

            colorSchema = colorHelper.colorSchemas.britechartsColorSchema,

            colorScale,
            categoryColorMap,

            layers,

            ease = d3Ease.easeQuadInOut,
            horizontal = false,

            svg,
            chartWidth, chartHeight,
            data,
            transformedData,
            stacks,

            tooltipThreshold = 480,

            baseLine,
            xAxisPadding = {
                top: 0,
                left: 0,
                bottom: 0,
                right: 0
            },
            maxBarNumber = 8,

            animationDelayStep = 20,
            animationDelays = d3Array.range(animationDelayStep, maxBarNumber* animationDelayStep, animationDelayStep),
            animationDuration = 1000,

            grid = null,

            nameLabel = 'name',
            valueLabel = 'value',
            stackLabel = 'stack',
            nameLabelFormat,
            valueLabelFormat = NUMBER_FORMAT,

            // getters
            getName = (data) =>  data[nameLabel],
            getValue = (data) => data[valueLabel],
            getStack = (data) => data[stackLabel],
            isAnimated = false,

            // events
            dispatcher = d3Dispatch.dispatch('customMouseOver', 'customMouseOut', 'customMouseMove');

        /**
         * This function creates the graph using the selection and data provided
         * @param {D3Selection} _selection A d3 selection that represents
         * the container(s) where the chart(s) will be rendered
         * @param {stackedBarData} _data The data to attach and generate the chart
         */
        function exports(_selection) {
            _selection.each(function(_data){
                chartWidth = width - margin.left - margin.right;
                chartHeight = height - margin.top - margin.bottom;
                data = cleanData(_data);

                prepareData(data);
                buildScales();
                buildLayers();
                buildSVG(this);
                drawGridLines();
                buildAxis();
                drawAxis();
                drawStackedBar();
                if (shouldShowTooltip()){
                    addMouseEvents();
                }
            });
        }

        /**
         * Prepare data for create chart.
         * @private
         */
        function prepareData(data) {
            stacks = uniq(data.map(({stack}) => stack));
            transformedData = d3Collection.nest()
                .key(getName)
                .rollup(function(values) {
                    let ret = {};

                    values.forEach((entry) => {
                        if (entry && entry[stackLabel]) {
                            ret[entry[stackLabel]] = getValue(entry);
                        }
                    });
                    ret.values = values; //for tooltip

                    return ret;
                })
                .entries(data)
                .map(function(data){
                    return assign({}, {
                        total:d3Array.sum( d3Array.permute(data.value, stacks) ),
                        key:data.key
                    }, data.value);
                });
        }

        /**
         * Adds events to the container group if the environment is not mobile
         * Adding: mouseover, mouseout and mousemove
         */
        function addMouseEvents() {
            svg
                .on('mouseover', handleMouseOver)
                .on('mouseout', handleMouseOut)
                .on('mousemove', handleMouseMove);
        }

        /**
         * Creates the d3 x and y axis, setting orientations
         * @private
         */
        function buildAxis() {
            if (!horizontal) {
                xAxis = d3Axis.axisBottom(xScale)
                yAxis = d3Axis.axisLeft(yScale)
                    .ticks(numOfVerticalTicks, valueLabelFormat)
            } else {
                xAxis = d3Axis.axisBottom(xScale)
                .ticks(numOfHorizontalTicks, valueLabelFormat);
                yAxis = d3Axis.axisLeft(yScale)
            }
        }

        /**
         * Builds containers for the chart, the axis and a wrapper for all of them
         * NOTE: The order of drawing of this group elements is really important,
         * as everything else will be drawn on top of them
         * @private
         */
        function buildContainerGroups(){
            let container = svg
                .append('g')
                .classed('container-group', true)
                .attr('transform', `translate(${margin.left},${margin.top})`);

            container
                .append('g').classed('x-axis-group', true)
                .append('g').classed('x axis', true);
            container.selectAll('.x-axis-group')
                .append('g').classed('month-axis', true);
            container
                .append('g').classed('y-axis-group axis', true);
            container
                .append('g').classed('grid-lines-group', true);
            container
                .append('g').classed('chart-group', true);
            container
                .append('g').classed('metadata-group', true);
        }

        /**
         * Builds the stacked layers layout
         * @return {D3Layout} Layout for drawing the chart
         * @private
         */
        function buildLayers(){
            let stack3 = d3Shape.stack().keys(stacks),
                dataInitial = transformedData.map((item) => {
                        let ret = {};

                        stacks.forEach((key) => {
                            ret[key] = item[key];
                        });

                        return assign({}, item, ret);
                });

            layers  = stack3(dataInitial);
        }

        /**
         * Creates the x, y and color scales of the chart
         * @private
         */
        function buildScales() {
            let yMax = d3Array.max(transformedData.map(function(d){
                return d.total;
            }));

            if (!horizontal) {
                xScale = d3Scale.scaleBand()
                    .domain(data.map(getName))
                    .rangeRound([0, chartWidth ])
                    .padding(0.1);

                yScale = d3Scale.scaleLinear()
                    .domain([0,yMax])
                    .rangeRound([chartHeight, 0])
                    .nice();
            } else {
                xScale = d3Scale.scaleLinear()
                    .domain([0, yMax])
                    .rangeRound([0, chartWidth - 1]);
                // 1 pix for edge tick

                yScale = d3Scale.scaleBand()
                    .domain(data.map(getName))
                    .rangeRound([chartHeight, 0])
                    .padding(0.1);
            }

            colorScale = d3Scale.scaleOrdinal()
                .range(colorSchema)
                .domain(data.map(getStack));

            categoryColorMap = colorScale
                .domain(data.map(getName)).domain()
                .reduce((memo, item, i) => {
                    data.forEach(function(v){
                        if (getName(v)==item){
                           memo[v.name] = colorScale(v.stack)
                           memo[v.stack] = colorScale(v.stack)
                           memo[v.stack + item] = colorScale(v.stack)
                       }
                   })
                    return memo;
                }, {});
        }

        /**
         * @param  {HTMLElement} container DOM element that will work as the container of the graph
         * @private
         */
        function buildSVG(container) {
            if (!svg) {
                svg = d3Selection.select(container)
                  .append('svg')
                    .classed('britechart stacked-bar', true);

                buildContainerGroups();
            }

            svg
                .attr('width', width)
                .attr('height', height);
        }

        /**
         * Parses dates and values into JS Date objects and numbers
         * @param  {obj} data Raw data from JSON file
         * @return {obj}      Parsed data with values and dates
         */
        function cleanData(data) {
            return data.map((d) => {
                    d.value = +d[valueLabel];
                    d.stack = d[stackLabel];
                    d.topicName = getStack(d); // for tooltip
                    d.name = d[nameLabel];

                    return d;
                });
        }

        /**
         * Draws the x and y axis on the svg object within their
         * respective groups
         * @private
         */
        function drawAxis(){
            if (!horizontal) {
                svg.select('.x-axis-group .axis.x')
                .attr('transform', `translate( 0, ${chartHeight} )`)
                .call(xAxis);

                svg.select('.y-axis-group.axis')
                    .attr('transform', `translate( ${-xAxisPadding.left}, 0)`)
                    .call(yAxis)
                    .call(adjustYTickLabels);
            } else {
                svg.select('.x-axis-group .axis.x')
                    .attr('transform', `translate( 0, ${chartHeight} )`)
                    .call(xAxis);

                svg.select('.y-axis-group.axis')
                    .attr('transform', `translate( ${-xAxisPadding.left}, 0)`)
                    .call(yAxis);
            }
        }

        /**
         * Adjusts the position of the y axis' ticks
         * @param  {D3Selection} selection Y axis group
         * @return void
         */
        function adjustYTickLabels(selection) {
            selection.selectAll('.tick text')
                .attr('transform', `translate(${yTickTextXOffset}, ${yTickTextYOffset})`);
        }

        /**
         * Draws grid lines on the background of the chart
         * @return void
         */
        function drawGridLines(xTicks, yTicks) {
            if (grid === 'horizontal' || grid === 'full') {
                svg.select('.grid-lines-group')
                    .selectAll('line.horizontal-grid-line')
                    .data(yScale.ticks(yTicks).slice(1))
                    .enter()
                      .append('line')
                        .attr('class', 'horizontal-grid-line')
                        .attr('x1', (-xAxisPadding.left + 1 ))
                        .attr('x2', chartWidth)
                        .attr('y1', (d) => yScale(d))
                        .attr('y2', (d) => yScale(d));
            }

            if (grid === 'vertical' || grid === 'full') {
                svg.select('.grid-lines-group')
                    .selectAll('line.vertical-grid-line')
                    .data(xScale.ticks(xTicks).slice(1))
                    .enter()
                      .append('line')
                        .attr('class', 'vertical-grid-line')
                        .attr('y1', 0)
                        .attr('y2', chartHeight)
                        .attr('x1', (d) => xScale(d))
                        .attr('x2', (d) => xScale(d));
            }

            if (horizontal) {
                drawVerticalExtendedLine();
            } else {
                drawHorizontalExtendedLine();
            }
        }

        /**
         * Draws the bars along the x axis
         * @param  {D3Selection} bars Selection of bars
         * @return {void}
         */
        function drawHorizontalBars(series) {
            // Enter + Update
            let context,
                bars = series
                    .data(layers)
                    .enter()
                      .append('g')
                        .classed('layer', true)
                        .attr('fill', (({key}) => categoryColorMap[key]))
                        .selectAll('.bar')
                        .data( (d)=> d)
                        .enter()
                          .append('rect')
                            .classed('bar', true)
                            .attr('x', (d) => xScale(d[0]) )
                            .attr('y', (d) => yScale(d.data.key) )
                            .attr('height', yScale.bandwidth())
                            .attr('fill', (({data}) => categoryColorMap[data.stack+data.key]));

            if (isAnimated){
                bars.style('opacity', 0.24)
                    .transition()
                    .delay((_, i) => animationDelays[i])
                    .duration(animationDuration)
                    .ease(ease)
                    .tween('attr.width', function(d ){
                        let node = d3Selection.select(this),
                        i = d3Interpolate.interpolateRound(0,xScale(d[1] - d[0] )),
                        j = d3Interpolate.interpolateNumber(0,1)
                        ;

                        return function(t){
                            node.attr('width',  i(t) );
                            node.style('opacity', j(t) );
                        }
                    });
            } else {
                bars.attr('width', (d) => xScale(d[1] - d[0] ) )
            }

            bars.on('mouseover', function(d) {
                    dispatcher.call('customMouseOver', this, !!d.values ? d:d.data, d3Selection.mouse(this), [chartWidth, chartHeight]);
                    d3Selection.select(this).attr('fill', () => d3Color.color(d3Selection.select(this.parentNode).attr('fill')).darker())
                })
                .on('mousemove', function(d) {
                    dispatcher.call('customMouseMove', this, !!d.values ? d:d.data, d3Selection.mouse(this), [chartWidth, chartHeight]);
                })
                .on('mouseout', function() {
                    dispatcher.call('customMouseOut', this);
                    d3Selection.select(this).attr('fill', () => d3Selection.select(this.parentNode).attr('fill'))
                });
        }

        /**
         * Draws a vertical line to extend x-axis till the edges
         * @return {void}
         */
        function drawHorizontalExtendedLine() {
            baseLine = svg.select('.grid-lines-group')
                .selectAll('line.extended-x-line')
                .data([0])
                .enter()
                  .append('line')
                    .attr('class', 'extended-x-line')
                    .attr('x1', (xAxisPadding.left))
                    .attr('x2', chartWidth)
                    .attr('y1', chartHeight)
                    .attr('y2', chartHeight);
        }

        /**
         * Draws the bars along the y axis
         * @param  {D3Selection} bars Selection of bars
         * @return {void}
         */
        function drawVerticalBars(series) {
            // Enter + Update
            let bars = series
                .data(layers)
                .enter()
                  .append('g')
                    .classed('layer', true)
                    .attr('fill', (({key}) => categoryColorMap[key]))
                    .selectAll('.bar')
                    .data((d) => d)
                    .enter()
                      .append('rect')
                        .classed('bar', true)
                        .attr('x', (d) => xScale(d.data.key))
                        .attr('y', (d) => yScale(d[1]))
                        .attr('width', xScale.bandwidth )
                        .attr('fill', (({data}) => categoryColorMap[data.stack+data.key])),context;

            if (isAnimated){
                bars.style('opacity', 0.24).transition()
                    .delay( (_, i) => animationDelays[i])
                    .duration(animationDuration)
                    .ease(ease)
                    .tween('attr.height', function(d ){
                        let node = d3Selection.select(this),
                        i = d3Interpolate.interpolateRound(0, yScale(d[0]) - yScale(d[1])),
                        j = d3Interpolate.interpolateNumber(0,1)
                        ;

                        return function(t){
                            node.attr('height',  i(t) );
                            node.style('opacity', j(t) );
                        }
                    });
            } else {
                bars.attr('height', (d) => yScale(d[0]) - yScale(d[1]) );
            }

            bars.on('mouseover', function(d) {
                    dispatcher.call('customMouseOver', this);
                    d3Selection.select(this).attr('fill', () => d3Color.color(d3Selection.select(this.parentNode).attr('fill')).darker())
                })
                .on('mousemove', function(d) {
                    dispatcher.call('customMouseMove', this, !!d.values ? d:d.data, d3Selection.mouse(this), [chartWidth, chartHeight]);
                })
                .on('mouseout', function() {
                    dispatcher.call('customMouseOut', this);
                    d3Selection.select(this).attr('fill', () => d3Selection.select(this.parentNode).attr('fill'))
                });
        }

        /**
         * Draws a vertical line to extend y-axis till the edges
         * @return {void}
         */
        function drawVerticalExtendedLine() {
            baseLine = svg.select('.grid-lines-group')
                .selectAll('line.extended-y-line')
                .data([0])
                .enter()
                  .append('line')
                    .attr('class', 'extended-y-line')
                    .attr('y1', (xAxisPadding.bottom))
                    .attr('y2', chartHeight)
                    .attr('x1', 0)
                    .attr('x2', 0);
        }

        /**
         * Draws the different areas into the chart-group element
         * @private
         */
        function drawStackedBar(){
            let series = svg.select('.chart-group').selectAll('.layer')

            if (!horizontal) {
                drawVerticalBars(series)
            } else {
                drawHorizontalBars(series)
            }
            // Exit
            series.exit()
                .transition()
                .style('opacity', 0)
                .remove();
        }

        /**
         * Extract X position on the chart from a given mouse event
         * @param  {obj} event D3 mouse event
         * @return {Number}       Position on the x axis of the mouse
         * @private
         */
        function getMousePosition(event) {
            return d3Selection.mouse(event);
        }

        /**
         * Finds out the data entry that is closer to the given position on pixels
         * @param  {Number} mouseX X position of the mouse
         * @return {obj}        Data entry that is closer to that x axis position
         */
        function getNearestDataPoint(mouseX) {
            let epsilon,
                nearest,
                dataByValueParsed = transformedData.map((item) => {
                    item.key = item.key
                    return item;
                });

            epsilon = (xScale(dataByValueParsed[1].key) - xScale(dataByValueParsed[0].key));
            nearest = dataByValueParsed.find(({key}) => Math.abs(xScale(key) - mouseX) <= epsilon);

            return nearest;
        }

         /**
         * Finds out the data entry that is closer to the given position on pixels
         * @param  {Number} mouseX X position of the mouse
         * @return {obj}        Data entry that is closer to that x axis position
         */
        function getNearestDataPoint2(pos) {
            let mouseY = pos[1] - margin.bottom,
                epsilon = yScale.bandwidth(),
                nearest;

            nearest = layers.map(function(stackedArray){
                return stackedArray.map(function(d1){
                   let found = d1.data.values.find((d2) => Math.abs(mouseY >= yScale(d2[nameLabel])) && Math.abs(mouseY - yScale(d2[nameLabel]) <= epsilon*2) );
                   return found ? d1.data :undefined;
               })
            });
            nearest = d3Array.merge( nearest).filter(function(e){return e});

            return nearest.length ? nearest[0] :undefined;
        }

        /**
         * MouseMove handler, calculates the nearest dataPoint to the cursor
         * and updates metadata related to it
         * @private
         */
        function handleMouseMove(){
            let mousePos = getMousePosition(this),
                dataPoint = !horizontal ? getNearestDataPoint(mousePos[0] - margin.left) : getNearestDataPoint2(mousePos),
                x,
                y;

            if (dataPoint) {
                // Move verticalMarker to that datapoint
                if (!horizontal) {
                    x =  xScale(dataPoint.key),y = yScale(dataPoint.total);
                    moveVerticalMarkerXY(x,y);
                } else {
                    x = mousePos[1],y = yScale(dataPoint.key) +  yScale.bandwidth()/2;
                    moveVerticalMarkerXY(x,y);
                }
                   // Emit event with xPosition for tooltip or similar feature
                dispatcher.call('customMouseMove', this, dataPoint, categoryColorMap, x,y);
            }
        }

        /**
         * MouseOut handler, hides overlay and removes active class on verticalMarkerLine
         * It also resets the container of the vertical marker
         * @private
         */
        function handleMouseOut(data){
            svg.select('.metadata-group').attr('transform', 'translate(9999, 0)');
            dispatcher.call('customMouseOut', this, data);
        }

        /**
         * Mouseover handler, shows overlay and adds active class to verticalMarkerLine
         * @private
         */
        function handleMouseOver(data){
            dispatcher.call('customMouseOver', this, data);
        }

        /**
         * Helper method to update the x position of the vertical marker
         * @param  {obj} dataPoint Data entry to extract info
         * @return void
         */
        function moveVerticalMarkerXY(verticalMarkerXPosition,verticalMarkerYPosition){
            svg.select('.metadata-group').attr('transform', `translate(${verticalMarkerXPosition},${verticalMarkerYPosition})`);
        }

        /**
         * Determines if we should add the tooltip related logic depending on the
         * size of the chart and the tooltipThreshold variable value
         * @return {boolean} Should we build the tooltip?
         * @private
         */
        function shouldShowTooltip() {
            return width > tooltipThreshold;
        }

        // API
        /**
         * Gets or Sets the aspect ratio of the chart
         * @param  {Number} _x Desired aspect ratio for the graph
         * @return { (Number | Module) } Current aspect ratio or Area Chart module to chain calls
         * @public
         */
        exports.aspectRatio = function(_x) {
            if (!arguments.length) {
                return aspectRatio;
            }
            aspectRatio = _x;

            return this;
        };

        /**
         * Gets or Sets the colorSchema of the chart
         * @param  {String[]} _x Desired colorSchema for the graph
         * @return { colorSchema | module} Current colorSchema or Chart module to chain calls
         * @public
         */
        exports.colorSchema = function(_x) {
            if (!arguments.length) {
                return colorSchema;
            }
            colorSchema = _x;

            return this;
        };

        /**
         * Gets or Sets the nameLabel of the chart
         * @param  {Number} _x Desired dateLabel for the graph
         * @return { nameLabel | module} Current nameLabel or Chart module to chain calls
         * @public
         */
        exports.nameLabel = function(_x) {
            if (!arguments.length) {
                return nameLabel;
            }
            nameLabel = _x;

            return this;
        };

        /**
         * Gets or Sets the valueLabelFormat of the chart
         * @param  {String[]} _x Desired valueLabelFormat for the graph
         * @return { valueLabelFormat | module} Current valueLabelFormat or Chart module to chain calls
         * @public
         */
        exports.nameLabelFormat = function(_x) {
            if (!arguments.length) {
                return nameLabelFormat;
            }
            nameLabelFormat = _x;

            return this;
        };

        /**
         * Configurable extension of the x axis
         * if your max point was 50% you might want to show x axis to 60%, pass 1.2
         * @param  {number} _x ratio to max data point to add to the x axis
         * @return { ratio | module} Current ratio or Bar Chart module to chain calls
         * @public
         */
        exports.percentageAxisToMaxRatio = function(_x) {
            if (!arguments.length) {
                return percentageAxisToMaxRatio;
            }
            percentageAxisToMaxRatio = _x;

            return this;
        };

        /**
         * Gets or Sets the stackLabel of the chart
         * @param  {String} _x Desired stackLabel for the graph
         * @return { stackLabel | module} Current stackLabel or Chart module to chain calls
         * @public
         */
        exports.stackLabel = function(_x) {
            if (!arguments.length) {
                return stackLabel;
            }
            stackLabel = _x;

            return this;
        };

        /**
         * Gets or Sets the grid mode.
         *
         * @param  {String} _x Desired mode for the grid ('vertical'|'horizontal'|'full')
         * @return { String | module} Current mode of the grid or Area Chart module to chain calls
         * @public
         */
        exports.grid = function(_x) {
            if (!arguments.length) {
                return grid;
            }
            grid = _x;

            return this;
        };

        /**
         * Gets or Sets the height of the chart
         * @param  {Number} _x Desired width for the graph
         * @return { height | module} Current height or Area Chart module to chain calls
         * @public
         */
        exports.height = function(_x) {
            if (!arguments.length) {
                return height;
            }
            if (aspectRatio) {
                width = Math.ceil(_x / aspectRatio);
            }
            height = _x;

            return this;
        };

        /**
         * Gets or Sets the horizontal direction of the chart
         * @param  {number} _x Desired horizontal direction for the graph
         * @return { horizontal | module} Current horizontal direction or Bar Chart module to chain calls
         * @public
         */
        exports.horizontal = function(_x) {
            if (!arguments.length) {
                return horizontal;
            }
            horizontal = _x;

            return this;
        };

        /**
         * Gets or Sets the isAnimated property of the chart, making it to animate when render.
         * By default this is 'false'
         *
         * @param  {Boolean} _x Desired animation flag
         * @return { isAnimated | module} Current isAnimated flag or Chart module
         * @public
         */
        exports.isAnimated = function(_x) {
            if (!arguments.length) {
                return isAnimated;
            }
            isAnimated = _x;

            return this;
        };

        /**
         * Gets or Sets the margin of the chart
         * @param  {Object} _x Margin object to get/set
         * @return { margin | module} Current margin or Area Chart module to chain calls
         * @public
         */
        exports.margin = function(_x) {
            if (!arguments.length) {
                return margin;
            }
            margin = _x;

            return this;
        };

        /**
         * Gets or Sets the minimum width of the graph in order to show the tooltip
         * NOTE: This could also depend on the aspect ratio
         *
         * @param  {Object} _x Margin object to get/set
         * @return { tooltipThreshold | module} Current tooltipThreshold or Area Chart module to chain calls
         * @public
         */
        exports.tooltipThreshold = function(_x) {
            if (!arguments.length) {
                return tooltipThreshold;
            }
            tooltipThreshold = _x;

            return this;
        };

        /**
         * Gets or Sets the valueLabel of the chart
         * @param  {Number} _x Desired valueLabel for the graph
         * @return { valueLabel | module} Current valueLabel or Chart module to chain calls
         * @public
         */
        exports.valueLabel = function(_x) {
            if (!arguments.length) {
                return valueLabel;
            }
            valueLabel = _x;

            return this;
        };

        /**
         * Gets or Sets the valueLabelFormat of the chart
         * @param  {String[]} _x Desired valueLabelFormat for the graph
         * @return { valueLabelFormat | module} Current valueLabelFormat or Chart module to chain calls
         * @public
         */
        exports.valueLabelFormat = function(_x) {
            if (!arguments.length) {
                return valueLabelFormat;
            }
            valueLabelFormat = _x;

            return this;
        };

        /**
         * Gets or Sets the number of verticalTicks of the yAxis on the chart
         * @param  {Number} _x Desired verticalTicks
         * @return { verticalTicks | module} Current verticalTicks or Chart module to chain calls
         * @public
         */
        exports.verticalTicks = function(_x) {
            if (!arguments.length) {
                return verticalTicks;
            }
            verticalTicks = _x;

            return this;
        };

        /**
         * Gets or Sets the width of the chart
         * @param  {Number} _x Desired width for the graph
         * @return { width | module} Current width or Area Chart module to chain calls
         * @public
         */
        exports.width = function(_x) {
            if (!arguments.length) {
                return width;
            }
            if (aspectRatio) {
                height = Math.ceil(_x * aspectRatio);
            }
            width = _x;

            return this;
        };

        /**
         * Chart exported to png and a download action is fired
         * @public
         */
        exports.exportChart = function(filename, title) {
            exportChart.call(exports, svg, filename, title);
        };

        /**
         * Exposes an 'on' method that acts as a bridge with the event dispatcher
         * We are going to expose this events:
         * customMouseOver, customMouseMove and customMouseOut
         *
         * @return {module} Bar Chart
         * @public
         */
        exports.on = function() {
            let value = dispatcher.on.apply(dispatcher, arguments);

            return value === dispatcher ? exports : value;
        };

        return exports;
    };
});

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Search results

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            	Eventbrite Copyright

            	Documentation generated by JSDoc 3.4.3

            	using the DocStrap template.


text:
from __future__ import absolute_import
from __future__ import print_function

import inspect

from ..host import Host
from .. import utils

def command(parent_parser):
  parser = parent_parser.add_parser(
      'host',
      help=inspect.getdoc(Host))

  subcommands = [
      host_ls,
      host_show,
      ]

  subparsers = parser.add_subparsers()
  for subcommand in subcommands:
      subcommand(subparsers)

def host_ls(parent_parser):
    def ls(client, args):
        host_list = client.host.ls()
        if not client.raw:
            for host_name in host_list:
                print('{name}'.format(name=host_name))
    parser = parent_parser.add_parser(
        'ls',
        help=inspect.getdoc(Host.ls))
    parser.set_defaults(func=ls)

def host_show(parent_parser):
    def show(client, args):
        for host_name in args.hosts:
            host_info = client.host.show(host_name)
            if not client.raw:
                print(
                    '[{state}] {host} ({ip}) - {status}'.format(
                        host=host_info['Hosts']['host_name'],
                        ip=host_info['Hosts']['ip'],
                        state=host_info['Hosts']['host_state'],
                        status=host_info['Hosts']['host_status']))
                if 'alerts' in host_info:
                    for alert in host_info['alerts']['detail']:
                        if alert['status'] != 'OK':
                            print(
                                '{indent}{service} {status} {desc}: {message}'.format(
                                    indent=' '*4,
                                    service=alert['service_name'],
                                    status=alert['status'],
                                    desc=alert['description'],
                                    message=alert['output']))
                if args.hardware:
                    print(
                        '{indent}{cohost_info}-core {memory}B {os} {rack}'.format(
                            indent=' '*4,
                            cohost_info=host_info['Hosts']['cpu_count'],
                            memory=host_info['Hosts']['total_mem'],
                            os=host_info['Hosts']['os_type'],
                            rack=host_info['Hosts']['rack_info']))
                    for disk in host_info['Hosts']['disk_info']:
                        print(
                            '{indent}{mount} {type} {percent} ({used}B/{size}B)'.format(
                                indent=' '*8,
                                mount=disk['mountpoint'],
                                type=disk['type'],
                                percent=disk['percent'],
                                used=disk['used'],
                                size=disk['size']))

    parser = parent_parser.add_parser(
        'show',
        help=inspect.getdoc(Host.show))
    parser.set_defaults(func=show)
    parser.add_argument(
        '--hardware',
        action='store_true',
        default=False,
        help="Print hardware specs.")
    parser.add_argument(
            'hosts',
            nargs='+',
            help="host name(s) to show")


text:
include_recipe 'apt' if node[:platform_family].to_s == 'debian'

cookbook_file "/#{cookbook_name.to_s.tr('-', '_')}_before_install.txt" do
  source 'foo.txt'
  owner 'root'
  group 'root'
  mode '0777'
  action :create
end

template '/foo.txt' do
  require 'securerandom'
  source 'foo.txt.erb'
  variables(var: SecureRandom.uuid)
end


text:
/*! \file BlockMatrix.hpp
  \brief Object to handle block-matrices.

*/

#ifndef __BlockMatrix__
#define __BlockMatrix__

#include "SiconosMatrix.hpp"

/** Object to handle block-matrices (ie lists of SiconosMatrix*)
 *
 * \author SICONOS Development Team - copyright INRIA
 *   \version 3.0.0.
 *   \date (Creation) 21/07/2006
 *
 *  A BlockMatrix is a boost::ublas::compressed_matrix of SP::SiconosMatrix.
 * The blocks positions are given by two Index objects, tabRow and tabCol.
 *
 * If block 1 is n1xm1, block2 n2xm2, block3 n3xm3 ..., then:\n
 *  tabRow = [ n1 n1+n2 n1+n2+n3 ...] \n
 *  tabCol = [ m1 m1+m2 m1+m2+m3 ...] \n
 *
 */
class BlockMatrix : public SiconosMatrix
{
private:
  /** serialization hooks
  */
  ACCEPT_SERIALIZATION(BlockMatrix);

  /** A container of pointers to SiconosMatrix
   */
  SP::BlocksMat _mat;

  /** list of blocks dimension - tabRow[i] = tabRow[i-1] + ni, ni being the number of rows of block i.
   */
  SP::Index _tabRow;

  /** list of blocks dimension - tabCol[i] = tabCol[i-1] + ni, ni being the number of columns of block i.
   */
  SP::Index _tabCol;

  /** Number of rows (Warning: total number of scalar elements, not number of blocks) */
  unsigned int _dimRow;

  /** Number of columns (Warning: total number of scalar elements, not number of blocks) */
  unsigned int _dimCol;

  /** default constructor
   */
  BlockMatrix() {};

public:

  /** copy constructor
   *  \param m a SiconosMatrix
   */
  BlockMatrix(const SiconosMatrix& m);

  /** copy constructor
   *  \param m a BlockMatrix
   */
  BlockMatrix(const BlockMatrix& m);

  /** constructor with a list of pointer to SiconosMatrix (!links with pointer, no copy!)
   *  \param m a vector of SiconosMatrix
   *  \param row number of blocks in a row
   *  \param col number of col in a row
   */
  BlockMatrix(const std::vector<SP::SiconosMatrix>& m, unsigned int row, unsigned int col);

  /** contructor with a list of 4 pointer to SiconosMatrix (!links with pointer, no copy!)
   *  \param A block (0,0)
   *  \param B block (0,1)
   *  \param C block (1,0)
   *  \param D block (1,1)
   */
  BlockMatrix(SP::SiconosMatrix A, SP::SiconosMatrix B, SP::SiconosMatrix C, SP::SiconosMatrix D);

  /** destructor
   */
  ~BlockMatrix(void);

  /** get the number of block (i=0, row, i=1 col)
   *  \param i unsigned int(i=0, row, i=1 col)
   *  \return an unsigned int
   */
  unsigned int getNumberOfBlocks(unsigned int i) const;

  /** get DenseMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a DenseMat
   */
  const DenseMat getDense(unsigned int row = 0, unsigned int col = 0) const;

  /** get TriangMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a TriangMat
   */
  const TriangMat getTriang(unsigned int row = 0, unsigned int col = 0) const;

  /** get SymMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a SymMat
   */
  const SymMat getSym(unsigned int row = 0, unsigned int col = 0)const;

  /** get BandedMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a BandedMat
   */
  const BandedMat getBanded(unsigned int row = 0, unsigned int col = 0)const;

  /** get SparseMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a SparseMat
   */
  const SparseMat getSparse(unsigned int row = 0, unsigned int col = 0)const;

  /** get ZeroMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a ZeroMat
   */
  const ZeroMat getZero(unsigned int row = 0, unsigned int col = 0) const;

  /** get  getIdentity matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return an IdentityMat
   */
  const IdentityMat getIdentity(unsigned int row = 0, unsigned int col = 0) const;

  /** get a pointer on DenseMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a DenseMat*
   */
  DenseMat* dense(unsigned int row = 0, unsigned int col = 0)const;

  /** get a pointer on TriangMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a TriangMat*
   */
  TriangMat* triang(unsigned int row = 0, unsigned int col = 0)const;

  /** get a pointer on SymMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col `an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a SymMat*
   */
  SymMat* sym(unsigned int row = 0, unsigned int col = 0)const;

  /** get a pointer on BandedMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a BandedMat*
   */
  BandedMat* banded(unsigned int row = 0, unsigned int col = 0)const;

  /** get a pointer on SparseMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a SparseMat*
   */
  SparseMat* sparse(unsigned int row = 0, unsigned int col = 0)const;

  /** get a pointer on ZeroMat matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return a ZeroMat*
   */
  ZeroMat* zero_mat(unsigned int row = 0, unsigned int col = 0) const;

  /** get a pointer on Identity matrix
   *  \param row an unsigned int, position of the block (row) - Useless for SimpleMatrix
   *  \param col an unsigned int, position of the block (column) - Useless for SimpleMatrix
   *  \return an IdentityMat*
   */
  IdentityMat* identity(unsigned int row = 0, unsigned int col = 0) const;

  /** return the adress of the array of double values of the matrix
   *  \param row position for the required block ->useless for SimpleMatrix
   *  \param col position for the required block ->useless for SimpleMatrix
   *  \return double* : the pointer on the double array
   */
  double* getArray(unsigned int row = 0, unsigned int col = 0) const;

  /** sets all the values of the matrix to 0.0
   */
  void zero();

  /** Initialize the matrix with random values
   */
  void randomize();

  /** Initialize a symmetric matrix with random values
   */
  void randomize_sym();

  /** set an identity matrix
   */
  void eye();

  /** get the number of rows or columns of the matrix
   *  \param index 0 for rows, 1 for columns
   *  \return an int
   */
  unsigned int size(unsigned int index) const;

  /** resize the matrix with nbrow rows and nbcol columns, lower and upper are useful only for SparseMat.The existing elements of the Block matrix are preseved when specified.
   * \param nbrow
   * \param nbcol
   * \param lower
   * \param upper
   * \param b
   */
  void resize(unsigned int nbrow, unsigned int nbcol, unsigned int lower = 0,
              unsigned int upper = 0, bool b = true);

  /** compute the infinite norm of the Block matrix
   *  \return a double
   */
  double normInf() const;

  /** display data on standard output
   */
  void display() const;

  /** get or set the element matrix[i,j]
   *  \param i an unsigned int
   *  \param j an unsigned int
   *  \exception SiconosMatrixException
   *  \return the element matrix[i,j]
   */
  double& operator()(unsigned int i, unsigned int j);

  /** get or set the element matrix[i,j]
   *  \param i an unsigned int
   *  \param j an unsigned int
   *  \exception SiconosMatrixException
   *  \return the element matrix[i,j]
   */
  double operator()(unsigned int i, unsigned int j) const;

  /** return the element matrix[i,j]
   *  \param i an unsigned int
   *  \param j an unsigned int
   *  \return a double
   */
  double getValue(unsigned int i, unsigned int j) const;

  /** set the element matrix[i,j]
   *  \param i an unsigned int i
   *  \param j an unsigned int j
   *  \param value
   */
  void setValue(unsigned int i, unsigned int j, double value);

  /** transpose in place: x->trans() is x = transpose of x.
   */
  void trans();

  /** transpose a matrix: x->trans(m) is x = transpose of m.
   *  \param m the matrix to be transposed.
   */
  void trans(const SiconosMatrix& m);

  /** get the vector tabRow
   *  \return a vector of int
   */
  inline Index getTabRow() const
  {
    return *_tabRow;
  };

  /** get the vector tabCol
   *  \return a vector of int
   */
  inline Index getTabCol() const
  {
    return *_tabCol;
  };

  /** get the vector tabRow
   *  \return a pointer to vector of int
   */
  inline const SP::Index tabRow() const
  {
    return _tabRow;
  };

  /** get the vector tabCol
   *  \return a pointer to vector of int
   */
  inline const SP::Index tabCol() const
  {
    return _tabCol;
  };

  /** get block at position row-col
   *  \param row unsigned int
   *  \param col unsigned int
   *  \return SP::SiconosMatrix the requested block
   */
  SP::SiconosMatrix block(unsigned int row = 0, unsigned int col = 0);

  /** get block at position row-col
   *  \param row unsigned int
   *  \param col unsigned int
   *  \return SP::SiconosMatrix the requested block
   */
  SPC::SiconosMatrix block(unsigned int row = 0, unsigned int col = 0) const;

  /** get row index of current matrix and save it in  v
   *  \param r index of required line
   *  \param[out] v a vector
   */
  void  getRow(unsigned int r, SiconosVector& v) const;

  /** set line row of the current matrix with vector v
   *  \param r index of required line
   *  \param v a vector
   */
  void  setRow(unsigned int r, const SiconosVector& v);

  /** get column index of current matrix and save it into vOut
   *  \param c index of required column
   *  \param[out] v a vector
   */
  void  getCol(unsigned int c, SiconosVector& v) const;

  /** set column col of the current matrix with vector
   *  \param c index of required column
   *  \param v a vector
   */
  void  setCol(unsigned int c, const SiconosVector& v);

  /** add a part of the input matrix (starting from (i,j) pos) to the current matrix
   *  \param i an unsigned int i (in-out)
   *  \param j an unsigned int j (in-out)
   *  \param m a SiconosMatrix (in-out)
   */
  void addSimple(unsigned int& i, unsigned int& j, const SiconosMatrix& m);

  /** subtract a part of the input matrix (starting from (i,j) pos) to the current matrix
   *  \param i an unsigned int i (in-out)
   *  \param j an unsigned int j (in-out)
   *  \param m a SiconosMatrix (in-out)
   */
  void subSimple(unsigned int& i, unsigned int& j, const SiconosMatrix& m);

  /** assignment
   * \param m the matrix to be copied
   * \return  BlockMatrix&
   */
  BlockMatrix& operator = (const SiconosMatrix& m);

  /** assignment
   *  \param m the matrix to be copied
   * \return  BlockMatrix&
   */
  BlockMatrix& operator = (const BlockMatrix& m);

  /** assignment
   *  \param m the matrix to be copied
   * \return  BlockMatrix&
   */
  BlockMatrix& operator = (const DenseMat& m);

  /** operator +=
   *  \param m the matrix to add
   * \return  BlockMatrix&
   */
  BlockMatrix& operator +=(const SiconosMatrix& m);

  /**operator -=
   *  \param m the matrix to subtract
   * \return  BlockMatrix&
   */
  BlockMatrix& operator -=(const SiconosMatrix& m);

  /** computes an LU factorization of a general M-by-N matrix using partial pivoting with row interchanges.
   *  The result is returned in this (InPlace). Based on Blas dgetrf function.
   */
  void PLUFactorizationInPlace();

  /**  compute inverse of this thanks to LU factorization with Partial pivoting. This method inverts U and then computes inv(A) by solving the system
   *  inv(A)*L = inv(U) for inv(A). The result is returned in this (InPlace). Based on Blas dgetri function.
   */
  void PLUInverseInPlace();

  /** solves a system of linear equations A * X = B  (A=this) with a general N-by-N matrix A using the LU factorization computed
   *   by PLUFactorizationInPlace. Based on Blas dgetrs function.
   *  \param[in,out] B on input the RHS matrix b; on output: the result x
   */
  void PLUForwardBackwardInPlace(SiconosMatrix &B);

  /** solves a system of linear equations A * X = B  (A=this) with a general N-by-N matrix A using the LU factorization computed
   *   by PLUFactorizationInPlace.  Based on Blas dgetrs function.
   *  \param[in,out] B on input the RHS matrix b; on output: the result x
   */
  void PLUForwardBackwardInPlace(SiconosVector &B);

  /** visitors hook
   */
  ACCEPT_STD_VISITORS();

  friend class SimpleMatrix;
  friend void scal(double, const SiconosMatrix&, SiconosMatrix&, bool);
  friend SiconosMatrix& operator *=(SiconosMatrix& m, const double& s);
  friend SiconosMatrix& operator /=(SiconosMatrix& m, const double& s);

  /** return the number of non-zero in the matrix
   * \param tol the tolerance to consider a number zero (not used if the matrix is sparse)
   * \return the number of non-zeros
   */
  virtual size_t nnz(double tol = 1e-14);
};

//DEFINE_SPTR(BlockMatrix)

#endif