text:
#include <memory>
#include <cstdint>
#include <string>
#include <list>
#include <nan.h>

#include <kaa/Kaa.hpp>
#include <kaa/log/strategies/RecordCountLogUploadStrategy.hpp>

using namespace kaa;

/*
 * A demo application that shows how to use the Kaa logging API.
 */
void messageUpdater( std::string data)
{
    std::cout << data << std::endl;

    /*
     * Initialize the Kaa endpoint.
     */
    auto kaaClient =  Kaa::newClient();

    /*
     * Set a custom strategy for uploading logs.
     */
    kaaClient->setLogUploadStrategy(std::make_shared<RecordCountLogUploadStrategy>(1, kaaClient->getKaaClientContext()));

    /*
     * Run the Kaa endpoint.
     */
    kaaClient->start();

    std::list<std::pair<RecordFuture, std::size_t>> futurePairs;

    // Send LOGS_TO_SEND_COUNT logs in a loop.
    std::size_t logNumber = 0;
        KaaUserLogRecord logRecord;
//        logRecord.level = kaa_log::Level::KAA_INFO;
//        logRecord.tag = "TAG";
//        logRecord.message = data;
//        logRecord.timeStamp = TimeUtils::getCurrentTimeInMs();
        logRecord.timestamp = TimeUtils::getCurrentTimeInMs();

        futurePairs.push_back(std::make_pair(std::move(kaaClient->addLogRecord(logRecord)), logRecord.timestamp));
        std::cout << "Sent " << logNumber << "th record" << std::endl;

    for (auto& pair : futurePairs) {
        try {
            RecordInfo recordInfo = pair.first.get();
            BucketInfo bucketInfo = recordInfo.getBucketInfo();

            std::size_t timeSpent = (recordInfo.getRecordAddedTimestampMs() - pair.second)
                                        + recordInfo.getRecordDeliveryTimeMs();

            std::cout << "Received log record delivery info. Bucket Id [" <<  bucketInfo.getBucketId() << "]. "
                      << "Record delivery time [" << timeSpent << " ms]." << std::endl;
        } catch (std::exception& e) {
            std::cout << "Exception was caught while waiting for callback future" << e.what();
        }
    }

    /*
     * Stop the Kaa endpoint.
     */
    kaaClient->stop();

    std::cout << "Data collection demo stopped" << std::endl;
}

void SendData(const Nan::FunctionCallbackInfo<v8::Value>& info) {

  if (info.Length() != 1) {
    Nan::ThrowTypeError("Wrong number of arguments");
    return;
  }

//  if (!info[0]->IsNumber() || !info[1]->IsNumber()) {
//    Nan::ThrowTypeError("Wrong arguments");
//    return;
//  }

  v8::Local<v8::String> arg0 = info[0]->ToString();
//  double arg1 = info[1]->NumberValue();
/////  v8::Local<v8::String> num = Nan::New(arg0);
  v8::String::Utf8Value param(arg0);
  std::string d = std::string(*param);
  messageUpdater(d);
  info.GetReturnValue().Set(arg0);
}

void Init(v8::Local<v8::Object> exports) {
  exports->Set(Nan::New("sendData").ToLocalChecked(),
               Nan::New<v8::FunctionTemplate>(SendData)->GetFunction());
}

NODE_MODULE(addon, Init)


text:
if [ -f ../../git-notifier.orig/git-notifier ]; then
    diff ../../git-notifier.orig/git-notifier ../git-notifier > icir.org.diff
fi

redpajama_set_name: RedPajamaGithub


text:
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

// .NAME vtkDelimitedTextReader - reads in delimited ascii or unicode text files
// and outputs a vtkTable data structure.
//
// .SECTION Description
// vtkDelimitedTextReader is an interface for pulling in data from a
// flat, delimited ascii or unicode text file (delimiter can be any character).
//
// The behavior of the reader with respect to ascii or unicode input
// is controlled by the SetUnicodeCharacterSet() method.  By default
// (without calling SetUnicodeCharacterSet()), the reader will expect
// to read ascii text and will output vtkStdString columns.  Use the
// Set and Get methods to set delimiters that do not contain UTF8 in
// the name when operating the reader in default ascii mode.  If the
// SetUnicodeCharacterSet() method is called, the reader will output
// vtkUnicodeString columns in the output table.  In addition, it is
// necessary to use the Set and Get methods that contain UTF8 in the
// name to specify delimiters when operating in unicode mode.
//
// There is also a special character set US-ASCII-WITH-FALLBACK that
// will treat the input text as ASCII no matter what.  If and when it
// encounters a character with its 8th bit set it will replace that
// character with the code point ReplacementCharacter.  You may use
// this if you have text that belongs to a code page like LATIN9 or
// ISO-8859-1 or friends: mostly ASCII but not entirely.  Eventually
// this class will acquire the ability to read gracefully text from
// any code page, making this option obsolete.
//
// This class emits ProgressEvent for every 100 lines it reads.
//
// .SECTION Thanks
// Thanks to Andy Wilson, Brian Wylie, Tim Shead, and Thomas Otahal
// from Sandia National Laboratories for implementing this class.
//
// .SECTION Caveats
//
// This reader assumes that the first line in the file (whether that's
// headers or the first document) contains at least as many fields as
// any other line in the file.

#ifndef vtkDelimitedTextReader_h
#define vtkDelimitedTextReader_h

#include "vtkIOInfovisModule.h" // For export macro
#include "vtkTableAlgorithm.h"
#include "vtkUnicodeString.h" // Needed for vtkUnicodeString
#include "vtkStdString.h" // Needed for vtkStdString

class VTKIOINFOVIS_EXPORT vtkDelimitedTextReader : public vtkTableAlgorithm
{
public:
  static vtkDelimitedTextReader* New();
  vtkTypeMacro(vtkDelimitedTextReader, vtkTableAlgorithm);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Specifies the delimited text file to be loaded.
  vtkGetStringMacro(FileName);
  vtkSetStringMacro(FileName);

  // Description:
  // Specify the InputString for use when reading from a character array.
  // Optionally include the length for binary strings. Note that a copy
  // of the string is made and stored. If this causes exceedingly large
  // memory consumption, consider using InputArray instead.
  void SetInputString(const char *in);
  vtkGetStringMacro(InputString);
  void SetInputString(const char *in, int len);
  vtkGetMacro(InputStringLength, int);
  void SetInputString(const vtkStdString& input)
    { this->SetInputString(input.c_str(), static_cast<int>(input.length())); }

  // Description:
  // Enable reading from an InputString or InputArray instead of the default,
  // a file.
  vtkSetMacro(ReadFromInputString,int);
  vtkGetMacro(ReadFromInputString,int);
  vtkBooleanMacro(ReadFromInputString,int);

  // Description:
  // Specifies the character set used in the input file.  Valid character set
  // names will be drawn from the list maintained by the Internet Assigned Name
  // Authority at
  //
  //   http://www.iana.org/assignments/character-sets
  //
  // Where multiple aliases are provided for a character set, the preferred MIME name
  // will be used.  vtkUnicodeDelimitedTextReader currently supports "US-ASCII", "UTF-8",
  // "UTF-16", "UTF-16BE", and "UTF-16LE" character sets.
  vtkGetStringMacro(UnicodeCharacterSet);
  vtkSetStringMacro(UnicodeCharacterSet);

  // Description:
  // Specify the character(s) that will be used to separate records.
  // The order of characters in the string does not matter.  Defaults
  // to "\r\n".
  void SetUTF8RecordDelimiters(const char* delimiters);
  const char* GetUTF8RecordDelimiters();
  void SetUnicodeRecordDelimiters(const vtkUnicodeString& delimiters);
  vtkUnicodeString GetUnicodeRecordDelimiters();

  // Description:
  // Specify the character(s) that will be used to separate fields.  For
  // example, set this to "," for a comma-separated value file.  Set
  // it to ".:;" for a file where columns can be separated by a
  // period, colon or semicolon.  The order of the characters in the
  // string does not matter.  Defaults to a comma.
  vtkSetStringMacro(FieldDelimiterCharacters);
  vtkGetStringMacro(FieldDelimiterCharacters);

  void SetUTF8FieldDelimiters(const char* delimiters);
  const char* GetUTF8FieldDelimiters();
  void SetUnicodeFieldDelimiters(const vtkUnicodeString& delimiters);
  vtkUnicodeString GetUnicodeFieldDelimiters();

  // Description:
  // Get/set the character that will begin and end strings.  Microsoft
  // Excel, for example, will export the following format:
  //
  // "First Field","Second Field","Field, With, Commas","Fourth Field"
  //
  // The third field has a comma in it.  By using a string delimiter,
  // this will be correctly read.  The delimiter defaults to '"'.
  vtkGetMacro(StringDelimiter, char);
  vtkSetMacro(StringDelimiter, char);

  void SetUTF8StringDelimiters(const char* delimiters);
  const char* GetUTF8StringDelimiters();
  void SetUnicodeStringDelimiters(const vtkUnicodeString& delimiters);
  vtkUnicodeString GetUnicodeStringDelimiters();

  // Description:
  // Set/get whether to use the string delimiter.  Defaults to on.
  vtkSetMacro(UseStringDelimiter, bool);
  vtkGetMacro(UseStringDelimiter, bool);
  vtkBooleanMacro(UseStringDelimiter, bool);

  // Description:
  // Set/get whether to treat the first line of the file as headers.
  // The default is false (no headers).
  vtkGetMacro(HaveHeaders, bool);
  vtkSetMacro(HaveHeaders, bool);

  // Description:
  // Set/get whether to merge successive delimiters.  Use this if (for
  // example) your fields are separated by spaces but you don't know
  // exactly how many.
  vtkSetMacro(MergeConsecutiveDelimiters, bool);
  vtkGetMacro(MergeConsecutiveDelimiters, bool);
  vtkBooleanMacro(MergeConsecutiveDelimiters, bool);

  // Description:
  // Specifies the maximum number of records to read from the file.  Limiting the
  // number of records to read is useful for previewing the contents of a file.
  vtkGetMacro(MaxRecords, vtkIdType);
  vtkSetMacro(MaxRecords, vtkIdType);

  // Description:
  // When set to true, the reader will detect numeric columns and create
  // vtkDoubleArray or vtkIntArray for those instead of vtkStringArray. Default
  // is off.
  vtkSetMacro(DetectNumericColumns, bool);
  vtkGetMacro(DetectNumericColumns, bool);
  vtkBooleanMacro(DetectNumericColumns, bool);

  // Description:
  // When set to true and DetectNumericColumns is also true, forces all
  // numeric columns to vtkDoubleArray even if they contain only
  // integer values. Default is off.
  vtkSetMacro(ForceDouble, bool);
  vtkGetMacro(ForceDouble, bool);
  vtkBooleanMacro(ForceDouble, bool);

  // Description:
  // When DetectNumericColumns is set to true, whether to trim whitespace from
  // strings prior to conversion to a numeric.
  // Default is false to preserve backward compatibility.
  //
  // vtkVariant handles whitespace inconsistently, so trim it before we try to
  // convert it.  For example:
  //
  // vtkVariant("  2.0").ToDouble() == 2.0 <-- leading whitespace is not a problem
  // vtkVariant("  2.0  ").ToDouble() == NaN <-- trailing whitespace is a problem
  // vtkVariant("  infinity  ").ToDouble() == NaN <-- any whitespace is a problem
  //
  // In these cases, trimming the whitespace gives us the result we expect:
  // 2.0 and INF respectively.
  vtkSetMacro(TrimWhitespacePriorToNumericConversion, bool);
  vtkGetMacro(TrimWhitespacePriorToNumericConversion, bool);
  vtkBooleanMacro(TrimWhitespacePriorToNumericConversion, bool);

  // Description:
  // When DetectNumericColumns is set to true, the reader use this value to populate
  // the vtkIntArray where empty strings are found. Default is 0.
  vtkSetMacro(DefaultIntegerValue, int);
  vtkGetMacro(DefaultIntegerValue, int);

  // Description:
  // When DetectNumericColumns is set to true, the reader use this value to populate
  // the vtkDoubleArray where empty strings are found. Default is 0.0
  vtkSetMacro(DefaultDoubleValue, double);
  vtkGetMacro(DefaultDoubleValue, double);

  // Description:
  // The name of the array for generating or assigning pedigree ids
  // (default "id").
  vtkSetStringMacro(PedigreeIdArrayName);
  vtkGetStringMacro(PedigreeIdArrayName);

  // Description:
  // If on (default), generates pedigree ids automatically.
  // If off, assign one of the arrays to be the pedigree id.
  vtkSetMacro(GeneratePedigreeIds, bool);
  vtkGetMacro(GeneratePedigreeIds, bool);
  vtkBooleanMacro(GeneratePedigreeIds, bool);

  // Description:
  // If on, assigns pedigree ids to output. Defaults to off.
  vtkSetMacro(OutputPedigreeIds, bool);
  vtkGetMacro(OutputPedigreeIds, bool);
  vtkBooleanMacro(OutputPedigreeIds, bool);

  // Description:
  // Returns a human-readable description of the most recent error, if any.
  // Otherwise, returns an empty string.  Note that the result is only valid
  // after calling Update().
  vtkStdString GetLastError();

  // Description:
  // Fallback character for use in the US-ASCII-WITH-FALLBACK
  // character set.  Any characters that have their 8th bit set will
  // be replaced with this code point.  Defaults to 'x'.
  vtkSetMacro(ReplacementCharacter, vtkTypeUInt32);
  vtkGetMacro(ReplacementCharacter, vtkTypeUInt32);

//BTX
protected:
  vtkDelimitedTextReader();
  ~vtkDelimitedTextReader();

  int RequestData(
    vtkInformation*,
    vtkInformationVector**,
    vtkInformationVector*);

  char* FileName;
  int ReadFromInputString;
  char *InputString;
  int InputStringLength;
  char* UnicodeCharacterSet;
  vtkIdType MaxRecords;
  vtkUnicodeString UnicodeRecordDelimiters;
  vtkUnicodeString UnicodeFieldDelimiters;
  vtkUnicodeString UnicodeStringDelimiters;
  vtkUnicodeString UnicodeWhitespace;
  vtkUnicodeString UnicodeEscapeCharacter;
  bool DetectNumericColumns;
  bool ForceDouble;
  bool TrimWhitespacePriorToNumericConversion;
  int DefaultIntegerValue;
  double DefaultDoubleValue;
  char* FieldDelimiterCharacters;
  char StringDelimiter;
  bool UseStringDelimiter;
  bool HaveHeaders;
  bool UnicodeOutputArrays;
  bool MergeConsecutiveDelimiters;
  char* PedigreeIdArrayName;
  bool GeneratePedigreeIds;
  bool OutputPedigreeIds;
  vtkStdString LastError;
  vtkTypeUInt32 ReplacementCharacter;

private:
  vtkDelimitedTextReader(const vtkDelimitedTextReader&); // Not implemented
  void operator=(const vtkDelimitedTextReader&);   // Not implemented
//ETX
};

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/people/age-and-gender/age/toddlers" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/people/age-and-gender/age/toddlers</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Toddlers</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/people/age-and-gender/age/toddlers</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/people/age-and-gender/age/toddlers</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE options SYSTEM
             "http://errorparser.sourceforge.net/xml/errorParserOptions20.dtd">
<!--
   This xml file provides the options to the errorParser program.

   Why a file? The number of options was getting too large. Using a file
   makes it easier to manage all these options and it will also make
   easier to add new options in the future (as needed).
   [Since changing options is usually something that will be done rarely
   once you are satisfy with the results, storing the options in a file
   makes it easier to reuse the same options, evidently]

   Why xml? Easier to program (libxml2 does the parsing) and easy to
   provide default values for some.

-->

<options version="2.0">
  <general_options>
    <!-- Prefix to be used for the error codes (enum or #define). -->
    <prefix_error_no_namespace> MY_PROG </prefix_error_no_namespace>

    <!-- The language that will be selected for the error messages and
         documentation.
         If absent, the first <message> tag will be used.

         For each error, if there are no <message> for the selected language
         the first <message> tag will be used. -->
    <selected_lang xml:lang="fr"/>
  </general_options>

  <header_file>
    <!-- The name of the enum. If absent, #define will be generated instead. -->
    <header_enum> enumErrors </header_enum>

    <!-- Name of the output dir for the error header file. If absent, the
         current directory will be used.

         Alternatively, you can put the directory directly in the header_name
         element. But if you do, the "GUARD" will use that directory name. -->
    <header_dirname> junk </header_dirname>

    <!-- The file name for the .h file which will hold the errors. -->
    <header_name> errors.h </header_name>
  </header_file>

  <errmsg_files>
    <!-- Name of the output dir for the code to retrieve the error messages.
         If absent, the current directory will be used.

         Alternatively, you can put the directory directly in the 2
         "errmsg_*_name" elements. If you do, the "GUARD" will use that
         directory name and the .c file will include the header using the
         full name (errmsg_header_name) -->
    <errmsg_dirname> junk </errmsg_dirname>
    <!-- The file name for the .h file for the code to retrieve the error
       messages. -->
    <errmsg_header_name> getError.h </errmsg_header_name>
    <!-- The file name for the .c file for the code to retrieve the error
         messages. -->
    <errmsg_c_fullname> junk/getError.c </errmsg_c_fullname>
    <!-- We want the Win32 export decoration -->
    <errmsg_options build_dll="yes" />
    <!-- Prefix to be used for all variables in the code to retrieve the
         error messages -->
    <errmsg_prefix_var> prog </errmsg_prefix_var>
    <!-- How to handle the error message. The problem: the generated C strings
         will be use, eventually, by standard C/C++ libraries and some
         sequence of characters could have some bad side effects, possibly
         including security issues.
         The defaults:
           - escape sequences are not permitted (a more fine grain approach
             could be written if the need arise).
           - quotes (' and ") are allowed (and will be escaped as needed)
           - The % symbol. No default. I recommend the textual "percent"
             (% is the most problematic one, IMHO. %d %p, etc are interpreted
             differently by libc (printf()) and the iostream library (cout) -->
    <errmsg_msg percent="percent" />
  </errmsg_files>
</options>


text:
package com.vladsch.MissingInActions.actions.character.custom;

import com.vladsch.MissingInActions.actions.character.AbstractNextOrPrevWordHandler;
import com.vladsch.MissingInActions.settings.ApplicationSettings;

public class NextOrPrevWordStartOrEndHandler extends AbstractNextOrPrevWordHandler {
    public enum BoundaryActionType {
        WORD,
        WORD_START,
        WORD_END,
    }

    final private BoundaryActionType myActionType;
    final private boolean myNext;
    final private boolean myWithSelection;
    final private boolean myInDifferentHumpsMode;
    final private ApplicationSettings mySettings;

    public NextOrPrevWordStartOrEndHandler(boolean next, boolean withSelection, boolean inDifferentHumpsMode, BoundaryActionType actionType) {
        super();

        myActionType = actionType;
        myNext = next;
        myWithSelection = withSelection;
        myInDifferentHumpsMode = inDifferentHumpsMode;

        mySettings = ApplicationSettings.getInstance();
    }

    public boolean isNext() {
        return myNext;
    }

    public boolean isWithSelection() {
        return myWithSelection;
    }

    public boolean isInDifferentHumpsMode() {
        return myInDifferentHumpsMode;
    }

    public int getBoundaryFlags() {
        if (myActionType == BoundaryActionType.WORD_END) {
            return myNext ? mySettings.getCustomizedNextWordEndBounds() : mySettings.getCustomizedPrevWordEndBounds();
        }
        if (myActionType == BoundaryActionType.WORD_START) {
            return myNext ? mySettings.getCustomizedNextWordStartBounds() : mySettings.getCustomizedPrevWordStartBounds();
        }
        return myNext ? mySettings.getCustomizedNextWordBounds() : mySettings.getCustomizedPrevWordBounds();
    }
}


text:
class CategoriesToJsonConverter {
public:
  // TODO: move semantics
  virtual std::string CategoriesToJsonStr(CategoriesElem *categories) = 0;
  virtual CategoriesElem * JsonStrToCategories(const std::string &json_str_categories) = 0;
  virtual ~CategoriesToJsonConverter() {}
};

class CategoriesToJsonConverterJsoncppLib : public CategoriesToJsonConverter {
public:
  // TODO: move semantics
  std::string CategoriesToJsonStr(CategoriesElem *categories);
  CategoriesElem * JsonStrToCategories(const std::string &json_str_categories);
private:
  void ConvertCategoriesToJson(Json::Value &json_value, const CategoriesElem* categories);
  void ConvertJsonToCategories(CategoriesElem* parent_category, const unsigned int &index, const Json::Value &json_value);
};

class CategoriesToJsonFileConverter final : public CategoriesToExtDbConverter {
public:
  CategoriesToJsonFileConverter(const std::string &json_db_filename, CategoriesToJsonConverter *categories_to_json_converter);
  void CategoriesToExtDb(CategoriesElem *categories) override;
  CategoriesElem * ExtDbToCategories() override;
private:
  std::string json_db_filename;
  CategoriesToJsonConverter *categories_to_json_converter;
};

#endif


text:
package org.redisson.executor;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import org.redisson.api.RScheduledFuture;
import org.redisson.misc.PromiseDelegator;

/**
 *
 * @author Nikita Koksharov
 *
 * @param <V> value type
 */
public class RedissonScheduledFuture<V> extends PromiseDelegator<V> implements RScheduledFuture<V> {

    private final long scheduledExecutionTime;
    private final String taskId;

    public RedissonScheduledFuture(RemotePromise<V> promise, long scheduledExecutionTime) {
        super(promise);
        this.scheduledExecutionTime = scheduledExecutionTime;
        this.taskId = promise.getRequestId();
    }

    @Override
    public int compareTo(Delayed other) {
        if (this == other) {
            return 0;
        }

        long diff = getDelay(TimeUnit.MILLISECONDS) - other.getDelay(TimeUnit.MILLISECONDS);

        if (diff == 0) {
            return 0;
        }
        if (diff < 0) {
            return -1;
        }
        return 1;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(scheduledExecutionTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public String getTaskId() {
        return taskId;
    }

}


text:
package jade.wrapper;

import jade.core.Location;

/**
This interface is a Proxy, allowing access to a JADE agent.
Invoking methods on instances of this class, it is possible to
trigger state transition of the agent life cycle.  This class must
not be instantiated by applications. Instead, use the
createAgent() method in class
AgentContainer.

NOT available in MIDP

@see jade.wrapper.AgentContainer#createNewAgent(String, String, Object[])
@author Giovanni Rimassa - Universita' di Parma
*/
public interface AgentController {

	/**
	     Constant representing an asynchronous rendez-vous policy.
	     @see jade.wrapper.Agent#putO2AObject(Object, boolean)
	 */
	public static final boolean ASYNC = false;
	/**
	     Constant representing a synchronous rendez-vous policy.
	     @see jade.wrapper.Agent#putO2AObject(Object o, boolean blocking)
	 */
	public static final boolean SYNC = true;

	/**
	 * Get the platforms name of the agent.
	 * This name would be what the platform would use to uniquely reference this agent.
	 * @return The agents name.
	 */
	public String getName() throws StaleProxyException;

	/**
	     Triggers a state transition from INITIATED to
	     ACTIVE. This call also starts the internal agent
	     thread. If this call is performed on an already started agent,
	     nothing happens.
	     @exception StaleProxyException If the underlying agent is dead or
	     gone.
	 */
	public void start() throws StaleProxyException;

	/**
	     Triggers a state transition from ACTIVE to
	     SUSPENDED.
	     @exception StaleProxyException If the underlying agent is dead or
	     gone.
	 */
	public void suspend() throws StaleProxyException;

	/**
	     Triggers a state transition from SUSPENDED to
	     ACTIVE.
	     @exception StaleProxyException If the underlying agent is dead or
	     gone.
	 */
	public void activate() throws StaleProxyException;

	/**
	     Triggers a state transition from ACTIVE to
	     DELETED. This call also stops the internal agent thread
	     and fully terminates the agent. If this call is performed on an
	     already terminated agent, nothing happens.
	     @exception StaleProxyException If the underlying agent is dead or
	     gone.
	 */
	public void kill() throws StaleProxyException;

	/**
	     Triggers a state transition from ACTIVE to
	     TRANSIT. This call also moves the agent code and data to
	     another container. This calls terminates the locally running
	     agent, so that this proxy object becomes detached from the moved
	     agent that keeps on executing elsewhere (i.e., no proxy
	     remotization is performed).

	     @param where A Location object, representing the
	     container the agent should move to.
	     @exception StaleProxyException If the underlying agent is dead or
	     gone.
	 */
	public void move(Location where) throws StaleProxyException;

	/**
	     Clones the current agent. Calling this method does not really
	     trigger a state transition in the current agent
	     lifecycle. Rather, it creates another agent on the given
	     location, that is just a copy of this agent.

	     @param where The Location object, representing the
	     container where the new agent copy will start.
	     @param newName The new nickname to give to the copy.
	     @exception StaleProxyException If the underlying agent is dead or
	     gone.
	 */
	public void clone(Location where, String newName) throws StaleProxyException;

	/**
	     Passes an application-specific object to a local agent, created
	     using JADE In-Process Interface. The object will be put into an
	     internal agent queue, from where it can be picked using the
	     jade.core.Agent.getO2AObject() method. The agent
	     must first declare its will to accept passed objects, using the
	     jade.core.Agent.setEnabledO2ACommunication() method.
	     @param o The object to put in the private agent queue.
	     @param blocking A flag, stating the desired rendez-vous policy;
	     it can be ASYNC, for a non-blocking call, returning
	     right after putting the object in the quque, or
	     SYNC, for a blocking call that does not return until
	     the agent picks the object from the private queue.
	     @see jade.core.Agent#getO2AObject()
	     @see jade.core.Agent#setEnabledO2ACommunication(boolean enabled, int queueSize)
	 */
	public void putO2AObject(Object o, boolean blocking) throws StaleProxyException;

	//#J2ME_EXCLUDE_BEGIN
	/**
	 * Retrieve an O2A (Object-to-Agent) interface to interact with the controlled
	 * agent.
	 * @param theInterface The O2A interface that must be retrieved
	 * @return An implementation of the indicated O2A interface
	 * @exception StaleProxyException If the underlying agent is dead or gone.
	 * @see jade.core.Agent#registerO2AInterface(Class<T> theClass, T theInterface)
	 */
	public <T> T getO2AInterface(Class<T> theInterface) throws StaleProxyException;
	//#J2ME_EXCLUDE_END

	/**
	     Read current agent state. This method can be used to query an
	     agent for its state from the outside.
	     @return the Agent Platform Life Cycle state this agent is currently in.
	 */
	public State getState() throws StaleProxyException;

}


text:
<!DOCTYPE html>

    <link rel="import" href="x-hr.html">

Custom Event

fire() custom events.

If your element is within another Polymer element, you can use the special on-* handlers to deal with the event.

<x-hr></x-hr>
<x-hr width="200"></x-hr>


text:
using grpc = global::Grpc.Core;

namespace Grpc.Testing {
  public static partial class WorkerService
  {
    static readonly string __ServiceName = "grpc.testing.WorkerService";

    static readonly grpc::Marshaller<global::Grpc.Testing.ServerArgs> __Marshaller_grpc_testing_ServerArgs = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ServerArgs.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::Grpc.Testing.ServerStatus> __Marshaller_grpc_testing_ServerStatus = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ServerStatus.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::Grpc.Testing.ClientArgs> __Marshaller_grpc_testing_ClientArgs = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ClientArgs.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::Grpc.Testing.ClientStatus> __Marshaller_grpc_testing_ClientStatus = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ClientStatus.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::Grpc.Testing.CoreRequest> __Marshaller_grpc_testing_CoreRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.CoreRequest.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::Grpc.Testing.CoreResponse> __Marshaller_grpc_testing_CoreResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.CoreResponse.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::Grpc.Testing.Void> __Marshaller_grpc_testing_Void = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Void.Parser.ParseFrom);

    static readonly grpc::Method<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> __Method_RunServer = new grpc::Method<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus>(
        grpc::MethodType.DuplexStreaming,
        __ServiceName,
        "RunServer",
        __Marshaller_grpc_testing_ServerArgs,
        __Marshaller_grpc_testing_ServerStatus);

    static readonly grpc::Method<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> __Method_RunClient = new grpc::Method<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus>(
        grpc::MethodType.DuplexStreaming,
        __ServiceName,
        "RunClient",
        __Marshaller_grpc_testing_ClientArgs,
        __Marshaller_grpc_testing_ClientStatus);

    static readonly grpc::Method<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse> __Method_CoreCount = new grpc::Method<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse>(
        grpc::MethodType.Unary,
        __ServiceName,
        "CoreCount",
        __Marshaller_grpc_testing_CoreRequest,
        __Marshaller_grpc_testing_CoreResponse);

    static readonly grpc::Method<global::Grpc.Testing.Void, global::Grpc.Testing.Void> __Method_QuitWorker = new grpc::Method<global::Grpc.Testing.Void, global::Grpc.Testing.Void>(
        grpc::MethodType.Unary,
        __ServiceName,
        "QuitWorker",
        __Marshaller_grpc_testing_Void,
        __Marshaller_grpc_testing_Void);

    /// Service descriptor
    public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
    {
      get { return global::Grpc.Testing.WorkerServiceReflection.Descriptor.Services[0]; }
    }

    /// Base class for server-side implementations of WorkerService
    [grpc::BindServiceMethod(typeof(WorkerService), "BindService")]
    public abstract partial class WorkerServiceBase
    {
      ///
      /// Start server with specified workload.
      /// First request sent specifies the ServerConfig followed by ServerStatus
      /// response. After that, a "Mark" can be sent anytime to request the latest
      /// stats. Closing the stream will initiate shutdown of the test server
      /// and once the shutdown has finished, the OK status is sent to terminate
      /// this RPC.
      ///
      /// <param name="requestStream">Used for reading requests from the client.</param>
      /// <param name="responseStream">Used for sending responses back to the client.</param>
      /// <param name="context">The context of the server-side call handler being invoked.</param>
      /// <returns>A task indicating completion of the handler.</returns>
      public virtual global::System.Threading.Tasks.Task RunServer(grpc::IAsyncStreamReader<global::Grpc.Testing.ServerArgs> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.ServerStatus> responseStream, grpc::ServerCallContext context)
      {
        throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
      }

      ///
      /// Start client with specified workload.
      /// First request sent specifies the ClientConfig followed by ClientStatus
      /// response. After that, a "Mark" can be sent anytime to request the latest
      /// stats. Closing the stream will initiate shutdown of the test client
      /// and once the shutdown has finished, the OK status is sent to terminate
      /// this RPC.
      ///
      /// <param name="requestStream">Used for reading requests from the client.</param>
      /// <param name="responseStream">Used for sending responses back to the client.</param>
      /// <param name="context">The context of the server-side call handler being invoked.</param>
      /// <returns>A task indicating completion of the handler.</returns>
      public virtual global::System.Threading.Tasks.Task RunClient(grpc::IAsyncStreamReader<global::Grpc.Testing.ClientArgs> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.ClientStatus> responseStream, grpc::ServerCallContext context)
      {
        throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
      }

      ///
      /// Just return the core count - unary call
      ///
      /// <param name="request">The request received from the client.</param>
      /// <param name="context">The context of the server-side call handler being invoked.</param>
      /// <returns>The response to send back to the client (wrapped by a task).</returns>
      public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.CoreResponse> CoreCount(global::Grpc.Testing.CoreRequest request, grpc::ServerCallContext context)
      {
        throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
      }

      ///
      /// Quit this worker
      ///
      /// <param name="request">The request received from the client.</param>
      /// <param name="context">The context of the server-side call handler being invoked.</param>
      /// <returns>The response to send back to the client (wrapped by a task).</returns>
      public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Void> QuitWorker(global::Grpc.Testing.Void request, grpc::ServerCallContext context)
      {
        throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
      }

    }

    /// Client for WorkerService
    public partial class WorkerServiceClient : grpc::ClientBase<WorkerServiceClient>
    {
      /// Creates a new client for WorkerService
      /// <param name="channel">The channel to use to make remote calls.</param>
      public WorkerServiceClient(grpc::ChannelBase channel) : base(channel)
      {
      }
      /// Creates a new client for WorkerService that uses a custom <c>CallInvoker</c>.
      /// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
      public WorkerServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
      {
      }
      /// Protected parameterless constructor to allow creation of test doubles.
      protected WorkerServiceClient() : base()
      {
      }
      /// Protected constructor to allow creation of configured clients.
      /// <param name="configuration">The client configuration.</param>
      protected WorkerServiceClient(ClientBaseConfiguration configuration) : base(configuration)
      {
      }

      ///
      /// Start server with specified workload.
      /// First request sent specifies the ServerConfig followed by ServerStatus
      /// response. After that, a "Mark" can be sent anytime to request the latest
      /// stats. Closing the stream will initiate shutdown of the test server
      /// and once the shutdown has finished, the OK status is sent to terminate
      /// this RPC.
      ///
      /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
      /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
      /// <param name="cancellationToken">An optional token for canceling the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
      {
        return RunServer(new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      ///
      /// Start server with specified workload.
      /// First request sent specifies the ServerConfig followed by ServerStatus
      /// response. After that, a "Mark" can be sent anytime to request the latest
      /// stats. Closing the stream will initiate shutdown of the test server
      /// and once the shutdown has finished, the OK status is sent to terminate
      /// this RPC.
      ///
      /// <param name="options">The options for the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(grpc::CallOptions options)
      {
        return CallInvoker.AsyncDuplexStreamingCall(__Method_RunServer, null, options);
      }
      ///
      /// Start client with specified workload.
      /// First request sent specifies the ClientConfig followed by ClientStatus
      /// response. After that, a "Mark" can be sent anytime to request the latest
      /// stats. Closing the stream will initiate shutdown of the test client
      /// and once the shutdown has finished, the OK status is sent to terminate
      /// this RPC.
      ///
      /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
      /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
      /// <param name="cancellationToken">An optional token for canceling the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
      {
        return RunClient(new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      ///
      /// Start client with specified workload.
      /// First request sent specifies the ClientConfig followed by ClientStatus
      /// response. After that, a "Mark" can be sent anytime to request the latest
      /// stats. Closing the stream will initiate shutdown of the test client
      /// and once the shutdown has finished, the OK status is sent to terminate
      /// this RPC.
      ///
      /// <param name="options">The options for the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(grpc::CallOptions options)
      {
        return CallInvoker.AsyncDuplexStreamingCall(__Method_RunClient, null, options);
      }
      ///
      /// Just return the core count - unary call
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
      /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
      /// <param name="cancellationToken">An optional token for canceling the call.</param>
      /// <returns>The response received from the server.</returns>
      public virtual global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
      {
        return CoreCount(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      ///
      /// Just return the core count - unary call
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="options">The options for the call.</param>
      /// <returns>The response received from the server.</returns>
      public virtual global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, grpc::CallOptions options)
      {
        return CallInvoker.BlockingUnaryCall(__Method_CoreCount, null, options, request);
      }
      ///
      /// Just return the core count - unary call
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
      /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
      /// <param name="cancellationToken">An optional token for canceling the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
      {
        return CoreCountAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      ///
      /// Just return the core count - unary call
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="options">The options for the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, grpc::CallOptions options)
      {
        return CallInvoker.AsyncUnaryCall(__Method_CoreCount, null, options, request);
      }
      ///
      /// Quit this worker
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
      /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
      /// <param name="cancellationToken">An optional token for canceling the call.</param>
      /// <returns>The response received from the server.</returns>
      public virtual global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
      {
        return QuitWorker(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      ///
      /// Quit this worker
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="options">The options for the call.</param>
      /// <returns>The response received from the server.</returns>
      public virtual global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, grpc::CallOptions options)
      {
        return CallInvoker.BlockingUnaryCall(__Method_QuitWorker, null, options, request);
      }
      ///
      /// Quit this worker
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
      /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
      /// <param name="cancellationToken">An optional token for canceling the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
      {
        return QuitWorkerAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      ///
      /// Quit this worker
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="options">The options for the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, grpc::CallOptions options)
      {
        return CallInvoker.AsyncUnaryCall(__Method_QuitWorker, null, options, request);
      }
      /// Creates a new instance of client from given <c>ClientBaseConfiguration</c>.
      protected override WorkerServiceClient NewInstance(ClientBaseConfiguration configuration)
      {
        return new WorkerServiceClient(configuration);
      }
    }

    /// Creates service definition that can be registered with a server
    /// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
    public static grpc::ServerServiceDefinition BindService(WorkerServiceBase serviceImpl)
    {
      return grpc::ServerServiceDefinition.CreateBuilder()
          .AddMethod(__Method_RunServer, serviceImpl.RunServer)
          .AddMethod(__Method_RunClient, serviceImpl.RunClient)
          .AddMethod(__Method_CoreCount, serviceImpl.CoreCount)
          .AddMethod(__Method_QuitWorker, serviceImpl.QuitWorker).Build();
    }

    /// Register service method with a service binder with or without implementation. Useful when customizing the  service binding logic.
    /// Note: this method is part of an experimental API that can change or be removed without any prior notice.
    /// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param>
    /// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
    public static void BindService(grpc::ServiceBinderBase serviceBinder, WorkerServiceBase serviceImpl)
    {
      serviceBinder.AddMethod(__Method_RunServer, serviceImpl == null ? null : new grpc::DuplexStreamingServerMethod<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus>(serviceImpl.RunServer));
      serviceBinder.AddMethod(__Method_RunClient, serviceImpl == null ? null : new grpc::DuplexStreamingServerMethod<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus>(serviceImpl.RunClient));
      serviceBinder.AddMethod(__Method_CoreCount, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse>(serviceImpl.CoreCount));
      serviceBinder.AddMethod(__Method_QuitWorker, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grpc.Testing.Void, global::Grpc.Testing.Void>(serviceImpl.QuitWorker));
    }

  }
}
#endregion


text:
package aufgabe5.flo;

/**
 * @author GEMEH, FLRAU, PAFAV
 *
 * Creates a simple List
 *
 */
public class List<A> implements Collection<A> {
	protected Node head = null;
	protected Node tail = null;

	/**
	 * Subclass Node
	 */
	protected class Node {
		A elem;
		Node next = null;
		Node (A elem) {this.elem = elem;}
	}
	/**
	 * Subclass Iterator
	 */
	protected class ListIter implements Iterator<A>{
		protected Node p = head;

		public ListIter() {
			// Iterator begins with head
			p = head;
		}

		public boolean hasNext() {
			// true if there is a next Element
			return p != null;
		}

		public A next(){
			// returns the next Element
			if (p == null) return null;

			A elem = p.elem;
			p = p.next;
			return elem;
		}
	}

	public void add(A x) {
		// Expects an Element x and inserts it into the list
		if (head == null) tail = head = new Node(x);
		else tail = tail.next = new Node(x);
	}

	public Iterator<A> iterator() {
		// returns the iterator of the list
		return new ListIter();
	}

}


text:
package godl

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"net/url"
	"os"
	"os/exec"
	"regexp"
	"strings"
	"sync"

	"github.com/LK4D4/vndr/godl/singleflight"
	"github.com/LK4D4/vndr/versioned"
)

// envForDir returns a copy of the environment
// suitable for running in the given directory.
// The environment is the current process's environment
// but with an updated $PWD, so that an os.Getwd in the
// child will be faster.
func envForDir(dir string, base []string) []string {
	// Internally we only use rooted paths, so dir is rooted.
	// Even if dir is not rooted, no harm done.
	return mergeEnvLists([]string{"PWD=" + dir}, base)
}

// mergeEnvLists merges the two environment lists such that
// variables with the same name in "in" replace those in "out".
func mergeEnvLists(in, out []string) []string {
NextVar:
	for _, inkv := range in {
		k := strings.SplitAfterN(inkv, "=", 2)[0]
		for i, outkv := range out {
			if strings.HasPrefix(outkv, k) {
				out[i] = inkv
				continue NextVar
			}
		}
		out = append(out, inkv)
	}
	return out
}

// A vcsCmd describes how to use a version control system
// like Mercurial, Git, or Subversion.
type vcsCmd struct {
	name string
	cmd  string // name of binary to invoke command

	createCmd    []string // commands to download a fresh copy of a repository
	createRevCmd []string // commands to download specified revision of a repository

	scheme  []string
	pingCmd string

	remoteRepo  func(v *vcsCmd, rootDir string) (remoteRepo string, err error)
	resolveRepo func(v *vcsCmd, rootDir, remoteRepo string) (realRepo string, err error)
}

var isSecureScheme = map[string]bool{
	"https":   true,
	"git+ssh": true,
	"bzr+ssh": true,
	"svn+ssh": true,
	"ssh":     true,
}

// vcsList lists the known version control systems
var vcsList = []*vcsCmd{
	vcsHg,
	vcsGit,
	vcsSvn,
	vcsBzr,
}

// vcsByCmd returns the version control system for the given
// command name (hg, git, svn, bzr).
func vcsByCmd(cmd string) *vcsCmd {
	for _, vcs := range vcsList {
		if vcs.cmd == cmd {
			return vcs
		}
	}
	return nil
}

// vcsHg describes how to use Mercurial.
var vcsHg = &vcsCmd{
	name: "Mercurial",
	cmd:  "hg",

	createCmd:    []string{"clone -U {repo} {dir}"},
	createRevCmd: []string{"clone --updaterev {rev} {repo} {dir}"},

	scheme:     []string{"https", "http", "ssh"},
	pingCmd:    "identify {scheme}://{repo}",
	remoteRepo: hgRemoteRepo,
}

func hgRemoteRepo(vcsHg *vcsCmd, rootDir string) (remoteRepo string, err error) {
	out, err := vcsHg.runOutput(rootDir, "paths default")
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(out)), nil
}

// vcsGit describes how to use Git.
var vcsGit = &vcsCmd{
	name: "Git",
	cmd:  "git",

	createCmd:    []string{"clone {repo} {dir}", "-C {dir} submodule update --init --recursive"},
	createRevCmd: []string{"clone {repo} {dir}", "-C {dir} submodule update --init --recursive", "-C {dir} checkout {rev}", "-C {dir} reset --hard {rev}"},

	scheme:     []string{"https", "http", "git+ssh", "ssh", "git"},
	pingCmd:    "ls-remote {scheme}://{repo}",
	remoteRepo: gitRemoteRepo,
}

// scpSyntaxRe matches the SCP-like addresses used by Git to access
// repositories by SSH.
var scpSyntaxRe = regexp.MustCompile(`^([a-zA-Z0-9_]+)@([a-zA-Z0-9._-]+):(.*)$`)

func gitRemoteRepo(vcsGit *vcsCmd, rootDir string) (remoteRepo string, err error) {
	cmd := "config remote.origin.url"
	errParse := errors.New("unable to parse output of git " + cmd)
	errRemoteOriginNotFound := errors.New("remote origin not found")
	outb, err := vcsGit.run1(rootDir, cmd, nil, false)
	if err != nil {
		// if it doesn't output any message, it means the config argument is correct,
		// but the config value itself doesn't exist
		if outb != nil && len(outb) == 0 {
			return "", errRemoteOriginNotFound
		}
		return "", err
	}
	out := strings.TrimSpace(string(outb))

	var repoURL *url.URL
	if m := scpSyntaxRe.FindStringSubmatch(out); m != nil {
		// Match SCP-like syntax and convert it to a URL.
		// Eg, "git@github.com:user/repo" becomes
		// "ssh://git@github.com/user/repo".
		repoURL = &url.URL{
			Scheme:  "ssh",
			User:    url.User(m[1]),
			Host:    m[2],
			RawPath: m[3],
		}
	} else {
		repoURL, err = url.Parse(out)
		if err != nil {
			return "", err
		}
	}

	// Iterate over insecure schemes too, because this function simply
	// reports the state of the repo. If we can't see insecure schemes then
	// we can't report the actual repo URL.
	for _, s := range vcsGit.scheme {
		if repoURL.Scheme == s {
			return repoURL.String(), nil
		}
	}
	return "", errParse
}

// vcsBzr describes how to use Bazaar.
var vcsBzr = &vcsCmd{
	name: "Bazaar",
	cmd:  "bzr",

	createCmd:    []string{"branch {repo} {dir}"},
	createRevCmd: []string{"branch {repo} -r {rev} {dir}"},

	scheme:      []string{"https", "http", "bzr", "bzr+ssh"},
	pingCmd:     "info {scheme}://{repo}",
	remoteRepo:  bzrRemoteRepo,
	resolveRepo: bzrResolveRepo,
}

func bzrRemoteRepo(vcsBzr *vcsCmd, rootDir string) (remoteRepo string, err error) {
	outb, err := vcsBzr.runOutput(rootDir, "config parent_location")
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(outb)), nil
}

func bzrResolveRepo(vcsBzr *vcsCmd, rootDir, remoteRepo string) (realRepo string, err error) {
	outb, err := vcsBzr.runOutput(rootDir, "info "+remoteRepo)
	if err != nil {
		return "", err
	}
	out := string(outb)

	// Expect:
	// ...
	//   (branch root|repository branch): <URL>
	// ...

	found := false
	for _, prefix := range []string{"\n  branch root: ", "\n  repository branch: "} {
		i := strings.Index(out, prefix)
		if i >= 0 {
			out = out[i+len(prefix):]
			found = true
			break
		}
	}
	if !found {
		return "", fmt.Errorf("unable to parse output of bzr info")
	}

	i := strings.Index(out, "\n")
	if i < 0 {
		return "", fmt.Errorf("unable to parse output of bzr info")
	}
	out = out[:i]
	return strings.TrimSpace(string(out)), nil
}

// vcsSvn describes how to use Subversion.
var vcsSvn = &vcsCmd{
	name: "Subversion",
	cmd:  "svn",

	createCmd:    []string{"checkout {repo} {dir}"},
	createRevCmd: []string{"checkout {repo} -r {rev} {dir}"},

	// There is no tag command in subversion.
	// The branch information is all in the path names.

	scheme:     []string{"https", "http", "svn", "svn+ssh"},
	pingCmd:    "info {scheme}://{repo}",
	remoteRepo: svnRemoteRepo,
}

func svnRemoteRepo(vcsSvn *vcsCmd, rootDir string) (remoteRepo string, err error) {
	outb, err := vcsSvn.runOutput(rootDir, "info")
	if err != nil {
		return "", err
	}
	out := string(outb)

	// Expect:
	// ...
	// Repository Root: <URL>
	// ...

	i := strings.Index(out, "\nRepository Root: ")
	if i < 0 {
		return "", fmt.Errorf("unable to parse output of svn info")
	}
	out = out[i+len("\nRepository Root: "):]
	i = strings.Index(out, "\n")
	if i < 0 {
		return "", fmt.Errorf("unable to parse output of svn info")
	}
	out = out[:i]
	return strings.TrimSpace(string(out)), nil
}

func (v *vcsCmd) String() string {
	return v.name
}

// runVerboseOnly is like run but only generates error output to standard error in verbose mode.
func (v *vcsCmd) runVerboseOnly(dir, cmd string, keyval ...string) error {
	_, err := v.run1(dir, cmd, keyval, false)
	return err
}

// runOutput is like run but returns the output of the command.
func (v *vcsCmd) runOutput(dir, cmd string, keyval ...string) ([]byte, error) {
	return v.run1(dir, cmd, keyval, true)
}

// run1 is the generalized implementation of run and runOutput.
func (v *vcsCmd) run1(dir, cmdline string, keyval []string, verbose bool) ([]byte, error) {
	m := make(map[string]string)
	for i := 0; i < len(keyval); i += 2 {
		m[keyval[i]] = keyval[i+1]
	}
	args := strings.Fields(cmdline)
	for i, arg := range args {
		args[i] = expand(m, arg)
	}

	_, err := exec.LookPath(v.cmd)
	if err != nil {
		fmt.Fprintf(os.Stderr,
			"go: missing %s command. See https://golang.org/s/gogetcmd\n",
			v.name)
		return nil, err
	}
	cmd := exec.Command(v.cmd, args...)
	cmd.Dir = dir
	cmd.Env = envForDir(cmd.Dir, os.Environ())
	var buf bytes.Buffer
	cmd.Stdout = &buf
	cmd.Stderr = &buf
	err = cmd.Run()
	out := buf.Bytes()
	if err != nil {
		return out, err
	}
	return out, nil
}

// ping pings to determine scheme to use.
func (v *vcsCmd) ping(scheme, repo string) error {
	return v.runVerboseOnly(".", v.pingCmd, "scheme", scheme, "repo", repo)
}

// create creates a new copy of repo in dir.
// The parent of dir must exist; dir must not.
func (v *vcsCmd) create(dir, repo string) error {
	for _, cmd := range v.createCmd {
		if out, err := v.runOutput(".", cmd, "dir", dir, "repo", repo); err != nil {
			return fmt.Errorf("Err: %v, out: %s", err, out)
		}
	}
	return nil
}

func (v *vcsCmd) createRev(dir, repo, rev string) error {
	for _, cmd := range v.createRevCmd {
		if out, err := v.runOutput(".", cmd, "dir", dir, "repo", repo, "rev", rev); err != nil {
			return fmt.Errorf("Err: %v, out: %s", err, out)
		}
	}
	return nil
}

// A vcsPath describes how to convert an import path into a
// version control system and repository name.
type vcsPath struct {
	prefix string                              // prefix this description applies to
	re     string                              // pattern for import path
	repo   string                              // repository to use (expand with match of re)
	vcs    string                              // version control system to use (expand with match of re)
	check  func(match map[string]string) error // additional checks
	ping   bool                                // ping for scheme to use to download repo

	regexp *regexp.Regexp // cached compiled form of re
}

// repoRoot represents a version control system, a repo, and a root of
// where to put it on disk.
type repoRoot struct {
	vcs *vcsCmd

	// repo is the repository URL, including scheme
	repo string

	// root is the import path corresponding to the root of the
	// repository
	root string
}

var httpPrefixRE = regexp.MustCompile(`^https?:`)

// securityMode specifies whether a function should make network
// calls using insecure transports (eg, plain text HTTP).
// The zero value is "secure".
type securityMode int

const (
	secure securityMode = iota
	insecure
)

// repoRootForImportPath analyzes importPath to determine the
// version control system, and code repository to use.
func repoRootForImportPath(importPath string, security securityMode) (*repoRoot, error) {
	rr, err := repoRootFromVCSPaths(importPath, "", security, vcsPaths)
	if err == errUnknownSite {
		// If there are wildcards, look up the thing before the wildcard,
		// hoping it applies to the wildcarded parts too.
		// This makes 'go get rsc.io/pdf/...' work in a fresh GOPATH.
		lookup := strings.TrimSuffix(importPath, "/...")
		if i := strings.Index(lookup, "/.../"); i >= 0 {
			lookup = lookup[:i]
		}
		rr, err = repoRootForImportDynamic(lookup, security)
		if err != nil {
			err = fmt.Errorf("unrecognized import path %q (%v)", importPath, err)
		}
	}
	if err != nil {
		rr1, err1 := repoRootFromVCSPaths(importPath, "", security, vcsPathsAfterDynamic)
		if err1 == nil {
			rr = rr1
			err = nil
		}
	}

	if err == nil && strings.Contains(importPath, "...") && strings.Contains(rr.root, "...") {
		// Do not allow wildcards in the repo root.
		rr = nil
		err = fmt.Errorf("cannot expand ... in %q", importPath)
	}
	return rr, err
}

// RootImport returns root path of import.
// i.e. golang.org/x/net for golang.org/x/net/context
func RootImport(importPath string) (string, error) {
	rr, err := repoRootForImportPath(importPath, secure)
	if err != nil {
		return "", err
	}
	return rr.root, err
}

var errUnknownSite = errors.New("dynamic lookup required to find mapping")

// repoRootFromVCSPaths attempts to map importPath to a repoRoot
// using the mappings defined in vcsPaths.
// If scheme is non-empty, that scheme is forced.
func repoRootFromVCSPaths(importPath, scheme string, security securityMode, vcsPaths []*vcsPath) (*repoRoot, error) {
	// A common error is to use https://packagepath because that's what
	// hg and git require. Diagnose this helpfully.
	if loc := httpPrefixRE.FindStringIndex(importPath); loc != nil {
		// The importPath has been cleaned, so has only one slash. The pattern
		// ignores the slashes; the error message puts them back on the RHS at least.
		return nil, fmt.Errorf("%q not allowed in import path", importPath[loc[0]:loc[1]]+"//")
	}
	for _, srv := range vcsPaths {
		if !strings.HasPrefix(importPath, srv.prefix) {
			continue
		}
		m := srv.regexp.FindStringSubmatch(importPath)
		if m == nil {
			if srv.prefix != "" {
				return nil, fmt.Errorf("invalid %s import path %q", srv.prefix, importPath)
			}
			continue
		}

		// Build map of named subexpression matches for expand.
		match := map[string]string{
			"prefix": srv.prefix,
			"import": importPath,
		}
		for i, name := range srv.regexp.SubexpNames() {
			if name != "" && match[name] == "" {
				match[name] = m[i]
			}
		}
		if srv.vcs != "" {
			match["vcs"] = expand(match, srv.vcs)
		}
		if srv.repo != "" {
			match["repo"] = expand(match, srv.repo)
		}
		if srv.check != nil {
			if err := srv.check(match); err != nil {
				return nil, err
			}
		}
		vcs := vcsByCmd(match["vcs"])
		if vcs == nil {
			return nil, fmt.Errorf("unknown version control system %q", match["vcs"])
		}
		if srv.ping {
			if scheme != "" {
				match["repo"] = scheme + "://" + match["repo"]
			} else {
				for _, scheme := range vcs.scheme {
					if security == secure && !isSecureScheme[scheme] {
						continue
					}
					if vcs.ping(scheme, match["repo"]) == nil {
						match["repo"] = scheme + "://" + match["repo"]
						break
					}
				}
			}
		}
		rr := &repoRoot{
			vcs:  vcs,
			repo: match["repo"],
			root: match["root"],
		}
		if versioned.IsVersioned(importPath) {
			rr.root = importPath
		}
		return rr, nil
	}
	return nil, errUnknownSite
}

// repoRootForImportDynamic finds a *repoRoot for a custom domain that's not
// statically known by repoRootForImportPathStatic.
//
// This handles custom import paths like "name.tld/pkg/foo" or just "name.tld".
func repoRootForImportDynamic(importPath string, security securityMode) (*repoRoot, error) {
	slash := strings.Index(importPath, "/")
	if slash < 0 {
		slash = len(importPath)
	}
	host := importPath[:slash]
	if !strings.Contains(host, ".") {
		return nil, errors.New("import path does not begin with hostname")
	}
	urlStr, body, err := httpsOrHTTP(importPath, security)
	if err != nil {
		msg := "https fetch: %v"
		if security == insecure {
			msg = "http/" + msg
		}
		return nil, fmt.Errorf(msg, err)
	}
	defer body.Close()
	imports, err := parseMetaGoImports(body)
	if err != nil {
		return nil, fmt.Errorf("parsing %s: %v", importPath, err)
	}
	// Find the matched meta import.
	mmi, err := matchGoImport(imports, importPath)
	if err != nil {
		if err != errNoMatch {
			return nil, fmt.Errorf("parse %s: %v", urlStr, err)
		}
		return nil, fmt.Errorf("parse %s: no go-import meta tags", urlStr)
	}
	// If the import was "uni.edu/bob/project", which said the
	// prefix was "uni.edu" and the RepoRoot was "evilroot.com",
	// make sure we don't trust Bob and check out evilroot.com to
	// "uni.edu" yet (possibly overwriting/preempting another
	// non-evil student).  Instead, first verify the root and see
	// if it matches Bob's claim.
	if mmi.Prefix != importPath {
		urlStr0 := urlStr
		var imports []metaImport
		urlStr, imports, err = metaImportsForPrefix(mmi.Prefix, security)
		if err != nil {
			return nil, err
		}
		metaImport2, err := matchGoImport(imports, importPath)
		if err != nil || mmi != metaImport2 {
			return nil, fmt.Errorf("%s and %s disagree about go-import for %s", urlStr0, urlStr, mmi.Prefix)
		}
	}

	if !strings.Contains(mmi.RepoRoot, "://") {
		return nil, fmt.Errorf("%s: invalid repo root %q; no scheme", urlStr, mmi.RepoRoot)
	}
	rr := &repoRoot{
		vcs:  vcsByCmd(mmi.VCS),
		repo: mmi.RepoRoot,
		root: mmi.Prefix,
	}
	if rr.vcs == nil {
		return nil, fmt.Errorf("%s: unknown vcs %q", urlStr, mmi.VCS)
	}
	if versioned.IsVersioned(importPath) {
		rr.root = importPath
	}
	return rr, nil
}

var fetchGroup singleflight.Group
var (
	fetchCacheMu sync.Mutex
	fetchCache   = map[string]fetchResult{} // key is metaImportsForPrefix's importPrefix
)

// metaImportsForPrefix takes a package's root import path as declared in a <meta> tag
// and returns its HTML discovery URL and the parsed metaImport lines
// found on the page.
//
// The importPath is of the form "golang.org/x/tools".
// It is an error if no imports are found.
// urlStr will still be valid if err != nil.
// The returned urlStr will be of the form "https://golang.org/x/tools?go-get=1"
func metaImportsForPrefix(importPrefix string, security securityMode) (urlStr string, imports []metaImport, err error) {
	setCache := func(res fetchResult) (fetchResult, error) {
		fetchCacheMu.Lock()
		defer fetchCacheMu.Unlock()
		fetchCache[importPrefix] = res
		return res, nil
	}

	resi, _ := fetchGroup.Do(importPrefix, func() (resi interface{}, err error) {
		fetchCacheMu.Lock()
		if res, ok := fetchCache[importPrefix]; ok {
			fetchCacheMu.Unlock()
			return res, nil
		}
		fetchCacheMu.Unlock()

		urlStr, body, err := httpsOrHTTP(importPrefix, security)
		if err != nil {
			return setCache(fetchResult{urlStr: urlStr, err: fmt.Errorf("fetch %s: %v", urlStr, err)})
		}
		imports, err := parseMetaGoImports(body)
		if err != nil {
			return setCache(fetchResult{urlStr: urlStr, err: fmt.Errorf("parsing %s: %v", urlStr, err)})
		}
		if len(imports) == 0 {
			err = fmt.Errorf("fetch %s: no go-import meta tag", urlStr)
		}
		return setCache(fetchResult{urlStr: urlStr, imports: imports, err: err})
	})
	res := resi.(fetchResult)
	return res.urlStr, res.imports, res.err
}

type fetchResult struct {
	urlStr  string // e.g. "https://foo.com/x/bar?go-get=1"
	imports []metaImport
	err     error
}

// metaImport represents the parsed <meta name="go-import"
// content="prefix vcs reporoot" /> tags from HTML files.
type metaImport struct {
	Prefix, VCS, RepoRoot string
}

// errNoMatch is returned from matchGoImport when there's no applicable match.
var errNoMatch = errors.New("no import match")

// matchGoImport returns the metaImport from imports matching importPath.
// An error is returned if there are multiple matches.
// errNoMatch is returned if none match.
func matchGoImport(imports []metaImport, importPath string) (_ metaImport, err error) {
	match := -1
	for i, im := range imports {
		if !strings.HasPrefix(importPath, im.Prefix) {
			continue
		}
		if match != -1 {
			err = fmt.Errorf("multiple meta tags match import path %q", importPath)
			return
		}
		match = i
	}
	if match == -1 {
		err = errNoMatch
		return
	}
	return imports[match], nil
}

// expand rewrites s to replace {k} with match[k] for each key k in match.
func expand(match map[string]string, s string) string {
	for k, v := range match {
		s = strings.Replace(s, "{"+k+"}", v, -1)
	}
	return s
}

// vcsPaths defines the meaning of import paths referring to
// commonly-used VCS hosting sites (github.com/user/dir)
// and import paths referring to a fully-qualified importPath
// containing a VCS type (foo.com/repo.git/dir)
var vcsPaths = []*vcsPath{
	// Google Code - new syntax
	{
		prefix: "code.google.com/",
		re:     `^(?P<root>code\.google\.com/p/(?P<project>[a-z0-9\-]+)(\.(?P<subrepo>[a-z0-9\-]+))?)(/[A-Za-z0-9_.\-]+)*$`,
		repo:   "https://{root}",
		check:  googleCodeVCS,
	},

	// Google Code - old syntax
	{
		re:    `^(?P<project>[a-z0-9_\-.]+)\.googlecode\.com/(git|hg|svn)(?P<path>/.*)?$`,
		check: oldGoogleCode,
	},

	// Github
	{
		prefix: "github.com/",
		re:     `^(?P<root>github\.com/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`,
		vcs:    "git",
		repo:   "https://{root}",
		check:  noVCSSuffix,
	},

	// Bitbucket
	{
		prefix: "bitbucket.org/",
		re:     `^(?P<root>bitbucket\.org/(?P<bitname>[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+))(/[A-Za-z0-9_.\-]+)*$`,
		repo:   "https://{root}",
		check:  bitbucketVCS,
	},

	// IBM DevOps Services (JazzHub)
	{
		prefix: "hub.jazz.net/git",
		re:     `^(?P<root>hub.jazz.net/git/[a-z0-9]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`,
		vcs:    "git",
		repo:   "https://{root}",
		check:  noVCSSuffix,
	},

	// Git at Apache
	{
		prefix: "git.apache.org",
		re:     `^(?P<root>git.apache.org/[a-z0-9_.\-]+\.git)(/[A-Za-z0-9_.\-]+)*$`,
		vcs:    "git",
		repo:   "https://{root}",
	},

	// General syntax for any server.
	// Must be last.
	{
		re:   `^(?P<root>(?P<repo>([a-z0-9.\-]+\.)+[a-z0-9.\-]+(:[0-9]+)?(/~?[A-Za-z0-9_.\-]+)+?)\.(?P<vcs>bzr|git|hg|svn))(/~?[A-Za-z0-9_.\-]+)*$`,
		ping: true,
	},
}

// vcsPathsAfterDynamic gives additional vcsPaths entries
// to try after the dynamic HTML check.
// This gives those sites a chance to introduce <meta> tags
// as part of a graceful transition away from the hard-coded logic.
var vcsPathsAfterDynamic = []*vcsPath{
	// Launchpad. See golang.org/issue/11436.
	{
		prefix: "launchpad.net/",
		re:     `^(?P<root>launchpad\.net/((?P<project>[A-Za-z0-9_.\-]+)(?P<series>/[A-Za-z0-9_.\-]+)?|~[A-Za-z0-9_.\-]+/(\+junk|[A-Za-z0-9_.\-]+)/[A-Za-z0-9_.\-]+))(/[A-Za-z0-9_.\-]+)*$`,
		vcs:    "bzr",
		repo:   "https://{root}",
		check:  launchpadVCS,
	},
}

func init() {
	// fill in cached regexps.
	// Doing this eagerly discovers invalid regexp syntax
	// without having to run a command that needs that regexp.
	for _, srv := range vcsPaths {
		srv.regexp = regexp.MustCompile(srv.re)
	}
	for _, srv := range vcsPathsAfterDynamic {
		srv.regexp = regexp.MustCompile(srv.re)
	}
}

// noVCSSuffix checks that the repository name does not
// end in .foo for any version control system foo.
// The usual culprit is ".git".
func noVCSSuffix(match map[string]string) error {
	repo := match["repo"]
	for _, vcs := range vcsList {
		if strings.HasSuffix(repo, "."+vcs.cmd) {
			return fmt.Errorf("invalid version control suffix in %s path", match["prefix"])
		}
	}
	return nil
}

var googleCheckout = regexp.MustCompile(`id="checkoutcmd">(hg|git|svn)`)

// googleCodeVCS determines the version control system for
// a code.google.com repository, by scraping the project's
// /source/checkout page.
func googleCodeVCS(match map[string]string) error {
	if err := noVCSSuffix(match); err != nil {
		return err
	}
	data, err := httpGET(expand(match, "https://code.google.com/p/{project}/source/checkout?repo={subrepo}"))
	if err != nil {
		return err
	}

	if m := googleCheckout.FindSubmatch(data); m != nil {
		if vcs := vcsByCmd(string(m[1])); vcs != nil {
			// Subversion requires the old URLs.
			// TODO: Test.
			if vcs == vcsSvn {
				if match["subrepo"] != "" {
					return fmt.Errorf("sub-repositories not supported in Google Code Subversion projects")
				}
				match["repo"] = expand(match, "https://{project}.googlecode.com/svn")
			}
			match["vcs"] = vcs.cmd
			return nil
		}
	}

	return fmt.Errorf("unable to detect version control system for code.google.com/ path")
}

// oldGoogleCode is invoked for old-style foo.googlecode.com paths.
// It prints an error giving the equivalent new path.
func oldGoogleCode(match map[string]string) error {
	return fmt.Errorf("invalid Google Code import path: use %s instead",
		expand(match, "code.google.com/p/{project}{path}"))
}

// bitbucketVCS determines the version control system for a
// Bitbucket repository, by using the Bitbucket API.
func bitbucketVCS(match map[string]string) error {
	if err := noVCSSuffix(match); err != nil {
		return err
	}

	var resp struct {
		SCM string `json:"scm"`
	}
	url := expand(match, "https://api.bitbucket.org/2.0/repositories/{bitname}?fields=scm")
	data, err := httpGET(url)
	if err != nil {
		if httpErr, ok := err.(*httpError); ok && httpErr.statusCode == 403 {
			// this may be a private repository. If so, attempt to determine which
			// VCS it uses. See issue 5375.
			root := match["root"]
			for _, vcs := range []string{"git", "hg"} {
				if vcsByCmd(vcs).ping("https", root) == nil {
					resp.SCM = vcs
					break
				}
			}
		}

		if resp.SCM == "" {
			return err
		}
	} else {
		if err := json.Unmarshal(data, &resp); err != nil {
			return fmt.Errorf("decoding %s: %v", url, err)
		}
	}

	if vcsByCmd(resp.SCM) != nil {
		match["vcs"] = resp.SCM
		if resp.SCM == "git" {
			match["repo"] += ".git"
		}
		return nil
	}

	return fmt.Errorf("unable to detect version control system for bitbucket.org/ path")
}

// launchpadVCS solves the ambiguity for "lp.net/project/foo". In this case,
// "foo" could be a series name registered in Launchpad with its own branch,
// and it could also be the name of a directory within the main project
// branch one level up.
func launchpadVCS(match map[string]string) error {
	if match["project"] == "" || match["series"] == "" {
		return nil
	}
	_, err := httpGET(expand(match, "https://code.launchpad.net/{project}{series}/.bzr/branch-format"))
	if err != nil {
		match["root"] = expand(match, "launchpad.net/{project}")
		match["repo"] = expand(match, "https://{root}")
	}
	return nil
}


text:
layout: model
title: English pipeline_image_classifier_vit_Infrastructures ViTForImageClassification from drab
author: John Snow Labs
name: pipeline_image_classifier_vit_Infrastructures
date: 2022-10-12
tags: [vit, en, images, open_source, pipeline]
task: Image Classification
language: en
edition: Spark NLP 4.2.1
spark_version: 3.0
supported: true
annotator: PipelineModel
article_header:
  type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

Pretrained VIT  model, adapted from Hugging Face and curated to provide scalability and production-readiness using Spark NLP.`image_classifier_vit_Infrastructures` is a English model originally trained by drab.

## Predicted Entities

`Cooling tower`, `Transmission grid`, `Wind turbines`

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/pipeline_image_classifier_vit_Infrastructures_en_4.2.1_3.0_1665537380624.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python

    pipeline = PretrainedPipeline('pipeline_image_classifier_vit_Infrastructures', lang = 'en')
    annotations =  pipeline.transform(imageDF)

```
```scala

    val pipeline = new PretrainedPipeline("pipeline_image_classifier_vit_Infrastructures", lang = "en")
    val annotations = pipeline.transform(imageDF)

```
</div>

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|pipeline_image_classifier_vit_Infrastructures|
|Type:|pipeline|
|Compatibility:|Spark NLP 4.2.1+|
|License:|Open Source|
|Edition:|Official|
|Language:|en|
|Size:|321.9 MB|

## Included Models

- ImageAssembler
- ViTForImageClassification


text:
package local

import (
	"math/rand"
	"testing"

	"github.com/ready-steady/adapt/algorithm"
)

func BenchmarkComputeBox(b *testing.B) {
	fixture := &fixtureBox
	algorithm, strategy := prepare(fixture)
	strategy.(*Strategy).lmax = 9

	for i := 0; i < b.N; i++ {
		algorithm.Compute(fixture.target, strategy)
	}
}

func BenchmarkComputeCube(b *testing.B) {
	fixture := &fixtureCube
	algorithm, strategy := prepare(fixture)

	for i := 0; i < b.N; i++ {
		algorithm.Compute(fixture.target, strategy)
	}
}

func BenchmarkComputeHat(b *testing.B) {
	fixture := &fixtureHat
	algorithm, strategy := prepare(fixture)

	for i := 0; i < b.N; i++ {
		algorithm.Compute(fixture.target, strategy)
	}
}

func BenchmarkComputeMany(b *testing.B) {
	const (
		ni = 2
		no = 1000
	)

	fixture := &fixture{
		rule:   "closed",
		target: many(ni, no),
		surrogate: &algorithm.Surrogate{
			Inputs:  ni,
			Outputs: no,
		},
	}
	fixture.initialize()

	algorithm, strategy := prepare(fixture)

	for i := 0; i < b.N; i++ {
		algorithm.Compute(fixture.target, strategy)
	}
}

func BenchmarkEvaluateBox(b *testing.B) {
	fixture := &fixtureBox
	algorithm, strategy := prepare(fixture)
	strategy.(*Strategy).lmax = 9
	surrogate := algorithm.Compute(fixture.target, strategy)
	points := generate(surrogate)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		algorithm.Evaluate(surrogate, points)
	}
}

func BenchmarkEvaluateCube(b *testing.B) {
	fixture := &fixtureCube
	algorithm, strategy := prepare(fixture)
	strategy.(*Strategy).lmax = 9
	surrogate := algorithm.Compute(fixture.target, strategy)
	points := generate(surrogate)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		algorithm.Evaluate(surrogate, points)
	}
}

func BenchmarkEvaluateHat(b *testing.B) {
	fixture := &fixtureHat
	algorithm, strategy := prepare(fixture)
	surrogate := algorithm.Compute(fixture.target, strategy)
	points := generate(surrogate)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		algorithm.Evaluate(surrogate, points)
	}
}

func BenchmarkEvaluateMany(b *testing.B) {
	const (
		ni = 2
		no = 1000
	)

	fixture := &fixture{
		rule:   "closed",
		target: many(ni, no),
		surrogate: &algorithm.Surrogate{
			Inputs:  ni,
			Outputs: no,
		},
	}
	fixture.initialize()

	algorithm, strategy := prepare(fixture)
	surrogate := algorithm.Compute(fixture.target, strategy)
	points := generate(surrogate)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		algorithm.Evaluate(surrogate, points)
	}
}

func generate(surrogate *algorithm.Surrogate) []float64 {
	const (
		count = 10000
	)

	generator := rand.New(rand.NewSource(0))
	points := make([]float64, count*surrogate.Inputs)
	for i := range points {
		points[i] = generator.Float64()
	}

	return points
}

func many(ni, no int) func([]float64, []float64) {
	return func(x, y []float64) {
		sum, value := 0.0, 0.0

		for i := 0; i < ni; i++ {
			sum += x[i]
		}

		if sum > float64(ni)/4 {
			value = 1
		}

		for i := 0; i < no; i++ {
			y[i] = value
		}
	}
}


text:
"""pytest for idfreader. very few tests"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import eppy.idfreader as idfreader
from StringIO import StringIO

def test_iddversiontuple():
    """py.test for iddversiontuple"""
    iddtxt = """stuff 9.8.4
    other stuff"""
    fhandle = StringIO(iddtxt)
    result = idfreader.iddversiontuple(fhandle)
    assert result == (9, 8, 4)


text:
@class NSDate;

@interface USInstallationTracker : NSObject
{
    NSDate *_installDate;
    id <UpsightDataStoreInterface> _dataStore;
}

+ (void)migrateInstallDateIfNeeded;
@property(readonly, nonatomic) id <UpsightDataStoreInterface> dataStore; // @synthesize dataStore=_dataStore;
- (void).cxx_destruct;
@property(retain) NSDate *installDate; // @synthesize installDate=_installDate;
- (void)trackInstallation;
- (id)initWithDataStore:(id)arg1;
- (id)init;

@end


text:
var form = document.getElementById('new-shop-form');
form.addEventListener('submit',handleEntrySubmit);

function handleEntrySubmit(event) {
  event.preventDefault();
  console.log(event);
  console.log(event.target.location.value);
  var location = event.target.location.value;
  var min = parseFloat(event.target.min.value);
  var max = parseFloat(event.target.max.value);
  var avgCups = parseFloat(event.target.avgCups.value);
  var avgPounds = parseFloat(event.target.avgPounds.value);

  var newShop = new Shops(location, min, max, avgCups, avgPounds);
  newShop.allCalcs();
  console.log(newShop);
  makeSecondRow(newShop);
  makeSecondRow2(newShop);
  event.target.location.value = '';
  event.target.min.value = '';
  event.target.max.value = '';
  event.target.avgCups.value = '';
  event.target.avgPounds.value = '';
}

// // Here's the constructor for the individual comments
// var Comment  = function(userName, text) {
//   this.userName = userName;
//   this.text = text;
// };
//
// Comment.prototype.render = function() {
//   var liEl = document.createElement('li');
//   liEl.innerHTML = ' ' + this.userName + ': ' + this.text + '';
//   return liEl;
// };
//
// // +++++++++++++++++++++++++++++++++++++++++++++++++++++
// // Just setting up some variables for DOM access
// var chatList = document.getElementById('chat-list');
// var chatForm = document.getElementById('chat-form');
// var clearChatList = document.getElementById('clear-chat-list');
// var allComments = [];
//
// var renderAllComments = function() {
//   chatList.innerHTML = '';
//   for (var i = 0; i < allComments.length; i++) {
//     chatList.appendChild(allComments[i].render());
//   }
//   // allComments.forEach(function(unicorn) {
//   //   chatList.appendChild(unicorn.render());
//   // });
// };
//
// // +++++++++++++++++++++++++++++++++++++++++++++++++++++
// // This function handles the submission of comments
// function handleCommentSubmit(event) {
//   // console.log(event);
//   event.preventDefault(); //gotta have it. prevents page reload
//
//   if (!event.target.says.value || !event.target.who.value) {
//     return alert('Fields cannot be empty!');
//   }
//
//   var commenter = event.target.who.value;
//   var remark = event.target.says.value;
//
//   // if (commenter === 'Dan') {
//   //   remark = '@$^#$%$^@#$%@';
//   // }
//   //
//   // if (commenter === 'Benton') {
//   //   remark = remark.toUpperCase();
//   // }
//
//   var newComment = new Comment(commenter, remark);
//
//   // console.log('Comment by ' + event.target.who.value + ' at ' + Date());
//
//   event.target.who.value = null;
//   event.target.says.value = null;
//
//   allComments.push(newComment);
//   renderAllComments();
// };
//
// // +++++++++++++++++++++++++++++++++++++++++++++++++++++
// // Event listener for comment submission form
// chatForm.addEventListener('submit', handleCommentSubmit);
//
// // +++++++++++++++++++++++++++++++++++++++++++++++++++++
// // Event listener for the 'Clear all comments' button
// clearChatList.addEventListener('click', function() {
//   chatList.innerHTML = '';
//   console.log('You just cleared the chat list!');
//   allComments = [];
// });
// Status API Training Shop Blog About


text:
require 'rails_helper'

describe SeriesStatement do
  fixtures :all

  it "should create manifestation" do
    series_statement = FactoryBot.create(:series_statement)
    series_statement.root_manifestation.should be_nil
  end
end

# == Schema Information
#
# Table name: series_statements
#
#  id                                 :bigint           not null, primary key
#  original_title                     :text
#  numbering                          :text
#  title_subseries                    :text
#  numbering_subseries                :text
#  position                           :integer
#  created_at                         :datetime         not null
#  updated_at                         :datetime         not null
#  title_transcription                :text
#  title_alternative                  :text
#  series_statement_identifier        :string
#  manifestation_id                   :bigint
#  note                               :text
#  title_subseries_transcription      :text
#  creator_string                     :text
#  volume_number_string               :text
#  volume_number_transcription_string :text
#  series_master                      :boolean
#  root_manifestation_id              :integer
#


text:
#include "tensorflow/c/tf_tensor.h"

#include <memory>
#include <vector>

#include "tensorflow/c/tf_status.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/c/tf_tensor_internal.h"
#include "tensorflow/core/framework/allocation_description.pb.h"
#include "tensorflow/core/framework/log_memory.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/coding.h"
#include "tensorflow/core/platform/casts.h"

using tensorflow::Status;
using tensorflow::Tensor;
using tensorflow::TensorBuffer;
using tensorflow::errors::FailedPrecondition;
using tensorflow::errors::InvalidArgument;

namespace tensorflow {
void* allocate_tensor(const char* operation, size_t len, Allocator* allocator) {
  void* data = allocator->AllocateRaw(EIGEN_MAX_ALIGN_BYTES, len);
  if (LogMemory::IsEnabled() && data != nullptr) {
    LogMemory::RecordRawAllocation(
        operation, LogMemory::EXTERNAL_TENSOR_ALLOCATION_STEP_ID, len, data,
        allocator);
  }
  return data;
}

void* allocate_tensor(const char* operation, size_t len) {
  return allocate_tensor(operation, len, cpu_allocator());
}

void deallocate_buffer(void* data, size_t len, void* arg) {
  Allocator* allocator = nullptr;
  if (arg == nullptr) {
    allocator = cpu_allocator();
  } else {
    allocator = reinterpret_cast<Allocator*>(arg);
  }
  if (LogMemory::IsEnabled() && data != nullptr) {
    LogMemory::RecordRawDeallocation(
        "TensorFlow C Api", LogMemory::EXTERNAL_TENSOR_ALLOCATION_STEP_ID, data,
        allocator, false);
  }
  allocator->DeallocateRaw(data);
}
}  // namespace tensorflow

namespace {
TF_Tensor* CreateTensor(TF_ManagedBuffer* buf, TF_DataType dtype,
                        const int64_t* dims, int num_dims, size_t len) {
  std::vector<tensorflow::int64> dimvec(num_dims);
  for (int i = 0; i < num_dims; ++i) {
    dimvec[i] = static_cast<tensorflow::int64>(dims[i]);
  }

  // TODO(gjn): Make the choice of interface a compile-time configuration.
  tensorflow::TensorInterface ret(
      Tensor(static_cast<tensorflow::DataType>(dtype),
             tensorflow::TensorShape(dimvec), buf));
  buf->Unref();
  size_t elem_size = TF_DataTypeSize(dtype);
  if (elem_size > 0 && len < (elem_size * ret.NumElements())) {
    return nullptr;
  }
  return new TF_Tensor{new tensorflow::TensorInterface(ret)};
}
}  // namespace

TF_Tensor* TF_AllocateTensor(TF_DataType dtype, const int64_t* dims,
                             int num_dims, size_t len) {
  void* data = tensorflow::allocate_tensor("TF_AllocateTensor", len,
                                           tensorflow::cpu_allocator());
  TF_ManagedBuffer* buf =
      new TF_ManagedBuffer(data, len, tensorflow::deallocate_buffer,
                           tensorflow::cpu_allocator(), /*owns_memory=*/true);
  return CreateTensor(buf, dtype, dims, num_dims, len);
}

TF_Tensor* TF_NewTensor(TF_DataType dtype, const int64_t* dims, int num_dims,
                        void* data, size_t len,
                        void (*deallocator)(void* data, size_t len, void* arg),
                        void* deallocator_arg) {
  TF_ManagedBuffer* buf = nullptr;
  if (dtype != TF_STRING && dtype != TF_RESOURCE &&
      tensorflow::DataTypeCanUseMemcpy(
          static_cast<tensorflow::DataType>(dtype)) &&
      reinterpret_cast<intptr_t>(data) % std::max(1, EIGEN_MAX_ALIGN_BYTES) !=
          0) {
    // TF_STRING and TF_RESOURCE tensors have a different representation in
    // TF_Tensor than they do in tensorflow::Tensor. So a copy here is a waste
    // (any alignment requirements will be taken care of by TF_TensorToTensor
    // and TF_TensorFromTensor).
    //
    // Other types have the same representation, so copy only if it is safe to
    // do so.
    buf = new TF_ManagedBuffer(tensorflow::allocate_tensor("TF_NewTensor", len),
                               len, tensorflow::deallocate_buffer, nullptr,
                               /*owns_memory=*/true);
    std::memcpy(buf->data(), data, len);
    // Free the original buffer.
    deallocator(data, len, deallocator_arg);
  } else {
    buf = new TF_ManagedBuffer(data, len, deallocator, deallocator_arg,
                               /*owns_memory=*/false);
  }

  return CreateTensor(buf, dtype, dims, num_dims, len);
}

TF_Tensor* TF_TensorMaybeMove(TF_Tensor* t) {
  return t->tensor->CanMove() ? t : nullptr;
}

void TF_DeleteTensor(TF_Tensor* t) {
  if (t == nullptr) {
    return;
  }

  if (t->tensor) {
    t->tensor->Release();
  }

  delete t;
}

TF_DataType TF_TensorType(const TF_Tensor* t) {
  return static_cast<TF_DataType>(t->tensor->Type());
}

int TF_NumDims(const TF_Tensor* t) { return t->tensor->NumDims(); }

int64_t TF_Dim(const TF_Tensor* t, int dim_index) {
  return t->tensor->Dim(dim_index);
}

size_t TF_TensorByteSize(const TF_Tensor* t) { return t->tensor->ByteSize(); }

void* TF_TensorData(const TF_Tensor* t) { return t->tensor->Data(); }

int64_t TF_TensorElementCount(const TF_Tensor* t) {
  int64_t result = 1;
  int rank = TF_NumDims(t);
  for (int dim = 0; dim < rank; ++dim) {
    result *= TF_Dim(t, dim);
  }
  return result;
}

void TF_TensorBitcastFrom(const TF_Tensor* from, TF_DataType type,
                          TF_Tensor* to, const int64_t* new_dims,
                          int num_new_dims, TF_Status* status) {
  TF_SetStatus(status, TF_OK, "");
  Status cc_status(
      tensorflow::down_cast<tensorflow::TensorInterface*>(to->tensor)
          ->BitcastFrom(
              *tensorflow::down_cast<const tensorflow::TensorInterface*>(
                  from->tensor),
              static_cast<tensorflow::DataType>(type), new_dims, num_new_dims));
  Set_TF_Status_from_Status(status, cc_status);
}

namespace tensorflow {

void TensorInterface::Release() { delete this; }

bool TensorInterface::CanMove() const {
  // It is safe to move the Tensor if and only if we own the unique reference to
  // it. In that case, we might as well not delete and reallocate, but a future
  // implementation might need to do so.
  TensorBuffer* buf = tensorflow::TensorCApi::Buffer(tensor_);
  if (buf->RefCountIsOne() && buf->root_buffer()->RefCountIsOne() &&
      buf->OwnsMemory()) {
    return true;
  }
  return false;
}

std::string TensorInterface::SummarizeValue() const {
  return tensor_.SummarizeValue(/*max_entries=*/3, /*print_v2=*/true);
}

DataType TensorInterface::Type() const { return tensor_.dtype(); }

int TensorInterface::NumDims() const { return tensor_.dims(); }

int64_t TensorInterface::Dim(int dim_index) const {
  return static_cast<int64_t>(tensor_.dim_size(dim_index));
}

int64_t TensorInterface::NumElements() const {
  return static_cast<int64_t>(tensor_.NumElements());
}

size_t TensorInterface::ByteSize() const {
  return tensorflow::TensorCApi::Buffer(tensor_)->size();
}

void* TensorInterface::Data() const {
  return tensorflow::TensorCApi::Buffer(tensor_)->data();
}

Status TensorInterface::BitcastFrom(const TensorInterface& from, DataType type,
                                    const int64_t* new_dims, int num_new_dims) {
  tensorflow::TensorShape s;
  for (int i = 0; i < num_new_dims; ++i) {
    s.AddDim(new_dims[i]);
  }
  return tensor_.BitcastFrom(from.tensor_, type, s);
}

}  // namespace tensorflow

// --------------------------------------------------------------------------

static void DeleteArray(void* data, size_t size, void* arg) {
  DCHECK_EQ(data, arg);
  delete[] reinterpret_cast<char*>(arg);
}

// Create an empty tensor of type 'dtype'. 'shape' can be arbitrary, but has to
// result in a zero-sized tensor.
static TF_Tensor* EmptyTensor(TF_DataType dtype,
                              const tensorflow::TensorShape& shape) {
  static char empty;
  tensorflow::int64 nelems = 1;
  std::vector<tensorflow::int64> dims;
  for (int i = 0; i < shape.dims(); ++i) {
    dims.push_back(shape.dim_size(i));
    nelems *= shape.dim_size(i);
  }
  CHECK_EQ(nelems, 0);
  static_assert(sizeof(int64_t) == sizeof(tensorflow::int64),
                "64-bit int types should match in size");
  return TF_NewTensor(
      dtype, reinterpret_cast<const int64_t*>(dims.data()), shape.dims(),
      reinterpret_cast<void*>(&empty), 0, [](void*, size_t, void*) {}, nullptr);
}

namespace tensorflow {

// Non-static for testing.
TF_Tensor* TF_TensorFromTensor(const tensorflow::Tensor& src, Status* status) {
  *status = tensorflow::Status::OK();
  if (!src.IsInitialized()) {
    *status = FailedPrecondition(
        "attempt to use a tensor with an uninitialized value");
    return nullptr;
  }
  if (src.NumElements() == 0) {
    return EmptyTensor(static_cast<TF_DataType>(src.dtype()), src.shape());
  }
  if (src.dtype() == tensorflow::DT_RESOURCE) {
    if (src.shape().dims() != 0) {
      *status = InvalidArgument(
          "Unexpected non-scalar DT_RESOURCE tensor seen (shape: ",
          src.shape().DebugString(),
          "). Please file a bug at "
          "https://github.com/tensorflow/tensorflow/issues/new, "
          "ideally with a "
          "short code snippet that reproduces this error.");
      return nullptr;
    }
    const string str =
        src.scalar<tensorflow::ResourceHandle>()().SerializeAsString();
    TF_Tensor* t = TF_AllocateTensor(TF_RESOURCE, {}, 0, str.size());
    std::memcpy(TF_TensorData(t), str.c_str(), str.size());
    return t;
  }

  Tensor tensor;
  if (!tensor.CopyFrom(src, src.shape())) {
    return nullptr;
  }
  return new TF_Tensor{new tensorflow::TensorInterface(std::move(tensor))};
}

Status TF_TensorToTensor(const TF_Tensor* src, Tensor* dst) {
  return tensorflow::down_cast<const tensorflow::TensorInterface*>(src->tensor)
      ->ToTensor(dst);
}

Status TensorInterface::ToTensor(tensorflow::Tensor* dst) const {
  if (tensor_.dtype() == DT_RESOURCE) {
    if (tensor_.dims() != 0) {
      return InvalidArgument(
          "Malformed TF_RESOURCE tensor: expected a scalar, got a tensor with "
          "shape ",
          tensor_.shape().DebugString());
    }
    *dst = tensorflow::Tensor(tensorflow::DT_RESOURCE, tensor_.shape());
    if (!dst->scalar<tensorflow::ResourceHandle>()().ParseFromString(
            string(static_cast<const char*>(Data()), ByteSize()))) {
      return InvalidArgument(
          "Malformed TF_RESOURCE tensor: unable to parse resource handle");
    }
    return Status::OK();
  }
  *dst = tensor_;
  return Status::OK();
}

bool TensorInterface::IsAligned() const { return tensor_.IsAligned(); }

}  // namespace tensorflow

bool TF_TensorIsAligned(const TF_Tensor* t) { return t->tensor->IsAligned(); }


text:
namespace King.Service.Tests.Unit.Data
{
    using King.Service.Data;
    using NUnit.Framework;
    using System.Threading.Tasks;

    [TestFixture]
    public class QueueActionTests
    {
        [Test]
        public void Constructor()
        {
            new QueueAction<object>();
        }

        [Test]
        public void IsQueueSetup()
        {
            Assert.IsNotNull(new QueueAction<object>() as QueueSetup<object>);
        }

        [Test]
        public void Activity()
        {
            var expected = new QueueActivity<object>(async (obj) => { return await Task.FromResult<bool>(true); });
            var qc = new QueueAction<object>()
            {
                Activity = expected,
            };

            Assert.AreEqual(expected, qc.Activity);
        }

        [Test]
        public void Processor()
        {
            var expected = new QueueActivity<object>(async (obj) => { return await Task.FromResult<bool>(true); });
            var qc = new QueueAction<object>()
            {
                Activity = expected,
            };

            Assert.IsNotNull(qc.Processor);
        }

        [Test]
        public void ProcessorValue()
        {
            var expected = new QueueActivity<object>(async (obj) => { return await Task.FromResult<bool>(true); });
            var qc = new QueueAction<object>()
            {
                Activity = expected,
            };

            Assert.IsNotNull(qc.Processor() as ActionProcessor<object>);
        }
    }
}


text:
package org.flowvisor.message.actions;

import java.util.List;

import org.flowvisor.classifier.FVClassifier;
import org.flowvisor.exceptions.ActionDisallowedException;
import org.flowvisor.log.FVLog;
import org.flowvisor.log.LogLevel;
import org.flowvisor.slicer.FVSlicer;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionEnqueue;

public class FVActionEnqueue extends OFActionEnqueue implements SlicableAction {

	@Override
	public void slice(List<OFAction> approvedActions, OFMatch match,
			FVClassifier fvClassifier, FVSlicer fvSlicer)
			throws ActionDisallowedException {
		// TODO Auto-generated method stub
		FVLog.log(LogLevel.CRIT, fvSlicer,
				"action slicing unimplemented for type: " + this);
		approvedActions.add(this);
	}

}