text:
package com.microsoft.azure.management.mediaservices.v2018_07_01.implementation;

import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.mediaservices.v2018_07_01.ContentKeyPolicies;
import rx.Completable;
import rx.Observable;
import rx.functions.Func1;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.mediaservices.v2018_07_01.ContentKeyPolicyProperties;
import com.microsoft.azure.management.mediaservices.v2018_07_01.ContentKeyPolicy;

class ContentKeyPoliciesImpl extends WrapperImpl<ContentKeyPoliciesInner> implements ContentKeyPolicies {
    private final MediaManager manager;

    ContentKeyPoliciesImpl(MediaManager manager) {
        super(manager.inner().contentKeyPolicies());
        this.manager = manager;
    }

    public MediaManager manager() {
        return this.manager;
    }

    @Override
    public ContentKeyPolicyImpl define(String name) {
        return wrapModel(name);
    }

    private ContentKeyPolicyImpl wrapModel(ContentKeyPolicyInner inner) {
        return  new ContentKeyPolicyImpl(inner, manager());
    }

    private ContentKeyPolicyImpl wrapModel(String name) {
        return new ContentKeyPolicyImpl(name, this.manager());
    }

    @Override
    public Observable<ContentKeyPolicyProperties> getPolicyPropertiesWithSecretsAsync(String resourceGroupName, String accountName, String contentKeyPolicyName) {
        ContentKeyPoliciesInner client = this.inner();
        return client.getPolicyPropertiesWithSecretsAsync(resourceGroupName, accountName, contentKeyPolicyName)
        .map(new Func1<ContentKeyPolicyPropertiesInner, ContentKeyPolicyProperties>() {
            @Override
            public ContentKeyPolicyProperties call(ContentKeyPolicyPropertiesInner inner) {
                return new ContentKeyPolicyPropertiesImpl(inner, manager());
            }
        });
    }

    @Override
    public Observable<ContentKeyPolicy> listAsync(final String resourceGroupName, final String accountName) {
        ContentKeyPoliciesInner client = this.inner();
        return client.listAsync(resourceGroupName, accountName)
        .flatMapIterable(new Func1<Page<ContentKeyPolicyInner>, Iterable<ContentKeyPolicyInner>>() {
            @Override
            public Iterable<ContentKeyPolicyInner> call(Page<ContentKeyPolicyInner> page) {
                return page.items();
            }
        })
        .map(new Func1<ContentKeyPolicyInner, ContentKeyPolicy>() {
            @Override
            public ContentKeyPolicy call(ContentKeyPolicyInner inner) {
                return wrapModel(inner);
            }
        });
    }

    @Override
    public Observable<ContentKeyPolicy> getAsync(String resourceGroupName, String accountName, String contentKeyPolicyName) {
        ContentKeyPoliciesInner client = this.inner();
        return client.getAsync(resourceGroupName, accountName, contentKeyPolicyName)
        .flatMap(new Func1<ContentKeyPolicyInner, Observable<ContentKeyPolicy>>() {
            @Override
            public Observable<ContentKeyPolicy> call(ContentKeyPolicyInner inner) {
                if (inner == null) {
                    return Observable.empty();
                } else {
                    return Observable.just((ContentKeyPolicy)wrapModel(inner));
                }
            }
       });
    }

    @Override
    public Completable deleteAsync(String resourceGroupName, String accountName, String contentKeyPolicyName) {
        ContentKeyPoliciesInner client = this.inner();
        return client.deleteAsync(resourceGroupName, accountName, contentKeyPolicyName).toCompletable();
    }

}


text:
#include <aws/drs/model/LifeCycleLastLaunch.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace drs
{
namespace Model
{

LifeCycleLastLaunch::LifeCycleLastLaunch() :
    m_initiatedHasBeenSet(false)
{
}

LifeCycleLastLaunch::LifeCycleLastLaunch(JsonView jsonValue) :
    m_initiatedHasBeenSet(false)
{
  *this = jsonValue;
}

LifeCycleLastLaunch& LifeCycleLastLaunch::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("initiated"))
  {
    m_initiated = jsonValue.GetObject("initiated");

    m_initiatedHasBeenSet = true;
  }

  return *this;
}

JsonValue LifeCycleLastLaunch::Jsonize() const
{
  JsonValue payload;

  if(m_initiatedHasBeenSet)
  {
   payload.WithObject("initiated", m_initiated.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace drs
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
import test = require('tape');

test('the interfaces module should only export type information', t => {
    const interfaces = require('../src/interfaces');
    // all exports should be TypeScript only and will not show up at runtime
    t.deepEqual(interfaces, {});
    t.end();
});


text:
export interface IRecipeIngredient {
    name?: string;
}


text:
Raspberry Pi
============

## Setup ##

This project uses CMake (minimum version 3.0), you can download it [here](http://www.cmake.org/download/) or install it with apt-get.

```bash
sudo apt-get install cmake
```

Make sure to update git submodules before you build:

```bash
git submodule update --init
```

To build on Rasberry Pi you will need a C++ toolchain with support for C++14. GCC 4.9.2 (or higher) and Clang 3.4 (or higher) are known to work (refer [here](https://community.thinger.io/t/starting-with-the-raspberry-pi/36) for instructions on getting GCC 4.9).

You will also need to install development packages for libcurl:

```
sudo apt-get install libcurl4-openssl-dev
```

The demo application uses the Mapzen vector tile service, so you will need a Mapzen API key to build and run the demo.

 1. Visit https://mapzen.com/documentation/overview/#get-started-developing-with-mapzen to get an API key.

 2. Setup an environment variable (`MAPZEN_API_KEY`) to point to your API key.
    ```bash
    export MAPZEN_API_KEY=YOUR_API_KEY
    ```

## Build ##

Compile the demo application with:

```
make rpi
```

You can optionally use `make -j` to parallelize the build and append `DEBUG=1` or `RELEASE=1` to choose the build type.

Run the demo program from the output folder:
```
cd build/rpi/bin
./tangram
```

You can provide several command line options:
 - `-s` or `--scene` followed by a path or URL to a scene file to load
 - `-lat` or `--latitude` followed by a latitude for the map view
 - `-lon` or `--longitude` followed by a longitude for the map view
 - `-z` or `--zoom` followed by a zoom level for the map view
 - `-x` or `--x_position` followed by a horizontal offset in pixels for the window
 - `-y` or `--y_position` followed by a vertical offset in pixels for the window
 - `-w` or `--width` followed by a horizontal size in pixels for the window
 - `-h` or `--height` followed by a vertical size in pixels for the window
 - `-t` or `--tilt` followed by a tilt in radians for the map view
 - `-r` or `--rotation` followed by a rotation from North in radians for the map view

You can move the map with `w`, `a`, `s`, and `d`, zoom in and out with `-` and `=`, and quit with `esc`.


text:
using Contentful.Core.Models;

namespace StockportContentApi.ContentfulModels
{
    public class ContentfulSocialMediaLink : IContentfulModel
    {
        public string Title { get; set; } = string.Empty;
        public string Slug { get; set; } = string.Empty;
        public string Url { get; set; } = string.Empty;
        public string Icon { get; set; } = string.Empty;
        public string AccountName { get; set; } = string.Empty;
        public string ScreenReader { get; set; } = string.Empty;
        public SystemProperties Sys { get; set; } = new SystemProperties();
    }
}


text:
var type = require('type-component');

module.exports = function (value, options) {
  var formatter = new Preceive(options || {});

  return formatter[type(value)](value);
};

function Preceive(options) {
  this.colors = (options.colors === true);
  this.indent = '';
  this.complexNewline = false;
}

/*
 * Helpers
 */
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
var COLOR_CODES = {
  'grey' : [90, 39],
  'cyan' : [36, 39],
  'green' : [32, 39],
  'magenta' : [35, 39],
  'red' : [31, 39],
  'yellow' : [33, 39]
};

Preceive.prototype._colorize = function (color, string) {
  if (this.colors) {
    return '\u001b[' + COLOR_CODES[color][0] + 'm' + string + '\u001b[' + COLOR_CODES[color][1] + 'm';
  } else {
    return string;
  }
};

Preceive.prototype._complexStart = function () {
  if (this.complexNewline) {
    return '\n';
  } else {
    this.complexNewline = true;
    return '';
  }
};

function stringLength(string) {
  return string.length;
}

var SPACEING = [' ', '  ', '   ', '    ', '     ', '      '];
var NO_SPACEING = [' ', ' ', ' ', ' ', ' '];

var COMPLEX = {
  'object': true,
  'array': true,
  'arguments': true,
  'string': false,
  'null': false,
  'boolean': false,
  'number': false,
  'undefined': false,
  'function': false,
  'regexp': false,
  'date': false
};

var QOUTE_STRING = /^(true|false|no|yes|null)$/i;
var SPECIAL_STRING = /(^'|^"|^!|\n|\r|:)/;

/*
 * Complex
 */
Preceive.prototype.object = function (value) {
  var keys = Object.keys(value);

  // Short circuit if its an empty object
  if (keys.length === 0) return '{}';

  // Determine if key spaceing should be used
  var keylens = keys.map(stringLength);
  var min = Math.min.apply(Math, keylens);
  var max = Math.max.apply(Math, keylens);
  var align = (max - min <= 5);

  // Increment indent
  var indent = this.indent;
  this.indent += '    ';

  // Create output
  var output = this._complexStart();

  for (var i = 0; i < keys.length; i++) {
    var item = value[ keys[i] ];
    var t = type(item);

    output += indent + keys[i] + ':' + (align ? SPACEING[max - keylens[i]] : ' ') + this[t](item);
    if (i !== keys.length - 1) output += '\n';
  }

  // Decrement indent
  this.indent = indent;
  return output;
};

Preceive.prototype.array = Preceive.prototype.arguments = function (value) {
  // Short circuit if its an empty array
  if (value.length === 0) return '[]';

  // Increment indent
  var indent = this.indent;
  this.indent += '    ';

  // Determin if array should be a oneliner by simulating a complex
  // condition
  var isComplex = this.complexNewline;
  this.complexNewline = true;

  var oneliner = true;
  var parts = new Array(value.length);
  var total = 0;
  var colorizeFactor = this.colors ? 9 : 0;
  for (var i = 0; i < value.length; i++) {
    var t = type(value[i]);

    parts[i] = this[t](value[i]);
    total += parts[i].length - colorizeFactor;

    if ( COMPLEX[t] || (t === 'string' && SPECIAL_STRING.test(value[i])) ) {
      oneliner = false;
    }
  }

  this.complexNewline = isComplex;
  if (this.indent.length + total > 70 || total > 20) oneliner = false;

  // Create output
  var output = '';

  if (oneliner) {
    output = '[' + parts.join(', ') + ']';
  } else {
    output += this._complexStart();
    for (var j = 0; j < value.length; j++) {
      output += indent + '- ' + parts[j];
      if (j !== value.length - 1) output += '\n';
    }
  }

  // Decrement indent
  this.indent = indent;
  return output;
};

/*
 * primitives
 */
Preceive.prototype.string = function (value) {
  var output = '', lines;

  if (SPECIAL_STRING.test(value)) {
    output += '|\n';
    lines = value.split('\n');

    for (var i = 0; i < lines.length; i++) {
      output += this.indent + this._colorize('green', lines[i]);
      if (i !== lines.length - 1) output += '\n';
    }
  } else if (QOUTE_STRING.test(value)) {
    output = '"' + this._colorize('green', value) + '"';
  } else {
    output = this._colorize('green', value);
  }

  return output;
};

Preceive.prototype.null = function (value) {
  return this._colorize('grey', 'null');
};

Preceive.prototype.boolean = function (value) {
  return this._colorize('yellow', (value ? 'true' : 'false'));
};

Preceive.prototype.number = function (value) {
  return this._colorize('yellow', value.toString());
};

/*
 * specials
 */
Preceive.prototype.undefined = function (value) {
  return this._colorize('grey', 'undefined');
};

Preceive.prototype.function = function (value) {
  return this._colorize('cyan', '[Function ' + (value.name || '(anonymous)') + ']');
};

Preceive.prototype.regexp = function (value) {
  return this._colorize('red', value.toString());
};

Preceive.prototype.date = function (value) {
  return this._colorize('magenta', value.toJSON());
};


text:
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace LinqToTwitter
{
    public record LikeQuery
    {
        //
        // Input parameters
        //

        /// <summary>
        /// type of blocks request to perform (input only)
        /// </summary>
        public LikeType? Type { get; set; }

        /// <summary>
        /// ID of user performing the block
        /// </summary>
        public string? ID { get; set; }

        /// <summary>
        /// Comma-separated list of expansion fields - <see cref="ExpansionField"/>
        /// </summary>
        public string? Expansions { get; set; }

        /// <summary>
        /// Max number of tweets to return per requrest - default 10 - possible 100
        /// </summary>
        public int MaxResults { get; set; }

        /// <summary>
        /// Comma-separated list of fields to return in the media object - <see cref="MediaField"/>
        /// </summary>
        public string? MediaFields { get; set; }

        /// <summary>
        /// If set, with token from previous response metadata, pages forward or backward
        /// </summary>
        public string? PaginationToken { get; set; }

        /// <summary>
        /// Comma-separated list of fields to return in the place object - <see cref="PlaceField"/>
        /// </summary>
        public string? PlaceFields { get; set; }

        /// <summary>
        /// Comma-separated list of fields to return in the poll object - <see cref="PollField"/>
        /// </summary>
        public string? PollFields { get; set; }

        /// <summary>
        /// Comma-separated list of fields to return in the Tweet object - <see cref="TweetField"/>
        /// </summary>
        public string? TweetFields { get; set; }

        /// <summary>
        /// Comma-separated list of fields to return in the User object - <see cref="UserField"/>
        /// </summary>
        public string? UserFields { get; set; }

        //
        // Output results
        //

        /// <summary>
        /// Tweet data returned from the search
        /// </summary>
        [JsonPropertyName("data")]
        public List<Tweet>? Tweets { get; init; }

        [JsonPropertyName("meta")]
        public LikeMeta? Meta { get; set; }
    }
}


text:
package ca.watier.echechess.configuration.dependent;

import ca.watier.echechess.communication.redis.configuration.RedisConfiguration;
import ca.watier.echechess.communication.redis.pojos.ServerInfoPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile("dependent-mode")
public class AppRedisConfiguration extends RedisConfiguration {
    @Autowired
    public AppRedisConfiguration(@Qualifier("redisServerPojo") ServerInfoPojo redisServerPojo) {
        super(redisServerPojo);
    }
}


text:
#import "DVTDocumentLocation.h"

@interface IDEBotExecutionSCMLogDocumentLocation : DVTDocumentLocation
{
}

@end


text:
package com.orientechnologies.orient.core.index;

import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordElement;
import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OIndexRIDContainer;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializer;
import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Fast index for full-text searches.
 *
 * @author Luca Garulli
 *
 */
public class OIndexFullText extends OIndexMultiValues {

  private static final String  CONFIG_STOP_WORDS      = "stopWords";
  private static final String  CONFIG_SEPARATOR_CHARS = "separatorChars";
  private static final String  CONFIG_IGNORE_CHARS    = "ignoreChars";
  private static final String  CONFIG_INDEX_RADIX     = "indexRadix";
  private static final String  CONFIG_MIN_WORD_LEN    = "minWordLength";
  private static final boolean DEF_INDEX_RADIX        = true;
  private static final String  DEF_SEPARATOR_CHARS    = " \r\n\t:;,.|+*/\\=!?[]()";
  private static final String  DEF_IGNORE_CHARS       = "'\"";
  private static final String  DEF_STOP_WORDS         = "the in a at as and or for his her " + "him this that what which while "
                                                          + "up with be was were is";
  private static int           DEF_MIN_WORD_LENGTH    = 3;
  private boolean              indexRadix;
  private String               separatorChars;
  private String               ignoreChars;
  private int                  minWordLength;

  private Set<String>          stopWords;

  public OIndexFullText(String typeId, String algorithm, OIndexEngine<Set<OIdentifiable>> indexEngine,
      String valueContainerAlgorithm, ODocument metadata) {
    super(typeId, algorithm, indexEngine, valueContainerAlgorithm, metadata);
    config();
    configWithMetadata(metadata);

  }

  /**
   * Indexes a value and save the index. Splits the value in single words and index each one. Save of the index is responsibility of
   * the caller.
   */
  @Override
  public OIndexFullText put(Object key, final OIdentifiable iSingleValue) {
    checkForRebuild();

    if (key == null)
      return this;

    key = getCollatingValue(key);

    final ODatabase database = getDatabase();
    final boolean txIsActive = database.getTransaction().isActive();

    if (txIsActive)
      keyLockManager.acquireSharedLock(key);
    try {
      modificationLock.requestModificationLock();

      try {
        final Set<String> words = splitIntoWords(key.toString());

        // FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT
        for (final String word : words) {
          acquireExclusiveLock();
          startStorageAtomicOperation();
          try {
            Set<OIdentifiable> refs;

            // SEARCH FOR THE WORD
            refs = indexEngine.get(word);

            if (refs == null) {
              // WORD NOT EXISTS: CREATE THE KEYWORD CONTAINER THE FIRST TIME THE WORD IS FOUND
              if (ODefaultIndexFactory.SBTREEBONSAI_VALUE_CONTAINER.equals(valueContainerAlgorithm)) {
                boolean durable = false;
                if (metadata != null && Boolean.TRUE.equals(metadata.field("durableInNonTxMode")))
                  durable = true;

                refs = new OIndexRIDContainer(getName(), durable);
              } else {
                refs = new OMVRBTreeRIDSet();
                ((OMVRBTreeRIDSet) refs).setAutoConvertToRecord(false);
              }
            }

            // ADD THE CURRENT DOCUMENT AS REF FOR THAT WORD
            refs.add(iSingleValue);

            // SAVE THE INDEX ENTRY
            indexEngine.put(word, refs);

            commitStorageAtomicOperation();
          } catch (RuntimeException e) {
            rollbackStorageAtomicOperation();
            throw new OIndexException("Error during put of key - value entry", e);
          } finally {
            releaseExclusiveLock();
          }
        }
        return this;
      } finally {
        modificationLock.releaseModificationLock();
      }
    } finally {
      if (txIsActive)
        keyLockManager.releaseSharedLock(key);
    }
  }

  /**
   * Splits passed in key on several words and remove records with keys equals to any item of split result and values equals to
   * passed in value.
   *
   * @param key
   *          Key to remove.
   * @param value
   *          Value to remove.
   * @return true if at least one record is removed.
   */
  @Override
  public boolean remove(Object key, final OIdentifiable value) {
    checkForRebuild();

    key = getCollatingValue(key);

    final ODatabase database = getDatabase();
    final boolean txIsActive = database.getTransaction().isActive();

    if (txIsActive)
      keyLockManager.acquireSharedLock(key);
    try {
      modificationLock.requestModificationLock();

      try {
        final Set<String> words = splitIntoWords(key.toString());
        boolean removed = false;

        for (final String word : words) {
          acquireExclusiveLock();
          startStorageAtomicOperation();
          try {

            final Set<OIdentifiable> recs = indexEngine.get(word);
            if (recs != null && !recs.isEmpty()) {
              if (recs.remove(value)) {
                if (recs.isEmpty())
                  indexEngine.remove(word);
                else
                  indexEngine.put(word, recs);
                removed = true;
              }
            }
            commitStorageAtomicOperation();
          } catch (RuntimeException e) {
            rollbackStorageAtomicOperation();
            throw new OIndexException("Error during removal of entry by key and value", e);
          } finally {
            releaseExclusiveLock();
          }
        }

        return removed;
      } finally {
        modificationLock.releaseModificationLock();
      }
    } finally {
      if (txIsActive)
        keyLockManager.releaseSharedLock(key);
    }
  }

  @Override
  public OIndexInternal<?> create(String name, OIndexDefinition indexDefinition, String clusterIndexName,
      Set<String> clustersToIndex, boolean rebuild, OProgressListener progressListener, OStreamSerializer valueSerializer) {

    if (indexDefinition.getFields().size() > 1) {
      throw new OIndexException(type + " indexes cannot be used as composite ones.");
    }

    return super.create(name, indexDefinition, clusterIndexName, clustersToIndex, rebuild, progressListener, valueSerializer);
  }

  @Override
  public OIndexMultiValues create(String name, OIndexDefinition indexDefinition, String clusterIndexName,
      Set<String> clustersToIndex, boolean rebuild, OProgressListener progressListener) {
    if (indexDefinition.getFields().size() > 1) {
      throw new OIndexException(type + " indexes cannot be used as composite ones.");
    }
    return super.create(name, indexDefinition, clusterIndexName, clustersToIndex, rebuild, progressListener);
  }

  @Override
  public ODocument updateConfiguration() {
    super.updateConfiguration();
    configuration.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);

    try {
      configuration.field(CONFIG_SEPARATOR_CHARS, separatorChars);
      configuration.field(CONFIG_IGNORE_CHARS, ignoreChars);
      configuration.field(CONFIG_STOP_WORDS, stopWords);
      configuration.field(CONFIG_MIN_WORD_LEN, minWordLength);
      configuration.field(CONFIG_INDEX_RADIX, indexRadix);

    } finally {
      configuration.setInternalStatus(ORecordElement.STATUS.LOADED);
    }
    return configuration;
  }

  public boolean canBeUsedInEqualityOperators() {
    return false;
  }

  public boolean supportsOrderedIterations() {
    return false;
  }

  protected void configWithMetadata(ODocument metadata) {
    if (metadata != null) {
      if (metadata.containsField(CONFIG_IGNORE_CHARS))
        ignoreChars = (String) metadata.field(CONFIG_IGNORE_CHARS);

      if (metadata.containsField(CONFIG_INDEX_RADIX))
        indexRadix = (Boolean) metadata.field(CONFIG_INDEX_RADIX);

      if (metadata.containsField(CONFIG_SEPARATOR_CHARS))
        separatorChars = (String) metadata.field(CONFIG_SEPARATOR_CHARS);

      if (metadata.containsField(CONFIG_MIN_WORD_LEN))
        minWordLength = (Integer) metadata.field(CONFIG_MIN_WORD_LEN);

      if (metadata.containsField(CONFIG_STOP_WORDS))
        stopWords = new HashSet<String>((Collection<? extends String>) metadata.field(CONFIG_STOP_WORDS));
    }

  }

  protected void config() {
    ignoreChars = DEF_IGNORE_CHARS;
    indexRadix = DEF_INDEX_RADIX;
    separatorChars = DEF_SEPARATOR_CHARS;
    minWordLength = DEF_MIN_WORD_LENGTH;
    stopWords = new HashSet<String>(OStringSerializerHelper.split(DEF_STOP_WORDS, ' '));
  }

  @Override
  protected void putInSnapshot(Object key, OIdentifiable value, Map<Object, Object> snapshot) {
    if (key == null)
      return;

    key = getCollatingValue(key);

    final Set<String> words = splitIntoWords(key.toString());

    // FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT
    for (final String word : words) {
      Set<OIdentifiable> refs;

      final Object snapshotValue = snapshot.get(word);
      if (snapshotValue == null)
        refs = indexEngine.get(word);
      else if (snapshotValue.equals(RemovedValue.INSTANCE))
        refs = null;
      else
        refs = (Set<OIdentifiable>) snapshotValue;

      if (refs == null) {
        // WORD NOT EXISTS: CREATE THE KEYWORD CONTAINER THE FIRST TIME THE WORD IS FOUND
        if (ODefaultIndexFactory.SBTREEBONSAI_VALUE_CONTAINER.equals(valueContainerAlgorithm)) {
          boolean durable = false;
          if (metadata != null && Boolean.TRUE.equals(metadata.field("durableInNonTxMode")))
            durable = true;

          refs = new OIndexRIDContainer(getName(), durable);
        } else {
          refs = new OMVRBTreeRIDSet();
          ((OMVRBTreeRIDSet) refs).setAutoConvertToRecord(false);
        }

        snapshot.put(word, refs);
      }
      // ADD THE CURRENT DOCUMENT AS REF FOR THAT WORD
      refs.add(value.getIdentity());
    }
  }

  @Override
  protected void removeFromSnapshot(Object key, OIdentifiable value, Map<Object, Object> snapshot) {
    key = getCollatingValue(key);

    final Set<String> words = splitIntoWords(key.toString());
    for (final String word : words) {
      final Set<OIdentifiable> recs;
      final Object snapshotValue = snapshot.get(word);
      if (snapshotValue == null)
        recs = indexEngine.get(word);
      else if (snapshotValue.equals(RemovedValue.INSTANCE))
        recs = null;
      else
        recs = (Set<OIdentifiable>) snapshotValue;

      if (recs != null && !recs.isEmpty()) {
        if (recs.remove(value)) {
          if (recs.isEmpty())
            snapshot.put(word, RemovedValue.INSTANCE);
          else
            snapshot.put(word, recs);
        }
      }
    }
  }

  private Set<String> splitIntoWords(final String iKey) {
    final Set<String> result = new HashSet<String>();

    final List<String> words = (List<String>) OStringSerializerHelper.split(new ArrayList<String>(), iKey, 0, -1, separatorChars);

    final StringBuilder buffer = new StringBuilder(64);
    // FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT

    char c;
    boolean ignore;
    for (String word : words) {
      buffer.setLength(0);

      for (int i = 0; i < word.length(); ++i) {
        c = word.charAt(i);
        ignore = false;
        for (int k = 0; k < ignoreChars.length(); ++k)
          if (c == ignoreChars.charAt(k)) {
            ignore = true;
            break;
          }

        if (!ignore)
          buffer.append(c);
      }

      int length = buffer.length();

      while (length >= minWordLength) {
        buffer.setLength(length);
        word = buffer.toString();

        // CHECK IF IT'S A STOP WORD
        if (!stopWords.contains(word))
          // ADD THE WORD TO THE RESULT SET
          result.add(word);

        if (indexRadix)
          length--;
        else
          break;
      }
    }

    return result;
  }
}


text:
<?php
/**
 * @file
 * Contains \Drupal\bootstrap\Plugin\Setting\SettingInterface.
 */

namespace Drupal\bootstrap\Plugin\Setting;

use Drupal\bootstrap\Plugin\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Defines the interface for an object oriented theme setting plugin.
 */
interface SettingInterface extends FormInterface {

  /**
   * Determines whether a theme setting should added to drupalSettings.
   *
   * By default, this value will be FALSE unless the method is overridden. This
   * is to ensure that no sensitive information can be potientially leaked.
   *
   * @see \Drupal\bootstrap\Plugin\Setting\SettingBase::drupalSettings()
   *
   * @return bool
   *   TRUE or FALSE
   */
  public function drupalSettings();

  /**
   * Retrieves the setting's default value.
   *
   * @return string
   *   The setting's default value.
   */
  public function getDefaultValue();

  /**
   * Retrieves the group form element the setting belongs to.
   *
   * @param array $form
   *   Nested array of form elements that comprise the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return \Drupal\bootstrap\Utility\Element
   *   The group element object.
   */
  public function getGroup(array &$form, FormStateInterface $form_state);

  /**
   * Retrieves the setting's groups.
   *
   * @return array
   *   The setting's group.
   */
  public function getGroups();

  /**
   * Retrieves the form element for the setting.
   *
   * @param array $form
   *   Nested array of form elements that comprise the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return \Drupal\bootstrap\Utility\Element
   *   The setting element object.
   */
  public function getElement(array &$form, FormStateInterface $form_state);

  /**
   * Retrieves the setting's human-readable title.
   *
   * @return string
   *   The setting's type.
   */
  public function getTitle();

}


text:
/* tcp socket abstraction module
 * you need to only declare a socket_type variable to use it
 * see types.h */
#include "os_def.h"
#include "types.h"
#include "network.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_CONNECTIONS 1
#define BUFF_SIZE 256
#define DELIM_CHAR '\0'

static saddr_in server, client;

static void die_with_error(const char * msg);

#ifdef WINDOWS
void socket_init(void)
{
	/* calls WSAStartup() in Windows */
	static WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
	{
		fprintf(stderr, "Err: socket initialization failed with code: %d", WSAGetLastError());
		die_with_error("");
	}
	return;
}
#endif

void socket_create(socket_type * s)
{
	/* creates the socket */
#ifdef WINDOWS
	socket_init();
#endif
	*s = socket(PF_INET, SOCK_STREAM , IPPROTO_TCP);

#ifdef WINDOWS
	if(*s == INVALID_SOCKET)
#else
	if(*s < 0)
#endif
		die_with_error("could not create socket");

	return;
}

void socket_connect(socket_type * s, const char * ip, unsigned short port)
{
	/* initiates the sockaddr_in for the desired server and connects to it */
	memset(&server, 0, sizeof(server)); // zero out memory
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = socket_resolve_name(ip).s_addr;
    server.sin_port = htons(port);

	if (connect(*s, (struct sockaddr *)&server , sizeof(server)) < 0)
		die_with_error("could not connect");

	return;
}

void socket_send(socket_type * s, const byte * message, int len)
{
	/* sends len bytes from the message buffer */
	if (send(*s, message, len, 0) != len)
		die_with_error("sending failed");

	return;
}

int socket_recv(socket_type * s, void(*do_with_data)(byte * data, int len))
{
	/* receives bytes one by one looking for a delimiter
	 * when it finds one it sends the received data to the do_with_data function */
	static byte recv_buff[BUFF_SIZE]; // allocate once
	int recv_size;
	int received = 0;

	while ( received < BUFF_SIZE &&
	(recv_size = recv(*s, recv_buff + received, 1, 0)) != 0 ) // get a single byte
	{
#ifdef WINDOWS
		if (recv_size == SOCKET_ERROR)
#else
		if (recv_size < 0)
#endif
			die_with_error("receiving failed");

		if (*(recv_buff + received) == DELIM_CHAR) // end of message?
		{
			do_with_data(recv_buff, ++received); // send to the worker function
			break;
		}

		++received;
	}

	return recv_size;
}

void socket_shutdown(socket_type * s, int how)
{
	/* shut the socket down */
	if (shutdown(*s, how) != 0)
		die_with_error("shutdown failed");

	return;
}

void socket_close(socket_type * s)
{
	/* properly close the socket */
#ifdef WINDOWS
	closesocket(*s);
	WSACleanup();
#else
	close(*s);
#endif
	return;
}

// server only functions
void socket_bind(socket_type * s, unsigned short port)
{
	/* sets the sockaddr_in when creating a server and binds to a port */
	int bind_r;

	memset(&server, 0, sizeof(server)); // zero out memory
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons(port);

	bind_r = bind(*s, (struct sockaddr *)&server, sizeof(server));

#ifdef WINDOWS
	if (bind_r == SOCKET_ERROR)
#else
	if (bind_r < 0)
#endif
	die_with_error("binding failed");

	return;
}

void socket_listen(socket_type * s)
{
	/* listens for incoming connections */
	int listen_r;

	listen_r = listen(*s, MAX_CONNECTIONS);
#ifdef WINDOWS
	if (listen_r == SOCKET_ERROR)
#else
	if (listen_r < 0)
#endif
	die_with_error("listen failed");

	return;
}

socket_type socket_accept(socket_type * serv_s)
{
	/* accept a connection and return new socket */
	socket_type ret;
	int clnt_len = sizeof(client);
	ret = accept(*serv_s, (struct sockaddr *)&client, &clnt_len);

#ifdef WINDOWS
	if (ret == INVALID_SOCKET)
#else
	if (ret < 0)
#endif
		die_with_error("connection not accepted");

	return ret;
}

// misc
struct in_addr socket_resolve_name(const char * name)
{
	/* resolves a hostname */
	struct hostent * host;

	if ( (host = gethostbyname(name)) == NULL )
		die_with_error("couldn't resolve hostname");

	return *((struct in_addr *)host->h_addr_list[0]);
}

char * socket_get_client_ip(void)
{
	/* returns the ip of the connected client */
	return inet_ntoa(client.sin_addr);
}

char * socket_get_server_ip(void)
{
	/* returns the ip of the connected client */
	return inet_ntoa(server.sin_addr);
}

static void die_with_error(const char * msg)
{
	/* go home when bad things happen */
	if (msg[0])
		fprintf(stderr, "Err: %s\n", msg);
	else
		fputc('\n', stderr);

#ifdef WINDOWS
	WSACleanup();
#endif
	exit(EXIT_FAILURE);
}


text:
static NSDictionary* supportedTestCases;

static NSString* defaultTestCase = @"en_GB0";
static NSString* appendNumber = @"%d";

// Add supported time zones here
static const int c_westernTimeZoneOffset = -28800;
static const int c_GMTTimeZoneOffset = 0;

void testSpecificFormat(int formatterStyle, NSString* formatted, NSString* testCaseKey) {
    NSArray* expectedValues = [supportedTestCases objectForKey:testCaseKey];
    ASSERT_OBJCEQ([expectedValues objectAtIndex:(int)formatterStyle], formatted);
}

bool isSupportedLocaleAndTimeZone(NSLocale* locale, NSTimeZone* timezone) {
    // Create any expected test cases here, must be in the order of NoStyle to FullStyle
    NSArray* expectedValuesWesternUS = @[
        @"",
        @"1/1/70 12:00 AM",
        @"Jan 1, 1970 12:00:00 AM",
        @"January 1, 1970 12:00:00 AM PST",
        @"Thursday, January 1, 1970 12:00:00 AM Pacific Standard Time"
    ];

    NSArray* expectedValuesGMT =
        @[ @"", @"01/01/1970 00:00", @"1 Jan 1970 00:00:00", @"1 January 1970 00:00:00 GMT", @"Thursday, 1 January 1970 00:00:00 GMT" ];

    supportedTestCases = @{
        [@"en_US" stringByAppendingFormat:appendNumber, c_westernTimeZoneOffset] : expectedValuesWesternUS,
        [@"en_GB" stringByAppendingFormat:appendNumber, c_GMTTimeZoneOffset] : expectedValuesGMT
    };

    // If the requested time zone and locale are supported then run the test for that locale.
    bool supportedTestCase = [supportedTestCases.allKeys
        containsObject:[[locale localeIdentifier] stringByAppendingFormat:appendNumber, [timezone secondsFromGMT]]];

    return supportedTestCase;
}

TEST(Foundation, NSDateFormatter) {
    NSLocale* currentLocale = [NSLocale currentLocale];
    NSTimeZone* systemTimeZone = [NSTimeZone systemTimeZone];

    NSLocale* localeToTest;
    NSTimeZone* timeZoneToTest;
    NSString* testCase;

    if (isSupportedLocaleAndTimeZone(currentLocale, systemTimeZone)) {
        localeToTest = currentLocale;
        timeZoneToTest = systemTimeZone;
        testCase = [[currentLocale localeIdentifier] stringByAppendingFormat:appendNumber, systemTimeZone.secondsFromGMT];
    } else {
        NSLog(@"System locale unverified. Running test with GMT's expected values.");
        localeToTest = [NSLocale localeWithLocaleIdentifier:@"en_GB"];
        timeZoneToTest = [NSTimeZone timeZoneWithName:@"GMT"];
        testCase = defaultTestCase;
    }

    // Need to offset the expected constant date by our system time offset.
    // A constant date should be used. 1970-01-01 00:00:00 +0000, This should never change.
    NSDate* someConstantDate = [NSDate dateWithTimeIntervalSince1970:(-1 * [timeZoneToTest secondsFromGMT])];

    NSString* formattedDateString;
    for (int i = 0; i < 5; i++) {
        formattedDateString = [NSDateFormatter _formatDateForLocale:someConstantDate
                                                             locale:localeToTest
                                                          dateStyle:((NSDateFormatterStyle)i)
                                                          timeStyle:((NSDateFormatterStyle)i)
                                                           timeZone:timeZoneToTest];

        testSpecificFormat(i, formattedDateString, testCase);
    }

    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

    // Test setting properties individually.
    for (int i = 0; i < 5; i++) {
        [dateFormatter setLocale:localeToTest];
        [dateFormatter setDateStyle:(NSDateFormatterStyle)i];
        [dateFormatter setTimeStyle:(NSDateFormatterStyle)i];
        [dateFormatter setTimeZone:timeZoneToTest];
        formattedDateString = [dateFormatter stringFromDate:someConstantDate];
        testSpecificFormat(i, formattedDateString, testCase);
    }

    // Try some simple formatting
    // (ensure setDateFormat: overrides individual properties set above).

    // Create an NSDate from string with dateFormatter
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate* date = [dateFormatter dateFromString:@"2009-03-18"];

    // Create an NSString from NSDate with new format
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSString* strMyDate = [dateFormatter stringFromDate:date];

    ASSERT_OBJCEQ(@"18-03-2009", strMyDate);
}


text:
<?php
/**
 * 用户等级说明数据访问层
 *
 * the last known user to change this file in the repository  <$LastChangedBy: suqian $>
 * @author Su qian <suqian@pipi.cn>
 * @version $Id: DoteyRankModel.php 9757 2013-05-07 12:29:09Z suqian $
 * @package model
 * @subpackage consume
 */
class DoteyRankModel extends PipiActiveRecord {
	public function tableName(){
		return '{{dotey_rank}}';
	}

	public function rules(){
		return array(
			array('rank,name','required'),
			array('rank,name','unique'),
		);
	}

	/**
	 * @param string $className
	 * @return DoteyRankModel
	 */
	public static function model($className = __CLASS__){
		return parent::model($className);
	}

	public function getDbConnection(){
		return Yii::app()->db_consume;
	}

	/**
	 * 根据魅力值取得当前等级
	 *
	 * @param int $charm
	 * @return DoteyRankModel
	 */
	public function getDoteyRankByCharm($charm){
	 	$criteria = $this->getDbCriteria();
	 	$criteria->condition = ' charm <= :charm ';
	 	$criteria->order = ' charm DESC ';
	 	$criteria->limit = 1;
	 	$criteria->params[':charm'] = $charm;
		return $this->find($criteria);
	}

	public function getDoteyAllRank(){
		$criteria = $this->getDbCriteria();
		$criteria->order = ' charm DESC ';
		return $this->findAll($criteria);
	}

	/**
	 * 取得等级详细信息
	 *
	 * @param int|array $grades
	 * @return array
	 */
	public function getRanksInfoByRanks($ranks){
		$ranks = is_array($ranks) ? $ranks : array(intval($ranks));
		$criteria = $this->getDbCriteria();
		$criteria->addInCondition('rank',$ranks);
		return $this->findAll($criteria);
	}
}

?>


text:
// Copyright (c) 2016, the M-Transform.js project authors. Please see the
// AUTHORS file for details. All rights reserved. Use of this source code is
// governed by a MIT-style license that can be found in the LICENSE file.
/*jslint node: true, nomen: true*/
"use strict";

var _ = require('lodash'),
    Exception = require('./exception');

var first = _.head,
    last = _.last,
    min = _.min,
    max = _.max,
    concat = _.identity;

function toArray(value) {
    if (Array.isArray(value)) { return value; }
    return [value];
}

function makeCompacter(policy, property) {
    if (typeof policy === 'function') { return policy; }
    switch (policy) {
    case 'first':
        return first;
    case 'last':
        return last;
    case 'min':
        return min;
    case 'max':
        return max;
    case 'concat':
    case undefined:
        return concat;
    default:
        throw new Exception('invalid reduce configuration for "' + property + '"');
    }
}

function makeReducer(compacters) {
    var mapValue = function (zip, property) {
        var values = _.chain(zip)
            .map(1)
            .map(toArray)
            .flatten()
            .value();
        if (compacters[property]) {
            return compacters[property](values);
        }
        return values;
    };
    return function (values) {
        return _.chain(values)
            .map(_.toPairs)
            .flatten()
            .groupBy(0)
            .mapValues(mapValue)
            .value();
    };
}

function Reducer(config) {
    if (config !== undefined && typeof config !== 'object') {
        throw new Exception('invalid configuration');
    }
    var compacters = _.mapValues(config || {}, makeCompacter);
    return makeReducer(compacters);
}

// Helpers
Reducer.first = first;
Reducer.last = last;
Reducer.min = min;
Reducer.max = max;
Reducer.concat = concat;

module.exports = Reducer;


text:
package io.skysail.app.wyt;

import akka.http.scaladsl.server.PathMatcher
import io.skysail.app.wyt.WytApplication._
import io.skysail.core.app.{ApplicationProvider, _}
import org.osgi.service.component.annotations._

object WytApplication {
  val APPLICATION_NAME = "wyt"
  val API_VERSION = ApiVersion(1)
}

@Component(immediate = true, property = { Array("service.pid=wyt") }, service = Array(classOf[ApplicationProvider]))
class WytApplication extends SkysailApplication(APPLICATION_NAME, API_VERSION, "Wait-your-turn backend") with ApplicationProvider {

  override def routesMappings = {
    val root: PathMatcher[Unit] = PathMatcher("root") / "app"
    List(
      RouteMapping("/pacts",root / "pacts", classOf[PactsResource]))
  }

}


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['stableinterface'],
                    'supported_by': 'core'}

DOCUMENTATION = '''
---
module: ec2_metadata_facts
short_description: Gathers facts (instance metadata) about remote hosts within ec2
version_added: "1.0"
author:
    - Silviu Dicu (@silviud)
    - Vinay Dandekar (@roadmapper)
description:
    - This module fetches data from the instance metadata endpoint in ec2 as per
      U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
      The module must be called from within the EC2 instance itself.
notes:
    - Parameters to filter on ec2_metadata_facts may be added later.
'''

EXAMPLES = '''
# Gather EC2 metadata facts
- ec2_metadata_facts:

- debug:
    msg: "This instance is a t1.micro"
  when: ansible_ec2_instance_type == "t1.micro"
'''

RETURN = '''
ansible_facts:
    description: Dictionary of new facts representing discovered properties of the EC2 instance.
    returned: changed
    type: complex
    contains:
        ansible_ec2_ami_id:
            description: The AMI ID used to launch the instance.
            type: str
            sample: "ami-XXXXXXXX"
        ansible_ec2_ami_launch_index:
            description:
                - If you started more than one instance at the same time, this value indicates the order in which the instance was launched.
                  The value of the first instance launched is 0.
            type: str
            sample: "0"
        ansible_ec2_ami_manifest_path:
            description:
                - The path to the AMI manifest file in Amazon S3.
                  If you used an Amazon EBS-backed AMI to launch the instance, the returned result is unknown.
            type: str
            sample: "(unknown)"
        ansible_ec2_ancestor_ami_ids:
            description:
                - The AMI IDs of any instances that were rebundled to create this AMI.
                  This value will only exist if the AMI manifest file contained an ancestor-amis key.
            type: str
            sample: "(unknown)"
        ansible_ec2_block_device_mapping_ami:
            description: The virtual device that contains the root/boot file system.
            type: str
            sample: "/dev/sda1"
        ansible_ec2_block_device_mapping_ebsN:
            description:
                - The virtual devices associated with Amazon EBS volumes, if any are present.
                  Amazon EBS volumes are only available in metadata if they were present at launch time or when the instance was last started.
                  The N indicates the index of the Amazon EBS volume (such as ebs1 or ebs2).
            type: str
            sample: "/dev/xvdb"
        ansible_ec2_block_device_mapping_ephemeralN:
            description: The virtual devices associated with ephemeral devices, if any are present. The N indicates the index of the ephemeral volume.
            type: str
            sample: "/dev/xvdc"
        ansible_ec2_block_device_mapping_root:
            description:
                - The virtual devices or partitions associated with the root devices, or partitions on the virtual device,
                  where the root (/ or C) file system is associated with the given instance.
            type: str
            sample: "/dev/sda1"
        ansible_ec2_block_device_mapping_swap:
            description: The virtual devices associated with swap. Not always present.
            type: str
            sample: "/dev/sda2"
        ansible_ec2_fws_instance_monitoring:
            description: "Value showing whether the customer has enabled detailed one-minute monitoring in CloudWatch."
            type: str
            sample: "enabled"
        ansible_ec2_hostname:
            description:
                - The private IPv4 DNS hostname of the instance.
                  In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).
            type: str
            sample: "ip-10-0-0-1.ec2.internal"
        ansible_ec2_iam_info:
            description:
                - If there is an IAM role associated with the instance, contains information about the last time the instance profile was updated,
                  including the instance's LastUpdated date, InstanceProfileArn, and InstanceProfileId. Otherwise, not present.
            type: complex
            sample: ""
        ansible_ec2_iam_info_instanceprofilearn:
            description: The IAM instance profile ARN.
            type: str
            sample: "arn:aws:iam::<account id>:instance-profile/<role name>"
        ansible_ec2_iam_info_instanceprofileid:
            description: IAM instance profile ID.
            type: str
            sample: ""
        ansible_ec2_iam_info_lastupdated:
            description: IAM info last updated time.
            type: str
            sample: "2017-05-12T02:42:27Z"
        ansible_ec2_iam_instance_profile_role:
            description: IAM instance role.
            type: str
            sample: "role_name"
        ansible_ec2_iam_security_credentials_<role name>:
            description:
                - If there is an IAM role associated with the instance, role-name is the name of the role,
                  and role-name contains the temporary security credentials associated with the role. Otherwise, not present.
            type: str
            sample: ""
        ansible_ec2_iam_security_credentials_<role name>_accesskeyid:
            description: IAM role access key ID.
            type: str
            sample: ""
        ansible_ec2_iam_security_credentials_<role name>_code:
            description: IAM code.
            type: str
            sample: "Success"
        ansible_ec2_iam_security_credentials_<role name>_expiration:
            description: IAM role credentials expiration time.
            type: str
            sample: "2017-05-12T09:11:41Z"
        ansible_ec2_iam_security_credentials_<role name>_lastupdated:
            description: IAM role last updated time.
            type: str
            sample: "2017-05-12T02:40:44Z"
        ansible_ec2_iam_security_credentials_<role name>_secretaccesskey:
            description: IAM role secret access key.
            type: str
            sample: ""
        ansible_ec2_iam_security_credentials_<role name>_token:
            description: IAM role token.
            type: str
            sample: ""
        ansible_ec2_iam_security_credentials_<role name>_type:
            description: IAM role type.
            type: str
            sample: "AWS-HMAC"
        ansible_ec2_instance_action:
            description: Notifies the instance that it should reboot in preparation for bundling.
            type: str
            sample: "none"
        ansible_ec2_instance_id:
            description: The ID of this instance.
            type: str
            sample: "i-XXXXXXXXXXXXXXXXX"
        ansible_ec2_instance_identity_document:
            description: JSON containing instance attributes, such as instance-id, private IP address, etc.
            type: str
            sample: ""
        ansible_ec2_instance_identity_document_accountid:
            description: ""
            type: str
            sample: "012345678901"
        ansible_ec2_instance_identity_document_architecture:
            description: Instance system architecture.
            type: str
            sample: "x86_64"
        ansible_ec2_instance_identity_document_availabilityzone:
            description: The Availability Zone in which the instance launched.
            type: str
            sample: "us-east-1a"
        ansible_ec2_instance_identity_document_billingproducts:
            description: Billing products for this instance.
            type: str
            sample: ""
        ansible_ec2_instance_identity_document_devpayproductcodes:
            description: Product codes for the launched AMI.
            type: str
            sample: ""
        ansible_ec2_instance_identity_document_imageid:
            description: The AMI ID used to launch the instance.
            type: str
            sample: "ami-01234567"
        ansible_ec2_instance_identity_document_instanceid:
            description: The ID of this instance.
            type: str
            sample: "i-0123456789abcdef0"
        ansible_ec2_instance_identity_document_instancetype:
            description: The type of instance.
            type: str
            sample: "m4.large"
        ansible_ec2_instance_identity_document_kernelid:
            description: The ID of the kernel launched with this instance, if applicable.
            type: str
            sample: ""
        ansible_ec2_instance_identity_document_pendingtime:
            description: The instance pending time.
            type: str
            sample: "2017-05-11T20:51:20Z"
        ansible_ec2_instance_identity_document_privateip:
            description:
                - The private IPv4 address of the instance.
                  In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).
            type: str
            sample: "10.0.0.1"
        ansible_ec2_instance_identity_document_ramdiskid:
            description: The ID of the RAM disk specified at launch time, if applicable.
            type: str
            sample: ""
        ansible_ec2_instance_identity_document_region:
            description: The Region in which the instance launched.
            type: str
            sample: "us-east-1"
        ansible_ec2_instance_identity_document_version:
            description: Identity document version.
            type: str
            sample: "2010-08-31"
        ansible_ec2_instance_identity_pkcs7:
            description: Used to verify the document's authenticity and content against the signature.
            type: str
            sample: ""
        ansible_ec2_instance_identity_rsa2048:
            description: Used to verify the document's authenticity and content against the signature.
            type: str
            sample: ""
        ansible_ec2_instance_identity_signature:
            description: Data that can be used by other parties to verify its origin and authenticity.
            type: str
            sample: ""
        ansible_ec2_instance_type:
            description: The type of instance.
            type: str
            sample: "m4.large"
        ansible_ec2_local_hostname:
            description:
                - The private IPv4 DNS hostname of the instance.
                  In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).
            type: str
            sample: "ip-10-0-0-1.ec2.internal"
        ansible_ec2_local_ipv4:
            description:
                - The private IPv4 address of the instance.
                  In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).
            type: str
            sample: "10.0.0.1"
        ansible_ec2_mac:
            description:
                - The instance's media access control (MAC) address.
                  In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).
            type: str
            sample: "00:11:22:33:44:55"
        ansible_ec2_metrics_vhostmd:
            description: Metrics.
            type: str
            sample: ""
        ansible_ec2_network_interfaces_macs_<mac address>_device_number:
            description:
                - The unique device number associated with that interface. The device number corresponds to the device name;
                  for example, a device-number of 2 is for the eth2 device.
                  This category corresponds to the DeviceIndex and device-index fields that are used by the Amazon EC2 API and the EC2 commands for the AWS CLI.
            type: str
            sample: "0"
        ansible_ec2_network_interfaces_macs_<mac address>_interface_id:
            description: The elastic network interface ID.
            type: str
            sample: "eni-12345678"
        ansible_ec2_network_interfaces_macs_<mac address>_ipv4_associations_<ip address>:
            description: The private IPv4 addresses that are associated with each public-ip address and assigned to that interface.
            type: str
            sample: ""
        ansible_ec2_network_interfaces_macs_<mac address>_ipv6s:
            description: The IPv6 addresses associated with the interface. Returned only for instances launched into a VPC.
            type: str
            sample: ""
        ansible_ec2_network_interfaces_macs_<mac address>_local_hostname:
            description: The interface's local hostname.
            type: str
            sample: ""
        ansible_ec2_network_interfaces_macs_<mac address>_local_ipv4s:
            description: The private IPv4 addresses associated with the interface.
            type: str
            sample: ""
        ansible_ec2_network_interfaces_macs_<mac address>_mac:
            description: The instance's MAC address.
            type: str
            sample: "00:11:22:33:44:55"
        ansible_ec2_network_interfaces_macs_<mac address>_owner_id:
            description:
                - The ID of the owner of the network interface.
                  In multiple-interface environments, an interface can be attached by a third party, such as Elastic Load Balancing.
                  Traffic on an interface is always billed to the interface owner.
            type: str
            sample: "01234567890"
        ansible_ec2_network_interfaces_macs_<mac address>_public_hostname:
            description:
                - The interface's public DNS (IPv4). If the instance is in a VPC,
                  this category is only returned if the enableDnsHostnames attribute is set to true.
            type: str
            sample: "ec2-1-2-3-4.compute-1.amazonaws.com"
        ansible_ec2_network_interfaces_macs_<mac address>_public_ipv4s:
            description: The Elastic IP addresses associated with the interface. There may be multiple IPv4 addresses on an instance.
            type: str
            sample: "1.2.3.4"
        ansible_ec2_network_interfaces_macs_<mac address>_security_group_ids:
            description: The IDs of the security groups to which the network interface belongs. Returned only for instances launched into a VPC.
            type: str
            sample: "sg-01234567,sg-01234568"
        ansible_ec2_network_interfaces_macs_<mac address>_security_groups:
            description: Security groups to which the network interface belongs. Returned only for instances launched into a VPC.
            type: str
            sample: "secgroup1,secgroup2"
        ansible_ec2_network_interfaces_macs_<mac address>_subnet_id:
            description: The ID of the subnet in which the interface resides. Returned only for instances launched into a VPC.
            type: str
            sample: "subnet-01234567"
        ansible_ec2_network_interfaces_macs_<mac address>_subnet_ipv4_cidr_block:
            description: The IPv4 CIDR block of the subnet in which the interface resides. Returned only for instances launched into a VPC.
            type: str
            sample: "10.0.1.0/24"
        ansible_ec2_network_interfaces_macs_<mac address>_subnet_ipv6_cidr_blocks:
            description: The IPv6 CIDR block of the subnet in which the interface resides. Returned only for instances launched into a VPC.
            type: str
            sample: ""
        ansible_ec2_network_interfaces_macs_<mac address>_vpc_id:
            description: The ID of the VPC in which the interface resides. Returned only for instances launched into a VPC.
            type: str
            sample: "vpc-0123456"
        ansible_ec2_network_interfaces_macs_<mac address>_vpc_ipv4_cidr_block:
            description: The IPv4 CIDR block of the VPC in which the interface resides. Returned only for instances launched into a VPC.
            type: str
            sample: "10.0.0.0/16"
        ansible_ec2_network_interfaces_macs_<mac address>_vpc_ipv4_cidr_blocks:
            description: The IPv4 CIDR block of the VPC in which the interface resides. Returned only for instances launched into a VPC.
            type: str
            sample: "10.0.0.0/16"
        ansible_ec2_network_interfaces_macs_<mac address>_vpc_ipv6_cidr_blocks:
            description: The IPv6 CIDR block of the VPC in which the interface resides. Returned only for instances launched into a VPC.
            type: str
            sample: ""
        ansible_ec2_placement_availability_zone:
            description: The Availability Zone in which the instance launched.
            type: str
            sample: "us-east-1a"
        ansible_ec2_placement_region:
            description: The Region in which the instance launched.
            type: str
            sample: "us-east-1"
        ansible_ec2_product_codes:
            description: Product codes associated with the instance, if any.
            type: str
            sample: "aw0evgkw8e5c1q413zgy5pjce"
        ansible_ec2_profile:
            description: EC2 instance hardware profile.
            type: str
            sample: "default-hvm"
        ansible_ec2_public_hostname:
            description:
                - The instance's public DNS. If the instance is in a VPC, this category is only returned if the enableDnsHostnames attribute is set to true.
            type: str
            sample: "ec2-1-2-3-4.compute-1.amazonaws.com"
        ansible_ec2_public_ipv4:
            description: The public IPv4 address. If an Elastic IP address is associated with the instance, the value returned is the Elastic IP address.
            type: str
            sample: "1.2.3.4"
        ansible_ec2_public_key:
            description: Public key. Only available if supplied at instance launch time.
            type: str
            sample: ""
        ansible_ec2_ramdisk_id:
            description: The ID of the RAM disk specified at launch time, if applicable.
            type: str
            sample: ""
        ansible_ec2_reservation_id:
            description: The ID of the reservation.
            type: str
            sample: "r-0123456789abcdef0"
        ansible_ec2_security_groups:
            description:
                - The names of the security groups applied to the instance. After launch, you can only change the security groups of instances running in a VPC.
                  Such changes are reflected here and in network/interfaces/macs/mac/security-groups.
            type: str
            sample: "securitygroup1,securitygroup2"
        ansible_ec2_services_domain:
            description: The domain for AWS resources for the region; for example, amazonaws.com for us-east-1.
            type: str
            sample: "amazonaws.com"
        ansible_ec2_services_partition:
            description:
                - The partition that the resource is in. For standard AWS regions, the partition is aws.
                  If you have resources in other partitions, the partition is aws-partitionname.
                  For example, the partition for resources in the China (Beijing) region is aws-cn.
            type: str
            sample: "aws"
        ansible_ec2_spot_termination_time:
            description:
                - The approximate time, in UTC, that the operating system for your Spot instance will receive the shutdown signal.
                  This item is present and contains a time value only if the Spot instance has been marked for termination by Amazon EC2.
                  The termination-time item is not set to a time if you terminated the Spot instance yourself.
            type: str
            sample: "2015-01-05T18:02:00Z"
        ansible_ec2_user_data:
            description: The instance user data.
            type: str
            sample: "#!/bin/bash"
'''

import json
import re
import socket
import time

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_text
from ansible.module_utils.urls import fetch_url
from ansible.module_utils.six.moves.urllib.parse import quote

socket.setdefaulttimeout(5)

class Ec2Metadata(object):
    ec2_metadata_uri = 'http://169.254.169.254/latest/meta-data/'
    ec2_sshdata_uri = 'http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key'
    ec2_userdata_uri = 'http://169.254.169.254/latest/user-data/'
    ec2_dynamicdata_uri = 'http://169.254.169.254/latest/dynamic/'

    def __init__(self, module, ec2_metadata_uri=None, ec2_sshdata_uri=None, ec2_userdata_uri=None, ec2_dynamicdata_uri=None):
        self.module = module
        self.uri_meta = ec2_metadata_uri or self.ec2_metadata_uri
        self.uri_user = ec2_userdata_uri or self.ec2_userdata_uri
        self.uri_ssh = ec2_sshdata_uri or self.ec2_sshdata_uri
        self.uri_dynamic = ec2_dynamicdata_uri or self.ec2_dynamicdata_uri
        self._data = {}
        self._prefix = 'ansible_ec2_%s'

    def _fetch(self, url):
        encoded_url = quote(url, safe='%/:=&?~#+!$,;\'@()*[]')
        response, info = fetch_url(self.module, encoded_url, force=True)

        if info.get('status') not in (200, 404):
            time.sleep(3)
            # request went bad, retry once then raise
            self.module.warn('Retrying query to metadata service. First attempt failed: {0}'.format(info['msg']))
            response, info = fetch_url(self.module, encoded_url, force=True)
            if info.get('status') not in (200, 404):
                # fail out now
                self.module.fail_json(msg='Failed to retrieve metadata from AWS: {0}'.format(info['msg']), response=info)
        if response:
            data = response.read()
        else:
            data = None
        return to_text(data)

    def _mangle_fields(self, fields, uri, filter_patterns=None):
        filter_patterns = ['public-keys-0'] if filter_patterns is None else filter_patterns

        new_fields = {}
        for key, value in fields.items():
            split_fields = key[len(uri):].split('/')
            # Parse out the IAM role name (which is _not_ the same as the instance profile name)
            if len(split_fields) == 3 and split_fields[0:2] == ['iam', 'security-credentials'] and ':' not in split_fields[2]:
                new_fields[self._prefix % "iam-instance-profile-role"] = split_fields[2]
            if len(split_fields) > 1 and split_fields[1]:
                new_key = "-".join(split_fields)
                new_fields[self._prefix % new_key] = value
            else:
                new_key = "".join(split_fields)
                new_fields[self._prefix % new_key] = value
        for pattern in filter_patterns:
            for key in dict(new_fields):
                match = re.search(pattern, key)
                if match:
                    new_fields.pop(key)
        return new_fields

    def fetch(self, uri, recurse=True):
        raw_subfields = self._fetch(uri)
        if not raw_subfields:
            return
        subfields = raw_subfields.split('\n')
        for field in subfields:
            if field.endswith('/') and recurse:
                self.fetch(uri + field)
            if uri.endswith('/'):
                new_uri = uri + field
            else:
                new_uri = uri + '/' + field
            if new_uri not in self._data and not new_uri.endswith('/'):
                content = self._fetch(new_uri)
                if field == 'security-groups' or field == 'security-group-ids':
                    sg_fields = ",".join(content.split('\n'))
                    self._data['%s' % (new_uri)] = sg_fields
                else:
                    try:
                        dict = json.loads(content)
                        self._data['%s' % (new_uri)] = content
                        for (key, value) in dict.items():
                            self._data['%s:%s' % (new_uri, key.lower())] = value
                    except Exception:
                        self._data['%s' % (new_uri)] = content  # not a stringifed JSON string

    def fix_invalid_varnames(self, data):
        """Change ':'' and '-' to '_' to ensure valid template variable names"""
        new_data = data.copy()
        for key, value in data.items():
            if ':' in key or '-' in key:
                newkey = re.sub(':|-', '_', key)
                new_data[newkey] = value
                del new_data[key]

        return new_data

    def run(self):
        self.fetch(self.uri_meta)  # populate _data with metadata
        data = self._mangle_fields(self._data, self.uri_meta)
        data[self._prefix % 'user-data'] = self._fetch(self.uri_user)
        data[self._prefix % 'public-key'] = self._fetch(self.uri_ssh)

        self._data = {}  # clear out metadata in _data
        self.fetch(self.uri_dynamic)  # populate _data with dynamic data
        dyndata = self._mangle_fields(self._data, self.uri_dynamic)
        data.update(dyndata)
        data = self.fix_invalid_varnames(data)

        # Maintain old key for backwards compatibility
        if 'ansible_ec2_instance_identity_document_region' in data:
            data['ansible_ec2_placement_region'] = data['ansible_ec2_instance_identity_document_region']
        return data

def main():
    module = AnsibleModule(
        argument_spec={},
        supports_check_mode=True,
    )

    ec2_metadata_facts = Ec2Metadata(module).run()
    ec2_metadata_facts_result = dict(changed=False, ansible_facts=ec2_metadata_facts)

    module.exit_json(**ec2_metadata_facts_result)

if __name__ == '__main__':
    main()


text:
set -euxo pipefail

NIX_PROFILE=~/.nix-profile/etc/profile.d/nix.sh

export MANPATH=
. $NIX_PROFILE

export NIX_PATH=nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/nixos-18.03.tar.gz

function nix-install() {
  nix-env -f '<nixpkgs>' -iA "$@"
}