text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/iam/v1/iam_policy.proto

package com.google.iam.v1;

/**
 *

 * Request message for `GetIamPolicy` method.
 *

 *
 * Protobuf type {@code google.iam.v1.GetIamPolicyRequest}
 */
public  final class GetIamPolicyRequest extends
    com.google.protobuf.GeneratedMessageV3 implements
    // @@protoc_insertion_point(message_implements:google.iam.v1.GetIamPolicyRequest)
    GetIamPolicyRequestOrBuilder {
private static final long serialVersionUID = 0L;
  // Use GetIamPolicyRequest.newBuilder() to construct.
  private GetIamPolicyRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }
  private GetIamPolicyRequest() {
    resource_ = "";
  }

  @Override
  public final com.google.protobuf.UnknownFieldSet
  getUnknownFields() {
    return this.unknownFields;
  }
  private GetIamPolicyRequest(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    this();
    if (extensionRegistry == null) {
      throw new NullPointerException();
    }
    int mutable_bitField0_ = 0;
    com.google.protobuf.UnknownFieldSet.Builder unknownFields =
        com.google.protobuf.UnknownFieldSet.newBuilder();
    try {
      boolean done = false;
      while (!done) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            done = true;
            break;
          case 10: {
            String s = input.readStringRequireUtf8();

            resource_ = s;
            break;
          }
          case 18: {
            GetPolicyOptions.Builder subBuilder = null;
            if (options_ != null) {
              subBuilder = options_.toBuilder();
            }
            options_ = input.readMessage(GetPolicyOptions.parser(), extensionRegistry);
            if (subBuilder != null) {
              subBuilder.mergeFrom(options_);
              options_ = subBuilder.buildPartial();
            }

            break;
          }
          default: {
            if (!parseUnknownField(
                input, unknownFields, extensionRegistry, tag)) {
              done = true;
            }
            break;
          }
        }
      }
    } catch (com.google.protobuf.InvalidProtocolBufferException e) {
      throw e.setUnfinishedMessage(this);
    } catch (java.io.IOException e) {
      throw new com.google.protobuf.InvalidProtocolBufferException(
          e).setUnfinishedMessage(this);
    } finally {
      this.unknownFields = unknownFields.build();
      makeExtensionsImmutable();
    }
  }
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return IamPolicyProto.internal_static_google_iam_v1_GetIamPolicyRequest_descriptor;
  }

  @Override
  protected FieldAccessorTable
      internalGetFieldAccessorTable() {
    return IamPolicyProto.internal_static_google_iam_v1_GetIamPolicyRequest_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            GetIamPolicyRequest.class, Builder.class);
  }

  public static final int RESOURCE_FIELD_NUMBER = 1;
  private volatile Object resource_;
  /**
   *

   * REQUIRED: The resource for which the policy is being requested.
   * See the operation documentation for the appropriate value for this field.
   *

   *
   * string resource = 1;
   */
  public String getResource() {
    Object ref = resource_;
    if (ref instanceof String) {
      return (String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      String s = bs.toStringUtf8();
      resource_ = s;
      return s;
    }
  }
  /**
   *

   * REQUIRED: The resource for which the policy is being requested.
   * See the operation documentation for the appropriate value for this field.
   *

   *
   * string resource = 1;
   */
  public com.google.protobuf.ByteString
      getResourceBytes() {
    Object ref = resource_;
    if (ref instanceof String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8(
              (String) ref);
      resource_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  public static final int OPTIONS_FIELD_NUMBER = 2;
  private GetPolicyOptions options_;
  /**
   *

   * OPTIONAL: A `GetPolicyOptions` object for specifying options to
   * `GetIamPolicy`. This field is only used by Cloud IAM.
   *

   *
   * .google.iam.v1.GetPolicyOptions options = 2;
   */
  public boolean hasOptions() {
    return options_ != null;
  }
  /**
   *

   * OPTIONAL: A `GetPolicyOptions` object for specifying options to
   * `GetIamPolicy`. This field is only used by Cloud IAM.
   *

   *
   * .google.iam.v1.GetPolicyOptions options = 2;
   */
  public GetPolicyOptions getOptions() {
    return options_ == null ? GetPolicyOptions.getDefaultInstance() : options_;
  }
  /**
   *

   * OPTIONAL: A `GetPolicyOptions` object for specifying options to
   * `GetIamPolicy`. This field is only used by Cloud IAM.
   *

   *
   * .google.iam.v1.GetPolicyOptions options = 2;
   */
  public com.google.iam.v1.GetPolicyOptionsOrBuilder getOptionsOrBuilder() {
    return getOptions();
  }

  private byte memoizedIsInitialized = -1;
  @Override
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  @Override
  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    if (!getResourceBytes().isEmpty()) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resource_);
    }
    if (options_ != null) {
      output.writeMessage(2, getOptions());
    }
    unknownFields.writeTo(output);
  }

  @Override
  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (!getResourceBytes().isEmpty()) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resource_);
    }
    if (options_ != null) {
      size += com.google.protobuf.CodedOutputStream
        .computeMessageSize(2, getOptions());
    }
    size += unknownFields.getSerializedSize();
    memoizedSize = size;
    return size;
  }

  @Override
  public boolean equals(final Object obj) {
    if (obj == this) {
     return true;
    }
    if (!(obj instanceof GetIamPolicyRequest)) {
      return super.equals(obj);
    }
    GetIamPolicyRequest other = (GetIamPolicyRequest) obj;

    if (!getResource()
        .equals(other.getResource())) return false;
    if (hasOptions() != other.hasOptions()) return false;
    if (hasOptions()) {
      if (!getOptions()
          .equals(other.getOptions())) return false;
    }
    if (!unknownFields.equals(other.unknownFields)) return false;
    return true;
  }

  @Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    hash = (37 * hash) + RESOURCE_FIELD_NUMBER;
    hash = (53 * hash) + getResource().hashCode();
    if (hasOptions()) {
      hash = (37 * hash) + OPTIONS_FIELD_NUMBER;
      hash = (53 * hash) + getOptions().hashCode();
    }
    hash = (29 * hash) + unknownFields.hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static GetIamPolicyRequest parseFrom(
      java.nio.ByteBuffer data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static GetIamPolicyRequest parseFrom(
      java.nio.ByteBuffer data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static GetIamPolicyRequest parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static GetIamPolicyRequest parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static GetIamPolicyRequest parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static GetIamPolicyRequest parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static GetIamPolicyRequest parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static GetIamPolicyRequest parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }
  public static GetIamPolicyRequest parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input);
  }
  public static GetIamPolicyRequest parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
  }
  public static GetIamPolicyRequest parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static GetIamPolicyRequest parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }

  @Override
  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }
  public static Builder newBuilder(GetIamPolicyRequest prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }
  @Override
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE
        ? new Builder() : new Builder().mergeFrom(this);
  }

  @Override
  protected Builder newBuilderForType(
      BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   *

   * Request message for `GetIamPolicy` method.
   *

   *
   * Protobuf type {@code google.iam.v1.GetIamPolicyRequest}
   */
  public static final class Builder extends
      com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
      // @@protoc_insertion_point(builder_implements:google.iam.v1.GetIamPolicyRequest)
      com.google.iam.v1.GetIamPolicyRequestOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return IamPolicyProto.internal_static_google_iam_v1_GetIamPolicyRequest_descriptor;
    }

    @Override
    protected FieldAccessorTable
        internalGetFieldAccessorTable() {
      return IamPolicyProto.internal_static_google_iam_v1_GetIamPolicyRequest_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              GetIamPolicyRequest.class, Builder.class);
    }

    // Construct using com.google.iam.v1.GetIamPolicyRequest.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }

    private Builder(
        BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }
    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessageV3
              .alwaysUseFieldBuilders) {
      }
    }
    @Override
    public Builder clear() {
      super.clear();
      resource_ = "";

      if (optionsBuilder_ == null) {
        options_ = null;
      } else {
        options_ = null;
        optionsBuilder_ = null;
      }
      return this;
    }

    @Override
    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return IamPolicyProto.internal_static_google_iam_v1_GetIamPolicyRequest_descriptor;
    }

    @Override
    public GetIamPolicyRequest getDefaultInstanceForType() {
      return GetIamPolicyRequest.getDefaultInstance();
    }

    @Override
    public GetIamPolicyRequest build() {
      GetIamPolicyRequest result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    @Override
    public GetIamPolicyRequest buildPartial() {
      GetIamPolicyRequest result = new GetIamPolicyRequest(this);
      result.resource_ = resource_;
      if (optionsBuilder_ == null) {
        result.options_ = options_;
      } else {
        result.options_ = optionsBuilder_.build();
      }
      onBuilt();
      return result;
    }

    @Override
    public Builder clone() {
      return super.clone();
    }
    @Override
    public Builder setField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        Object value) {
      return super.setField(field, value);
    }
    @Override
    public Builder clearField(
        com.google.protobuf.Descriptors.FieldDescriptor field) {
      return super.clearField(field);
    }
    @Override
    public Builder clearOneof(
        com.google.protobuf.Descriptors.OneofDescriptor oneof) {
      return super.clearOneof(oneof);
    }
    @Override
    public Builder setRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        int index, Object value) {
      return super.setRepeatedField(field, index, value);
    }
    @Override
    public Builder addRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        Object value) {
      return super.addRepeatedField(field, value);
    }
    @Override
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof GetIamPolicyRequest) {
        return mergeFrom((GetIamPolicyRequest)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(GetIamPolicyRequest other) {
      if (other == GetIamPolicyRequest.getDefaultInstance()) return this;
      if (!other.getResource().isEmpty()) {
        resource_ = other.resource_;
        onChanged();
      }
      if (other.hasOptions()) {
        mergeOptions(other.getOptions());
      }
      this.mergeUnknownFields(other.unknownFields);
      onChanged();
      return this;
    }

    @Override
    public final boolean isInitialized() {
      return true;
    }

    @Override
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      GetIamPolicyRequest parsedMessage = null;
      try {
        parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        parsedMessage = (GetIamPolicyRequest) e.getUnfinishedMessage();
        throw e.unwrapIOException();
      } finally {
        if (parsedMessage != null) {
          mergeFrom(parsedMessage);
        }
      }
      return this;
    }

    private Object resource_ = "";
    /**
     *

     * REQUIRED: The resource for which the policy is being requested.
     * See the operation documentation for the appropriate value for this field.
     *

     *
     * string resource = 1;
     */
    public String getResource() {
      Object ref = resource_;
      if (!(ref instanceof String)) {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        String s = bs.toStringUtf8();
        resource_ = s;
        return s;
      } else {
        return (String) ref;
      }
    }
    /**
     *

     * REQUIRED: The resource for which the policy is being requested.
     * See the operation documentation for the appropriate value for this field.
     *

     *
     * string resource = 1;
     */
    public com.google.protobuf.ByteString
        getResourceBytes() {
      Object ref = resource_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (String) ref);
        resource_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     *

     * REQUIRED: The resource for which the policy is being requested.
     * See the operation documentation for the appropriate value for this field.
     *

     *
     * string resource = 1;
     */
    public Builder setResource(
        String value) {
      if (value == null) {
    throw new NullPointerException();
  }

      resource_ = value;
      onChanged();
      return this;
    }
    /**
     *

     * REQUIRED: The resource for which the policy is being requested.
     * See the operation documentation for the appropriate value for this field.
     *

     *
     * string resource = 1;
     */
    public Builder clearResource() {

      resource_ = getDefaultInstance().getResource();
      onChanged();
      return this;
    }
    /**
     *

     * REQUIRED: The resource for which the policy is being requested.
     * See the operation documentation for the appropriate value for this field.
     *

     *
     * string resource = 1;
     */
    public Builder setResourceBytes(
        com.google.protobuf.ByteString value) {
      if (value == null) {
    throw new NullPointerException();
  }
  checkByteStringIsUtf8(value);

      resource_ = value;
      onChanged();
      return this;
    }

    private GetPolicyOptions options_;
    private com.google.protobuf.SingleFieldBuilderV3<
        GetPolicyOptions, GetPolicyOptions.Builder, com.google.iam.v1.GetPolicyOptionsOrBuilder> optionsBuilder_;
    /**
     *

     * OPTIONAL: A `GetPolicyOptions` object for specifying options to
     * `GetIamPolicy`. This field is only used by Cloud IAM.
     *

     *
     * .google.iam.v1.GetPolicyOptions options = 2;
     */
    public boolean hasOptions() {
      return optionsBuilder_ != null || options_ != null;
    }
    /**
     *

     * OPTIONAL: A `GetPolicyOptions` object for specifying options to
     * `GetIamPolicy`. This field is only used by Cloud IAM.
     *

     *
     * .google.iam.v1.GetPolicyOptions options = 2;
     */
    public GetPolicyOptions getOptions() {
      if (optionsBuilder_ == null) {
        return options_ == null ? GetPolicyOptions.getDefaultInstance() : options_;
      } else {
        return optionsBuilder_.getMessage();
      }
    }
    /**
     *

     * OPTIONAL: A `GetPolicyOptions` object for specifying options to
     * `GetIamPolicy`. This field is only used by Cloud IAM.
     *

     *
     * .google.iam.v1.GetPolicyOptions options = 2;
     */
    public Builder setOptions(GetPolicyOptions value) {
      if (optionsBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        options_ = value;
        onChanged();
      } else {
        optionsBuilder_.setMessage(value);
      }

      return this;
    }
    /**
     *

     * OPTIONAL: A `GetPolicyOptions` object for specifying options to
     * `GetIamPolicy`. This field is only used by Cloud IAM.
     *

     *
     * .google.iam.v1.GetPolicyOptions options = 2;
     */
    public Builder setOptions(
        GetPolicyOptions.Builder builderForValue) {
      if (optionsBuilder_ == null) {
        options_ = builderForValue.build();
        onChanged();
      } else {
        optionsBuilder_.setMessage(builderForValue.build());
      }

      return this;
    }
    /**
     *

     * OPTIONAL: A `GetPolicyOptions` object for specifying options to
     * `GetIamPolicy`. This field is only used by Cloud IAM.
     *

     *
     * .google.iam.v1.GetPolicyOptions options = 2;
     */
    public Builder mergeOptions(GetPolicyOptions value) {
      if (optionsBuilder_ == null) {
        if (options_ != null) {
          options_ =
            GetPolicyOptions.newBuilder(options_).mergeFrom(value).buildPartial();
        } else {
          options_ = value;
        }
        onChanged();
      } else {
        optionsBuilder_.mergeFrom(value);
      }

      return this;
    }
    /**
     *

     * OPTIONAL: A `GetPolicyOptions` object for specifying options to
     * `GetIamPolicy`. This field is only used by Cloud IAM.
     *

     *
     * .google.iam.v1.GetPolicyOptions options = 2;
     */
    public Builder clearOptions() {
      if (optionsBuilder_ == null) {
        options_ = null;
        onChanged();
      } else {
        options_ = null;
        optionsBuilder_ = null;
      }

      return this;
    }
    /**
     *

     * OPTIONAL: A `GetPolicyOptions` object for specifying options to
     * `GetIamPolicy`. This field is only used by Cloud IAM.
     *

     *
     * .google.iam.v1.GetPolicyOptions options = 2;
     */
    public GetPolicyOptions.Builder getOptionsBuilder() {

      onChanged();
      return getOptionsFieldBuilder().getBuilder();
    }
    /**
     *

     * OPTIONAL: A `GetPolicyOptions` object for specifying options to
     * `GetIamPolicy`. This field is only used by Cloud IAM.
     *

     *
     * .google.iam.v1.GetPolicyOptions options = 2;
     */
    public com.google.iam.v1.GetPolicyOptionsOrBuilder getOptionsOrBuilder() {
      if (optionsBuilder_ != null) {
        return optionsBuilder_.getMessageOrBuilder();
      } else {
        return options_ == null ?
            GetPolicyOptions.getDefaultInstance() : options_;
      }
    }
    /**
     *

     * OPTIONAL: A `GetPolicyOptions` object for specifying options to
     * `GetIamPolicy`. This field is only used by Cloud IAM.
     *

     *
     * .google.iam.v1.GetPolicyOptions options = 2;
     */
    private com.google.protobuf.SingleFieldBuilderV3<
        GetPolicyOptions, GetPolicyOptions.Builder, com.google.iam.v1.GetPolicyOptionsOrBuilder>
        getOptionsFieldBuilder() {
      if (optionsBuilder_ == null) {
        optionsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
            GetPolicyOptions, GetPolicyOptions.Builder, com.google.iam.v1.GetPolicyOptionsOrBuilder>(
                getOptions(),
                getParentForChildren(),
                isClean());
        options_ = null;
      }
      return optionsBuilder_;
    }
    @Override
    public final Builder setUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.setUnknownFields(unknownFields);
    }

    @Override
    public final Builder mergeUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.mergeUnknownFields(unknownFields);
    }

    // @@protoc_insertion_point(builder_scope:google.iam.v1.GetIamPolicyRequest)
  }

  // @@protoc_insertion_point(class_scope:google.iam.v1.GetIamPolicyRequest)
  private static final GetIamPolicyRequest DEFAULT_INSTANCE;
  static {
    DEFAULT_INSTANCE = new GetIamPolicyRequest();
  }

  public static GetIamPolicyRequest getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final com.google.protobuf.Parser<GetIamPolicyRequest>
      PARSER = new com.google.protobuf.AbstractParser<GetIamPolicyRequest>() {
    @Override
    public GetIamPolicyRequest parsePartialFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return new GetIamPolicyRequest(input, extensionRegistry);
    }
  };

  public static com.google.protobuf.Parser<GetIamPolicyRequest> parser() {
    return PARSER;
  }

  @Override
  public com.google.protobuf.Parser<GetIamPolicyRequest> getParserForType() {
    return PARSER;
  }

  @Override
  public GetIamPolicyRequest getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SteamKit2;

namespace SteamIrcBot
{
    class PackageInfoCommand : Command<PackageInfoCommand.Request>
    {
        public class Request : BaseRequest
        {
            public JobID JobID { get; set; }

            public uint PackageID { get; set; }
        }

        public PackageInfoCommand()
        {
            Triggers.Add( "!packageinfo" );
            HelpText = "!packageinfo <packageid> - Requests package info for a given PackageID, and serves it";

            Steam.Instance.CallbackManager.Subscribe<SteamApps.PICSProductInfoCallback>( OnProductInfo );
        }

        protected override void OnRun( CommandDetails details )
        {
            if ( !Settings.Current.IsWebEnabled )
            {
                IRC.Instance.Send( details.Channel, "{0}: Web support is disabled", details.Sender.Nickname );
                return;
            }

            if ( details.Args.Length == 0 )
            {
                IRC.Instance.Send( details.Channel, "{0}: PackageID argument required", details.Sender.Nickname );
                return;
            }

            uint packageId;
            if ( !uint.TryParse( details.Args[ 0 ], out packageId ) )
            {
                IRC.Instance.Send( details.Channel, "{0}: Invalid PackageID", details.Sender.Nickname );
                return;
            }

            if ( !Steam.Instance.Connected )
            {
                IRC.Instance.Send( details.Channel, details.Sender.Nickname + ": Unable to request package info: not connected to Steam!" );
                return;
            }

            var jobId = Steam.Instance.Apps.PICSGetProductInfo( null, packageId, false, false );
            AddRequest( details, new Request { JobID = jobId, PackageID = packageId } );
        }

        void OnProductInfo( SteamApps.PICSProductInfoCallback callback )
        {
            if ( callback.ResponsePending )
                return;

            var req = GetRequest( r => r.JobID == callback.JobID );

            if ( req == null )
                return;

            bool isUnknownPackage = callback.UnknownPackages.Contains( req.PackageID ) || !callback.Packages.ContainsKey( req.PackageID );

            if ( isUnknownPackage )
            {
                IRC.Instance.Send( req.Channel, "{0}: Unable to request package info for {1}: unknown PackageID", req.Requester.Nickname, req.PackageID );
                return;
            }

            var packageInfo = callback.Packages[ req.PackageID ];
            var kv = packageInfo.KeyValues.Children
                .FirstOrDefault(); // sigh, inconsistencies

            var path = Path.Combine( "packageinfo", string.Format( "{0}.vdf", req.PackageID ) );
            var fsPath = Path.Combine( Settings.Current.WebPath, path );

            var webUri = new Uri( new Uri( Settings.Current.WebURL ), path );

            try
            {
                kv.SaveToFile( fsPath, false );
            }
            catch ( IOException ex )
            {
                IRC.Instance.Send( req.Channel, "{0}: Unable to save package info for {1} to web path!", req.Requester.Nickname, req.PackageID );
                Log.WriteError( "PackageInfoCommand", "Unable to save package info for {0} to web path: {1}", req.PackageID, ex );

                return;
            }

            IRC.Instance.Send( req.Channel, "{0}: {1} {2}", req.Requester.Nickname, webUri, packageInfo.MissingToken ? "(requires token)" : "" );
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
get "/deck/:id/card/new" do
  @deck = Deck.find_by(id: params[:id])
  @add_card = true
  erb :"deck/create_deck"
end

post "/deck/:id/card/new" do
  @deck = Deck.find_by(id: params[:id])
  @deck.update_cards(params[:cards]) if params[:cards]
  redirect "/deck/#{@deck.id}/card/new"
end


text:
#pragma once

#include <pdal/plang/Invocation.hpp>
#include <pdal/PointView.hpp>

namespace pdal
{
namespace plang
{

class PDAL_DLL BufferedInvocation : public Invocation
{
public:
    BufferedInvocation(const Script& script);

    void begin(PointView& view);
    void end(PointView& view);

private:
    std::vector<void *> m_buffers;
    BufferedInvocation& operator=(BufferedInvocation const& rhs); // nope
};

} // namespace plang
} // namespace pdal


text:
module ActiveRecord
  class BaseWithoutTable < Base
    self.abstract_class = true

    def create_or_update
      errors.empty?
    end

    class << self

      def inherited(klass)
        columns_hash.each do |name, column|
          klass.columns << column unless klass.column_names.include(name)
        end
      end

      def columns()
        @columns ||= []
      end

      def column(name, sql_type = nil, default = nil, null = true)
        columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
        reset_column_information
      end

      # Do not reset @columns
      def reset_column_information
        generated_methods.each { |name| undef_method(name) }
        @column_names = @columns_hash = @content_columns = @dynamic_methods_hash = @read_methods = nil
      end
    end
  end
end


text:
package com.jfilowk.teamfactory.datasource.entities;

import java.io.Serializable;

/**
 * Created by Javi on 21/09/14.
 */
public class RandomUser implements Serializable {

  int id;
  String firstName;
  String lastName;
  String gender;
  String picture;
  String seed;
  int team_id;
  String created_at;

  public RandomUser() {

  }

  public RandomUser(int id, String firstName, String lastName, String gender, String picture,
      String seed, int team_id, String created_at) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.gender = gender;
    this.picture = picture;
    this.seed = seed;
    this.team_id = team_id;
    this.created_at = created_at;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getGender() {
    return gender;
  }

  public void setGender(String gender) {
    this.gender = gender;
  }

  public String getPicture() {
    return picture;
  }

  public void setPicture(String picture) {
    this.picture = picture;
  }

  public String getSeed() {
    return seed;
  }

  public void setSeed(String seed) {
    this.seed = seed;
  }

  public int getTeam_id() {
    return team_id;
  }

  public void setTeam_id(int team_id) {
    this.team_id = team_id;
  }

  public String getCreated_at() {
    return created_at;
  }

  public void setCreated_at(String created_at) {
    this.created_at = created_at;
  }
}


text:
Hello! Thank you for choosing to help contribute to one of the Twilio SendGrid open-source libraries. There are many ways you can contribute and help is always welcome.  We simply ask that you follow the following contribution policies.

**All third-party contributors acknowledge that any contributions they provide will be made under the same open-source license that the open-source project is provided under.**
- [Improvements to the Codebase](#improvements-to-the-codebase)
  - [Development Environment](#development-environment)
    - [Install and Run Locally](#install-and-run-locally)
      - [Prerequisites](#prerequisites)
      - [Initial setup:](#initial-setup)
  - [Environment Variables](#environment-variables)
      - [Execute:](#execute)
- [Understanding the Code Base](#understanding-the-code-base)
- [Testing](#testing)
- [Style Guidelines & Naming Conventions](#style-guidelines--naming-conventions)
- [Creating a Pull Request](#creating-a-pull-request)
- [Code Reviews](#code-reviews)

There are a few ways to contribute, which we'll enumerate below:

## Improvements to the Codebase

We welcome direct contributions to the sendgrid-ruby code base. Thank you!

### Development Environment ###

#### Install and Run Locally ####

##### Prerequisites #####

- Ruby 2.1+
- [ruby_http_client](https://github.com/sendgrid/ruby-http-client)

##### Initial setup: #####

1. Clone the project

   ```bash
   git clone https://github.com/sendgrid/sendgrid-ruby.git
   cd sendgrid-ruby
   ```

1. Install bundler and bundle

   ```bash
   bundle install
   ```

### Environment Variables

First, get your free Twilio SendGrid account [here](https://sendgrid.com/free?source=sendgrid-ruby).

Next, update your environment with your [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys).

```bash
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
```

##### Execute: #####

See the [examples folder](examples) to get started quickly.

To run the examples using the local version of this library from the root directory of this repo, please replace:

`require 'sendgrid-ruby'`

with:

`require_relative './lib/sendgrid-ruby.rb'`

Then run using:

```bash
ruby example.rb
```

## Understanding the Code Base

**/examples**

Working examples that demonstrate usage.

**/test**

Tests for the mail send and Web API v3 endpoints.

**/lib**

The Web API v3 client is `sendgrid-ruby.rb`

## Testing

All PRs require passing tests before the PR will be reviewed. All test files are in the [`tests`](test) directory. For the purposes of contributing to this repo, please update the [`test_sendgrid-ruby.rb`](test/sendgrid/test_sendgrid-ruby.rb) file with unit tests as you modify the code.

The integration tests require a Twilio SendGrid mock API in order to execute. We've simplified setting this up using Docker to run the tests. You will just need [Docker Desktop](https://docs.docker.com/get-docker/) and `make`.

Once these are available, simply execute the Docker test target to run all tests: `make test-docker`. This command can also be used to open an interactive shell into the container where this library is installed. To start a *bash* shell for example, use this command: `command=bash make test-docker`.

## Style Guidelines & Naming Conventions

Generally, we follow the style guidelines as suggested by the official language. However, we ask that you conform to the styles that already exist in the library. If you wish to deviate, please explain your reasoning.

- [Community Driven Style Guide](https://github.com/bbatsov/ruby-style-guide)

Please run your code through:

- [rubocop](https://github.com/bbatsov/rubocop).

## Creating a Pull Request

1. [Fork](https://help.github.com/fork-a-repo/) the project, clone your fork,
   and configure the remotes:

   ```bash
   # Clone your fork of the repo into the current directory
   git clone https://github.com/sendgrid/sendgrid-ruby

   # Navigate to the newly cloned directory
   cd sendgrid-ruby

   # Assign the original repo to a remote called "upstream"
   git remote add upstream https://github.com/sendgrid/sendgrid-ruby
   ```

2. If you cloned a while ago, get the latest changes from upstream:

   ```bash
   git checkout <dev-branch>
   git pull upstream <dev-branch>
   ```

3. Create a new topic branch (off the main project development branch) to
   contain your feature, change, or fix:

   ```bash
   git checkout -b <topic-branch-name>
   ```

4. Commit your changes in logical chunks. Please adhere to these [git commit
   message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
   or your code is unlikely to be merged into the main project. Use Git's
   [interactive rebase](https://help.github.com/articles/interactive-rebase)
   feature to tidy up your commits before making them public.

4a. Create tests.

4b. Create or update the example code that demonstrates the functionality of this change to the code.

5. Locally merge (or rebase) the upstream development branch into your topic branch:

   ```bash
   git pull [--rebase] upstream main
   ```

6. Push your topic branch up to your fork:

   ```bash
   git push origin <topic-branch-name>
   ```

7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
    with a clear title and description against the `main` branch. All tests must be passing before we will review the PR.

## Code Reviews

If you can, please look at open PRs and review them. Give feedback and help us merge these PRs much faster! If you don't know how, Github has some [great information on how to review a Pull Request](https://help.github.com/articles/about-pull-request-reviews/).


text:
package org.jetbrains.plugins.textmate.editor;

import com.intellij.codeInsight.highlighting.BraceMatchingUtil;
import com.intellij.openapi.application.ReadAction;
import org.jetbrains.plugins.textmate.TextMateAcceptanceTestCase;

public class TextMateBraceMatcherTest extends TextMateAcceptanceTestCase {
  public void testBracesInLatex() {
    myFixture.configureByText("text.tex", "\\setlength<caret>{\\parskip}");
    assertEquals(19, getMatchedOffset());
  }

  public void testMatchingInInjectedCode() {
    myFixture.configureByText("text.md_hack", "<caret>
Paragraph
");
    assertEquals(8, getMatchedOffset());
  }

  public void testJsx() {
    myFixture.configureByText("text.jsx_hack", "foo() {<caret> return
Paragraph
;}");
    assertEquals(32, getMatchedOffset());
  }

  public void testJsxTags() {
    myFixture.configureByText("text.jsx_hack", "foo() { return <caret>
Paragraph
;}");
    assertEquals(17, getMatchedOffset());
  }

  public void testBrackets() {
    myFixture.configureByText("text.md_hack", "<caret>[link](url)");
    assertEquals(5, getMatchedOffset());
  }

  private int getMatchedOffset() {
    return ReadAction
      .compute(() -> BraceMatchingUtil.getMatchedBraceOffset(myFixture.getEditor(), true, myFixture.getFile()));
  }
}


text:
package wizard

import (
	"encoding/json"
	"fmt"
	log "github.com/Sirupsen/logrus"
	"github.com/flexiant/concerto/api/types"
	"github.com/flexiant/concerto/utils"
)

// AppService manages app operations
type AppService struct {
	concertoService utils.ConcertoService
}

// NewAppService returns a Concerto app service
func NewAppService(concertoService utils.ConcertoService) (*AppService, error) {
	if concertoService == nil {
		return nil, fmt.Errorf("Must initialize ConcertoService before using it")
	}

	return &AppService{
		concertoService: concertoService,
	}, nil
}

// GetAppList returns the list of apps as an array of App
func (as *AppService) GetAppList() (apps []types.WizardApp, err error) {
	log.Debug("GetAppList")

	data, status, err := as.concertoService.Get("/v1/wizard/apps")
	if err != nil {
		return nil, err
	}

	if err = utils.CheckStandardStatus(status, data); err != nil {
		return nil, err
	}

	if err = json.Unmarshal(data, &apps); err != nil {
		return nil, err
	}

	return apps, nil
}

// DeployApp deploys a app
func (as *AppService) DeployApp(appVector *map[string]interface{}) (app *types.WizardApp, err error) {
	log.Debug("DeployApp")

	data, status, err := as.concertoService.Post("/v1/wizard/apps/", appVector)
	if err != nil {
		return nil, err
	}

	if err = utils.CheckStandardStatus(status, data); err != nil {
		return nil, err
	}

	if err = json.Unmarshal(data, &app); err != nil {
		return nil, err
	}

	return app, nil
}


text:
// <copyright file="Parameter.cs" company="Techyian">
// Copyright (c) Ian Auty and contributors. All rights reserved.
// Licensed under the MIT License. Please see LICENSE.txt for License info.
// </copyright>

using System;

namespace MMALSharp
{
    internal class Parameter
    {
        public Parameter(int paramVal, Type paramType, string paramName)
        {
            this.ParamValue = paramVal;
            this.ParamType = paramType;
            this.ParamName = paramName;
        }

        public int ParamValue { get; set; }

        public Type ParamType { get; set; }

        public string ParamName { get; set; }
    }
}


text:
{% load hq_shared_tags %}
{% load report_tags %}
{% load i18n %}

 {% trans "Go to All Invoices page for this Project Space" %}

     {% trans "Export to Excel" %}

            {{ headers.render_html|safe }}

        {% block tabular-body %}
        {% for row in rows %}

                {% for col in row %}
                    {% include 'reports/async/partials/tabular_cell.html' %}
                {% endfor %}

        {% endfor %}
        {% endblock %}


text:
layout: post
title:  "VR Graphics"
date:   2017-02-27 19:00 -0000
categories: software update
---

For the past couple weeks the software part of the project entered its major design phase. Part of this effort is the graphics for the virtual reality system. For budget reasons, the VR hardware used for the project is the Google cardboard.

The backbone of the system is the Google view Java API, with the graphics drawn in OpenGL. This required a bit of overhead work to get the system drawing. We created an Android program for loading asset files, starting the OpenGL call into the game object, and some shaders to do the drawing work. But now that that has finished we can start sharing what the VR environment will look like.

![Development screenshot]({{ site.url }}/assets/image/gr1.png)

First fully functional rendering.

As you can see, it is a humble start. But the objects are clearly being drawn and respond to the user moving their head. The graphic style is a cell shaded look. This is in part to create a lighthearted environment for the user and to save on graphic asset development.

![Development screenshot]({{ site.url }}/assets/image/gr2.png)

Looking a little more familiar.

Later, some of the assets are replaced with more complete versions, and the lighting shaders get a much needed update.

![Development screenshot]({{ site.url }}/assets/image/gr3.png)

Outdoor lighting.

The simple shader is then replaced with a three part outdoor lighting shader. One light for the sun, sky, and ground. However the sky itself looks a little off and the fog takes on a somewhat toxic yellow colour.

![Development screenshot]({{ site.url }}/assets/image/gr4.png)

The sky's the limit

This last update replaces the shy and fog. the fog is made more white and burns off to meet the sky and the sun is painted onto the sky. Notice the simulated diffraction on the of the light around the sun.

The graphics still need more game assets and code to move, but things are advancing at an encouraging pace.


text:
using content::WebContents;

RenderProcessHostTest::RenderProcessHostTest() {
  EnableDOMAutomation();
}

int RenderProcessHostTest::RenderProcessHostCount() {
  content::RenderProcessHost::iterator hosts =
      content::RenderProcessHost::AllHostsIterator();
  int count = 0;
  while (!hosts.IsAtEnd()) {
    if (hosts.GetCurrentValue()->HasConnection())
      count++;
    hosts.Advance();
  }
  return count;
}

void PostQuit(MessageLoop* loop) {
  loop->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}

// Show a tab, activating the current one if there is one, and wait for
// the renderer process to be created or foregrounded, returning the process
// handle.
base::ProcessHandle RenderProcessHostTest::ShowSingletonTab(const GURL& page) {
  browser()->ShowSingletonTab(page);
  WebContents* wc = browser()->GetSelectedWebContents();
  CHECK(wc->GetURL() == page);

  // Ensure that the backgrounding / foregrounding gets a chance to run.
  content::BrowserThread::PostTaskAndReply(
      content::BrowserThread::PROCESS_LAUNCHER, FROM_HERE,
      base::Bind(&base::DoNothing), MessageLoop::QuitClosure());
  MessageLoop::current()->Run();

  return wc->GetRenderProcessHost()->GetHandle();
}

IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, ProcessPerTab) {
  // Set max renderers to 1 to force running out of processes.
  content::RenderProcessHost::SetMaxRendererProcessCountForTest(1);

  CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
  parsed_command_line.AppendSwitch(switches::kProcessPerTab);

  int tab_count = 1;
  int host_count = 1;

#if defined(USE_VIRTUAL_KEYBOARD)
  ++host_count;  // For the virtual keyboard.
#endif

  // Change the first tab to be the new tab page (TYPE_WEBUI).
  GURL newtab(chrome::kTestNewTabURL);
  ui_test_utils::NavigateToURL(browser(), newtab);
  EXPECT_EQ(tab_count, browser()->tab_count());
  EXPECT_EQ(host_count, RenderProcessHostCount());

  // Create a new TYPE_TABBED tab.  It should be in its own process.
  GURL page1("data:text/html,hello world1");
  browser()->ShowSingletonTab(page1);
  if (browser()->tab_count() == tab_count)
    ui_test_utils::WaitForNewTab(browser());
  tab_count++;
  host_count++;
  EXPECT_EQ(tab_count, browser()->tab_count());
  EXPECT_EQ(host_count, RenderProcessHostCount());

  // Create another TYPE_TABBED tab.  It should share the previous process.
  GURL page2("data:text/html,hello world2");
  browser()->ShowSingletonTab(page2);
  if (browser()->tab_count() == tab_count)
    ui_test_utils::WaitForNewTab(browser());
  tab_count++;
  EXPECT_EQ(tab_count, browser()->tab_count());
  EXPECT_EQ(host_count, RenderProcessHostCount());

  // Create another new tab.  It should share the process with the other WebUI.
  browser()->NewTab();
  if (browser()->tab_count() == tab_count)
    ui_test_utils::WaitForNewTab(browser());
  tab_count++;
  EXPECT_EQ(tab_count, browser()->tab_count());
  EXPECT_EQ(host_count, RenderProcessHostCount());

  // Create another new tab.  It should share the process with the other WebUI.
  browser()->NewTab();
  if (browser()->tab_count() == tab_count)
    ui_test_utils::WaitForNewTab(browser());
  tab_count++;
  EXPECT_EQ(tab_count, browser()->tab_count());
  EXPECT_EQ(host_count, RenderProcessHostCount());
}

// We don't change process priorities on Mac or Posix because the user lacks the
// permission to raise a process' priority even after lowering it.
#if defined(OS_WIN) || defined(OS_LINUX)
IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, Backgrounding) {
  if (!base::Process::CanBackgroundProcesses()) {
    LOG(ERROR) << "Can't background processes";
    return;
  }
  CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
  parsed_command_line.AppendSwitch(switches::kProcessPerTab);

  // Change the first tab to be the new tab page (TYPE_WEBUI).
  GURL newtab(chrome::kTestNewTabURL);
  ui_test_utils::NavigateToURL(browser(), newtab);

  // Create a new tab. It should be foreground.
  GURL page1("data:text/html,hello world1");
  base::ProcessHandle pid1 = ShowSingletonTab(page1);
  EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded());

  // Create another tab. It should be foreground, and the first tab should
  // now be background.
  GURL page2("data:text/html,hello world2");
  base::ProcessHandle pid2 = ShowSingletonTab(page2);
  EXPECT_NE(pid1, pid2);
  EXPECT_TRUE(base::Process(pid1).IsProcessBackgrounded());
  EXPECT_FALSE(base::Process(pid2).IsProcessBackgrounded());

  // Navigate back to first page. It should be foreground again, and the second
  // tab should be background.
  EXPECT_EQ(pid1, ShowSingletonTab(page1));
  EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded());
  EXPECT_TRUE(base::Process(pid2).IsProcessBackgrounded());
}
#endif

// When we hit the max number of renderers, verify that the way we do process
// sharing behaves correctly.  In particular, this test is verifying that even
// when we hit the max process limit, that renderers of each type will wind up
// in a process of that type, even if that means creating a new process.
IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, ProcessOverflow) {
  // Set max renderers to 1 to force running out of processes.
  content::RenderProcessHost::SetMaxRendererProcessCountForTest(1);

  int tab_count = 1;
  int host_count = 1;
  WebContents* tab1 = NULL;
  WebContents* tab2 = NULL;
  content::RenderProcessHost* rph1 = NULL;
  content::RenderProcessHost* rph2 = NULL;
  content::RenderProcessHost* rph3 = NULL;

#if defined(USE_VIRTUAL_KEYBOARD)
  ++host_count;  // For the virtual keyboard.
#endif

  // Change the first tab to be the new tab page (TYPE_WEBUI).
  GURL newtab(chrome::kTestNewTabURL);
  ui_test_utils::NavigateToURL(browser(), newtab);
  EXPECT_EQ(tab_count, browser()->tab_count());
  tab1 = browser()->GetWebContentsAt(tab_count - 1);
  rph1 = tab1->GetRenderProcessHost();
  EXPECT_EQ(tab1->GetURL(), newtab);
  EXPECT_EQ(host_count, RenderProcessHostCount());

  // Create a new TYPE_TABBED tab.  It should be in its own process.
  GURL page1("data:text/html,hello world1");
  browser()->ShowSingletonTab(page1);
  if (browser()->tab_count() == tab_count)
    ui_test_utils::WaitForNewTab(browser());
  tab_count++;
  host_count++;
  EXPECT_EQ(tab_count, browser()->tab_count());
  tab1 = browser()->GetWebContentsAt(tab_count - 1);
  rph2 = tab1->GetRenderProcessHost();
  EXPECT_EQ(tab1->GetURL(), page1);
  EXPECT_EQ(host_count, RenderProcessHostCount());
  EXPECT_NE(rph1, rph2);

  // Create another TYPE_TABBED tab.  It should share the previous process.
  GURL page2("data:text/html,hello world2");
  browser()->ShowSingletonTab(page2);
  if (browser()->tab_count() == tab_count)
    ui_test_utils::WaitForNewTab(browser());
  tab_count++;
  EXPECT_EQ(tab_count, browser()->tab_count());
  tab2 = browser()->GetWebContentsAt(tab_count - 1);
  EXPECT_EQ(tab2->GetURL(), page2);
  EXPECT_EQ(host_count, RenderProcessHostCount());
  EXPECT_EQ(tab2->GetRenderProcessHost(), rph2);

  // Create another TYPE_WEBUI tab.  It should share the process with newtab.
  // Note: intentionally create this tab after the TYPE_TABBED tabs to exercise
  // bug 43448 where extension and WebUI tabs could get combined into normal
  // renderers.
  GURL history(chrome::kTestHistoryURL);
  browser()->ShowSingletonTab(history);
  if (browser()->tab_count() == tab_count)
    ui_test_utils::WaitForNewTab(browser());
  tab_count++;
  EXPECT_EQ(tab_count, browser()->tab_count());
  tab2 = browser()->GetWebContentsAt(tab_count - 1);
  EXPECT_EQ(tab2->GetURL(), history);
  EXPECT_EQ(host_count, RenderProcessHostCount());
  EXPECT_EQ(tab2->GetRenderProcessHost(), rph1);

  // Create a TYPE_EXTENSION tab.  It should be in its own process.
  // (the bookmark manager is implemented as an extension)
  GURL bookmarks(chrome::kTestBookmarksURL);
  browser()->ShowSingletonTab(bookmarks);
  if (browser()->tab_count() == tab_count)
    ui_test_utils::WaitForNewTab(browser());
  tab_count++;
#if !defined(USE_VIRTUAL_KEYBOARD)
  // The virtual keyboard already creates an extension process. So this
  // should not increase the process count.
  host_count++;
#endif
  EXPECT_EQ(tab_count, browser()->tab_count());
  tab1 = browser()->GetWebContentsAt(tab_count - 1);
  rph3 = tab1->GetRenderProcessHost();
  EXPECT_EQ(tab1->GetURL(), bookmarks);
  EXPECT_EQ(host_count, RenderProcessHostCount());
  EXPECT_NE(rph1, rph3);
  EXPECT_NE(rph2, rph3);
}


text:
namespace content {

UIResourceProviderImpl::UIResourceProviderImpl()
    : system_ui_resource_manager_(this), host_(NULL) {
}

UIResourceProviderImpl::~UIResourceProviderImpl() {
  SetLayerTreeHost(NULL);
}

void UIResourceProviderImpl::SetLayerTreeHost(cc::LayerTreeHost* host) {
  if (host_ == host)
    return;
  host_ = host;
  UIResourcesAreInvalid();
}

void UIResourceProviderImpl::UIResourcesAreInvalid() {
  UIResourceClientMap client_map = ui_resource_client_map_;
  ui_resource_client_map_.clear();
  for (UIResourceClientMap::iterator iter = client_map.begin();
       iter != client_map.end();
       iter++) {
    iter->second->UIResourceIsInvalid();
  }
}

cc::UIResourceId UIResourceProviderImpl::CreateUIResource(
    UIResourceClientAndroid* client) {
  if (!host_)
    return 0;
  cc::UIResourceId id = host_->CreateUIResource(client);
  DCHECK(ui_resource_client_map_.find(id) == ui_resource_client_map_.end());

  ui_resource_client_map_[id] = client;
  return id;
}

void UIResourceProviderImpl::DeleteUIResource(cc::UIResourceId ui_resource_id) {
  UIResourceClientMap::iterator iter =
      ui_resource_client_map_.find(ui_resource_id);
  DCHECK(iter != ui_resource_client_map_.end());

  ui_resource_client_map_.erase(iter);

  if (!host_)
    return;
  host_->DeleteUIResource(ui_resource_id);
}

ui::SystemUIResourceManager&
UIResourceProviderImpl::GetSystemUIResourceManager() {
  return system_ui_resource_manager_;
}

}  // namespace content


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

namespace Peregrine.Data
{
	[System.Diagnostics.DebuggerDisplay("Tournament {Key}")]
	public class Tournament
	{
		public virtual int Id { get; set; }
		public virtual Guid Key { get; set; }
		public virtual string Name { get; set; }
		public virtual int Seed { get; set; }
		public virtual int? ActiveRoundNumber { get; set; }
		public virtual ICollection<Player> Players { get; set; }
		public virtual ICollection<ApplicationUser> Organizers { get; set; }
		public virtual ICollection<Round> Rounds { get; set; }
	}
}


text:
using System;
using Android.Content;
using Android.Util;
using Android.Runtime;
using Android.Widget;

namespace FFImageLoading.Views
{
    [Preserve(AllMembers = true)]
    [Register("ffimageloading.views.ImageViewAsync")]
	[Obsolete("You can now use Android's ImageView")]
    public class ImageViewAsync : ImageView
    {
        private bool _customFit;

        public ImageViewAsync(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
        {
        }

        public ImageViewAsync(Context context) : base(context)
        {
        }

        public ImageViewAsync(Context context, IAttributeSet attrs) : base(context, attrs)
        {
        }

        public ImageViewAsync(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
        {
        }

		public void CancelLoading()
		{
			ImageService.Instance.CancelWorkForView(this);
		}

		private bool _scaleToFit;
        /// <summary>
        /// Gets or sets a value if the image should be scale to fit in the available space keeping aspect ratio.
        /// <remarks>AdjustViewToBounds should be false and ScaleType should be matrix.</remarks>
        /// </summary>
        public bool ScaleToFit
        {
            get => _scaleToFit;
            set
            {
                _customFit = true;
                _scaleToFit = value;
                SetAdjustViewBounds(false);
                SetScaleType(ScaleType.Matrix);
            }
        }

        private AlignMode _bottomAlign;
        /// <summary>
        /// Gets or sets a value if the image should be aligned to left and bottom in the available space.
        /// <remarks>AdjustViewToBounds should be false and ScaleType should be matrix.</remarks>
        /// </summary>
        public AlignMode AlignMode
        {
            get => _bottomAlign;
            set
            {
                _customFit = true;
                _bottomAlign = value;
                SetAdjustViewBounds(false);
                SetScaleType(ScaleType.Matrix);
            }
        }

        /* FMT: this is not fine when working with RecyclerView... It can detach and cache the view, then reattach it
        protected override void OnDetachedFromWindow()
        {
            CancelLoading();
            base.OnDetachedFromWindow();
        }*/

        protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            if (_customFit && Drawable == null)
            {
                SetMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
            }
            else
            {
                base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
            }
        }

        protected override bool SetFrame(int l, int t, int r, int b)
        {
            if (_customFit && Drawable != null && Drawable.IntrinsicWidth != 0)
            {
                var bottomAlignmentDefined = AlignMode != AlignMode.None;
                if (ScaleToFit || bottomAlignmentDefined)
                {
                    var matrix = ImageMatrix;
                    var scaleFactor = 1f;

                    if (ScaleToFit)
                    {
                        var scaleFactorWidth = (float)Width / Drawable.IntrinsicWidth;
                        var scaleFactorHeight = (float)Height / Drawable.IntrinsicHeight;

                        if (scaleFactorHeight < scaleFactorWidth)
                        {
                            scaleFactor = scaleFactorHeight;
                        }
                        else
                        {
                            scaleFactor = scaleFactorWidth;
                        }

                        if (Math.Abs(scaleFactor - 1f) > float.Epsilon)
                        {
                            matrix.SetScale(scaleFactor, scaleFactor, 0, 0);
                        }
                    }

                    if (AlignMode != AlignMode.None)
                    {
                        if (AlignMode != AlignMode.TopCenter && Height - (Drawable.IntrinsicHeight * scaleFactor) > 0)
                        {
                            //align to the bottom
                            matrix.PostTranslate(0, Height - (Drawable.IntrinsicHeight * scaleFactor));
                        }

                        if (Width - (Drawable.IntrinsicWidth * scaleFactor) > 0)
                        {
                            switch (AlignMode)
                            {
                                case AlignMode.BottomLeft:
                                    //by default is aligned to the left
                                    break;
                                case AlignMode.BottomCenter:
                                    matrix.PostTranslate((Width - (Drawable.IntrinsicWidth * scaleFactor)) / 2, 0);
                                    break;
                                case AlignMode.BottomRight:
                                    matrix.PostTranslate(Width - (Drawable.IntrinsicWidth * scaleFactor), 0);
                                    break;
                                case AlignMode.TopCenter:
                                    matrix.PostTranslate((Width - (Drawable.IntrinsicWidth * scaleFactor)) / 2, 0);
                                    break;
                            }
                        }

                    }

                    ImageMatrix = matrix;
                }
            }

            return base.SetFrame(l, t, r, b);
        }
    }

    public enum AlignMode
    {
        None,
        TopCenter,
        BottomLeft,
        BottomCenter,
        BottomRight
    }
}


text:
@implementation HDBookViewCell

@end


text:
package org.apache.carbondata.common.logging.impl;

import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.log4j.Level;
import org.apache.log4j.RollingFileAppender;
import org.apache.log4j.helpers.CountingQuietWriter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

/**
 * Copied from log4j to remove the hard coding for the file name from it Copied
 * form log4j and modified for renaming files
 */
public class ExtendedRollingFileAppender extends RollingFileAppender {

  private static final String DATE_FORMAT_FOR_TRANSFER = "yyyy-MM-dd'_'HH-mm-ss";
  protected int currentLevel = Level.FATAL_INT;
  /**
   * Now in log file rolling(after file size
   * exceeded the threshold) and deletion (after file count exceeded the file
   * count threshold) it will print log message
   */

  private long nextRollover = 0;
  private volatile boolean cleanupInProgress = false;

  /**
   * Total number of files at any point of time should be Backup number of
   * files + current file
   */
  private static void cleanLogs(final String startName, final String folderPath,
      int maxBackupIndex) {
    final String fileStartName = startName.toLowerCase(Locale.US);
    // Delete the oldest file, to keep Windows happy.
    File file = new File(folderPath);

    if (file.exists()) {
      File[] files = file.listFiles(f ->
          !f.isDirectory() && f.getName().toLowerCase(Locale.US).startsWith(fileStartName));

      if (null == files) {
        return;
      }

      int backupFiles = files.length - 1;

      if (backupFiles <= maxBackupIndex) {
        return;
      }

      // Sort the file based on its name.
      TreeMap<String, File> sortedMap = new TreeMap<>();
      for (File file1 : files) {
        sortedMap.put(file1.getName(), file1);
      }

      // Remove the first log file from map. it will be <startName>.log
      // itself which will be backed up in rollover
      sortedMap.remove(sortedMap.firstKey());

      Iterator<Entry<String, File>> it = sortedMap.entrySet().iterator();
      Entry<String, File> temp;

      // After clean up the files should be maxBackupIndex -1 number of
      // files. Because one more backup file
      // will be created after this method call is over
      while (it.hasNext() && backupFiles > maxBackupIndex) {
        temp = it.next();
        File deleteFile = temp.getValue();
        // Delete the file
        // After deletion of log file it
        // will print the log message in ReportService.log
        if (deleteFile.delete()) {
          backupFiles--;
        } else {
          LogLog.error("Couldn't delete file :: " + deleteFile.getPath());
        }
      }
    }
  }

  /**
   * Copied from log4j to remove hardcoding of file name
   */
  public void rollOver() {
    File target;
    File file = new File(fileName);

    String fileStartName = file.getName();
    int dotIndex = fileStartName.indexOf('.');

    if (dotIndex != -1) {
      fileStartName = fileStartName.substring(0, dotIndex);
    }
    final String startName = fileStartName;
    final String folderPath = file.getParent();

    if (qw != null) {
      long size = ((CountingQuietWriter) qw).getCount();
      LogLog.debug("rolling over count=" + size);
      // if operation fails, do not roll again until
      // maxFileSize more bytes are written
      nextRollover = size + maxFileSize;
    }

    LogLog.debug("maxBackupIndex=" + maxBackupIndex);

    boolean renameSucceeded = true;

    // If maxBackups <= 0, then there is no file renaming to be done.
    if (maxBackupIndex > 0) {
      DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_FOR_TRANSFER);

      StringBuilder buffer = new StringBuilder();
      String extension = "";
      if (fileName.contains(".")) {
        extension = fileName.substring(fileName.lastIndexOf("."));
        buffer.append(fileName, 0, fileName.lastIndexOf("."));
      } else {
        buffer.append(fileName);
      }
      buffer.append("_").append(dateFormat.format(new Date())).append(extension);
      // Rename fileName to fileName.1
      target = new File(buffer.toString());

      this.closeFile(); // keep windows happy.

      LogLog.debug("Renaming file " + file + " to " + target);
      renameSucceeded = file.renameTo(target);

      //
      // if file rename failed, reopen file with append = true
      //
      if (!renameSucceeded) {
        try {
          this.setFile(fileName, true, bufferedIO, bufferSize);
        } catch (InterruptedIOException e) {
          Thread.currentThread().interrupt();
        } catch (IOException e) {
          LogLog.error("setFile(" + fileName + ", true) call failed.", e);
        }
      }
    }

    //
    // if all renames were successful, then
    //
    if (renameSucceeded) {
      try {
        // This will also close the file. This is OK since multiple
        // close operations are safe.
        this.setFile(fileName, false, bufferedIO, bufferSize);
        nextRollover = 0;
      } catch (InterruptedIOException e) {
        Thread.currentThread().interrupt();
      } catch (IOException e) {
        LogLog.error("setFile(" + fileName + ", false) call failed.", e);
      }
    }

    // Do clean up finally
    if (!cleanupInProgress) {
      cleanUpLogs(startName, folderPath);
    }
  }

  private void cleanUpLogs(final String startName, final String folderPath) {
    if (maxBackupIndex > 0) {
      // Clean the logs files
      Runnable r = new Runnable() {

        public void run() {
          synchronized (ExtendedRollingFileAppender.class) {
            cleanupInProgress = true;
            try {
              cleanLogs(startName, folderPath, maxBackupIndex);
            } catch (Throwable e) {
              // ignore any error
              LogLog.error("Cleaning logs failed", e);
            } finally {
              cleanupInProgress = false;
            }
          }
        }
      };

      Thread t = new Thread(r);
      t.start();
    }
  }

  protected void subAppend(LoggingEvent event) {
    if (event.getLevel().toInt() <= currentLevel) {
      super.subAppend(event);
      if (fileName != null && qw != null) {
        long size = ((CountingQuietWriter) qw).getCount();
        if (size >= maxFileSize && size >= nextRollover) {
          rollOver();
        }
      }
    }
  }

}


text:
<?php
final class Encryption {
	private $key;

	public function __construct($key) {
		$this->key = hash('sha256', $key, true);
	}

	public function encrypt($value) {
		return strtr(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, hash('sha256', $this->key, true), $value, MCRYPT_MODE_ECB)), '+/=', '-_,');
	}

	public function decrypt($value) {
		return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, hash('sha256', $this->key, true), base64_decode(strtr($value, '-_,', '+/=')), MCRYPT_MODE_ECB));
	}
}


text:
    /**
     * @ngdoc service
     * @name merchello.models.invoiceStatusDisplayBuilder
     *
     * @description
     * A utility service that builds InvoiceStatusDisplay models
     */
    angular.module('merchello.models')
        .factory('invoiceStatusDisplayBuilder',
        ['genericModelBuilder', 'InvoiceStatusDisplay',
            function(genericModelBuilder, InvoiceStatusDisplay) {
                var Constructor = InvoiceStatusDisplay;
                return {
                    createDefault: function() {
                        return new Constructor();
                    },
                    transform: function(jsonResult) {
                        return genericModelBuilder.transform(jsonResult, Constructor);
                    }
                };
            }]);


text:
using FluentAssertions;
using Neutronium.Core.WebBrowserEngine.JavascriptObject;
using Xunit;

namespace Neutronium.Core.Test.WebBrowserEngine.JavascriptObject
{
    public class JavascriptNamerTest
    {
        [Theory]
        [InlineData("a", "'a'")]
        [InlineData("cat", "'cat'")]
        [InlineData(@"\", @"'\\'")]
        [InlineData("\n", @"'\n'")]
        [InlineData("\r", @"'\r'")]
        [InlineData("\b", @"'\b'")]
        [InlineData("\f", @"'\f'")]
        [InlineData("\t", @"'\t'")]
        [InlineData("'", @"'\''")]
        [InlineData(@"""", @"'\""'")]
        public void GetCreateExpression_Returns_Correct_Information(string value, string expected)
        {
            var actual = JavascriptNamer.GetCreateExpression(value);
            actual.Should().Be(expected);
        }
    }
}


text:
import numpy as np
import pandas as pd
from copy import deepcopy

def main(net):
  '''
  calculate pvalue of category closeness
  '''
  # calculate the distance between the data points within the same category and
  # compare to null distribution
  for inst_rc in ['row', 'col']:

    inst_nodes = deepcopy(net.dat['nodes'][inst_rc])

    inst_index = deepcopy(net.dat['node_info'][inst_rc]['clust'])

    # reorder based on clustered order
    inst_nodes = [ inst_nodes[i] for i in inst_index]

    # make distance matrix dataframe
    dm = dist_matrix_lattice(inst_nodes)

    node_infos = list(net.dat['node_info'][inst_rc].keys())

    all_cats = []
    for inst_info in node_infos:
      if 'dict_cat_' in inst_info:
        all_cats.append(inst_info)

    for cat_dict in all_cats:

      tmp_dict = net.dat['node_info'][inst_rc][cat_dict]

      pval_name = cat_dict.replace('dict_','pval_')
      net.dat['node_info'][inst_rc][pval_name] = {}

      for cat_name in tmp_dict:

        subset = tmp_dict[cat_name]

        inst_median = calc_median_dist_subset(dm, subset)

        hist = calc_hist_distances(dm, subset, inst_nodes)

        pval = 0

        for i in range(len(hist['prob'])):
          if i == 0:
            pval = hist['prob'][i]
          if i >= 1:
            if inst_median >= hist['bins'][i]:
              pval = pval + hist['prob'][i]

        net.dat['node_info'][inst_rc][pval_name][cat_name] = pval

def dist_matrix_lattice(names):
  from scipy.spatial.distance import pdist, squareform

  lattice_size = len(names)
  mat = np.zeros([lattice_size, 1])
  mat[:,0] = list(range(lattice_size))

  inst_dm = pdist(mat, metric='euclidean')

  inst_dm[inst_dm < 0] = float(0)

  inst_dm = squareform(inst_dm)

  df = pd.DataFrame(data=inst_dm, columns=names, index=names)

  return df

def calc_median_dist_subset(dm, subset):
  return np.median(dm[subset].loc[subset].values)

def calc_hist_distances(dm, subset, inst_nodes):
  np.random.seed(100)

  num_null = 1000
  num_points = len(subset)

  median_dist = []
  for i in range(num_null):
    tmp = np.random.choice(inst_nodes, num_points, replace=False)
    median_dist.append( np.median(dm[tmp].loc[tmp].values)  )

  tmp_dist = sorted(deepcopy(median_dist))

  median_dist = np.asarray(median_dist)
  s1 = pd.Series(median_dist)
  hist = np.histogram(s1, bins=30)

  H = {}
  H['prob'] = hist[0]/np.float(num_null)
  H['bins'] = hist[1]

  return H


text:
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../../JavaScriptSDK/Telemetry/PageVisitTimeManager.ts" />
class PageVisitTimeManagerTests extends TestClass {

    private throwInternalNonUserActionableSpy;
    private throwInternalUserActionableSpy;
    private getStorageObjectStub;

    /** Method called before the start of each test method */
    public testInitialize() {
        var storage = this.getMockStorage();
        this.getStorageObjectStub = sinon.stub(Microsoft.ApplicationInsights.Util, "_getSessionStorageObject",() => storage);

        this.throwInternalNonUserActionableSpy = sinon.spy(Microsoft.ApplicationInsights._InternalLogging, "throwInternalNonUserActionable");
        this.throwInternalUserActionableSpy = sinon.spy(Microsoft.ApplicationInsights._InternalLogging, "throwInternalUserActionable");
    }

    /** Method called after each test method has completed */
    public testCleanup() {
        this.getStorageObjectStub.restore();
        this.throwInternalNonUserActionableSpy.restore();
        this.throwInternalUserActionableSpy.restore();
    }

    public registerTests() {

        var testValues = {
            page1Name: "page1",
            page1Url: "page1Url",
            page1ViewTime: 10,

            page2Name: "page2",
            page2Url: "page2Url",
            page2ViewTime: 20,

            page3Name: "page3",
            page3Url: "page3Url",
            page3ViewTime: 30
        };

        this.testCase({
            name: "PageVisitTimeManager: When trackPreviousPageVisit is called once, the tracking delegate is not called since there are no previous pages",
            test: () => {

                //setup
                var object = { method: function () { } };
                var spy = sinon.spy(object, "method");
                var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(spy);

                //act
                pageVisitTimeManager.trackPreviousPageVisit(testValues.page1Name, testValues.page1Url);
                this.clock.tick(testValues.page1ViewTime);

                // verify
                Assert.ok(spy.notCalled, "telemetry wasn't sent");
            }
        });

        this.testCase({
            name: "PageVisitTimeManager: When trackPreviousPageVisit is called twice, the tracking delegate is called once with correct details",
            test: () => {

                //setup
                var object = { method: function () { } };
                var spy = sinon.spy(object, "method");
                var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(spy);

                //act
                pageVisitTimeManager.trackPreviousPageVisit(testValues.page1Name, testValues.page1Url);
                this.clock.tick(testValues.page1ViewTime);

                pageVisitTimeManager.trackPreviousPageVisit(testValues.page2Name, testValues.page2Url);

                // verify
                Assert.ok(spy.calledOnce, "telemetry sent once");
                Assert.ok(spy.calledWith(testValues.page1Name, testValues.page1Url, testValues.page1ViewTime));

            }
        });

        this.testCase({
            name: "PageVisitTimeManager: consecutive calls to start and stop returns expected information",
            test: () => {

                //setup
                var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(() => {});

                //act
                pageVisitTimeManager.startPageVisitTimer(testValues.page1Name, testValues.page1Url);
                this.clock.tick(testValues.page1ViewTime);
                var page1VisitData = pageVisitTimeManager.stopPageVisitTimer();

                //verify
                Assert.equal(testValues.page1Name, page1VisitData.pageName);
                Assert.equal(testValues.page1Url, page1VisitData.pageUrl);
                Assert.equal(testValues.page1ViewTime, page1VisitData.pageVisitTime);
            }
        });

        this.testCase({
            name: "PageVisitTimeManager: first call to restart returns null",
            test: () => {

                //setup
                var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(() => { });

                //act
                var nullPageData = pageVisitTimeManager.restartPageVisitTimer(testValues.page1Name, testValues.page1Url);

                //verify
                Assert.equal(null, nullPageData);

            }
        });

        this.testCase({
            name: "PageVisitTimeManager: consecutive calls to restart returns expected information",
            test: () => {

                //setup
                var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(() => { });

                //act
                pageVisitTimeManager.restartPageVisitTimer(testValues.page1Name, testValues.page1Url);
                this.clock.tick(testValues.page1ViewTime);

                var page1VisitData = pageVisitTimeManager.restartPageVisitTimer(testValues.page2Name, testValues.page2Url);

                //verify
                Assert.equal(testValues.page1Name, page1VisitData.pageName);
                Assert.equal(testValues.page1Url, page1VisitData.pageUrl);
                Assert.equal(testValues.page1ViewTime, page1VisitData.pageVisitTime);
            }
        });

        this.testCase({
            name: "PageVisitTimeManager: stopPageVisitTimer returns null if start has not been called",
            test: () => {

                //setup
                // Mock storage so this will work in all browsers for tests
                var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(() => { });

                //act
                var retval = pageVisitTimeManager.stopPageVisitTimer();
                Assert.equal(null, retval);

            }
        });

        this.testCase({
            name: "PageVisitTimeManager: startPageVisitTime fails silently if called twice without a call to stop",
            test: () => {

                //setup
                var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(() => {});

                //act
                try {
                    pageVisitTimeManager.startPageVisitTimer(testValues.page1Name, testValues.page1Url);
                    pageVisitTimeManager.startPageVisitTimer(testValues.page1Name, testValues.page1Url);
                    Assert.ok(true);

                } catch (e) {
                    Assert.ok(false);
                }

            }
        });
    }

    private getMockStorage() {
        var storage = <any>{};
        storage.getItem = (name) => storage[name];
        storage.setItem = (name, value) => (storage[name] = value);
        storage.removeItem = (name, value) => (storage[name] = undefined);
        return storage;
    }
}

new PageVisitTimeManagerTests().registerTests();


text:
package org.vash.vate.startup;

import org.vash.vate.VT;
import org.vash.vate.client.VTClient;
import org.vash.vate.console.VTConsole;
import org.vash.vate.help.VTHelpManager;
import org.vash.vate.server.VTServer;

public final class VTGraphicalStart
{
  private static String option;

  public static final void main(String[] args)
  {
    VTConsole.setLanterna(true);
    VTConsole.setGraphical(true);
    VTConsole.setRemoteIcon(true);
    //VTConsole.setCommandEcho(false);
    //VTLanternaConsole
    // VTTerminal.setSplit(true);
    if (args.length == 0)
    {
      VTConsole.initialize();
      VTConsole.setTitle("Variable-Terminal " + VT.VT_VERSION + " - Console");
      VTConsole.print("VT>Variable-Terminal " + VT.VT_VERSION + "\n" +
      "VT>Copyright (c) " + VT.VT_YEAR + " - wknishio@gmail.com\n" +
      "VT>This software is under MIT license, see license.txt!\n" +
      "VT>This software comes with no warranty, use at your own risk!\n");
      VTConsole.print("VT>Enter module(client as C or server as S, default:C):");
      if (VTConsole.isGraphical())
      {
        VTGraphicalStartDialog dialog = new VTGraphicalStartDialog(VTConsole.getFrame());
        dialog.setVisible(true);
        if (dialog.getMode() == 1)
        {
          try
          {
            VTClient client = new VTClient();
            //client.setDaemon(true);
            // client.initialize();
            // client.configure();
            client.start();
            return;
          }
          catch (Throwable e)
          {
            // e.printStackTrace();
          }
        }
        else if (dialog.getMode() == 2)
        {
          try
          {
            VTServer server = new VTServer();
            server.setDaemon(false);
            // server.initialize();
            // server.configure();
            server.start();
            return;
          }
          catch (Throwable e)
          {
            // e.printStackTrace();
          }
        }
      }
      try
      {
        option = VTConsole.readLine(true);
        if (option.toUpperCase().startsWith("S"))
        {
          VTServer server = new VTServer();
          server.setDaemon(false);
          // server.initialize();
          // server.configure();
          server.start();
        }
        else if (option != null)
        {
          VTClient client = new VTClient();
          // client.initialize();
          // client.configure();
          client.start();
        }
        else
        {
          System.exit(0);
        }
      }
      catch (Throwable e)
      {
        System.exit(0);
      }
    }
    else
    {
      int type = 0;
      for (int i = 0; i < args.length; i++)
      {
        if ("-C".equalsIgnoreCase(args[i]))
        {
          type = 1;
        }
        if ("-S".equalsIgnoreCase(args[i]))
        {
          type = 2;
        }
        if ("-D".equalsIgnoreCase(args[i]))
        {
          type = 3;
        }
        if ("-H".equalsIgnoreCase(args[i]))
        {
          type = 4;
        }
        if ("-A".equalsIgnoreCase(args[i]))
        {
          type = 5;
        }
      }
      if (type == 1)
      {
        VTClient client = new VTClient();
        try
        {
          client.parseParameters(args);
        }
        catch (Throwable e)
        {
          System.exit(-1);
        }
        // client.initialize();
        client.start();
      }
      else if (type == 2)
      {
        VTServer server = new VTServer();
        try
        {
          server.parseParameters(args);
        }
        catch (Throwable e)
        {
          System.exit(-1);
        }
        // server.initialize();
        server.setDaemon(false);
        server.start();
      }
      else if (type == 3)
      {
        VTConsole.setDaemon(true);
        VTServer server = new VTServer();
        try
        {
          server.parseParameters(args);
        }
        catch (Throwable e)
        {
          System.exit(-1);
        }
        // server.initialize();
        server.setDaemon(true);
        server.start();
      }
      else if (type == 4)
      {
        VTConsole.initialize();
        VTConsole.setTitle("Variable-Terminal " + VT.VT_VERSION + " - Console");
        // VTConsole.print(VTHelpManager.printApplicationParametersHelp());
        VTConsole.print(VTHelpManager.printGeneralModeParameterHelp());
        VTConsole.print(VTHelpManager.printConnnectionParametersHelp());
        if (VTConsole.isGraphical())
        {
          try
          {
            VTConsole.readLine();
          }
          catch (Throwable e)
          {

          }
        }
        System.exit(0);
      }
      else if (type == 5)
      {
        VTClient client = new VTClient();
        try
        {
          client.parseParameters(args);
        }
        catch (Throwable e)
        {
          System.exit(-1);
        }
        client.setDaemon(true);
        // client.initialize();
        client.start();
      }
      else
      {
        VTConsole.initialize();
        VTConsole.setTitle("Variable-Terminal " + VT.VT_VERSION + " - Console");
        VTConsole.print("VT>Variable-Terminal " + VT.VT_VERSION + "\n" +
        "VT>Copyright (c) " + VT.VT_YEAR + " - wknishio@gmail.com\n" +
        "VT>This software is under MIT license, see license.txt!\n" +
        "VT>This software comes with no warranty, use at your own risk!\n");
        VTConsole.print("VT>Enter module(client as C or server as S, default:C):");
        if (VTConsole.isGraphical())
        {
          VTGraphicalStartDialog dialog = new VTGraphicalStartDialog(VTConsole.getFrame());
          dialog.setVisible(true);
          if (dialog.getMode() == 1)
          {
            try
            {
              VTClient client = new VTClient();
              // client.initialize();
              // client.configure();
              try
              {
                client.parseParameters(args);
              }
              catch (Throwable e)
              {

              }
              client.start();
              return;
            }
            catch (Throwable e)
            {
              // e.printStackTrace();
            }
          }
          else if (dialog.getMode() == 2)
          {
            try
            {
              VTServer server = new VTServer();
              server.setDaemon(false);
              // server.initialize();
              // server.configure();
              try
              {
                server.parseParameters(args);
              }
              catch (Throwable e)
              {

              }
              server.start();
              return;
            }
            catch (Throwable e)
            {
              // e.printStackTrace();
            }
          }
        }
        try
        {
          option = VTConsole.readLine(true);
          if (option.toUpperCase().startsWith("S"))
          {
            VTServer server = new VTServer();
            server.setDaemon(false);
            try
            {
              server.parseParameters(args);
            }
            catch (Throwable e)
            {

            }
            // server.initialize();
            // server.configure();
            server.start();
          }
          else
          {
            VTClient client = new VTClient();
            try
            {
              client.parseParameters(args);
            }
            catch (Throwable e)
            {

            }
            // client.initialize();
            // client.configure();
            client.start();
          }
        }
        catch (Throwable e)
        {
          System.exit(0);
        }
      }
    }
  }
}


text:
package mock_bfd

import (
	reflect "reflect"

	gomock "github.com/golang/mock/gomock"
)

// MockSource is a mock of Source interface.
type MockSource struct {
	ctrl     *gomock.Controller
	recorder *MockSourceMockRecorder
}

// MockSourceMockRecorder is the mock recorder for MockSource.
type MockSourceMockRecorder struct {
	mock *MockSource
}

// NewMockSource creates a new mock instance.
func NewMockSource(ctrl *gomock.Controller) *MockSource {
	mock := &MockSource{ctrl: ctrl}
	mock.recorder = &MockSourceMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockSource) EXPECT() *MockSourceMockRecorder {
	return m.recorder
}

// Intn mocks base method.
func (m *MockSource) Intn(arg0 int) int {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Intn", arg0)
	ret0, _ := ret[0].(int)
	return ret0
}

// Intn indicates an expected call of Intn.
func (mr *MockSourceMockRecorder) Intn(arg0 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Intn", reflect.TypeOf((*MockSource)(nil).Intn), arg0)
}

// MockIntervalGenerator is a mock of IntervalGenerator interface.
type MockIntervalGenerator struct {
	ctrl     *gomock.Controller
	recorder *MockIntervalGeneratorMockRecorder
}

// MockIntervalGeneratorMockRecorder is the mock recorder for MockIntervalGenerator.
type MockIntervalGeneratorMockRecorder struct {
	mock *MockIntervalGenerator
}

// NewMockIntervalGenerator creates a new mock instance.
func NewMockIntervalGenerator(ctrl *gomock.Controller) *MockIntervalGenerator {
	mock := &MockIntervalGenerator{ctrl: ctrl}
	mock.recorder = &MockIntervalGeneratorMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIntervalGenerator) EXPECT() *MockIntervalGeneratorMockRecorder {
	return m.recorder
}

// Generate mocks base method.
func (m *MockIntervalGenerator) Generate(arg0, arg1 int) int {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Generate", arg0, arg1)
	ret0, _ := ret[0].(int)
	return ret0
}

// Generate indicates an expected call of Generate.
func (mr *MockIntervalGeneratorMockRecorder) Generate(arg0, arg1 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Generate", reflect.TypeOf((*MockIntervalGenerator)(nil).Generate), arg0, arg1)
}


text:
$framework = '4.0'

task default -depends MsBuild

task MsBuild {
  exec { msbuild /version }
}


text:
> see https://aka.ms/autorest

``` yaml
input-file: hidden-methods.yaml
output-artifact: code-model-v1.yaml
```

## Regular run

``` yaml
csharp:
  - output-folder: Client
```

## Hide method

``` yaml
csharp:
  - output-folder: ClientFancy
    directive:
      from: code-model-v1
      where: $.operations[*].methods[?(@["#serializedName"] == "Cowbell_Add")]
      transform: $.hidden = true
```

The directive activates the `hidden` flag for method `Cowbell_Add`.
As a result, the C# generator will mark associated methods as `internal` which can be useful to hide methods for which a convenience layer was provided.


text:
XRM.onActivate(function() {

	var ns = XRM.namespace('editable.Attribute.handlers');
	var $ = XRM.jQuery;
	var yuiSkinClass = XRM.yuiSkinClass;

	ns.text = function(attributeContainer, attributeDisplayName, attributeName, attributeValue, entityServiceUri, editCompleteCallback) {
		// Build the DOM necessary to support our UI.
		var yuiContainer = $('<div />').addClass(yuiSkinClass).appendTo(document.body);
		var dialogContainer = $('<div />').addClass('xrm-editable-panel xrm-editable-dialog').appendTo(yuiContainer);

		function completeEdit(dialog) {
			dialog.cancel();
			yuiContainer.remove();

			if ($.isFunction(editCompleteCallback)) {
				editCompleteCallback();
			}
		}

		function handleCancel(dialog) {
			completeEdit(dialog);
		}

		function handleSave(dialog) {
			var dialogInput = $('.xrm-text', dialog.body);
			var dialogInputValue = dialogInput.val();
			var dialogFooter = $(dialog.footer);

			// If the attribute value has been changed, persist the new value.
			if (dialogInputValue != attributeValue) {
				dialogFooter.hide();
				dialogInput.hide();
				dialogContainer.addClass('xrm-editable-wait');
				XRM.data.services.putAttribute(entityServiceUri, attributeName, dialogInputValue, {
					success: function() {
						$('.xrm-attribute-value', attributeContainer).html(dialogInputValue);
						completeEdit(dialog);
					},
					error: function(xhr) {
						dialogContainer.removeClass('xrm-editable-wait');
						dialogFooter.show();
						dialogInput.show();
						XRM.ui.showDataServiceError(xhr);
					}
				});
			}
			// Otherwise, just dismiss the edit dialog without doing anything.
			else {
				completeEdit(dialog);
			}
		}

		// Create our modal editing dialog.
		var dialog = new YAHOO.widget.Dialog(dialogContainer.get(0), {
			visible: false,
			constraintoviewport: true,
			zindex: XRM.zindex,
			xy: YAHOO.util.Dom.getXY(attributeContainer.get(0)),
			buttons: [
				{ text: XRM.localize('editable.save.label'), handler: function() { handleSave(this) }, isDefault: true },
				{ text: XRM.localize('editable.cancel.label'), handler: function() { handleCancel(this) } }]
		});

		dialog.setHeader('Edit ' + (attributeDisplayName || ''));
		dialog.setBody(' ');

		$('<input />').attr('type', 'text').addClass('xrm-text').val(attributeValue || '').appendTo(dialog.body);

		// Add ctrl+s shortcut for saving content.
		$('.xrm-text', dialog.body).keypress(function(e) {
			if (!(e.which == ('s').charCodeAt(0) && e.ctrlKey)) {
				return true;
			}
			handleSave(dialog);
			return false;
		});

		dialog.render();
		dialog.show();

		XRM.ui.registerOverlay(dialog);
		dialog.focus();

		$('.xrm-text', dialog.body).focus();
	}

});