text:
package com.amazonaws.services.servicecatalog.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Information about a provisioning artifact (also known as a version) for a product.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ProvisioningArtifactDetail implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The identifier of the provisioning artifact.
     *

     */
    private String id;
    /**
     *

     * The name of the provisioning artifact.
     *

     */
    private String name;
    /**
     *

     * The description of the provisioning artifact.
     *

     */
    private String description;
    /**
     *

     * The type of provisioning artifact.
     *

     *

     *

     *

     * CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     * MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     * MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     *

     */
    private String type;
    /**
     *

     * The UTC time stamp of the creation time.
     *

     */
    private java.util.Date createdTime;
    /**
     *

     * Indicates whether the product version is active.
     *

     */
    private Boolean active;
    /**
     *

     * Information set by the administrator to provide guidance to end users about which provisioning artifacts to use.
     *

     */
    private String guidance;
    /**
     *

     * Specifies the revision of the external artifact that was used to automatically sync the Service Catalog product
     * and create the provisioning artifact. Service Catalog includes this response parameter as a high level field to
     * the existing ProvisioningArtifactDetail type, which is returned as part of the response for
     * CreateProduct, UpdateProduct, DescribeProductAsAdmin,
     * DescribeProvisioningArtifact, ListProvisioningArtifact, and
     * UpdateProvisioningArticat APIs.
     *

     *

     * This field only exists for Repo-Synced products.
     *

     */
    private String sourceRevision;

    /**
     *

     * The identifier of the provisioning artifact.
     *

     *
     * @param id
     *        The identifier of the provisioning artifact.
     */

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

    /**
     *

     * The identifier of the provisioning artifact.
     *

     *
     * @return The identifier of the provisioning artifact.
     */

    public String getId() {
        return this.id;
    }

    /**
     *

     * The identifier of the provisioning artifact.
     *

     *
     * @param id
     *        The identifier of the provisioning artifact.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ProvisioningArtifactDetail withId(String id) {
        setId(id);
        return this;
    }

    /**
     *

     * The name of the provisioning artifact.
     *

     *
     * @param name
     *        The name of the provisioning artifact.
     */

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

    /**
     *

     * The name of the provisioning artifact.
     *

     *
     * @return The name of the provisioning artifact.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * The name of the provisioning artifact.
     *

     *
     * @param name
     *        The name of the provisioning artifact.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ProvisioningArtifactDetail withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * The description of the provisioning artifact.
     *

     *
     * @param description
     *        The description of the provisioning artifact.
     */

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

    /**
     *

     * The description of the provisioning artifact.
     *

     *
     * @return The description of the provisioning artifact.
     */

    public String getDescription() {
        return this.description;
    }

    /**
     *

     * The description of the provisioning artifact.
     *

     *
     * @param description
     *        The description of the provisioning artifact.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ProvisioningArtifactDetail withDescription(String description) {
        setDescription(description);
        return this;
    }

    /**
     *

     * The type of provisioning artifact.
     *

     *

     *

     *

     * CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     * MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     * MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     *

     *
     * @param type
     *        The type of provisioning artifact.

     *

     *

     *

     *        CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     *        MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     *        MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     * @see ProvisioningArtifactType
     */

    public void setType(String type) {
        this.type = type;
    }

    /**
     *

     * The type of provisioning artifact.
     *

     *

     *

     *

     * CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     * MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     * MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     *

     *
     * @return The type of provisioning artifact.

     *

     *

     *

     *         CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     *         MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     *         MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     * @see ProvisioningArtifactType
     */

    public String getType() {
        return this.type;
    }

    /**
     *

     * The type of provisioning artifact.
     *

     *

     *

     *

     * CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     * MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     * MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     *

     *
     * @param type
     *        The type of provisioning artifact.

     *

     *

     *

     *        CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     *        MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     *        MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ProvisioningArtifactType
     */

    public ProvisioningArtifactDetail withType(String type) {
        setType(type);
        return this;
    }

    /**
     *

     * The type of provisioning artifact.
     *

     *

     *

     *

     * CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     * MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     * MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     *

     *
     * @param type
     *        The type of provisioning artifact.

     *

     *

     *

     *        CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     *        MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     *        MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     * @see ProvisioningArtifactType
     */

    public void setType(ProvisioningArtifactType type) {
        withType(type);
    }

    /**
     *

     * The type of provisioning artifact.
     *

     *

     *

     *

     * CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     * MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     * MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     *

     *
     * @param type
     *        The type of provisioning artifact.

     *

     *

     *

     *        CLOUD_FORMATION_TEMPLATE - CloudFormation template
     *

     *

     *

     *

     *        MARKETPLACE_AMI - Amazon Web Services Marketplace AMI
     *

     *

     *

     *

     *        MARKETPLACE_CAR - Amazon Web Services Marketplace Clusters and Amazon Web Services Resources
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ProvisioningArtifactType
     */

    public ProvisioningArtifactDetail withType(ProvisioningArtifactType type) {
        this.type = type.toString();
        return this;
    }

    /**
     *

     * The UTC time stamp of the creation time.
     *

     *
     * @param createdTime
     *        The UTC time stamp of the creation time.
     */

    public void setCreatedTime(java.util.Date createdTime) {
        this.createdTime = createdTime;
    }

    /**
     *

     * The UTC time stamp of the creation time.
     *

     *
     * @return The UTC time stamp of the creation time.
     */

    public java.util.Date getCreatedTime() {
        return this.createdTime;
    }

    /**
     *

     * The UTC time stamp of the creation time.
     *

     *
     * @param createdTime
     *        The UTC time stamp of the creation time.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ProvisioningArtifactDetail withCreatedTime(java.util.Date createdTime) {
        setCreatedTime(createdTime);
        return this;
    }

    /**
     *

     * Indicates whether the product version is active.
     *

     *
     * @param active
     *        Indicates whether the product version is active.
     */

    public void setActive(Boolean active) {
        this.active = active;
    }

    /**
     *

     * Indicates whether the product version is active.
     *

     *
     * @return Indicates whether the product version is active.
     */

    public Boolean getActive() {
        return this.active;
    }

    /**
     *

     * Indicates whether the product version is active.
     *

     *
     * @param active
     *        Indicates whether the product version is active.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ProvisioningArtifactDetail withActive(Boolean active) {
        setActive(active);
        return this;
    }

    /**
     *

     * Indicates whether the product version is active.
     *

     *
     * @return Indicates whether the product version is active.
     */

    public Boolean isActive() {
        return this.active;
    }

    /**
     *

     * Information set by the administrator to provide guidance to end users about which provisioning artifacts to use.
     *

     *
     * @param guidance
     *        Information set by the administrator to provide guidance to end users about which provisioning artifacts
     *        to use.
     * @see ProvisioningArtifactGuidance
     */

    public void setGuidance(String guidance) {
        this.guidance = guidance;
    }

    /**
     *

     * Information set by the administrator to provide guidance to end users about which provisioning artifacts to use.
     *

     *
     * @return Information set by the administrator to provide guidance to end users about which provisioning artifacts
     *         to use.
     * @see ProvisioningArtifactGuidance
     */

    public String getGuidance() {
        return this.guidance;
    }

    /**
     *

     * Information set by the administrator to provide guidance to end users about which provisioning artifacts to use.
     *

     *
     * @param guidance
     *        Information set by the administrator to provide guidance to end users about which provisioning artifacts
     *        to use.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ProvisioningArtifactGuidance
     */

    public ProvisioningArtifactDetail withGuidance(String guidance) {
        setGuidance(guidance);
        return this;
    }

    /**
     *

     * Information set by the administrator to provide guidance to end users about which provisioning artifacts to use.
     *

     *
     * @param guidance
     *        Information set by the administrator to provide guidance to end users about which provisioning artifacts
     *        to use.
     * @see ProvisioningArtifactGuidance
     */

    public void setGuidance(ProvisioningArtifactGuidance guidance) {
        withGuidance(guidance);
    }

    /**
     *

     * Information set by the administrator to provide guidance to end users about which provisioning artifacts to use.
     *

     *
     * @param guidance
     *        Information set by the administrator to provide guidance to end users about which provisioning artifacts
     *        to use.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ProvisioningArtifactGuidance
     */

    public ProvisioningArtifactDetail withGuidance(ProvisioningArtifactGuidance guidance) {
        this.guidance = guidance.toString();
        return this;
    }

    /**
     *

     * Specifies the revision of the external artifact that was used to automatically sync the Service Catalog product
     * and create the provisioning artifact. Service Catalog includes this response parameter as a high level field to
     * the existing ProvisioningArtifactDetail type, which is returned as part of the response for
     * CreateProduct, UpdateProduct, DescribeProductAsAdmin,
     * DescribeProvisioningArtifact, ListProvisioningArtifact, and
     * UpdateProvisioningArticat APIs.
     *

     *

     * This field only exists for Repo-Synced products.
     *

     *
     * @param sourceRevision
     *        Specifies the revision of the external artifact that was used to automatically sync the Service Catalog
     *        product and create the provisioning artifact. Service Catalog includes this response parameter as a high
     *        level field to the existing ProvisioningArtifactDetail type, which is returned as part of the
     *        response for CreateProduct, UpdateProduct, DescribeProductAsAdmin,
     *        DescribeProvisioningArtifact, ListProvisioningArtifact, and
     *        UpdateProvisioningArticat APIs.

     *

     *        This field only exists for Repo-Synced products.
     */

    public void setSourceRevision(String sourceRevision) {
        this.sourceRevision = sourceRevision;
    }

    /**
     *

     * Specifies the revision of the external artifact that was used to automatically sync the Service Catalog product
     * and create the provisioning artifact. Service Catalog includes this response parameter as a high level field to
     * the existing ProvisioningArtifactDetail type, which is returned as part of the response for
     * CreateProduct, UpdateProduct, DescribeProductAsAdmin,
     * DescribeProvisioningArtifact, ListProvisioningArtifact, and
     * UpdateProvisioningArticat APIs.
     *

     *

     * This field only exists for Repo-Synced products.
     *

     *
     * @return Specifies the revision of the external artifact that was used to automatically sync the Service Catalog
     *         product and create the provisioning artifact. Service Catalog includes this response parameter as a high
     *         level field to the existing ProvisioningArtifactDetail type, which is returned as part of
     *         the response for CreateProduct, UpdateProduct,
     *         DescribeProductAsAdmin, DescribeProvisioningArtifact,
     *         ListProvisioningArtifact, and UpdateProvisioningArticat APIs.

     *

     *         This field only exists for Repo-Synced products.
     */

    public String getSourceRevision() {
        return this.sourceRevision;
    }

    /**
     *

     * Specifies the revision of the external artifact that was used to automatically sync the Service Catalog product
     * and create the provisioning artifact. Service Catalog includes this response parameter as a high level field to
     * the existing ProvisioningArtifactDetail type, which is returned as part of the response for
     * CreateProduct, UpdateProduct, DescribeProductAsAdmin,
     * DescribeProvisioningArtifact, ListProvisioningArtifact, and
     * UpdateProvisioningArticat APIs.
     *

     *

     * This field only exists for Repo-Synced products.
     *

     *
     * @param sourceRevision
     *        Specifies the revision of the external artifact that was used to automatically sync the Service Catalog
     *        product and create the provisioning artifact. Service Catalog includes this response parameter as a high
     *        level field to the existing ProvisioningArtifactDetail type, which is returned as part of the
     *        response for CreateProduct, UpdateProduct, DescribeProductAsAdmin,
     *        DescribeProvisioningArtifact, ListProvisioningArtifact, and
     *        UpdateProvisioningArticat APIs.

     *

     *        This field only exists for Repo-Synced products.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ProvisioningArtifactDetail withSourceRevision(String sourceRevision) {
        setSourceRevision(sourceRevision);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getId() != null)
            sb.append("Id: ").append(getId()).append(",");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getDescription() != null)
            sb.append("Description: ").append(getDescription()).append(",");
        if (getType() != null)
            sb.append("Type: ").append(getType()).append(",");
        if (getCreatedTime() != null)
            sb.append("CreatedTime: ").append(getCreatedTime()).append(",");
        if (getActive() != null)
            sb.append("Active: ").append(getActive()).append(",");
        if (getGuidance() != null)
            sb.append("Guidance: ").append(getGuidance()).append(",");
        if (getSourceRevision() != null)
            sb.append("SourceRevision: ").append(getSourceRevision());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ProvisioningArtifactDetail == false)
            return false;
        ProvisioningArtifactDetail other = (ProvisioningArtifactDetail) obj;
        if (other.getId() == null ^ this.getId() == null)
            return false;
        if (other.getId() != null && other.getId().equals(this.getId()) == false)
            return false;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getDescription() == null ^ this.getDescription() == null)
            return false;
        if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
            return false;
        if (other.getType() == null ^ this.getType() == null)
            return false;
        if (other.getType() != null && other.getType().equals(this.getType()) == false)
            return false;
        if (other.getCreatedTime() == null ^ this.getCreatedTime() == null)
            return false;
        if (other.getCreatedTime() != null && other.getCreatedTime().equals(this.getCreatedTime()) == false)
            return false;
        if (other.getActive() == null ^ this.getActive() == null)
            return false;
        if (other.getActive() != null && other.getActive().equals(this.getActive()) == false)
            return false;
        if (other.getGuidance() == null ^ this.getGuidance() == null)
            return false;
        if (other.getGuidance() != null && other.getGuidance().equals(this.getGuidance()) == false)
            return false;
        if (other.getSourceRevision() == null ^ this.getSourceRevision() == null)
            return false;
        if (other.getSourceRevision() != null && other.getSourceRevision().equals(this.getSourceRevision()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
        hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode());
        hashCode = prime * hashCode + ((getCreatedTime() == null) ? 0 : getCreatedTime().hashCode());
        hashCode = prime * hashCode + ((getActive() == null) ? 0 : getActive().hashCode());
        hashCode = prime * hashCode + ((getGuidance() == null) ? 0 : getGuidance().hashCode());
        hashCode = prime * hashCode + ((getSourceRevision() == null) ? 0 : getSourceRevision().hashCode());
        return hashCode;
    }

    @Override
    public ProvisioningArtifactDetail clone() {
        try {
            return (ProvisioningArtifactDetail) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.servicecatalog.model.transform.ProvisioningArtifactDetailMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/browser_child_process_host_impl.h"

#include "base/base_switches.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/dump_without_crashing.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/synchronization/waitable_event.h"
#include "build/build_config.h"
#include "components/tracing/tracing_switches.h"
#include "content/browser/histogram_message_filter.h"
#include "content/browser/loader/resource_message_filter.h"
#include "content/browser/memory/memory_message_filter.h"
#include "content/browser/profiler_message_filter.h"
#include "content/browser/tracing/trace_message_filter.h"
#include "content/common/child_process_host_impl.h"
#include "content/common/child_process_messages.h"
#include "content/public/browser/browser_child_process_host_delegate.h"
#include "content/public/browser/browser_child_process_observer.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/process_type.h"
#include "content/public/common/result_codes.h"
#include "ipc/attachment_broker.h"
#include "ipc/attachment_broker_privileged.h"
#include "mojo/edk/embedder/embedder.h"

#if defined(OS_MACOSX)
#include "content/browser/mach_broker_mac.h"
#endif

namespace content {
namespace {

static base::LazyInstance<BrowserChildProcessHostImpl::BrowserChildProcessList>
    g_child_process_list = LAZY_INSTANCE_INITIALIZER;

base::LazyInstance<base::ObserverList<BrowserChildProcessObserver>>
    g_observers = LAZY_INSTANCE_INITIALIZER;

void NotifyProcessLaunchedAndConnected(const ChildProcessData& data) {
  FOR_EACH_OBSERVER(BrowserChildProcessObserver, g_observers.Get(),
                    BrowserChildProcessLaunchedAndConnected(data));
}

void NotifyProcessHostConnected(const ChildProcessData& data) {
  FOR_EACH_OBSERVER(BrowserChildProcessObserver, g_observers.Get(),
                    BrowserChildProcessHostConnected(data));
}

void NotifyProcessHostDisconnected(const ChildProcessData& data) {
  FOR_EACH_OBSERVER(BrowserChildProcessObserver, g_observers.Get(),
                    BrowserChildProcessHostDisconnected(data));
}

void NotifyProcessCrashed(const ChildProcessData& data, int exit_code) {
  FOR_EACH_OBSERVER(BrowserChildProcessObserver, g_observers.Get(),
                    BrowserChildProcessCrashed(data, exit_code));
}

void NotifyProcessKilled(const ChildProcessData& data, int exit_code) {
  FOR_EACH_OBSERVER(BrowserChildProcessObserver, g_observers.Get(),
                    BrowserChildProcessKilled(data, exit_code));
}

}  // namespace

BrowserChildProcessHost* BrowserChildProcessHost::Create(
    content::ProcessType process_type,
    BrowserChildProcessHostDelegate* delegate) {
  return new BrowserChildProcessHostImpl(process_type, delegate);
}

BrowserChildProcessHost* BrowserChildProcessHost::FromID(int child_process_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  BrowserChildProcessHostImpl::BrowserChildProcessList* process_list =
      g_child_process_list.Pointer();
  for (BrowserChildProcessHostImpl* host : *process_list) {
    if (host->GetData().id == child_process_id)
      return host;
  }
  return nullptr;
}

#if defined(OS_MACOSX)
base::PortProvider* BrowserChildProcessHost::GetPortProvider() {
  return MachBroker::GetInstance();
}
#endif

// static
BrowserChildProcessHostImpl::BrowserChildProcessList*
    BrowserChildProcessHostImpl::GetIterator() {
  return g_child_process_list.Pointer();
}

// static
void BrowserChildProcessHostImpl::AddObserver(
    BrowserChildProcessObserver* observer) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  g_observers.Get().AddObserver(observer);
}

// static
void BrowserChildProcessHostImpl::RemoveObserver(
    BrowserChildProcessObserver* observer) {
  // TODO(phajdan.jr): Check thread after fixing http://crbug.com/167126.
  g_observers.Get().RemoveObserver(observer);
}

BrowserChildProcessHostImpl::BrowserChildProcessHostImpl(
    content::ProcessType process_type,
    BrowserChildProcessHostDelegate* delegate)
    : data_(process_type),
      delegate_(delegate),
      power_monitor_message_broadcaster_(this),
      is_channel_connected_(false),
      notify_child_disconnected_(false) {
  data_.id = ChildProcessHostImpl::GenerateChildProcessUniqueId();

#if USE_ATTACHMENT_BROKER
  // Construct the privileged attachment broker early in the life cycle of a
  // child process. This ensures that when a test is being run in one of the
  // single process modes, the global attachment broker is the privileged
  // attachment broker, rather than an unprivileged attachment broker.
#if defined(OS_MACOSX)
  IPC::AttachmentBrokerPrivileged::CreateBrokerIfNeeded(
      MachBroker::GetInstance());
#else
  IPC::AttachmentBrokerPrivileged::CreateBrokerIfNeeded();
#endif  // defined(OS_MACOSX)
#endif  // USE_ATTACHMENT_BROKER

  child_process_host_.reset(ChildProcessHost::Create(this));
  AddFilter(new TraceMessageFilter(data_.id));
  AddFilter(new ProfilerMessageFilter(process_type));
  AddFilter(new HistogramMessageFilter);
  AddFilter(new MemoryMessageFilter(this, process_type));

  g_child_process_list.Get().push_back(this);
  GetContentClient()->browser()->BrowserChildProcessHostCreated(this);

  power_monitor_message_broadcaster_.Init();
}

BrowserChildProcessHostImpl::~BrowserChildProcessHostImpl() {
  g_child_process_list.Get().remove(this);

  if (notify_child_disconnected_) {
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                            base::Bind(&NotifyProcessHostDisconnected, data_));
  }
}

// static
void BrowserChildProcessHostImpl::TerminateAll() {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // Make a copy since the BrowserChildProcessHost dtor mutates the original
  // list.
  BrowserChildProcessList copy = g_child_process_list.Get();
  for (BrowserChildProcessList::iterator it = copy.begin();
       it != copy.end(); ++it) {
    delete (*it)->delegate();  // ~*HostDelegate deletes *HostImpl.
  }
}

// static
void BrowserChildProcessHostImpl::CopyFeatureAndFieldTrialFlags(
    base::CommandLine* cmd_line) {
  std::string enabled_features;
  std::string disabled_features;
  base::FeatureList::GetInstance()->GetFeatureOverrides(&enabled_features,
                                                        &disabled_features);
  if (!enabled_features.empty())
    cmd_line->AppendSwitchASCII(switches::kEnableFeatures, enabled_features);
  if (!disabled_features.empty())
    cmd_line->AppendSwitchASCII(switches::kDisableFeatures, disabled_features);

  // If we run base::FieldTrials, we want to pass to their state to the
  // child process so that it can act in accordance with each state.
  std::string field_trial_states;
  base::FieldTrialList::AllStatesToString(&field_trial_states);
  if (!field_trial_states.empty()) {
    cmd_line->AppendSwitchASCII(switches::kForceFieldTrials,
                                field_trial_states);
  }
}

void BrowserChildProcessHostImpl::Launch(
    SandboxedProcessLauncherDelegate* delegate,
    base::CommandLine* cmd_line,
    bool terminate_on_shutdown) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  GetContentClient()->browser()->AppendExtraCommandLineSwitches(
      cmd_line, data_.id);

  const base::CommandLine& browser_command_line =
      *base::CommandLine::ForCurrentProcess();
  static const char* kForwardSwitches[] = {
    switches::kDisableLogging,
    switches::kEnableLogging,
    switches::kIPCConnectionTimeout,
    switches::kLoggingLevel,
    switches::kTraceToConsole,
    switches::kV,
    switches::kVModule,
  };
  cmd_line->CopySwitchesFrom(browser_command_line, kForwardSwitches,
                             arraysize(kForwardSwitches));

  notify_child_disconnected_ = true;
  child_process_.reset(new ChildProcessLauncher(
      delegate,
      cmd_line,
      data_.id,
      this,
      terminate_on_shutdown));
}

const ChildProcessData& BrowserChildProcessHostImpl::GetData() const {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  return data_;
}

ChildProcessHost* BrowserChildProcessHostImpl::GetHost() const {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  return child_process_host_.get();
}

const base::Process& BrowserChildProcessHostImpl::GetProcess() const {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  DCHECK(child_process_.get())
      << "Requesting a child process handle before launching.";
  DCHECK(child_process_->GetProcess().IsValid())
      << "Requesting a child process handle before launch has completed OK.";
  return child_process_->GetProcess();
}

void BrowserChildProcessHostImpl::SetName(const base::string16& name) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  data_.name = name;
}

void BrowserChildProcessHostImpl::SetHandle(base::ProcessHandle handle) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  data_.handle = handle;
}

ServiceRegistry* BrowserChildProcessHostImpl::GetServiceRegistry() {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  return delegate_->GetServiceRegistry();
}

void BrowserChildProcessHostImpl::ForceShutdown() {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  g_child_process_list.Get().remove(this);
  child_process_host_->ForceShutdown();
}

void BrowserChildProcessHostImpl::SetBackgrounded(bool backgrounded) {
  child_process_->SetProcessBackgrounded(backgrounded);
}

void BrowserChildProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
  child_process_host_->AddFilter(filter->GetFilter());
}

void BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
    int process_type) {
  UMA_HISTOGRAM_ENUMERATION("ChildProcess.BadMessgeTerminated", process_type,
                            PROCESS_TYPE_MAX);
}

base::TerminationStatus BrowserChildProcessHostImpl::GetTerminationStatus(
    bool known_dead, int* exit_code) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  if (!child_process_)  // If the delegate doesn't use Launch() helper.
    return base::GetTerminationStatus(data_.handle, exit_code);
  return child_process_->GetChildTerminationStatus(known_dead,
                                                   exit_code);
}

bool BrowserChildProcessHostImpl::OnMessageReceived(
    const IPC::Message& message) {
  return delegate_->OnMessageReceived(message);
}

void BrowserChildProcessHostImpl::OnChannelConnected(int32_t peer_pid) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  is_channel_connected_ = true;
  notify_child_disconnected_ = true;

#if defined(OS_WIN)
  // From this point onward, the exit of the child process is detected by an
  // error on the IPC channel.
  early_exit_watcher_.StopWatching();
#endif

  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                          base::Bind(&NotifyProcessHostConnected, data_));

  delegate_->OnChannelConnected(peer_pid);

  if (IsProcessLaunched()) {
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                            base::Bind(&NotifyProcessLaunchedAndConnected,
                                       data_));
  }
}

void BrowserChildProcessHostImpl::OnChannelError() {
  delegate_->OnChannelError();
}

void BrowserChildProcessHostImpl::OnBadMessageReceived(
    const IPC::Message& message) {
  TerminateOnBadMessageReceived(message.type());
}

void BrowserChildProcessHostImpl::TerminateOnBadMessageReceived(uint32_t type) {
  HistogramBadMessageTerminated(data_.process_type);
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableKillAfterBadIPC)) {
    return;
  }
  LOG(ERROR) << "Terminating child process for bad IPC message of type "
             << type;

  // Create a memory dump. This will contain enough stack frames to work out
  // what the bad message was.
  base::debug::DumpWithoutCrashing();

  child_process_->GetProcess().Terminate(RESULT_CODE_KILLED_BAD_MESSAGE, false);
}

bool BrowserChildProcessHostImpl::CanShutdown() {
  return delegate_->CanShutdown();
}

void BrowserChildProcessHostImpl::OnChildDisconnected() {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
#if defined(OS_WIN)
  // OnChildDisconnected may be called without OnChannelConnected, so stop the
  // early exit watcher so GetTerminationStatus can close the process handle.
  early_exit_watcher_.StopWatching();
#endif
  if (child_process_.get() || data_.handle) {
    int exit_code;
    base::TerminationStatus status = GetTerminationStatus(
        true /* known_dead */, &exit_code);
    switch (status) {
      case base::TERMINATION_STATUS_PROCESS_CRASHED:
      case base::TERMINATION_STATUS_ABNORMAL_TERMINATION: {
        delegate_->OnProcessCrashed(exit_code);
        BrowserThread::PostTask(
            BrowserThread::UI, FROM_HERE,
            base::Bind(&NotifyProcessCrashed, data_, exit_code));
        UMA_HISTOGRAM_ENUMERATION("ChildProcess.Crashed2",
                                  data_.process_type,
                                  PROCESS_TYPE_MAX);
        break;
      }
#if defined(OS_ANDROID)
      case base::TERMINATION_STATUS_OOM_PROTECTED:
#endif
#if defined(OS_CHROMEOS)
      case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
#endif
      case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: {
        delegate_->OnProcessCrashed(exit_code);
        BrowserThread::PostTask(
            BrowserThread::UI, FROM_HERE,
            base::Bind(&NotifyProcessKilled, data_, exit_code));
        // Report that this child process was killed.
        UMA_HISTOGRAM_ENUMERATION("ChildProcess.Killed2",
                                  data_.process_type,
                                  PROCESS_TYPE_MAX);
        break;
      }
      case base::TERMINATION_STATUS_STILL_RUNNING: {
        UMA_HISTOGRAM_ENUMERATION("ChildProcess.DisconnectedAlive2",
                                  data_.process_type,
                                  PROCESS_TYPE_MAX);
      }
      default:
        break;
    }
    UMA_HISTOGRAM_ENUMERATION("ChildProcess.Disconnected2",
                              data_.process_type,
                              PROCESS_TYPE_MAX);
#if defined(OS_CHROMEOS)
    if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM) {
      UMA_HISTOGRAM_ENUMERATION("ChildProcess.Killed2.OOM",
                                data_.process_type,
                                PROCESS_TYPE_MAX);
    }
#endif
  }
  delete delegate_;  // Will delete us
}

bool BrowserChildProcessHostImpl::Send(IPC::Message* message) {
  return child_process_host_->Send(message);
}

void BrowserChildProcessHostImpl::OnProcessLaunchFailed() {
  delegate_->OnProcessLaunchFailed();
  notify_child_disconnected_ = false;
  delete delegate_;  // Will delete us
}

void BrowserChildProcessHostImpl::OnProcessLaunched() {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  const base::Process& process = child_process_->GetProcess();
  DCHECK(process.IsValid());

  mojo::edk::ScopedPlatformHandle client_pipe =
      mojo::edk::ChildProcessLaunched(process.Handle());
  Send(new ChildProcessMsg_SetMojoParentPipeHandle(
      IPC::GetPlatformFileForTransit(client_pipe.release().handle, true)));

#if defined(OS_WIN)
  // Start a WaitableEventWatcher that will invoke OnProcessExitedEarly if the
  // child process exits. This watcher is stopped once the IPC channel is
  // connected and the exit of the child process is detecter by an error on the
  // IPC channel thereafter.
  DCHECK(!early_exit_watcher_.GetWatchedObject());
  early_exit_watcher_.StartWatchingOnce(process.Handle(), this);
#endif

  // TODO(rvargas) crbug.com/417532: Don't store a handle.
  data_.handle = process.Handle();
  delegate_->OnProcessLaunched();

  if (is_channel_connected_) {
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                            base::Bind(&NotifyProcessLaunchedAndConnected,
                                       data_));
  }
}

bool BrowserChildProcessHostImpl::IsProcessLaunched() const {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  return child_process_.get() && child_process_->GetProcess().IsValid();
}

#if defined(OS_WIN)

void BrowserChildProcessHostImpl::OnObjectSignaled(HANDLE object) {
  OnChildDisconnected();
}

#endif

}  // namespace content

redpajama_set_name: RedPajamaGithub


text:
package consulo.sandboxPlugin.ide.eap;

import consulo.ide.eap.EarlyAccessProgramDescriptor;
import javax.annotation.Nonnull;

/**
 * @author VISTALL
 * @since 30.08.14
 */
public class Sand6EapDescriptor extends EarlyAccessProgramDescriptor {
  @Nonnull
  @Override
  public String getName() {
    return "F";
  }

  @Nonnull
  @Override
  public String getDescription() {
    return "test";
  }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('CloudList', '0001_initial'),
        ('AccountSystem', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Complaint',
            fields=[
                ('cmpid', models.AutoField(primary_key=True, serialize=False)),
                ('state', models.IntegerField()),
                ('notes', models.CharField(max_length=300)),
            ],
            options={
                'db_table': 'Complaints',
            },
        ),
        migrations.CreateModel(
            name='Order',
            fields=[
                ('oid', models.AutoField(primary_key=True, serialize=False)),
                ('notes', models.CharField(max_length=300)),
                ('fee', models.FloatField()),
                ('typeid', models.IntegerField()),
                ('itemList', models.CharField(max_length=200)),
                ('state', models.IntegerField()),
                ('create_time', models.DateTimeField()),
                ('paid_time', models.DateTimeField()),
                ('finish_time', models.DateTimeField()),
                ('prepayid', models.CharField(max_length=50)),
                ('signature', models.CharField(max_length=50)),
                ('showid', models.CharField(max_length=50)),
                ('addr', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='CloudList.Address')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='AccountSystem.User')),
            ],
            options={
                'db_table': 'orders',
            },
        ),
        migrations.CreateModel(
            name='VIPOrder',
            fields=[
                ('void', models.AutoField(primary_key=True, serialize=False)),
                ('month', models.IntegerField()),
                ('level', models.IntegerField()),
                ('prepayid', models.CharField(max_length=50)),
                ('fee', models.CharField(max_length=50)),
                ('state', models.IntegerField()),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='AccountSystem.User')),
            ],
            options={
                'db_table': 'order_vip',
            },
        ),
        migrations.AddField(
            model_name='complaint',
            name='order',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='OrderSystem.Order'),
        ),
        migrations.AddField(
            model_name='complaint',
            name='user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='AccountSystem.User'),
        ),
    ]


text:
@implementation DiscussListModel

+ (NSDictionary *)modelContainerPropertyGenericClass
{
    return @{@"forum_threadlist" : [ForumThread class]};
}

@end

@implementation ForumThread

+ (NSDictionary *)modelCustomPropertyMapper
{
    return @{@"typeId" : @"typeid"};
}

@end


text:
package org.apache.eagle.flink;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * Created on 7/27/16.
 */
public class SiddhiPolicyStateHandler extends SiddhiPolicyHandler {

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

    public SiddhiPolicyStateHandler(Map<String, StreamDefinition> sds, int index) {
        super(sds, index);
    }

    @Override
    protected String generateExecutionPlan(PolicyDefinition policyDefinition, Map<String, StreamDefinition> sds) throws StreamNotDefinedException {
        StringBuilder builder = new StringBuilder();
        PolicyDefinition.Definition stateDefiniton = policyDefinition.getStateDefinition();
        List<String> inputStreams = stateDefiniton.getInputStreams();
        for (String inputStream : inputStreams) { // the state stream follow the output stream of the policy definition
            builder.append(SiddhiDefinitionAdapter.buildStreamDefinition(sds.get(inputStream)));
            builder.append("\n");
        }
        builder.append(stateDefiniton.value);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Generated siddhi state execution plan: {} from definiton: {}", builder.toString(), stateDefiniton);
        }
        return builder.toString();
    }

    @Override
    protected List<String> getOutputStreams(PolicyDefinition policy) {
        return policy.getStateDefinition().getOutputStreams();
    }

    // more validation on prepare

}


text:
    <uib-accordion close-others="oneAtATime">

                <uib-accordion-heading>
                    {{categoria}}
                </uib-accordion-heading>

                    <li ng-click ="cargarPregunta(person.idpreg)" ng-repeat="person in list.people"
                        dnd-draggable="person"
                        dnd-type="person.categoria"
                        dnd-disable-if="person.categoria == 'unknown'"
                        dnd-moved="list.people.splice($index, 1)"
                        dnd-effect-allowed="move"
                        class="background-{{person.categoria}}"
                        ng-if="person.categoria == categoria"

                    >
                        <dnd-nodrag>

{{person.name}}

                        </dnd-nodrag>

                        Drop any {{list.allowedTypes.join(' or ')}} here

    </uib-accordion>


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.10.09 at 10:10:23 AM CST
//

package com.elong.nb.model.elong;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import java.util.List;
import com.alibaba.fastjson.annotation.JSONField;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for HotelCredits complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="HotelCredits">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="HCredits" type="{}ArrayOfHCredit" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HotelCredits", propOrder = {
    "hCredits"
})
public class HotelCredits {

    @JSONField(name = "HCredits")
    protected List<HCredit> hCredits;

    /**
     * Gets the value of the hCredits property.
     *
     * @return
     *     possible object is
     *     {@link List<HCredit> }
     *
     */
    public List<HCredit> getHCredits() {
        return hCredits;
    }

    /**
     * Sets the value of the hCredits property.
     *
     * @param value
     *     allowed object is
     *     {@link List<HCredit> }
     *
     */
    public void setHCredits(List<HCredit> value) {
        this.hCredits = value;
    }

}


text:
namespace AAWebSmartHouse.Common
{
    public class GlobalConstants
    {
        public const int DefaultPageSize = 10;
    }
}


text:
import com.atomicscala.royals.Royalty

val royal = new Royalty("Henry", "Laughs")
val title = royal.title()
assert("Sir Laughsalot" == title, "Expected Sir Laughsalot, Got " + title)
println(title)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Moq;
using Hatfield.EnviroData.Core;
using Hatfield.EnviroData.DataAcquisition.ESDAT.Converters;
using System.Data.Entity;
using Hatfield.EnviroData.WQDataProfile;

namespace Hatfield.EnviroData.DataAcquisition.ESDAT.Test.Converters
{
    [TestFixture]
    class SampleCollectionUnitMapperTest
    {
        [Test]
        public void ScaffoldTest()
        {
            var esdatModel = new ESDATModel();

            var mockDb = new Mock<IDbContext>();
            var mockDbContext = mockDb.Object;
            var duplicateChecker = new ODM2DuplicateChecker(mockDbContext);
            var defaultValueProvider = new StaticWQDefaultValueProvider();
            var wayToHandleNewData = WayToHandleNewData.ThrowExceptionForNewData;
            var results = new List<IResult>();
            var mapper = new SampleCollectionUnitMapper(duplicateChecker, defaultValueProvider, wayToHandleNewData, results);

            var unit = mapper.Draft(esdatModel);

            Assert.AreEqual(defaultValueProvider.DefaultUnitsTypeCVSampleCollection, unit.UnitsTypeCV);
            Assert.AreEqual(mapper.AbbereviateUnit(defaultValueProvider.DefaultUnitsTypeCVSampleCollection), unit.UnitsAbbreviation);
            Assert.AreEqual(defaultValueProvider.DefaultUnitsTypeCVSampleCollection, unit.UnitsName);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

using Microsoft.Win32;

namespace DevAudit.AuditLibrary
{
    public class ChocolateyPackageSource : PackageSource
    {
        #region Constructors
        public ChocolateyPackageSource(Dictionary<string, object> package_source_options, EventHandler<EnvironmentEventArgs> message_handler) : base(package_source_options,message_handler) {
        }
        #endregion

        #region Overriden properties
        public override string PackageManagerId { get { return "chocolatey"; } }

        public override string PackageManagerLabel { get { return "Chocolatey"; } }

        public override string DefaultPackageManagerConfigurationFile { get { return string.Empty; } }

        #endregion

        #region Overriden methods
        //run and parse output from choco list -lo command.
        public override IEnumerable<Package> GetPackages(params string[] o)
        {
            string choco_command = @"C:\ProgramData\chocolatey\choco.exe";
            string process_output = "", process_error = "";
            ProcessStartInfo psi = new ProcessStartInfo(choco_command);
            psi.Arguments = @"list -lo";
            psi.CreateNoWindow = true;
            psi.RedirectStandardError = true;
            psi.RedirectStandardOutput = true;
            psi.UseShellExecute = false;
            Process p = new Process();
            p.EnableRaisingEvents = true;
            p.StartInfo = psi;
            List<Package> packages = new List<Package>();
            p.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
            {
                string first = @"(\d+)\s+packages installed";
                if (!String.IsNullOrEmpty(e.Data))
                {
                    process_output += e.Data + Environment.NewLine;
                    Match m = Regex.Match(e.Data.Trim(), first);
                    if (m.Success)
                    {
                        return;
                    }
                    else
                    {
                        string[] output = e.Data.Trim().Split(' ');
                        if ((output == null) || (output != null) && (output.Length < 2))
                        {
                            throw new Exception("Could not parse output from choco command: " + e.Data);
                        }
                        else
                        {
                            packages.Add(new Package("chocolatey", output[0], output[1], ""));
                        }
                    }

                };
            };
            p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
            {
                if (!String.IsNullOrEmpty(e.Data))
                {
                    process_error += e.Data + Environment.NewLine;
                };
            };
            try
            {
                p.Start();
            }
            catch (Win32Exception e)
            {
                if (e.Message == "The system cannot find the file specified")
                {
                    throw new Exception("Chocolatey is not installed on this computer or is not on the current PATH.", e);
                }
            }
            p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                p.WaitForExit();
                p.Close();

            return packages;
        }

        public override bool IsVulnerabilityVersionInPackageVersionRange(string vulnerability_version, string package_version)
        {
            return vulnerability_version == package_version;
        }
        #endregion
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>libguac: guacamole/client.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

libguac
    0.9.7

Main Page

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

Globals

guacamole

Data Structures |
Functions |
Variables

client.h File Reference

Functions and structure contents for the Guacamole proxy client.
More...

Go to the source code of this file.

Data Structures

struct  	guac_client_info

 	Information exposed by the remote client during the connection handshake which can be used by a client plugin.  More...

struct  	guac_client

 	Guacamole proxy client.  More...

Functions

guac_client * 	guac_client_alloc ()

 	Returns a new, barebones guac_client.  More...

void 	guac_client_free (guac_client *client)

 	Free all resources associated with the given client.  More...

int 	guac_client_handle_instruction (guac_client *client, guac_instruction *instruction)

 	Call the appropriate handler defined by the given client for the given instruction.  More...

void 	guac_client_log (guac_client *client, guac_client_log_level level, const char *format,...)

 	Writes a message in the log used by the given client.  More...

void 	vguac_client_log (guac_client *client, guac_client_log_level level, const char *format, va_list ap)

 	Writes a message in the log used by the given client.  More...

void 	guac_client_stop (guac_client *client)

 	Signals the given client to stop gracefully.  More...

void 	guac_client_abort (guac_client *client, guac_protocol_status status, const char *format,...)

 	Signals the given client to stop gracefully, while also signalling via the Guacamole protocol that an error has occurred.  More...

void 	vguac_client_abort (guac_client *client, guac_protocol_status status, const char *format, va_list ap)

 	Signals the given client to stop gracefully, while also signalling via the Guacamole protocol that an error has occurred.  More...

guac_layer * 	guac_client_alloc_buffer (guac_client *client)

 	Allocates a new buffer (invisible layer).  More...

guac_layer * 	guac_client_alloc_layer (guac_client *client)

 	Allocates a new layer.  More...

void 	guac_client_free_buffer (guac_client *client, guac_layer *layer)

 	Returns the given buffer to the pool of available buffers, such that it can be reused by any subsequent call to guac_client_allow_buffer().  More...

void 	guac_client_free_layer (guac_client *client, guac_layer *layer)

 	Returns the given layer to the pool of available layers, such that it can be reused by any subsequent call to guac_client_allow_layer().  More...

guac_stream * 	guac_client_alloc_stream (guac_client *client)

 	Allocates a new stream.  More...

void 	guac_client_free_stream (guac_client *client, guac_stream *stream)

 	Returns the given stream to the pool of available streams, such that it can be reused by any subsequent call to guac_client_alloc_stream().  More...

Variables

const guac_layer * 	GUAC_DEFAULT_LAYER

 	The default Guacamole client layer, layer 0.

Detailed Description

Functions and structure contents for the Guacamole proxy client.

Function Documentation

          void guac_client_abort
          (
          guac_client *
          client,

          guac_protocol_status
          status,

          const char *
          format,

          ...

          )

Signals the given client to stop gracefully, while also signalling via the Guacamole protocol that an error has occurred.

Note that this is a completely cooperative signal, and can be ignored by the client or the hosting daemon. The message given will be logged to the system logs.

Parameters

client	The proxy client to signal to stop.

status	The status to send over the Guacamole protocol.

format	A printf-style format string to log.

...	Arguments to use when filling the format string for printing.

          guac_client* guac_client_alloc
          (
          	)

Returns a new, barebones guac_client.

This new guac_client has no handlers set, but is otherwise usable.

Returns

A pointer to the new client.

          guac_layer* guac_client_alloc_buffer
          (
          guac_client *
          client	)

Allocates a new buffer (invisible layer).

An arbitrary index is automatically assigned if no existing buffer is available for use.

Parameters

client	The proxy client to allocate the buffer for.

Returns

The next available buffer, or a newly allocated buffer.

          guac_layer* guac_client_alloc_layer
          (
          guac_client *
          client	)

Allocates a new layer.

An arbitrary index is automatically assigned if no existing layer is available for use.

Parameters

client	The proxy client to allocate the layer buffer for.

Returns

The next available layer, or a newly allocated layer.

          guac_stream* guac_client_alloc_stream
          (
          guac_client *
          client	)

Allocates a new stream.

An arbitrary index is automatically assigned if no previously-allocated stream is available for use.

Parameters

client	The proxy client to allocate the layer buffer for.

Returns

The next available stream, or a newly allocated stream.

          void guac_client_free
          (
          guac_client *
          client	)

Free all resources associated with the given client.

Parameters

client	The proxy client to free all reasources of.

          void guac_client_free_buffer
          (
          guac_client *
          client,

          guac_layer *
          layer

          )

Returns the given buffer to the pool of available buffers, such that it can be reused by any subsequent call to guac_client_allow_buffer().

Parameters

client	The proxy client to return the buffer to.

layer	The buffer to return to the pool of available buffers.

          void guac_client_free_layer
          (
          guac_client *
          client,

          guac_layer *
          layer

          )

Returns the given layer to the pool of available layers, such that it can be reused by any subsequent call to guac_client_allow_layer().

Parameters

client	The proxy client to return the layer to.

layer	The buffer to return to the pool of available layer.

          void guac_client_free_stream
          (
          guac_client *
          client,

          guac_stream *
          stream

          )

Returns the given stream to the pool of available streams, such that it can be reused by any subsequent call to guac_client_alloc_stream().

Parameters

client	The proxy client to return the buffer to.

stream	The stream to return to the pool of available stream.

          int guac_client_handle_instruction
          (
          guac_client *
          client,

          guac_instruction *
          instruction

          )

Call the appropriate handler defined by the given client for the given instruction.

A comparison is made between the instruction opcode and the initial handler lookup table defined in client-handlers.c. The intial handlers will in turn call the client's handler (if defined).

Parameters

client	The proxy client whose handlers should be called.

instruction	The instruction to pass to the proxy client via the appropriate handler.

          void guac_client_log
          (
          guac_client *
          client,

          guac_client_log_level
          level,

          const char *
          format,

          ...

          )

Writes a message in the log used by the given client.

The logger used will normally be defined by guacd (or whichever program loads the proxy client) by setting the logging handlers of the client when it is loaded.

Parameters

client	The proxy client logging this message.

level	The level at which to log this message.

format	A printf-style format string to log.

...	Arguments to use when filling the format string for printing.

          void guac_client_stop
          (
          guac_client *
          client	)

Signals the given client to stop gracefully.

This is a completely cooperative signal, and can be ignored by the client or the hosting daemon.

Parameters

client	The proxy client to signal to stop.

          void vguac_client_abort
          (
          guac_client *
          client,

          guac_protocol_status
          status,

          const char *
          format,

          va_list
          ap

          )

Signals the given client to stop gracefully, while also signalling via the Guacamole protocol that an error has occurred.

Note that this is a completely cooperative signal, and can be ignored by the client or the hosting daemon. The message given will be logged to the system logs.

Parameters

client	The proxy client to signal to stop.

status	The status to send over the Guacamole protocol.

format	A printf-style format string to log.

ap	The va_list containing the arguments to be used when filling the format string for printing.

          void vguac_client_log
          (
          guac_client *
          client,

          guac_client_log_level
          level,

          const char *
          format,

          va_list
          ap

          )

Writes a message in the log used by the given client.

The logger used will normally be defined by guacd (or whichever program loads the proxy client) by setting the logging handlers of the client when it is loaded.

Parameters

client	The proxy client logging this message.

level	The level at which to log this message.

format	A printf-style format string to log.

ap	The va_list containing the arguments to be used when filling the format string for printing.

<address class="footer">
Generated on Wed Jun 10 2015 21:39:32 for libguac by

 1.8.9.1
</address>


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Copyright (c) 2010-2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<query xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
       xmlns="http://prism.evolveum.com/xml/ns/public/query-3">
   <filter>
    <and>
        <equal>
        <path>c:name</path>
            <matching>polyStringNorm</matching>
            <value>generic object</value>
        </equal>
        <equal>
            <path xmlns:p="http://example.com/p">c:extension/p:intType</path>
            <value>123</value>
        </equal>
    </and>
    </filter>
</query>


text:
JsrtRuntime::JsrtRuntime(ThreadContext * threadContext, bool useIdle, bool dispatchExceptions)
{
    Assert(threadContext != NULL);
    this->threadContext = threadContext;
    this->contextList = NULL;
    this->collectCallback = NULL;
    this->beforeCollectCallback = NULL;
    this->beforeCollectCallbackContext = NULL;
#ifdef _CHAKRACOREBUILD
    this->beforeSweepCallback = NULL;
    this->beforeSweepCallbackContext = NULL;
#endif
    this->allocationPolicyManager = threadContext->GetAllocationPolicyManager();
    this->useIdle = useIdle;
    this->dispatchExceptions = dispatchExceptions;
    if (useIdle)
    {
        this->threadService.Initialize(threadContext);
    }
    threadContext->SetJSRTRuntime(this);

#ifdef ENABLE_DEBUG_CONFIG_OPTIONS
    serializeByteCodeForLibrary = false;
#endif
#ifdef ENABLE_SCRIPT_DEBUGGING
    this->jsrtDebugManager = nullptr;
#endif
}

JsrtRuntime::~JsrtRuntime()
{
    HeapDelete(allocationPolicyManager);
#ifdef ENABLE_SCRIPT_DEBUGGING
    if (this->jsrtDebugManager != nullptr)
    {
        HeapDelete(this->jsrtDebugManager);
        this->jsrtDebugManager = nullptr;
    }
#endif
}

// This is called at process detach.
// threadcontext created from runtime should not be destroyed in ThreadBoundThreadContext
// we should clean them up at process detach only as runtime can be used in other threads
// even after the current physical thread was destroyed.
// This is called after ThreadBoundThreadContext are cleaned up, so the remaining items
// in the globalthreadContext linklist should be for jsrt only.
void JsrtRuntime::Uninitialize()
{
    ThreadContext* currentThreadContext = ThreadContext::GetThreadContextList();
    ThreadContext* tmpThreadContext;
    while (currentThreadContext)
    {
        Assert(!currentThreadContext->IsScriptActive());
        JsrtRuntime* currentRuntime = static_cast<JsrtRuntime*>(currentThreadContext->GetJSRTRuntime());
        tmpThreadContext = currentThreadContext;
        currentThreadContext = currentThreadContext->Next();

#ifdef CHAKRA_STATIC_LIBRARY
        // xplat-todo: Cleanup staticlib shutdown. This only shuts down threads.
        // Other closing contexts / finalizers having trouble with current
        // runtime/context.
        RentalThreadContextManager::DestroyThreadContext(tmpThreadContext);
#else
        currentRuntime->CloseContexts();
        RentalThreadContextManager::DestroyThreadContext(tmpThreadContext);
        HeapDelete(currentRuntime);
#endif
    }
}

void JsrtRuntime::CloseContexts()
{
    while (this->contextList != NULL)
    {
        this->contextList->Dispose(false);
        // This will remove it from the list
    }
}

void JsrtRuntime::SetBeforeCollectCallback(JsBeforeCollectCallback beforeCollectCallback, void * callbackContext)
{
    if (beforeCollectCallback != nullptr)
    {
        if (this->collectCallback == nullptr)
        {
            this->collectCallback = this->threadContext->AddRecyclerCollectCallBack(RecyclerCollectCallbackStatic, this);
        }

        this->beforeCollectCallback = beforeCollectCallback;
        this->beforeCollectCallbackContext = callbackContext;
    }
    else
    {
        if (this->collectCallback != nullptr
#ifdef _CHAKRACOREBUILD
            && this->beforeSweepCallback == nullptr
#endif
            )
        {
            this->threadContext->RemoveRecyclerCollectCallBack(this->collectCallback);
            this->collectCallback = nullptr;
        }

        this->beforeCollectCallback = nullptr;
        this->beforeCollectCallbackContext = nullptr;
    }
}

#ifdef _CHAKRACOREBUILD
void JsrtRuntime::SetBeforeSweepCallback(JsBeforeSweepCallback afterCollectCallback, void * callbackContext)
{
    if (afterCollectCallback != nullptr)
    {
        if (this->collectCallback == nullptr)
        {
            this->collectCallback = this->threadContext->AddRecyclerCollectCallBack(RecyclerCollectCallbackStatic, this);
        }

        this->beforeSweepCallback = afterCollectCallback;
        this->beforeSweepCallbackContext = callbackContext;
    }
    else
    {
        if (this->collectCallback != nullptr && this->beforeCollectCallback == nullptr)
        {
            this->threadContext->RemoveRecyclerCollectCallBack(this->collectCallback);
            this->collectCallback = nullptr;
        }

        this->beforeSweepCallback = nullptr;
        this->beforeSweepCallbackContext = nullptr;
    }
}
#endif

void JsrtRuntime::RecyclerCollectCallbackStatic(void * context, RecyclerCollectCallBackFlags flags)
{
    if (flags & Collect_Begin)
    {
        JsrtRuntime * _this = reinterpret_cast<JsrtRuntime *>(context);
        if (_this->beforeCollectCallback == nullptr)
        {
            return;
        }
        try
        {
            JsrtCallbackState scope(reinterpret_cast<ThreadContext*>(_this->GetThreadContext()));
            _this->beforeCollectCallback(_this->beforeCollectCallbackContext);
        }
        catch (...)
        {
            AssertMsg(false, "Unexpected non-engine exception.");
        }
    }
#ifdef _CHAKRACOREBUILD
    else if (flags & Collect_Begin_Sweep)
    {
        JsrtRuntime * _this = reinterpret_cast<JsrtRuntime *>(context);
        if (_this->beforeSweepCallback == nullptr)
        {
            return;
        }
        try
        {
            JsrtCallbackState scope(reinterpret_cast<ThreadContext*>(_this->GetThreadContext()));
            _this->beforeSweepCallback(_this->beforeSweepCallbackContext);
        }
        catch (...)
        {
            AssertMsg(false, "Unexpected non-engine exception.");
        }
    }
#endif
}

unsigned int JsrtRuntime::Idle()
{
    return this->threadService.Idle();
}

#ifdef ENABLE_SCRIPT_DEBUGGING
void JsrtRuntime::EnsureJsrtDebugManager()
{
    if (this->jsrtDebugManager == nullptr)
    {
        this->jsrtDebugManager = HeapNew(JsrtDebugManager, this->threadContext);
    }
    Assert(this->jsrtDebugManager != nullptr);
}

void JsrtRuntime::DeleteJsrtDebugManager()
{
    if (this->jsrtDebugManager != nullptr)
    {
        HeapDelete(this->jsrtDebugManager);
        this->jsrtDebugManager = nullptr;
    }
}

JsrtDebugManager * JsrtRuntime::GetJsrtDebugManager()
{
    return this->jsrtDebugManager;
}

#if ENABLE_TTD
uint32 JsrtRuntime::BPRegister_TTD(int64 bpID, Js::ScriptContext* scriptContext, Js::Utf8SourceInfo* utf8SourceInfo, uint32 line, uint32 column, BOOL* isNewBP)
{
    TTDAssert(this->jsrtDebugManager != nullptr, "This needs to be setup before registering any breakpoints.");

    Js::BreakpointProbe* probe = this->jsrtDebugManager->SetBreakpointHelper_TTD(bpID, scriptContext, utf8SourceInfo, line, column, isNewBP);
    return probe->GetId();
}

void JsrtRuntime::BPDelete_TTD(uint32 bpID)
{
    TTDAssert(this->jsrtDebugManager != nullptr, "This needs to be setup before deleting any breakpoints.");

    this->jsrtDebugManager->GetDebugDocumentManager()->RemoveBreakpoint(bpID);
}

void JsrtRuntime::BPClearDocument_TTD()
{
    TTDAssert(this->jsrtDebugManager != nullptr, "This needs to be setup before deleting any breakpoints.");

    this->jsrtDebugManager->ClearBreakpointDebugDocumentDictionary();
}
#endif
#endif


text:
namespace NetInterop.Routing.Ospf
{
    public enum NeighborEventType
    {
        HelloReceived,
        Start,
        TwoWayReceived,
        NegotiationDone,
        ExchangeDone,
        BadLSReq,
        LoadingDone,
        AdjOK,
        SeqNumberMismatch,
        OneWayReceived,
        KillNbr,
        InactivityTimer,
        LLDown
    }
}


text:
using System;
using System.Collections.Generic;
using Prometheus.Client.MetricsWriter;

namespace Prometheus.Client.Collectors.DotNetStats
{
    public class GCTotalMemoryCollector : ICollector
    {
        private const string _help = "Total known allocated memory";
        private const string _name = "dotnet_totalmemory";

        public GCTotalMemoryCollector()
        {
            Configuration = new CollectorConfiguration(nameof(GCTotalMemoryCollector));
            MetricNames = new[] { _name };
        }

        public CollectorConfiguration Configuration { get; }

        public IReadOnlyList<string> MetricNames { get; }

        public void Collect(IMetricsWriter writer)
        {
            writer.WriteMetricHeader(_name, MetricType.Gauge, _help);
            writer.WriteSample(GC.GetTotalMemory(false));
            writer.EndMetric();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GitVersion.Logging;
using LibGit2Sharp;

namespace GitVersion.Extensions
{
    public static class RepositoryExtensions
    {
        public static string GetRepositoryDirectory(this IRepository repository, bool omitGitPostFix = true)
        {
            var gitDirectory = repository.Info.Path;

            gitDirectory = gitDirectory.TrimEnd(Path.DirectorySeparatorChar);

            if (omitGitPostFix && gitDirectory.EndsWith(".git"))
            {
                gitDirectory = gitDirectory.Substring(0, gitDirectory.Length - ".git".Length);
                gitDirectory = gitDirectory.TrimEnd(Path.DirectorySeparatorChar);
            }

            return gitDirectory;
        }

        public static Branch FindBranch(this IRepository repository, string branchName)
        {
            return repository.Branches.FirstOrDefault(x => x.NameWithoutRemote() == branchName);
        }

        public static void DumpGraph(this IRepository repository, Action<string> writer = null, int? maxCommits = null)
        {
            LibGitExtensions.DumpGraph(repository.Info.Path, writer, maxCommits);
        }

        public static void EnsureLocalBranchExistsForCurrentBranch(this IGitRepository repo, ILog log, Remote remote, string currentBranch)
        {
            if (log is null)
            {
                throw new ArgumentNullException(nameof(log));
            }

            if (remote is null)
            {
                throw new ArgumentNullException(nameof(remote));
            }

            if (string.IsNullOrEmpty(currentBranch)) return;

            var isRef = currentBranch.Contains("refs");
            var isBranch = currentBranch.Contains("refs/heads");
            var localCanonicalName = !isRef
                ? "refs/heads/" + currentBranch
                : isBranch
                    ? currentBranch
                    : currentBranch.Replace("refs/", "refs/heads/");

            var repoTip = repo.Head.Tip;

            // We currently have the rep.Head of the *default* branch, now we need to look up the right one
            var originCanonicalName = $"{remote.Name}/{currentBranch}";
            var originBranch = repo.Branches[originCanonicalName];
            if (originBranch != null)
            {
                repoTip = originBranch.Tip;
            }

            var repoTipId = repoTip.Id;

            if (repo.Branches.All(b => !b.CanonicalName.IsEquivalentTo(localCanonicalName)))
            {
                log.Info(isBranch ? $"Creating local branch {localCanonicalName}"
                    : $"Creating local branch {localCanonicalName} pointing at {repoTipId}");
                repo.Refs.Add(localCanonicalName, repoTipId);
            }
            else
            {
                log.Info(isBranch ? $"Updating local branch {localCanonicalName} to point at {repoTip.Sha}"
                    : $"Updating local branch {localCanonicalName} to match ref {currentBranch}");
                var localRef = repo.Refs[localCanonicalName];
                repo.Refs.UpdateTarget(localRef, repoTipId);
            }

            repo.Commands.Checkout(localCanonicalName);
        }

        public static void AddMissingRefSpecs(this IRepository repo, ILog log, Remote remote)
        {
            if (remote.FetchRefSpecs.Any(r => r.Source == "refs/heads/*"))
                return;

            var allBranchesFetchRefSpec = $"+refs/heads/*:refs/remotes/{remote.Name}/*";

            log.Info($"Adding refspec: {allBranchesFetchRefSpec}");

            repo.Network.Remotes.Update(remote.Name,
                r => r.FetchRefSpecs.Add(allBranchesFetchRefSpec));
        }

        public static void CreateFakeBranchPointingAtThePullRequestTip(this IGitRepository repo, ILog log, AuthenticationInfo authentication)
        {
            var remote = repo.Network.Remotes.Single();

            log.Info("Fetching remote refs to see if there is a pull request ref");
            var remoteTips = (string.IsNullOrEmpty(authentication.Username) ?
                    repo.GetRemoteTipsForAnonymousUser(remote) :
                    repo.GetRemoteTipsUsingUsernamePasswordCredentials(remote, authentication.Username, authentication.Password))
                .ToList();

            log.Info($"Remote Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, remoteTips.Select(r => r.CanonicalName)));

            var headTipSha = repo.Head.Tip.Sha;

            var refs = remoteTips.Where(r => r.TargetIdentifier == headTipSha).ToList();

            if (refs.Count == 0)
            {
                var message = $"Couldn't find any remote tips from remote '{remote.Url}' pointing at the commit '{headTipSha}'.";
                throw new WarningException(message);
            }

            if (refs.Count > 1)
            {
                var names = string.Join(", ", refs.Select(r => r.CanonicalName));
                var message = $"Found more than one remote tip from remote '{remote.Url}' pointing at the commit '{headTipSha}'. Unable to determine which one to use ({names}).";
                throw new WarningException(message);
            }

            var reference = refs[0];
            var canonicalName = reference.CanonicalName;
            log.Info($"Found remote tip '{canonicalName}' pointing at the commit '{headTipSha}'.");

            if (canonicalName.StartsWith("refs/tags"))
            {
                log.Info($"Checking out tag '{canonicalName}'");
                repo.Commands.Checkout(reference.Target.Sha);
                return;
            }

            if (!canonicalName.StartsWith("refs/pull/") && !canonicalName.StartsWith("refs/pull-requests/"))
            {
                var message = $"Remote tip '{canonicalName}' from remote '{remote.Url}' doesn't look like a valid pull request.";
                throw new WarningException(message);
            }

            var fakeBranchName = canonicalName.Replace("refs/pull/", "refs/heads/pull/").Replace("refs/pull-requests/", "refs/heads/pull-requests/");

            log.Info($"Creating fake local branch '{fakeBranchName}'.");
            repo.Refs.Add(fakeBranchName, new ObjectId(headTipSha));

            log.Info($"Checking local branch '{fakeBranchName}' out.");
            repo.Commands.Checkout(fakeBranchName);
        }

        public static void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(this IRepository repo, ILog log, string remoteName)
        {
            var prefix = $"refs/remotes/{remoteName}/";
            var remoteHeadCanonicalName = $"{prefix}HEAD";
            var remoteTrackingReferences = repo.Refs
                .FromGlob(prefix + "*")
                .Where(r => !r.CanonicalName.IsEquivalentTo(remoteHeadCanonicalName));

            foreach (var remoteTrackingReference in remoteTrackingReferences)
            {
                var remoteTrackingReferenceName = remoteTrackingReference.CanonicalName;
                var branchName = remoteTrackingReferenceName.Substring(prefix.Length);
                var localCanonicalName = "refs/heads/" + branchName;

                // We do not want to touch our current branch
                if (branchName.IsEquivalentTo(repo.Head.FriendlyName)) continue;

                if (repo.Refs.Any(x => x.CanonicalName.IsEquivalentTo(localCanonicalName)))
                {
                    var localRef = repo.Refs[localCanonicalName];
                    var remotedirectReference = remoteTrackingReference.ResolveToDirectReference();
                    if (localRef.ResolveToDirectReference().TargetIdentifier == remotedirectReference.TargetIdentifier)
                    {
                        log.Info($"Skipping update of '{remoteTrackingReference.CanonicalName}' as it already matches the remote ref.");
                        continue;
                    }
                    var remoteRefTipId = remotedirectReference.Target.Id;
                    log.Info($"Updating local ref '{localRef.CanonicalName}' to point at {remoteRefTipId}.");
                    repo.Refs.UpdateTarget(localRef, remoteRefTipId);
                    continue;
                }

                log.Info($"Creating local branch from remote tracking '{remoteTrackingReference.CanonicalName}'.");
                repo.Refs.Add(localCanonicalName, new ObjectId(remoteTrackingReference.ResolveToDirectReference().TargetIdentifier), true);

                var branch = repo.Branches[branchName];
                repo.Branches.Update(branch, b => b.TrackedBranch = remoteTrackingReferenceName);
            }
        }

        public static Remote EnsureOnlyOneRemoteIsDefined(this IRepository repo, ILog log)
        {
            var remotes = repo.Network.Remotes;
            var howMany = remotes.Count();

            if (howMany == 1)
            {
                var remote = remotes.Single();
                log.Info($"One remote found ({remote.Name} -> '{remote.Url}').");
                return remote;
            }

            var message = $"{howMany} remote(s) have been detected. When being run on a build server, the Git repository is expected to bear one (and no more than one) remote.";
            throw new WarningException(message);
        }

        private static IEnumerable<DirectReference> GetRemoteTipsUsingUsernamePasswordCredentials(this IRepository repository, Remote remote, string username, string password)
        {
            return repository.Network.ListReferences(remote, (url, fromUrl, types) => new UsernamePasswordCredentials
            {
                Username = username,
                Password = password ?? string.Empty
            }).Select(r => r.ResolveToDirectReference());
        }

        private static IEnumerable<DirectReference> GetRemoteTipsForAnonymousUser(this IRepository repository, Remote remote)
        {
            return repository.Network.ListReferences(remote).Select(r => r.ResolveToDirectReference());
        }
    }
}


text:
<?php

namespace JSiefer\MageMock\PHPUnit;

use JSiefer\MageMock\Mage\MageFacade;
use PHPUnit_Framework_Test as Test;

/**
 * Class TestListener
 *
 * @package JSiefer\MageMock
 */
class TestListener extends \PHPUnit_Framework_BaseTestListener
{
    /**
     * Reset Mage god class after each test
     *
     * @param Test $test
     * @param float $time
     */
    public function endTest(Test $test, $time)
    {
        MageFacade::reset();
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.inria.anhalytics.harvest.exceptions;

/**
 *
 * @author azhar
 */
public class GrobidTimeoutException extends RuntimeException {

    private static final long serialVersionUID = -3337770841815682150L;

    public GrobidTimeoutException() {
        super();
    }

    public GrobidTimeoutException(String message) {
        super(message);
    }

    public GrobidTimeoutException(Throwable cause) {
        super(cause);
    }

    public GrobidTimeoutException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
"""Views for Zinnia quick entry"""
try:
    from urllib.parse import urlencode
except:  # Python 2
    from urllib import urlencode

from django import forms
from django.shortcuts import redirect
from django.utils.html import linebreaks
from django.views.generic.base import View
from django.utils.encoding import smart_str
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.template.defaultfilters import slugify
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import permission_required
from django.utils import timezone

from zinnia.models.entry import Entry
from zinnia.managers import DRAFT
from zinnia.managers import PUBLISHED
from zinnia.settings import MARKUP_LANGUAGE

class QuickEntryForm(forms.ModelForm):
    """
    Form for posting an entry quickly.
    """

    class Meta:
        model = Entry
        exclude = ('comment_count',
                   'pingback_count',
                   'trackback_count')

class QuickEntry(View):
    """
    View handling the quick post of a short Entry.
    """

    @method_decorator(permission_required('zinnia.add_entry'))
    def dispatch(self, *args, **kwargs):
        """
        Decorate the view dispatcher with permission_required.
        """
        return super(QuickEntry, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        """
        GET only do a redirection to the admin for adding and entry.
        """
        return redirect('admin:zinnia_entry_add')

    def post(self, request, *args, **kwargs):
        """
        Handle the datas for posting a quick entry,
        and redirect to the admin in case of error or
        to the entry's page in case of success.
        """
        data = {
            'title': request.POST.get('title'),
            'slug': slugify(request.POST.get('title')),
            'status': DRAFT if 'save_draft' in request.POST else PUBLISHED,
            'sites': [Site.objects.get_current().pk],
            'authors': [request.user.pk],
            'content_template': 'zinnia/_entry_detail.html',
            'detail_template': 'entry_detail.html',
            'creation_date': timezone.now(),
            'last_update': timezone.now(),
            'content': request.POST.get('content'),
            'tags': request.POST.get('tags')}
        form = QuickEntryForm(data)
        if form.is_valid():
            form.instance.content = self.htmlize(form.cleaned_data['content'])
            entry = form.save()
            return redirect(entry)

        data = {'title': smart_str(request.POST.get('title', '')),
                'content': smart_str(self.htmlize(
                    request.POST.get('content', ''))),
                'tags': smart_str(request.POST.get('tags', '')),
                'slug': slugify(request.POST.get('title', '')),
                'authors': request.user.pk,
                'sites': Site.objects.get_current().pk}
        return redirect('%s?%s' % (reverse('admin:zinnia_entry_add'),
                                   urlencode(data)))

    def htmlize(self, content):
        """
        Convert to HTML the content if the MARKUP_LANGUAGE
        is set to HTML to optimize the rendering and avoid
        ugly effect in WYMEditor.
        """
        if MARKUP_LANGUAGE == 'html':
            return linebreaks(content)
        return content


text:
#pragma once
namespace fb{
	FB_DECLARE_SMART_PTR_STRUCT(CVar);
	class ICVarObserver
	{
	public:
		enum{
			Default
		};
		virtual bool OnChangeCVar(CVarPtr pCVar) = 0;
	};
}


text:
require 'rails_helper'

describe 'hq/users/new.html.erb', type: :view do

  before :each do
    assign :user, build_stubbed(:user)
  end

  it 'renders the form partial' do
    render
    expect(view).to render_template(partial: '_form')
  end

  it 'cancel button goes to index page' do
    render
    expect(rendered).to have_link('Cancel', href: hq_users_path)
  end

end


text:
/*---
skip: true
---*/

/*===
*** test_raw (duk_safe_call)
Hello world from a file!
return value is: 123
compile rc=1 -> SyntaxError: invalid object literal (line 1)
top: 0
==> rc=0, result='undefined'
===*/

#define  TMPFILE  "/tmp/duk-test-compile-file-temp.js"

#include <stdio.h>

static void write_file(const char *filename, const char *data) {
	FILE *f;
	size_t ret;

	/* Write temporary data to a temp file.  This now expects to be
	 * executed on Linux, so that /tmp works.  Less than ideal, also
	 * doesn't delete the temporary file.
	 */

	f = fopen(filename, "wb");
	if (!f) {
		printf("failed to open %s\n", TMPFILE);
		return;
	}
	ret = fwrite((const void *) data, 1, strlen(data), f);
	fflush(f);
	fclose(f);
	f = NULL;
	if (ret != strlen(data)) {
		printf("failed to write test data fully\n");
		return;
	}
}

static duk_ret_t test_raw(duk_context *ctx, void *udata) {
	const char *data1 = "print('Hello world from a file!'); 123;";
	const char *data2 = "print('Hello world from a file, with syntax error'); obj = {";
	duk_ret_t rc;

	(void) udata;

	write_file(TMPFILE, data1);
	duk_compile_file(ctx, 0, TMPFILE);
	duk_call(ctx, 0);
	printf("return value is: %s\n", duk_safe_to_string(ctx, -1));
	duk_pop(ctx);

	write_file(TMPFILE, data2);
	rc = duk_pcompile_file(ctx, 0, TMPFILE);
	printf("compile rc=%d -> %s\n", (int) rc, duk_safe_to_string(ctx, -1));
	duk_pop(ctx);

	printf("top: %ld\n", (long) duk_get_top(ctx));
	return 0;
}

void test(duk_context *ctx) {
	TEST_SAFE_CALL(test_raw);
}


text:
/*
 * Node2ElementMapper.java
 *
 * Created on April 14, 2003, 11:08 PM
 */

package xal.sim.slg;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import xal.smf.*;

/**
 * A visitor that generates the forward dictionary [(key,value)=(node,element)].
 *
 * @author  wdklotz
 */
public class Node2ElementMapper implements Visitor {
	private Map<AcceleratorNode,Element> node2ElementMap; //dictionary (key,value)=(node,element)
	private Map<String,AcceleratorNode> id2NodeMap; //dictionary (key,value)=(node ID,node)

	/** Creates a new instance of Node2ElementMapper */
	Node2ElementMapper() {
		node2ElementMap= new HashMap<AcceleratorNode,Element>();
		id2NodeMap= new HashMap<String,AcceleratorNode>();
	}
	/**
	 * Returns a set view of the mappings contained in this map.
	 */
	Set<Map.Entry<AcceleratorNode,Element>> entrySet() {
		return node2ElementMap.entrySet();
	}

	/**
	 * Getter for the map property.
	 */
	Map<AcceleratorNode,Element> getMap() {
		return node2ElementMap;
	}

	public String NodeId2ElementId(String nodeId) throws LatticeError {
		try {
			AcceleratorNode node= id2NodeMap.get(nodeId);
			Element element= node2ElementMap.get(node);
			String elementId= element.getName();
			return elementId;
		} catch (Throwable t) {
			throw new LatticeError(nodeId+": not a lattice element!");
		}
	}

	public Element NodeId2Element(String nodeId) {
		AcceleratorNode node= id2NodeMap.get(nodeId);
		return node2ElementMap.get(node);
	}

	public String Node2ElementId(AcceleratorNode node) {
		Element element= node2ElementMap.get(node);
		String elementId= element.getName();
		return elementId;
	}

	public Element Node2Element(AcceleratorNode node) {
		return node2ElementMap.get(node);
	}

	/** visit a RFGap lattice element  */
	public void visit(RFGap e) {
		node2ElementMap.put(e.getAcceleratorNode(), e);
		id2NodeMap.put(e.getAcceleratorNode().getId(), e.getAcceleratorNode());
	}

	/** visit a PermMarker lattice element  */
	public void visit(PermMarker e) {
		StringTokenizer strtok= new StringTokenizer(e.getName(), ":");
		if (strtok.nextToken().equals("ELEMENT_CENTER")) {
			node2ElementMap.put(e.getAcceleratorNode(), e);
			id2NodeMap.put(e.getAcceleratorNode().getId(), e.getAcceleratorNode());
		}
	}

	/** visit a SkewSext lattice element  */
	public void visit(SkewSext e) {
	}

	/** visit a Octupole lattice element  */
	public void visit(Octupole e) {
	}

	/** visit a BCMonitor lattice element  */
	public void visit(BCMonitor e) {
		node2ElementMap.put(e.getAcceleratorNode(), e);
		id2NodeMap.put(e.getAcceleratorNode().getId(), e.getAcceleratorNode());
	}

	/** visit a HSteerer lattice element  */
	public void visit(HSteerer e) {
		node2ElementMap.put(e.getAcceleratorNode(), e);
		id2NodeMap.put(e.getAcceleratorNode().getId(), e.getAcceleratorNode());
	}

	/** visit a Dipole lattice element  */
	public void visit(Dipole e) {
	        node2ElementMap.put(e.getAcceleratorNode(), e);
		id2NodeMap.put(e.getAcceleratorNode().getId(), e.getAcceleratorNode());
	}

	/** visit a EKicker lattice element  */
	public void visit( final EKicker element ) {
		node2ElementMap.put( element.getAcceleratorNode(), element );
		id2NodeMap.put( element.getAcceleratorNode().getId(), element.getAcceleratorNode() );
	}

	/** visit a VSteerer lattice element  */
	public void visit(VSteerer e) {
		node2ElementMap.put(e.getAcceleratorNode(), e);
		id2NodeMap.put(e.getAcceleratorNode().getId(), e.getAcceleratorNode());
	}

	/** visit a Drift lattice element  */
	public void visit(Drift e) {
	}

	/** visit a Quadrupole lattice element  */
	public void visit(Quadrupole e) {
	}

	/** visit a Quadrupole lattice element  */
	public void visit(EQuad e) {
	}

	/** visit a Solenoid lattice element  */
	public void visit(Solenoid e) {
	}

	/** visit a WScanner lattice element  */
	public void visit(WScanner e) {
		node2ElementMap.put(e.getAcceleratorNode(), e);
		id2NodeMap.put(e.getAcceleratorNode().getId(), e.getAcceleratorNode());
	}

	/** visit a BPMonitor lattice element  */
	public void visit(BPMonitor e) {
		node2ElementMap.put(e.getAcceleratorNode(), e);
		id2NodeMap.put(e.getAcceleratorNode().getId(), e.getAcceleratorNode());
	}

	/** visit a BLMonitor lattice element  */
	public void visit(BLMonitor e) {
		node2ElementMap.put(e.getAcceleratorNode(), e);
		id2NodeMap.put(e.getAcceleratorNode().getId(), e.getAcceleratorNode());
	}

	/** visit a BSMonitor lattice element  */
	public void visit( final BSMonitor element ) {
		node2ElementMap.put( element.getAcceleratorNode(), element );
		id2NodeMap.put( element.getAcceleratorNode().getId(), element.getAcceleratorNode() );
	}

	/** visit a SkewQuad lattice element  */
	public void visit(SkewQuad e) {
	}

	/** visit a Sextupole lattice element  */
	public void visit(Sextupole e) {
	}

	/** visit a Marker lattice element  */
	public void visit(Marker e) {
	}

	@Override
	public void visit(EDipole e) {

	}
}