text:
package com.corundumstudio.socketio.handler;

import io.netty.channel.Channel;
import io.netty.util.internal.PlatformDependent;

import java.util.Map;
import java.util.UUID;

import com.corundumstudio.socketio.HandshakeData;

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

public class ClientsBox {
    private final Logger log = LoggerFactory.getLogger(getClass());

    private final Map<UUID, ClientHead> uuid2clients = PlatformDependent.newConcurrentHashMap();
    private final Map<Channel, ClientHead> channel2clients = PlatformDependent.newConcurrentHashMap();

    // TODO use storeFactory
    public HandshakeData getHandshakeData(UUID sessionId) {
        ClientHead client = uuid2clients.get(sessionId);
        if (client == null) {
            return null;
        }

        return client.getHandshakeData();
    }

    public void addClient(ClientHead clientHead) {
        uuid2clients.put(clientHead.getSessionId(), clientHead);
    }

    public void removeClient(UUID sessionId) {
        uuid2clients.remove(sessionId);
    }

    public ClientHead get(UUID sessionId) {
        return uuid2clients.get(sessionId);
    }

    public void add(Channel channel, ClientHead clientHead) {
        channel2clients.put(channel, clientHead);
    }

    public void remove(Channel channel) {
        channel2clients.remove(channel);
    }

    public ClientHead get(Channel channel) {
        return channel2clients.get(channel);
    }

    public void dumpStats() {
        log.info("Memory Sizes: " +
            "uuid2clients=" + uuid2clients.keySet().size() + ", " +
            "channel2clients=" + channel2clients.keySet().size()
        );
    }
}


text:
Enables apache2 module `mod_php`.

This resource will install and enable the Apache PHP module. See `apache_mod_php_package` for the platform-specific module package.
If installing PHP outside of this resource (i.e. with the [`php` cookbook](https://github.com/sous-chefs/php)), you should set `install_package` to false to avoid a possible version conflict.

**Note: call this resource directly, not through `apache2_module`!**
This resource will call `_module` with the correct identifiers for you.

## Properties

| Name             | Type   | Default                      | Description                                                                                |
| ---------------- | ------ | ---------------------------- | --------------------------------------------------------------------------------------------------------------- |
| module_name      | String | `apache_mod_php_modulename`  | The name of the php module.                                                                                |
| so_filename      | String | `apache_mod_php_filename`    | The filename of the module object.                                                                              |
| package_name     | String | `apache_mod_php_package`     | The package that contains the PHP module itself, which is sometimes not included with the default PHP packages. |
| install_package  | Bool   | `true`                       | Whether to install the PHP module package.                                                                      |

redpajama_set_name: RedPajamaGithub


text:
enum  CDVWechatSharingType {
    CDVWXSharingTypeApp = 1,
    CDVWXSharingTypeEmotion,
    CDVWXSharingTypeFile,
    CDVWXSharingTypeImage,
    CDVWXSharingTypeMusic,
    CDVWXSharingTypeVideo,
    CDVWXSharingTypeWebPage
};

@interface CDVWechat:CDVPlugin <WXApiDelegate>

@property (nonatomic, strong) NSString *currentCallbackId;
@property (nonatomic, strong) NSString *wechatAppId;

- (void)isWXAppInstalled:(CDVInvokedUrlCommand *)command;
- (void)share:(CDVInvokedUrlCommand *)command;
- (void)sendAuthRequest:(CDVInvokedUrlCommand *)command;
- (void)sendPaymentRequest:(CDVInvokedUrlCommand *)command;

@end


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

namespace QTFK.Services
{
    public interface IRepositoryBuilder
    {
        //IRepository<T> Build(typeof(ISampleRepository), queryFactory, methodParsers);
        //T Build<T>(queryFactory, methodParsers) where T: IRepository<>;
        //Assembly Build(Type interfaceType, IQueryFactory<> queryFactory, IEnumerable<IMethodParser> methodParsers);
        Assembly Build(Type interfaceType);
    }
}


text:
package org.apache.storm.state;

import java.util.List;

public class SynchronizeOutputCollector implements ISynchronizeOutputCollector {

    @Override
    public void add(int streamId, Object id, List<Object> tuple) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}


text:
package co.uk.niadel.napi.common.block;

import net.minecraft.block.Block;
import co.uk.niadel.napi.measuresapi.ModMeasureBase;

public interface IMeasureTransferer
{
	/**
	 * Called to transfer the measure to the target.
	 * @param target - What you're transferring to.
	 * @param measure - What you're transferring.
	 */
	public void transferMeasure(IMeasureTransferer target, ModMeasureBase measure);

	/**
	 * Called when you receive a measure. Or should be anyways.
	 * @param transferer
	 * @param measure
	 */
	public void onReceiveMeasure(IMeasureTransferer transferer, ModMeasureBase measure);

	/**
	 * Called to determine whether or not the target is a suitable transfer target.
	 * @param target
	 * @return
	 */
	public boolean canTransferTo(IMeasureTransferer target);

	/**
	 * Called to determine whether or not the target Block is a suitable transferer.
	 * @param theBlock
	 * @return
	 */
	public boolean canTransferToBlock(Block theBlock, int direction);

	/**
	 * Gets this transferer's mod measure.
	 * @return
	 */
	public ModMeasureBase getMeasure();
}


text:
Sorts: sortSubNumbersTotal
#PURPOSE of the 4 number and alpha fields, sort by the second to last one
#
#
#
If [ steward::chosenSortTotal = "sub" ]
Set Variable [ $$record; Value:brainstate::_lockBrainstateID ]
Sort Records [ Specified Sort Order: brainstate::sortSubNumber; descending
brainstate::sortCategory; descending
brainstate::description; ascending ]
[ Restore; No dialog ]
Set Field [ steward::chosenSortTotal; "bus" ]
Go to Record/Request/Page
[ First ]
Loop
Exit Loop If [ $$record = brainstate::_lockBrainstateID ]
Go to Record/Request/Page
[ Next ]
End Loop
Set Variable [ $$record ]
Go to Field [ ]
Halt Script
End If
If [ steward::chosenSortTotal ≠ "sub" ]
Set Variable [ $$record; Value:brainstate::_lockBrainstateID ]
Sort Records [ Specified Sort Order: brainstate::sortSubNumber; based on value list: "__-99"
brainstate::sortCategory; based on value list: "sortAlpha"
brainstate::description; ascending ]
[ Restore; No dialog ]
Set Field [ steward::chosenSortTotal; "sub" ]
Go to Record/Request/Page
[ First ]
Loop
Exit Loop If [ $$record = brainstate::_lockBrainstateID ]
Go to Record/Request/Page
[ Next ]
End Loop
Set Variable [ $$record ]
Go to Field [ ]
End If
January 6, 平成26 0:53:12 ActionLog.fp7 - sortSubNumbersTotal -1-


text:
/*
 * Machine Generated include file for message "Death Message".
 * NOTE: This file is read only. DO NOT ATTEMPT TO MODIFY IT BY HAND.
 * Generated on 24-July-1997 at 18:20:03
 * Generated from file EVENTS.XLS by Kevin Klemmick
 */

#ifndef _DEATHMESSAGE_H
#define _DEATHMESSAGE_H

/*
 * Required Include Files
 */
#include "F4vu.h"
#include "mission.h"
#include "FalcMesg.h"

//sfr: for chks
#include "InvalidBufferException.h"

#pragma pack (1)

/*
 * Message Type Death Message
 */
class FalconDeathMessage : public FalconEvent
{
public:
    FalconDeathMessage(VU_ID entityId, VuTargetEntity *target, VU_BOOL loopback = TRUE);
    FalconDeathMessage(VU_MSG_TYPE type, VU_ID senderid, VU_ID target);
    ~FalconDeathMessage(void);
    virtual int Size() const
    {
        return sizeof(dataBlock) + FalconEvent::Size();
    };
    //sfr: changed to ong *
    int Decode(VU_BYTE **buf, long *rem)
    {
        long init = *rem;

        FalconEvent::Decode(buf, rem);
        memcpychk(&dataBlock, buf, sizeof(dataBlock), rem);
        return init - *rem;
    };
    int Encode(VU_BYTE **buf)
    {
        int size;

        size = FalconEvent::Encode(buf);
        memcpy(*buf, &dataBlock, sizeof(dataBlock));
        *buf += sizeof(dataBlock);
        size += sizeof(dataBlock);
        return size;
    };
    class DATA_BLOCK
    {
    public:
        unsigned int damageType;
        float deathPctStrength;
        VU_ID dEntityID;
        ushort dCampID;
        uchar dPilotID;
        ushort dIndex;
        uchar dSide;
        VU_ID fEntityID;
        ushort fCampID;
        uchar fPilotID;
        ushort fIndex;
        uchar fSide;
        ushort fWeaponID;
        VU_ID fWeaponUID;
    } dataBlock;

protected:
    int Process(uchar autodisp);
};

#pragma pack ()

#endif


text:
package io.druid.segment;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import io.druid.java.util.common.io.Closer;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.guava.CloseQuietly;
import io.druid.java.util.common.logger.Logger;
import io.druid.query.monomorphicprocessing.RuntimeShapeInspector;
import io.druid.segment.column.BitmapIndex;
import io.druid.segment.column.Column;
import io.druid.segment.column.ColumnCapabilities;
import io.druid.segment.column.ComplexColumn;
import io.druid.segment.column.DictionaryEncodedColumn;
import io.druid.segment.column.GenericColumn;
import io.druid.segment.column.IndexedFloatsGenericColumn;
import io.druid.segment.column.IndexedLongsGenericColumn;
import io.druid.segment.column.ValueType;
import io.druid.segment.data.BitmapCompressedIndexedInts;
import io.druid.segment.data.EmptyIndexedInts;
import io.druid.segment.data.Indexed;
import io.druid.segment.data.IndexedInts;
import io.druid.segment.data.IndexedIterable;
import io.druid.segment.data.ListIndexed;
import org.joda.time.Interval;

import java.io.Closeable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

/**
 */
public class QueryableIndexIndexableAdapter implements IndexableAdapter
{
  private static final Logger log = new Logger(QueryableIndexIndexableAdapter.class);
  private final int numRows;
  private final QueryableIndex input;
  private final List<String> availableDimensions;
  private final Metadata metadata;

  public QueryableIndexIndexableAdapter(QueryableIndex input)
  {
    this.input = input;
    numRows = input.getNumRows();

    // It appears possible that the dimensions have some columns listed which do not have a DictionaryEncodedColumn
    // This breaks current logic, but should be fine going forward.  This is a work-around to make things work
    // in the current state.  This code shouldn't be needed once github tracker issue #55 is finished.
    this.availableDimensions = Lists.newArrayList();
    for (String dim : input.getAvailableDimensions()) {
      final Column col = input.getColumn(dim);

      if (col == null) {
        log.warn("Wtf!? column[%s] didn't exist!?!?!?", dim);
      } else {
        if (col.getDictionaryEncoding() == null) {
          log.info("No dictionary on dimension[%s]", dim);
        }
        availableDimensions.add(dim);
      }
    }

    this.metadata = input.getMetadata();
  }

  @Override
  public Interval getDataInterval()
  {
    return input.getDataInterval();
  }

  @Override
  public int getNumRows()
  {
    return numRows;
  }

  @Override
  public Indexed<String> getDimensionNames()
  {
    return new ListIndexed<>(availableDimensions, String.class);
  }

  @Override
  public Indexed<String> getMetricNames()
  {
    final Set<String> columns = Sets.newLinkedHashSet(input.getColumnNames());
    final HashSet<String> dimensions = Sets.newHashSet(getDimensionNames());

    return new ListIndexed<>(
        Lists.newArrayList(Sets.difference(columns, dimensions)),
        String.class
    );
  }

  @Override
  public Indexed<Comparable> getDimValueLookup(String dimension)
  {
    final Column column = input.getColumn(dimension);

    if (column == null) {
      return null;
    }

    final DictionaryEncodedColumn dict = column.getDictionaryEncoding();

    if (dict == null) {
      return null;
    }

    return new Indexed<Comparable>()
    {
      @Override
      public Class<? extends Comparable> getClazz()
      {
        return Comparable.class;
      }

      @Override
      public int size()
      {
        return dict.getCardinality();
      }

      @Override
      public Comparable get(int index)
      {
        return dict.lookupName(index);
      }

      @Override
      public int indexOf(Comparable value)
      {
        return dict.lookupId(value);
      }

      @Override
      public Iterator<Comparable> iterator()
      {
        return IndexedIterable.create(this).iterator();
      }

      @Override
      public void inspectRuntimeShape(RuntimeShapeInspector inspector)
      {
        inspector.visit("dict", dict);
      }
    };
  }

  @Override
  public Iterable<Rowboat> getRows()
  {
    return new Iterable<Rowboat>()
    {
      @Override
      public Iterator<Rowboat> iterator()
      {
        return new Iterator<Rowboat>()
        {
          final GenericColumn timestamps = input.getColumn(Column.TIME_COLUMN_NAME).getGenericColumn();
          final Closeable[] metrics;
          final Closeable[] columns;
          final Closer closer = Closer.create();

          final int numMetrics = getMetricNames().size();

          final DimensionHandler[] handlers = new DimensionHandler[availableDimensions.size()];
          Collection<DimensionHandler> handlerSet = input.getDimensionHandlers().values();

          int currRow = 0;
          boolean done = false;

          {
            closer.register(timestamps);

            handlerSet.toArray(handlers);
            this.columns = FluentIterable
                .from(handlerSet)
                .transform(
                    new Function<DimensionHandler, Closeable>()
                    {
                      @Override
                      public Closeable apply(DimensionHandler handler)
                      {
                        Column column = input.getColumn(handler.getDimensionName());
                        return handler.getSubColumn(column);
                      }
                    }
                ).toArray(Closeable.class);
            for (Closeable column : columns) {
              closer.register(column);
            }

            final Indexed<String> availableMetrics = getMetricNames();
            metrics = new Closeable[availableMetrics.size()];
            for (int i = 0; i < metrics.length; ++i) {
              final Column column = input.getColumn(availableMetrics.get(i));
              final ValueType type = column.getCapabilities().getType();
              switch (type) {
                case FLOAT:
                case LONG:
                  metrics[i] = column.getGenericColumn();
                  break;
                case COMPLEX:
                  metrics[i] = column.getComplexColumn();
                  break;
                default:
                  throw new ISE("Cannot handle type[%s]", type);
              }
            }
            for (Closeable metricColumn : metrics) {
              closer.register(metricColumn);
            }
          }

          @Override
          public boolean hasNext()
          {
            final boolean hasNext = currRow < numRows;
            if (!hasNext && !done) {
              CloseQuietly.close(closer);
              done = true;
            }
            return hasNext;
          }

          @Override
          public Rowboat next()
          {
            if (!hasNext()) {
              throw new NoSuchElementException();
            }

            final Object[] dims = new Object[columns.length];
            int dimIndex = 0;
            for (final Closeable column : columns) {
              dims[dimIndex] = handlers[dimIndex].getEncodedKeyComponentFromColumn(column, currRow);
              dimIndex++;
            }

            Object[] metricArray = new Object[numMetrics];
            for (int i = 0; i < metricArray.length; ++i) {
              if (metrics[i] instanceof IndexedFloatsGenericColumn) {
                metricArray[i] = ((GenericColumn) metrics[i]).getFloatSingleValueRow(currRow);
              } else if (metrics[i] instanceof IndexedLongsGenericColumn) {
                metricArray[i] = ((GenericColumn) metrics[i]).getLongSingleValueRow(currRow);
              } else if (metrics[i] instanceof ComplexColumn) {
                metricArray[i] = ((ComplexColumn) metrics[i]).getRowValue(currRow);
              }
            }

            final Rowboat retVal = new Rowboat(
                timestamps.getLongSingleValueRow(currRow), dims, metricArray, currRow, handlers
            );

            ++currRow;

            return retVal;
          }

          @Override
          public void remove()
          {
            throw new UnsupportedOperationException();
          }
        };
      }
    };
  }

  @VisibleForTesting
  IndexedInts getBitmapIndex(String dimension, String value)
  {
    final Column column = input.getColumn(dimension);

    if (column == null) {
      return EmptyIndexedInts.EMPTY_INDEXED_INTS;
    }

    final BitmapIndex bitmaps = column.getBitmapIndex();
    if (bitmaps == null) {
      return EmptyIndexedInts.EMPTY_INDEXED_INTS;
    }

    return new BitmapCompressedIndexedInts(bitmaps.getBitmap(bitmaps.getIndex(value)));
  }

  @Override
  public String getMetricType(String metric)
  {
    final Column column = input.getColumn(metric);

    final ValueType type = column.getCapabilities().getType();
    switch (type) {
      case FLOAT:
        return "float";
      case LONG:
        return "long";
      case COMPLEX: {
        try (ComplexColumn complexColumn = column.getComplexColumn() ) {
          return complexColumn.getTypeName();
        }
      }
      default:
        throw new ISE("Unknown type[%s]", type);
    }
  }

  @Override
  public ColumnCapabilities getCapabilities(String column)
  {
    return input.getColumn(column).getCapabilities();
  }

  @Override
  public IndexedInts getBitmapIndex(String dimension, int dictId)
  {
    final Column column = input.getColumn(dimension);
    if (column == null) {
      return EmptyIndexedInts.EMPTY_INDEXED_INTS;
    }

    final BitmapIndex bitmaps = column.getBitmapIndex();
    if (bitmaps == null) {
      return EmptyIndexedInts.EMPTY_INDEXED_INTS;
    }

    if (dictId >= 0) {
      return new BitmapCompressedIndexedInts(bitmaps.getBitmap(dictId));
    } else {
      return EmptyIndexedInts.EMPTY_INDEXED_INTS;
    }
  }

  @Override
  public Metadata getMetadata()
  {
    return metadata;
  }

  @Override
  public Map<String, DimensionHandler> getDimensionHandlers()
  {
    return input.getDimensionHandlers();
  }
}


text:
require 'itamae'

module Itamae
  class Definition < Resource::Base
    class << self
      def create_class(name, params, &block)
        Class.new(self).tap do |klass|
          klass.definition_block = block

          klass.define_attribute :action, default: :run
          params.each_pair do |key, value|
            klass.define_attribute key.to_sym, type: Object, default: value
          end
        end
      end

      def definition_block=(block)
        @definition_block = block
      end

      def definition_block
        @definition_block
      end
    end

    def initialize(*args)
      super

      construct_resources
    end

    def action_run(options)
      @children.run(options)
    end

    private

    def construct_resources
      block = self.class.definition_block

      context = Context.new(@attributes.merge(name: resource_name))
      context.instance_exec(&block)
      @children = context.children
    end

    class Context
      attr_reader :params
      attr_reader :children

      def initialize(params, &block)
        @params = params
        @children = RecipeChildren.new
      end

      def method_missing(method, name, &block)
        klass = Resource.get_resource_class(method)
        resource = klass.new(self, name, &block)
        @children << resource
      end
    end
  end
end


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


text:
<head>
  <title>hooks</title>
</head>

<template name="loading">
  Loading template
</template>

<template name="404">
  404
</template>

<template name="adminRequired">
  ADMIN REQUIRED!
</template>

<template name="login">
  {{loginButtons}}
</template>

<template name="userPage">
  Hey, you've logged in, here's your dashboard
</template>

<template name="adminPage">
  This is an admin only page!
</template>


text:
'use strict';

let Reflux = require('reflux');
let request = require('superagent');
let actions = require('../actions/app-actions');

let ItemStore = Reflux.createStore({

  init() {
    this.data = {
      items: {
        books: [],
        categories: [],
        people: []
      }
    };

    this.listenTo(actions.loadPage, this.loadPage);
  },

  loadPage(itemType,cached) {
    if (!this.data.items[itemType])
      return;

    if(cached !== true || this.data.items[itemType].length === 0) {
      request.get('data/' + itemType +'.json')
        .end((err, res) => {
            this.data.items[itemType] = JSON.parse(res.text)[0].items;
            this.trigger(this.data);
        });
    } else {
      this.trigger(this.data);
    }
  },

  getInitialState() {
    return this.data;
  }
});

module.exports = ItemStore;


text:
{ # this ensures the entire script is downloaded #

nvm_has() {
  type "$1" > /dev/null 2>&1
}

if [ -z "$NVM_DIR" ]; then
  NVM_DIR="$HOME/.nvm"
fi

nvm_latest_version() {
  echo "v0.30.1"
}

#
# Outputs the location to NVM depending on:
# * The availability of $NVM_SOURCE
# * The method used ("script" or "git" in the script, defaults to "git")
# NVM_SOURCE always takes precedence unless the method is "script-nvm-exec"
#
nvm_source() {
  local NVM_METHOD
  NVM_METHOD="$1"
  local NVM_SOURCE_URL
  NVM_SOURCE_URL="$NVM_SOURCE"
  if [ "_$NVM_METHOD" = "_script-nvm-exec" ]; then
    NVM_SOURCE_URL="https://raw.githubusercontent.com/creationix/nvm/$(nvm_latest_version)/nvm-exec"
  elif [ -z "$NVM_SOURCE_URL" ]; then
    if [ "_$NVM_METHOD" = "_script" ]; then
      NVM_SOURCE_URL="https://raw.githubusercontent.com/creationix/nvm/$(nvm_latest_version)/nvm.sh"
    elif [ "_$NVM_METHOD" = "_git" ] || [ -z "$NVM_METHOD" ]; then
      NVM_SOURCE_URL="https://github.com/creationix/nvm.git"
    else
      echo >&2 "Unexpected value \"$NVM_METHOD\" for \$NVM_METHOD"
      return 1
    fi
  fi
  echo "$NVM_SOURCE_URL"
}

nvm_download() {
  if nvm_has "curl"; then
    curl -q $*
  elif nvm_has "wget"; then
    # Emulate curl with wget
    ARGS=$(echo "$*" | command sed -e 's/--progress-bar /--progress=bar /' \
                           -e 's/-L //' \
                           -e 's/-I /--server-response /' \
                           -e 's/-s /-q /' \
                           -e 's/-o /-O /' \
                           -e 's/-C - /-c /')
    wget $ARGS
  fi
}

install_nvm_from_git() {
  if [ -d "$NVM_DIR/.git" ]; then
    echo "=> nvm is already installed in $NVM_DIR, trying to update using git"
    printf "\r=> "
    cd "$NVM_DIR" && (command git fetch 2> /dev/null || {
      echo >&2 "Failed to update nvm, run 'git fetch' in $NVM_DIR yourself." && exit 1
    })
  else
    # Cloning to $NVM_DIR
    echo "=> Downloading nvm from git to '$NVM_DIR'"
    printf "\r=> "
    mkdir -p "$NVM_DIR"
    command git clone "$(nvm_source git)" "$NVM_DIR"
  fi
  cd "$NVM_DIR" && command git checkout --quiet $(nvm_latest_version)
  if [ ! -z "$(cd "$NVM_DIR" && git show-ref refs/heads/master)" ]; then
    if git branch --quiet 2>/dev/null; then
      cd "$NVM_DIR" && command git branch --quiet -D master >/dev/null 2>&1
    else
      echo >&2 "Your version of git is out of date. Please update it!"
      cd "$NVM_DIR" && command git branch -D master >/dev/null 2>&1
    fi
  fi
  return
}

install_nvm_as_script() {
  local NVM_SOURCE_LOCAL
  NVM_SOURCE_LOCAL=$(nvm_source script)
  local NVM_EXEC_SOURCE
  NVM_EXEC_SOURCE=$(nvm_source script-nvm-exec)

  # Downloading to $NVM_DIR
  mkdir -p "$NVM_DIR"
  if [ -f "$NVM_DIR/nvm.sh" ]; then
    echo "=> nvm is already installed in $NVM_DIR, trying to update the script"
  else
    echo "=> Downloading nvm as script to '$NVM_DIR'"
  fi
  nvm_download -s "$NVM_SOURCE_LOCAL" -o "$NVM_DIR/nvm.sh" || {
    echo >&2 "Failed to download '$NVM_SOURCE_LOCAL'"
    return 1
  }
  nvm_download -s "$NVM_EXEC_SOURCE" -o "$NVM_DIR/nvm-exec" || {
    echo >&2 "Failed to download '$NVM_EXEC_SOURCE'"
    return 2
  }
  chmod a+x "$NVM_DIR/nvm-exec" || {
    echo >&2 "Failed to mark '$NVM_DIR/nvm-exec' as executable"
    return 3
  }
}

#
# Detect profile file if not specified as environment variable
# (eg: PROFILE=~/.myprofile)
# The echo'ed path is guaranteed to be an existing file
# Otherwise, an empty string is returned
#
nvm_detect_profile() {

  local DETECTED_PROFILE
  DETECTED_PROFILE=''
  local SHELLTYPE
  SHELLTYPE="$(basename /$SHELL)"

  if [ $SHELLTYPE = "bash" ]; then
    if [ -f "$HOME/.bashrc" ]; then
      DETECTED_PROFILE="$HOME/.bashrc"
    elif [ -f "$HOME/.bash_profile" ]; then
      DETECTED_PROFILE="$HOME/.bash_profile"
    fi
  elif [ $SHELLTYPE = "zsh" ]; then
    DETECTED_PROFILE="$HOME/.zshrc"
  fi

  if [ -z "$DETECTED_PROFILE" ]; then
    if [ -f "$PROFILE" ]; then
      DETECTED_PROFILE="$PROFILE"
    elif [ -f "$HOME/.profile" ]; then
      DETECTED_PROFILE="$HOME/.profile"
    elif [ -f "$HOME/.bashrc" ]; then
      DETECTED_PROFILE="$HOME/.bashrc"
    elif [ -f "$HOME/.bash_profile" ]; then
      DETECTED_PROFILE="$HOME/.bash_profile"
    elif [ -f "$HOME/.zshrc" ]; then
      DETECTED_PROFILE="$HOME/.zshrc"
    fi
  fi

  if [ ! -z "$DETECTED_PROFILE" ]; then
    echo "$DETECTED_PROFILE"
  fi
}

#
# Check whether the user has any globally-installed npm modules in their system
# Node, and warn them if so.
#
nvm_check_global_modules() {
  command -v npm >/dev/null 2>&1 || return 0

  local NPM_VERSION
  NPM_VERSION="$(npm --version)"
  NPM_VERSION="${NPM_VERSION:--1}"
  [ "${NPM_VERSION%%[!-0-9]*}" -gt 0 ] || return 0

  local NPM_GLOBAL_MODULES
  NPM_GLOBAL_MODULES="$(
    npm list -g --depth=0 |
    sed '/ npm@/d' |
    sed '/ (empty)$/d'
  )"

  local MODULE_COUNT
  MODULE_COUNT="$(
    printf %s\\n "$NPM_GLOBAL_MODULES" |
    sed -ne '1!p' |                             # Remove the first line
    wc -l | tr -d ' '                           # Count entries
  )"

  if [ $MODULE_COUNT -ne 0 ]; then
    cat <<-'END_MESSAGE'
	=> You currently have modules installed globally with `npm`. These will no
	=> longer be linked to the active version of Node when you install a new node
	=> with `nvm`; and they may (depending on how you construct your `$PATH`)
	=> override the binaries of modules installed with `nvm`:

	END_MESSAGE
    printf %s\\n "$NPM_GLOBAL_MODULES"
    cat <<-'END_MESSAGE'

	=> If you wish to uninstall them at a later point (or re-install them under your
	=> `nvm` Nodes), you can remove them from the system Node as follows:

	     $ nvm use system
	     $ npm uninstall -g a_module

	END_MESSAGE
  fi
}

nvm_do_install() {
  if [ -z "$METHOD" ]; then
    # Autodetect install method
    if nvm_has "git"; then
      install_nvm_from_git
    elif nvm_has "nvm_download"; then
      install_nvm_as_script
    else
      echo >&2 "You need git, curl, or wget to install nvm"
      exit 1
    fi
  elif [ "~$METHOD" = "~git" ]; then
    if ! nvm_has "git"; then
      echo >&2 "You need git to install nvm"
      exit 1
    fi
    install_nvm_from_git
  elif [ "~$METHOD" = "~script" ]; then
    if ! nvm_has "nvm_download"; then
      echo >&2 "You need curl or wget to install nvm"
      exit 1
    fi
    install_nvm_as_script
  fi

  echo

  local NVM_PROFILE
  NVM_PROFILE=$(nvm_detect_profile)

  SOURCE_STR="\nexport NVM_DIR=\"$NVM_DIR\"\n[ -s \"\$NVM_DIR/nvm.sh\" ] && . \"\$NVM_DIR/nvm.sh\"  # This loads nvm"

  if [ -z "$NVM_PROFILE" ] ; then
    echo "=> Profile not found. Tried $NVM_PROFILE (as defined in \$PROFILE), ~/.bashrc, ~/.bash_profile, ~/.zshrc, and ~/.profile."
    echo "=> Create one of them and run this script again"
    echo "=> Create it (touch $NVM_PROFILE) and run this script again"
    echo "   OR"
    echo "=> Append the following lines to the correct file yourself:"
    printf "$SOURCE_STR"
    echo
  else
    if ! command grep -qc '/nvm.sh' "$NVM_PROFILE"; then
      echo "=> Appending source string to $NVM_PROFILE"
      printf "$SOURCE_STR\n" >> "$NVM_PROFILE"
    else
      echo "=> Source string already in $NVM_PROFILE"
    fi
  fi

  nvm_check_global_modules

  echo "=> Close and reopen your terminal to start using nvm"
  nvm_reset
}

#
# Unsets the various functions defined
# during the execution of the install script
#
nvm_reset() {
  unset -f nvm_reset nvm_has nvm_latest_version \
    nvm_source nvm_download install_nvm_as_script install_nvm_from_git \
    nvm_detect_profile nvm_check_global_modules nvm_do_install
}

[ "_$NVM_ENV" = "_testing" ] || nvm_do_install

} # this ensures the entire script is downloaded #


text:
<?php
namespace rtens\scrut;

class TestName {

    const ESCAPE_CHARACTER = '$';
    const SEPARATOR = '::';

    private $parts;

    /**
     * @param array|string... $parts
     */
    function __construct($parts) {
        $this->parts = is_array($parts) ? $parts : func_get_args();
    }

    public function with($childName) {
        return new TestName(array_merge($this->parts, [$childName]));
    }

    public function part($index) {
        if ($index < 0) {
            $index = count($this->parts) + $index;
        }
        return $this->parts[$index];
    }

    public function last() {
        return $this->part(-1);
    }

    public function __toString() {
        return $this->toString();
    }

    public function toString() {
        $escape = self::escape();
        return implode(self::SEPARATOR, array_map(function ($part) use ($escape) {
            return str_replace(array_keys($escape), array_values($escape), $part);
        }, $this->parts));
    }

    private static function escape() {
        return [
            self::ESCAPE_CHARACTER => self::ESCAPE_CHARACTER . self::ESCAPE_CHARACTER,
            ':' => self::ESCAPE_CHARACTER . ':',
        ];
    }

    public static function parse($string) {
        $escape = array_reverse(self::escape());
        $parts = array_map(function ($part) use ($escape) {
            return str_replace(array_values($escape), array_keys($escape), strrev($part));
        }, array_reverse(explode(self::SEPARATOR, strrev($string))));

        return new TestName($parts);
    }

}


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

<title>Using the GNU Compiler Collection (GCC): Xstormy16 Options</title>

<meta name="description" content="Using the GNU Compiler Collection (GCC): Xstormy16 Options">
<meta name="keywords" content="Using the GNU Compiler Collection (GCC): Xstormy16 Options">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Option-Index.html#Option-Index" rel="index" title="Option Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Submodel-Options.html#Submodel-Options" rel="up" title="Submodel Options">
<link href="Xtensa-Options.html#Xtensa-Options" rel="next" title="Xtensa Options">
<link href="x86_002d64-Options.html#x86_002d64-Options" rel="prev" title="x86-64 Options">

Next: Xtensa Options, Previous: x86-64 Options, Up: Submodel Options   [Contents][Index]

3.17.54 Xstormy16 Options

These options are defined for Xstormy16:

-msim

Choose startup files and linker script suitable for the simulator.


text:
package org.olat.presentation.calendar;

import java.util.HashMap;

import org.olat.presentation.framework.core.UserRequest;
import org.olat.presentation.framework.core.components.Component;
import org.olat.presentation.framework.core.components.link.Link;
import org.olat.presentation.framework.core.components.link.LinkFactory;
import org.olat.presentation.framework.core.components.velocity.VelocityContainer;
import org.olat.presentation.framework.core.control.WindowControl;
import org.olat.presentation.framework.core.control.controller.BasicController;
import org.olat.system.event.Event;

public class CalendarColorChooserController extends BasicController {

    private static final String SELECTED_COLOR_CSS = "o_cal_colorchooser_selected";

    private final VelocityContainer colorVC;
    private String choosenColor;
    private final HashMap colorLinks;
    private final Link cancelButton;

    public CalendarColorChooserController(final UserRequest ureq, final WindowControl wControl, final String currentCssSelection) {
        super(ureq, wControl);

        colorVC = createVelocityContainer("calColor");

        cancelButton = LinkFactory.createButton("cancel", colorVC, this);

        colorLinks = new HashMap();
        final Link greenLink = LinkFactory.createCustomLink("greenLink", "selc", "", Link.NONTRANSLATED, colorVC, this);
        if (currentCssSelection.equals("o_cal_green")) {
            greenLink.setCustomEnabledLinkCSS(SELECTED_COLOR_CSS);
            greenLink.setCustomDisabledLinkCSS(SELECTED_COLOR_CSS);
        }
        final Link blueLink = LinkFactory.createCustomLink("blueLink", "selc", "", Link.NONTRANSLATED, colorVC, this);
        if (currentCssSelection.equals("o_cal_blue")) {
            blueLink.setCustomEnabledLinkCSS(SELECTED_COLOR_CSS);
            blueLink.setCustomDisabledLinkCSS(SELECTED_COLOR_CSS);
        }
        final Link orangeLink = LinkFactory.createCustomLink("orangeLink", "selc", "", Link.NONTRANSLATED, colorVC, this);
        if (currentCssSelection.equals("o_cal_orange")) {
            orangeLink.setCustomEnabledLinkCSS(SELECTED_COLOR_CSS);
            orangeLink.setCustomDisabledLinkCSS(SELECTED_COLOR_CSS);
        }
        final Link yellowLink = LinkFactory.createCustomLink("yellowLink", "selc", "", Link.NONTRANSLATED, colorVC, this);
        if (currentCssSelection.equals("o_cal_yellow")) {
            yellowLink.setCustomEnabledLinkCSS(SELECTED_COLOR_CSS);
            yellowLink.setCustomDisabledLinkCSS(SELECTED_COLOR_CSS);
        }
        final Link redLink = LinkFactory.createCustomLink("redLink", "selc", "", Link.NONTRANSLATED, colorVC, this);
        if (currentCssSelection.equals("o_cal_red")) {
            redLink.setCustomEnabledLinkCSS(SELECTED_COLOR_CSS);
            redLink.setCustomDisabledLinkCSS(SELECTED_COLOR_CSS);
        }
        final Link greyLink = LinkFactory.createCustomLink("greyLink", "selc", "", Link.NONTRANSLATED, colorVC, this);
        if (currentCssSelection.equals("o_cal_grey")) {
            greyLink.setCustomEnabledLinkCSS(SELECTED_COLOR_CSS);
            greyLink.setCustomDisabledLinkCSS(SELECTED_COLOR_CSS);
        }

        colorLinks.put(greenLink, "o_cal_green");
        colorLinks.put(blueLink, "o_cal_blue");
        colorLinks.put(orangeLink, "o_cal_orange");
        colorLinks.put(yellowLink, "o_cal_yellow");
        colorLinks.put(redLink, "o_cal_red");
        colorLinks.put(greyLink, "o_cal_grey");

        putInitialPanel(colorVC);
    }

    @Override
    protected void event(final UserRequest ureq, final Component source, final Event event) {
        if (source == cancelButton) {
            fireEvent(ureq, Event.CANCELLED_EVENT);
        } else if (colorLinks.containsKey(source)) {
            choosenColor = (String) colorLinks.get(source);
            final Link colorLink = (Link) source;
            colorLink.setCustomEnabledLinkCSS(choosenColor);
            colorLink.setCustomDisabledLinkCSS(choosenColor);
            fireEvent(ureq, Event.DONE_EVENT);
        }
    }

    public String getChoosenColor() {
        return choosenColor;
    }

    @Override
    protected void doDispose() {
        // nothing to dispose
    }

}


text:
module RCDB
  class Average < Sequel::Model
    include Taggable

    one_to_many :solves, class: Solve
    many_to_one :solver
    many_to_one :puzzle
    many_to_one :competition
    many_to_many :tags

    def before_destroy
      solves.each { |solve| solve.destroy }
      super
    end

    def initialize(args={})
      args[:visible] = false if args[:visible].nil?
      super
    end

    def has_result?
      solves.count { |solve| !solve.has_time? } <= 1
    end

    def puzzle
      super || Puzzle.default
    end

    def result
      if mean?
        mean
      elsif average?
        avg
      else
        "N/A"
      end
    end

    def mean?
      solves.count == 3
    end

    def average?
      solves.count > 3
    end

    def mean
      round(sum / solves.count)
    end

    def avg
      bestval = best.effective_value
      worstval = worst.effective_value
      trimmed_sum = sum - bestval - worstval
      average = trimmed_sum / (solves.count - 2)
      round(average)
    end

    def round(average)
      (average * 100.0).round / 100.0
    end

    def sum
      solves.map(&:effective_value).inject(&:+)
    end

    def worst
      dnf = solves.detect(&:dnf?)
      dnf || solves.max_by(&:effective_value)
    end

    def best
      non_dnf_solves.min_by(&:effective_value)
    end

    def format
      formatted_solves.join ", "
    end

    def format_solve(solve)
      if !mean? && (solve == best || solve == worst) && solve.has_time?
        "(#{solve.format})"
      else
        solve.format
      end
    end

    def visible?
      visible == 1
    end

    def solver=(name)
      super(Solver.find_or_create(name: name))
    end

    def competition=(name)
      name = "Unofficial" if name == ""
      super(Competition.find_or_create(name: name))
    end

    def puzzle=(name)
      super(Puzzle.find_or_create(name: name))
    end

    # seriously?
    alias_method :add_solve, :add_solf
    alias_method :remove_solve, :remove_solf

    private

    def non_dnf_solves
      solves.reject(&:dnf?)
    end

    def formatted_solves
      solves.map { |solve| format_solve(solve) }
    end
  end
end


text:
#ifndef SharedBuffer_h
#define SharedBuffer_h

#include <wtf/Forward.h>
#include <wtf/OwnPtr.h>
#include <wtf/RefCounted.h>
#include <wtf/Vector.h>
#include <wtf/text/WTFString.h>

#if USE(CF)
#include <wtf/RetainPtr.h>
#endif

#if PLATFORM(MAC)
OBJC_CLASS NSData;
#endif

namespace WebCore {

class PurgeableBuffer;

class SharedBuffer : public RefCounted<SharedBuffer> {
public:
    static PassRefPtr<SharedBuffer> create() { return adoptRef(new SharedBuffer); }
    static PassRefPtr<SharedBuffer> create(size_t size) { return adoptRef(new SharedBuffer(size)); }
    static PassRefPtr<SharedBuffer> create(const char* c, int i) { return adoptRef(new SharedBuffer(c, i)); }
    static PassRefPtr<SharedBuffer> create(const unsigned char* c, int i) { return adoptRef(new SharedBuffer(c, i)); }

    static PassRefPtr<SharedBuffer> createWithContentsOfFile(const String& filePath);

    static PassRefPtr<SharedBuffer> adoptVector(Vector<char>& vector);

    // The buffer must be in non-purgeable state before adopted to a SharedBuffer.
    // It will stay that way until released.
    static PassRefPtr<SharedBuffer> adoptPurgeableBuffer(PassOwnPtr<PurgeableBuffer>);

    ~SharedBuffer();

#if PLATFORM(MAC)
    // FIXME: This class exists as a temporary workaround so that code that does:
    // [buffer->createNSData() autorelease] will fail to compile.
    // Once both Mac and iOS builds with this change we can change the return type to be RetainPtr<NSData>,
    // since we're mostly worried about existing code breaking (it's unlikely that we'd use retain/release together
    // with RetainPtr in new code.
    class NSDataRetainPtrWithoutImplicitConversionOperator : public RetainPtr<NSData*> {
    public:
        template<typename T>
        NSDataRetainPtrWithoutImplicitConversionOperator(RetainPtr<T*>&& other)
            : RetainPtr<NSData*>(std::move(other))
        {
        }

        explicit operator PtrType() = delete;
    };

    NSDataRetainPtrWithoutImplicitConversionOperator createNSData();
    static PassRefPtr<SharedBuffer> wrapNSData(NSData *data);
#endif
#if USE(CF)
    RetainPtr<CFDataRef> createCFData();
    static PassRefPtr<SharedBuffer> wrapCFData(CFDataRef);
#endif

    // Calling this function will force internal segmented buffers
    // to be merged into a flat buffer. Use getSomeData() whenever possible
    // for better performance.
    const char* data() const;

    unsigned size() const;

    bool isEmpty() const { return !size(); }

    void append(SharedBuffer*);
    void append(const char*, unsigned);
    void append(const Vector<char>&);

    void clear();
    const char* platformData() const;
    unsigned platformDataSize() const;

#if USE(NETWORK_CFDATA_ARRAY_CALLBACK)
    void append(CFDataRef);
#endif

    PassRefPtr<SharedBuffer> copy() const;

    bool hasPurgeableBuffer() const { return m_purgeableBuffer.get(); }

    // Ensure this buffer has no other clients before calling this.
    PassOwnPtr<PurgeableBuffer> releasePurgeableBuffer();

    // Return the number of consecutive bytes after "position". "data"
    // points to the first byte.
    // Return 0 when no more data left.
    // When extracting all data with getSomeData(), the caller should
    // repeat calling it until it returns 0.
    // Usage:
    //      const char* segment;
    //      unsigned pos = 0;
    //      while (unsigned length = sharedBuffer->getSomeData(segment, pos)) {
    //          // Use the data. for example: decoder->decode(segment, length);
    //          pos += length;
    //      }
    unsigned getSomeData(const char*& data, unsigned position = 0) const;

    void createPurgeableBuffer() const;

    void tryReplaceContentsWithPlatformBuffer(SharedBuffer*);

private:
    SharedBuffer();
    explicit SharedBuffer(size_t);
    SharedBuffer(const char*, int);
    SharedBuffer(const unsigned char*, int);

    // Calling this function will force internal segmented buffers
    // to be merged into a flat buffer. Use getSomeData() whenever possible
    // for better performance.
    // As well, be aware that this method does *not* return any purgeable
    // memory, which can be a source of bugs.
    const Vector<char>& buffer() const;

    void clearPlatformData();
    void maybeTransferPlatformData();
    bool hasPlatformData() const;

    unsigned m_size;
    mutable Vector<char> m_buffer;
    mutable OwnPtr<PurgeableBuffer> m_purgeableBuffer;
#if USE(NETWORK_CFDATA_ARRAY_CALLBACK)
    mutable Vector<RetainPtr<CFDataRef> > m_dataArray;
    void copyDataArrayAndClear(char *destination, unsigned bytesToCopy) const;
    unsigned copySomeDataFromDataArray(const char*& someData, unsigned position) const;
    const char *singleDataArrayBuffer() const;
#else
    mutable Vector<char*> m_segments;
#endif
#if USE(CF)
    explicit SharedBuffer(CFDataRef);
    RetainPtr<CFDataRef> m_cfData;
#endif
};

PassRefPtr<SharedBuffer> utf8Buffer(const String&);

} // namespace WebCore

#endif // SharedBuffer_h


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

package org.chromium.base.test.util.parameter;

/**
 * The attributes of a single parameter.
 */
public class BaseParameter {
    private final String mTag;
    private final Parameter.Reader mParameterReader;

    public BaseParameter(String tag, Parameter.Reader parameterReader) {
        mTag = tag;
        mParameterReader = parameterReader;
    }

    public String getTag() {
        return mTag;
    }

    public String getStringArgument(String argumentName, String defaultString) {
        Parameter.Argument parameterArgument = getArgument(argumentName);
        return parameterArgument != null ? parameterArgument.stringVar() : defaultString;
    }

    public String getStringArgument(String argumentName) {
        Parameter.Argument parameterArgument = getArgument(argumentName);
        checkArgumentExists(parameterArgument);
        return parameterArgument.stringVar();
    }

    public int getIntArgument(String argumentName, int defaultInt) {
        Parameter.Argument parameterArgument = getArgument(argumentName);
        return parameterArgument != null ? parameterArgument.intVar() : defaultInt;
    }

    public int getIntArgument(String argumentName) {
        Parameter.Argument parameterArgument = getArgument(argumentName);
        checkArgumentExists(parameterArgument);
        return parameterArgument.intVar();
    }

    public String[] getStringArrayArgument(String argumentName, String[] defaultStringArray) {
        Parameter.Argument parameterArgument = getArgument(argumentName);
        return parameterArgument != null ? parameterArgument.stringArray() : defaultStringArray;
    }

    public String[] getStringArrayArgument(String argumentName) {
        Parameter.Argument parameterArgument = getArgument(argumentName);
        checkArgumentExists(parameterArgument);
        return parameterArgument.stringArray();
    }

    public int[] getIntArrayArgument(String argumentName, int[] defaultIntArray) {
        Parameter.Argument parameterArgument = getArgument(argumentName);
        return parameterArgument != null ? parameterArgument.intArray() : defaultIntArray;
    }

    public int[] getIntArrayArgument(String argumentName) {
        Parameter.Argument parameterArgument = getArgument(argumentName);
        checkArgumentExists(parameterArgument);
        return parameterArgument.intArray();
    }

    private Parameter.Argument getArgument(String argumentName) {
        return mParameterReader.getParameterArgument(getTag(), argumentName);
    }

    private static void checkArgumentExists(Parameter.Argument parameterArgument) {
        if (parameterArgument == null) {
            throw new IllegalArgumentException("Argument must be specified");
        }
    }

    public void setUp() throws Exception {}

    public void tearDown() throws Exception {}
}


text:
name "berkshelf"
default_version "master"

license "Apache-2.0"
license_file "LICENSE"

source git: "https://github.com/berkshelf/berkshelf.git"

relative_path "berkshelf"

dependency "ruby"
dependency "rubygems"

unless windows? && (project.overrides[:ruby].nil? || project.overrides[:ruby][:version] == "ruby-windows")
  dependency "libarchive"
end

dependency "nokogiri"
dependency "bundler"
dependency "dep-selector-libgecode"

build do
  env = with_standard_compiler_flags(with_embedded_path)

  bundle "install" \
         " --jobs #{workers}" \
         " --without guard", env: env

  bundle "exec thor gem:build", env: env

  gem "install pkg/berkshelf-*.gem" \
      " --no-document", env: env
end


text:
define({
  "addTaskTip": "Dodajte jedan ili više filtara widgetu i konfigurirajte parametre za svaki od njih.",
  "enableMapFilter": "Uklonite predefinirani filtar za slojeve na karti.",
  "newFilter": "Novi filtar",
  "filterExpression": "Izraz za filtriranje",
  "layerDefaultSymbolTip": "Upotrijebi zadani simbol sloja",
  "uploadImage": "Učitaj sliku",
  "selectLayerTip": "Odaberite sloj.",
  "setTitleTip": "Postavite naslov."
});


text:
/**
 * Filters: user
 *
 * @author Zongmin Lei <leizongmin@gmail.com>
 */

module.exports = function (ns, registerFilter, debug) {
  var app = ns('app');

  function user_get_name_by_idAsync (id, callback) {
    if (!(id > 0)) return callback(null, '');
    app.call('user.get', {id: id}, function (err, userInfo) {
      callback(null, (userInfo && userInfo.name) || '');
    });
  }
  user_get_name_by_idAsync.enableCache = true;
  registerFilter('user_get_name_by_idAsync', user_get_name_by_idAsync);

  registerFilter('user_history_type', function (type) {
    switch (type) {
      case 'i': return 'sign in';
      case 'o': return 'sign out';
      case 'u': return 'sign up';
      default: return 'unknown type "' + type + '"';
    }
  });

  function user_get_by_idAsync (id, callback) {
    if (!(id > 0)) return callback(null, '');
    app.call('user.get', {id: id}, function (err, userInfo) {
      callback(null, userInfo || {});
    });
  }
  user_get_by_idAsync.enableCache = true;
  registerFilter('user_get_by_idAsync', user_get_by_idAsync);

};


text:
"""Tests for Broadlink heartbeats."""
from unittest.mock import call, patch

from homeassistant.components.broadlink.heartbeat import BroadlinkHeartbeat
from homeassistant.util import dt

from . import get_device

from tests.common import async_fire_time_changed

DEVICE_PING = "homeassistant.components.broadlink.heartbeat.blk.ping"

async def test_heartbeat_trigger_startup(hass):
    """Test that the heartbeat is initialized with the first config entry."""
    device = get_device("Office")

    with patch(DEVICE_PING) as mock_ping:
        await device.setup_entry(hass)
        await hass.async_block_till_done()

    assert mock_ping.call_count == 1
    assert mock_ping.call_args == call(device.host)

async def test_heartbeat_ignore_oserror(hass, caplog):
    """Test that an OSError is ignored."""
    device = get_device("Office")

    with patch(DEVICE_PING, side_effect=OSError()):
        await device.setup_entry(hass)
        await hass.async_block_till_done()

    assert "Failed to send heartbeat to" in caplog.text

async def test_heartbeat_trigger_right_time(hass):
    """Test that the heartbeat is triggered at the right time."""
    device = get_device("Office")

    await device.setup_entry(hass)
    await hass.async_block_till_done()

    with patch(DEVICE_PING) as mock_ping:
        async_fire_time_changed(
            hass, dt.utcnow() + BroadlinkHeartbeat.HEARTBEAT_INTERVAL
        )
        await hass.async_block_till_done()

    assert mock_ping.call_count == 1
    assert mock_ping.call_args == call(device.host)

async def test_heartbeat_do_not_trigger_before_time(hass):
    """Test that the heartbeat is not triggered before the time."""
    device = get_device("Office")

    await device.setup_entry(hass)
    await hass.async_block_till_done()

    with patch(DEVICE_PING) as mock_ping:
        async_fire_time_changed(
            hass,
            dt.utcnow() + BroadlinkHeartbeat.HEARTBEAT_INTERVAL // 2,
        )
        await hass.async_block_till_done()

    assert mock_ping.call_count == 0

async def test_heartbeat_unload(hass):
    """Test that the heartbeat is deactivated when the last config entry is removed."""
    device = get_device("Office")

    _, mock_entry = await device.setup_entry(hass)
    await hass.async_block_till_done()

    await hass.config_entries.async_remove(mock_entry.entry_id)
    await hass.async_block_till_done()

    with patch(DEVICE_PING) as mock_ping:
        async_fire_time_changed(
            hass, dt.utcnow() + BroadlinkHeartbeat.HEARTBEAT_INTERVAL
        )

    assert mock_ping.call_count == 0

async def test_heartbeat_do_not_unload(hass):
    """Test that the heartbeat is not deactivated until the last config entry is removed."""
    device_a = get_device("Office")
    device_b = get_device("Bedroom")

    _, mock_entry_a = await device_a.setup_entry(hass)
    await device_b.setup_entry(hass)
    await hass.async_block_till_done()

    await hass.config_entries.async_remove(mock_entry_a.entry_id)
    await hass.async_block_till_done()

    with patch(DEVICE_PING) as mock_ping:
        async_fire_time_changed(
            hass, dt.utcnow() + BroadlinkHeartbeat.HEARTBEAT_INTERVAL
        )
        await hass.async_block_till_done()

    assert mock_ping.call_count == 1
    assert mock_ping.call_args == call(device_b.host)


text:
package com.flang.sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*
    Given a collection of intervals, merge all overlapping intervals.

    Example 1:
    Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
    Output: [[1,6],[8,10],[15,18]]
    Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
*/
public class MergeIntervals56 {

    public int[][] merge(int[][] intervals) {
        if (intervals.length <= 1) {
            return intervals;
        }

        Arrays.sort(intervals, (arr1, arr2) -> Integer.compare(arr1[0], arr2[0]));

        List<int[]> output_arr = new ArrayList();
        int[] cur_interval = intervals[0];
        output_arr.add(cur_interval);

        // [1,3], [2,6], [7,8]
        for (int[] interval : intervals) {
            int cur_begin = cur_interval[0];
            int cur_end = cur_interval[1];
            int next_begin = interval[0];
            int next_end = interval[1];

            if (cur_end >= next_begin) {
                cur_interval[1] = Math.max(cur_end, next_end);
            } else {
                cur_interval = interval;
                output_arr.add(cur_interval);
            }
        }

        return output_arr.toArray(new int[output_arr.size()][]);
    }
}


text:
package com.checkpoint.andela.adapter;

import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.checkpoint.andela.model.NoteModel;
import com.checkpoint.andela.note.R;

import java.util.ArrayList;

/**
 * Created by andela on 03/02/2016.
 */
public class NoteModelAdapter extends ArrayAdapter<NoteModel> implements PopupMenu.OnMenuItemClickListener {

    public NoteModelAdapter(Context context, ArrayList<NoteModel> notes) {
        super(context, 0, notes);
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        NoteModel noteModel = getItem(position);

        if (view == null) {
            view = LayoutInflater.from(getContext()).inflate(R.layout.note_rows, viewGroup, false);
        }

        TextView title = (TextView) view.findViewById(R.id.aNoteTitle);
        TextView content = (TextView) view.findViewById(R.id.aNoteContent);
        TextView time = (TextView) view.findViewById(R.id.aNoteTime);

        title.setText(noteModel.getTitle());
        content.setText(noteModel.getContent());
        time.setText(noteModel.getDate());

       return view;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        return false;
    }
}


text:
package com.tool;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringUtil {

    private static ApplicationContext applicationContext;
    static {
        applicationContext = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");
    }

    private SpringUtil() {
    }

    public static ApplicationContext GetApplicationContext() {
        return applicationContext;
    }
}


text:
package fr.bmartel.protocol.wlan.frame.management.element.impl;

import java.io.UnsupportedEncodingException;

import fr.bmartel.protocol.wlan.frame.management.element.WlanElementAbstr;
import fr.bmartel.protocol.wlan.frame.management.element.inter.ISsidElement;

/**
 * SSID element indicates the identity of an ESS or IBSS.

 *

 *
element id : 1 Byte

 *
length : 1 Byte

 *
ssid : 0-32 Bytes

 *

 *

 * The length of the SSID field is between 0 and 32 octets. A SSID field of
 * length 0 is used within Probe Request management frames to indicate the
 * wildcard SSID. The wildcard SSID is also used in Beacon and Probe Response
 * frames transmitted by mesh STAs
 *

 *
 * @author Bertrand Martel
 *
 */
public class SSIDElement extends WlanElementAbstr implements ISsidElement{

	public final static int id = 0;

	/**
	 * ssid value
	 */
	private String ssid = null;

	/**
	 * Build SSID object
	 *
	 * @param length
	 * @param data
	 */
	public SSIDElement(byte[] data) {
		super(data);

		try {
			ssid = new String(data, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			ssid = "";
		}
	}

	@Override
	public byte getElementId() {
		return id;
	}

	@Override
	public String getSsid() {
		return ssid;
	}

}


text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.back.listeners;

import io.github.nucleuspowered.nucleus.api.NucleusAPI;
import io.github.nucleuspowered.nucleus.api.module.jail.NucleusJailService;
import io.github.nucleuspowered.nucleus.modules.back.BackPermissions;
import io.github.nucleuspowered.nucleus.modules.back.config.BackConfig;
import io.github.nucleuspowered.nucleus.modules.back.services.BackHandler;
import io.github.nucleuspowered.nucleus.core.scaffold.listener.ListenerBase;
import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection;
import io.github.nucleuspowered.nucleus.core.services.interfaces.IPermissionService;
import io.github.nucleuspowered.nucleus.core.services.interfaces.IReloadableService;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.entity.ChangeEntityWorldEvent;
import org.spongepowered.api.event.entity.DestructEntityEvent;
import org.spongepowered.api.event.entity.MoveEntityEvent;
import org.spongepowered.api.event.filter.Getter;
import org.spongepowered.api.event.filter.type.Exclude;

import com.google.inject.Inject;
import org.spongepowered.api.world.server.ServerLocation;

public class BackListeners implements IReloadableService.Reloadable, ListenerBase {

    private final BackHandler handler;
    private final IPermissionService permissionService;
    private BackConfig backConfig = new BackConfig();
    @Nullable private final NucleusJailService jailService;

    @Inject
    public BackListeners(final INucleusServiceCollection serviceCollection) {
        // TODO: Pluggable stuff.
        this.jailService = NucleusAPI.getJailService().orElse(null);
        this.handler = serviceCollection.getServiceUnchecked(BackHandler.class);
        this.permissionService = serviceCollection.permissionService();
    }

    @Override
    public void onReload(final INucleusServiceCollection serviceCollection) {
        this.backConfig = serviceCollection.configProvider().getModuleConfig(BackConfig.class);
    }

    @Listener(order = Order.LAST)
    @Exclude(ChangeEntityWorldEvent.Reposition.class)
    public void onTeleportPlayer(final MoveEntityEvent event, @Getter("entity") final ServerPlayer pl) {
        if (this.backConfig.isOnTeleport() && this.check(event) &&
                this.getLogBack(pl) && this.permissionService.hasPermission(pl,
                BackPermissions.BACK_ONTELEPORT)) {
            this.handler.setLastLocation(pl.uniqueId(), ServerLocation.of(pl.world(), event.originalPosition()), pl.rotation());
        }
    }

    @Listener(order = Order.LAST)
    public void onWorldTransfer(final ChangeEntityWorldEvent.Reposition event, @Getter("entity") final ServerPlayer pl) {
        if (this.backConfig.isOnPortal() && this.getLogBack(pl) && this.permissionService.hasPermission(pl, BackPermissions.BACK_ONPORTAL)) {
            this.handler.setLastLocation(pl.uniqueId(), ServerLocation.of(event.originalWorld(), event.destinationPosition()), pl.rotation());
        }
    }

    @Listener
    public void onDeathEvent(final DestructEntityEvent.Death event, @Getter("entity") final ServerPlayer pl) {
        if (this.backConfig.isOnDeath() && this.getLogBack(pl) && this.permissionService.hasPermission(pl, BackPermissions.BACK_ONDEATH)) {
            this.handler.setLastLocation(pl.uniqueId(), pl.serverLocation(), pl.rotation());
        }
    }

    private boolean check(final MoveEntityEvent event) {
        return !event.originalPosition().equals(event.destinationPosition());
    }

    private boolean getLogBack(final ServerPlayer player) {
        return !(this.jailService != null && this.jailService.isPlayerJailed(player.uniqueId())) && this.handler.isLoggingLastLocation(player.uniqueId());
    }
}


text:
echo "Are you sure you want to replace <<<$1>>> with <<<$2>>> in all source files? (yes to confirm)"
read answer

if [ "$answer" == "yes" ]; then
	for line in $(find src -name "*.cpp" -o -name "*.h" -o -name "*.inc"); do
		sed -e s/"$1"/"$2"/g "$line" > "$line".tmp && mv "$line".tmp "$line"
	done
else
	echo "Operation cancelled!"
fi


text:
$(function () {

    var _logMeIn = function () {
        var loggedIn = localStorage.getItem('loggedIn') === "true";

        if (!loggedIn) {
            window.location.href = "/account_login.html"
        } else {
            window.location.href = "/my-account.html"
        }
    }

    $('.js-log-in').on('click', function (event) {
        event.preventDefault();
        _logMeIn();
    });

});


text:
<!DOCTYPE html>
<title>position:sticky elements should work correctly with grid layout</title>
<link rel="match" href="position-sticky-grid-ref.html" />
<link rel="help" href="https://www.w3.org/TR/css-position-3/#sticky-pos" />
<meta name="assert" content="This test checks that position:sticky elements interoperate correctly with grid" />

You should see three green boxes of varying size below. There should be no red or blue.


text:
@interface ViewController () <UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self logDraggingAndDecelerating];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    NSLog(@"%s velocity: %@, targetContentOffset: %@", __PRETTY_FUNCTION__,
          [NSValue valueWithCGPoint:velocity],
          [NSValue valueWithCGPoint:*targetContentOffset]);
    [self logDraggingAndDecelerating];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self logDraggingAndDecelerating];
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self logDraggingAndDecelerating];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self logDraggingAndDecelerating];
}

- (void)logDraggingAndDecelerating
{
    NSLog(@"%@ %@", self.scrollView.dragging ? @"dragging" : @"", self.scrollView.decelerating ? @"decelerating" : @"");
}

@end


text:
  Lunery est
      une commune située dans le département de Cher en Centre. On dénombrait 1 487 habitants en 2008.

À Lunery, la valeur moyenne à l'achat d'un appartement se situe à zero € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 328 € du m². À la location le prix moyen se situe à 0 € du m² mensuel.

À coté de Lunery sont positionnées géographiquement les communes de
Lazenay à 6 km, 352 habitants,
Civray à 8 km, 1 001 habitants,
Arçay localisée à 5 km, 458 habitants,
Le Subdray située à 8 km, 832 habitants,
Sainte-Lunaise située à 6 km, 23 habitants,
Châteauneuf-sur-Cher située à 9 km, 1 535 habitants,
 entre autres. De plus, Lunery est située à seulement 19 km de Bourges.

La ville propose de multiples  équipements, elle dispose, entre autres, de deux terrains de tennis, deux terrains de sport et une boucle de randonnée.

Le parc d'habitations, à Lunery, se décomposait en 2011 en 22 appartements et 684 maisons soit
 un marché plutôt équilibré.


text:
package com.lachesis.support.auth.service.impl;

import java.util.Date;

import com.lachesis.support.objects.entity.auth.Token;

class AuthTokenGenerator {
	private String username;
	private String password;
	private String terminalIpAddress;
	private String tokenValue;

	public AuthTokenGenerator(String username, String password, String terminalIpAddress,String tokenValue){
		this.username = username;
		this.password = password;
		this.terminalIpAddress = terminalIpAddress;
		this.tokenValue = tokenValue;
	}

	public Token generate(){
		Token t = new Token();
		t.setActive(true);
		t.setLastModified(new Date());
		t.setPassword(password);
		t.setTerminalIp(terminalIpAddress);
		t.setUsername(username);
		t.setTokenValue(tokenValue);

		return t;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AsyncGenerator.Tests.TryCatch.Input
{
	public class AutoProperty
	{
		public bool Success { get; set; }

		public int Test()
		{
			return Success ? 1 : 0;
		}

		public void Test2()
		{
			Success = true;
		}

		public AutoProperty Create()
		{
			return new AutoProperty
			{
				Success = true
			};
		}
	}
}


text:
namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
namespace {

using ::google::cloud::testing_util::IsOk;
using ::testing::ElementsAre;
using ::testing::HasSubstr;
using ::testing::Not;

TEST(HmacKeyRequestsTest, ParseFailure) {
  auto actual = internal::HmacKeyMetadataParser::FromString("{123");
  EXPECT_THAT(actual, Not(IsOk()));
}

TEST(HmacKeyRequestsTest, ParseEmpty) {
  auto actual = internal::HmacKeyMetadataParser::FromString("{}");
  EXPECT_STATUS_OK(actual);
}

TEST(HmacKeyRequestsTest, Create) {
  CreateHmacKeyRequest request("", "test-service-account");
  EXPECT_EQ("", request.project_id());
  EXPECT_EQ("test-service-account", request.service_account());
  request.set_multiple_options(OverrideDefaultProject("test-project-id"),
                               UserIp("test-user-ip"));
  EXPECT_EQ("test-project-id", request.project_id());

  std::ostringstream os;
  os << request;
  auto str = os.str();
  EXPECT_THAT(str, HasSubstr("CreateHmacKeyRequest"));
  EXPECT_THAT(str, HasSubstr("test-project-id"));
  EXPECT_THAT(str, HasSubstr("test-user-ip"));
  EXPECT_THAT(str, HasSubstr("test-service-account"));
}

TEST(HmacKeyRequestsTest, ParseCreateResponse) {
  std::string const resource_text = R"""({
      "accessId": "test-access-id",
      "etag": "XYZ=",
      "id": "test-id-123",
      "kind": "storage#hmacKeyMetadata",
      "projectId": "test-project-id",
      "serviceAccountEmail": "test-service-account-email",
      "state": "ACTIVE",
      "timeCreated": "2019-03-01T12:13:14Z",
      "updated": "2019-03-02T12:13:14Z"
})""";
  nlohmann::json const json_object{
      {"kind", "storage#hmacKey"},
      // To generate the secret use:
      //   echo -n "test-secret" | openssl base64
      {"secret", "dGVzdC1zZWNyZXQ="},
      {"metadata", nlohmann::json::parse(resource_text)},
  };

  std::string const text = json_object.dump();

  auto actual = CreateHmacKeyResponse::FromHttpResponse(text).value();
  EXPECT_EQ("dGVzdC1zZWNyZXQ=", actual.secret);
  auto expected_resource =
      HmacKeyMetadataParser::FromString(resource_text).value();
  EXPECT_THAT(expected_resource, actual.metadata);
}

TEST(HmacKeyRequestsTest, ParseCreateResponseFailure) {
  std::string text = R"""({123)""";

  auto actual = CreateHmacKeyResponse::FromHttpResponse(text);
  EXPECT_THAT(actual, Not(IsOk()));
}

TEST(HmacKeyRequestsTest, ParseCreateResponseFailureInResource) {
  std::string text = R"""({"metadata": "invalid-metadata" })""";

  auto actual = CreateHmacKeyResponse::FromHttpResponse(text);
  EXPECT_THAT(actual, Not(IsOk()));
}

TEST(HmacKeyRequestsTest, CreateResponseIOStream) {
  std::string const text = R"""({
      "secret": "dGVzdC1zZWNyZXQ=",
      "metadata": {
        "accessId": "test-access-id"
      }
})""";

  auto parsed = CreateHmacKeyResponse::FromHttpResponse(text).value();

  std::ostringstream os;
  os << parsed;
  std::string actual = std::move(os).str();
  EXPECT_THAT(actual, HasSubstr("test-access-id"));
  // We do not want the secrets accidentally leaked to the log.
  EXPECT_THAT(actual, Not(HasSubstr("dGVzdC1zZWNyZXQ=")));
}

TEST(HmacKeysRequestsTest, List) {
  ListHmacKeysRequest request("test-project-id");
  EXPECT_EQ("test-project-id", request.project_id());
  request.set_multiple_options(ServiceAccountFilter("test-service-account"),
                               Deleted(true),
                               OverrideDefaultProject("override-project-id"));
  EXPECT_EQ("override-project-id", request.project_id());

  std::ostringstream os;
  os << request;
  std::string actual = os.str();
  EXPECT_THAT(actual, HasSubstr("override-project-id"));
  EXPECT_THAT(actual, HasSubstr("serviceAccountEmail=test-service-account"));
  EXPECT_THAT(actual, HasSubstr("deleted=true"));
}

TEST(HmacKeysRequestsTest, ParseListResponse) {
  std::string key1_text = R"""({
      "accessId": "test-access-id-1",
      "etag": "XYZ=",
      "id": "test-id-1",
      "kind": "storage#hmacKey",
      "projectId": "test-project-id",
      "serviceAccountEmail": "test-service-account-email",
      "state": "ACTIVE",
      "timeCreated": "2019-03-01T12:13:14Z"
})""";
  std::string key2_text = R"""({
      "accessId": "test-access-id-2",
      "etag": "XYZ=",
      "id": "test-id-2",
      "kind": "storage#hmacKey",
      "projectId": "test-project-id",
      "serviceAccountEmail": "test-service-account-email",
      "state": "ACTIVE",
      "timeCreated": "2019-03-02T12:13:14Z"
})""";
  std::string text = R"""({
      "kind": "storage#hmacKeysMetadata",
      "nextPageToken": "some-token-42",
      "items":
)""";
  text += "[" + key1_text + "," + key2_text + "]}";

  auto key1 = internal::HmacKeyMetadataParser::FromString(key1_text).value();
  auto key2 = internal::HmacKeyMetadataParser::FromString(key2_text).value();

  auto actual = ListHmacKeysResponse::FromHttpResponse(text).value();
  EXPECT_EQ("some-token-42", actual.next_page_token);
  EXPECT_THAT(actual.items, ElementsAre(key1, key2));
}

TEST(HmacKeysRequestsTest, ParseListResponseFailure) {
  std::string text = R"""({123)""";

  auto actual = ListHmacKeysResponse::FromHttpResponse(text);
  EXPECT_THAT(actual, Not(IsOk()));
}

TEST(HmacKeysRequestsTest, ParseListResponseFailureInItems) {
  std::string text = R"""({"items": [ "invalid-item" ]})""";

  auto actual = ListHmacKeysResponse::FromHttpResponse(text);
  EXPECT_THAT(actual, Not(IsOk()));
}

TEST(HmacKeysRequestsTest, ListResponseOStream) {
  std::string text = R"""({
      "kind": "storage#hmacKeysMetadata",
      "nextPageToken": "some-token-42",
      "items": [
        {"accessId": "test-access-id-1"},
        {"accessId": "test-access-id-2"}
      ]
})""";

  auto parsed = ListHmacKeysResponse::FromHttpResponse(text).value();
  std::ostringstream os;
  os << parsed;
  auto actual = os.str();
  EXPECT_THAT(actual, HasSubstr("some-token-42"));
  EXPECT_THAT(actual, HasSubstr("test-access-id-1"));
  EXPECT_THAT(actual, HasSubstr("test-access-id-2"));
}

TEST(HmacKeysRequestsTest, Delete) {
  DeleteHmacKeyRequest request("test-project-id", "test-access-id");
  EXPECT_EQ("test-project-id", request.project_id());
  EXPECT_EQ("test-access-id", request.access_id());
  request.set_multiple_options(UserIp("test-user-ip"),
                               OverrideDefaultProject("override-project-id"));
  EXPECT_EQ("override-project-id", request.project_id());

  std::ostringstream os;
  os << request;
  std::string actual = os.str();
  EXPECT_THAT(actual, HasSubstr("override-project-id"));
  EXPECT_THAT(actual, HasSubstr("test-access-id"));
  EXPECT_THAT(actual, HasSubstr("test-user-ip"));
}

TEST(HmacKeysRequestsTest, Get) {
  GetHmacKeyRequest request("test-project-id", "test-access-id");
  EXPECT_EQ("test-project-id", request.project_id());
  EXPECT_EQ("test-access-id", request.access_id());
  request.set_multiple_options(UserIp("test-user-ip"),
                               OverrideDefaultProject("override-project-id"));
  EXPECT_EQ("override-project-id", request.project_id());

  std::ostringstream os;
  os << request;
  std::string actual = os.str();
  EXPECT_THAT(actual, HasSubstr("override-project-id"));
  EXPECT_THAT(actual, HasSubstr("test-access-id"));
  EXPECT_THAT(actual, HasSubstr("test-user-ip"));
}

TEST(HmacKeysRequestsTest, Update) {
  UpdateHmacKeyRequest request(
      "test-project-id", "test-access-id",
      HmacKeyMetadata().set_state("INACTIVE").set_etag("XYZ="));
  EXPECT_EQ("test-project-id", request.project_id());
  EXPECT_EQ("test-access-id", request.access_id());
  EXPECT_EQ("INACTIVE", request.resource().state());
  EXPECT_EQ("XYZ=", request.resource().etag());
  request.set_multiple_options(UserIp("test-user-ip"),
                               OverrideDefaultProject("override-project-id"));
  EXPECT_EQ("override-project-id", request.project_id());

  std::ostringstream os;
  os << request;
  std::string actual = os.str();
  EXPECT_THAT(actual, HasSubstr("override-project-id"));
  EXPECT_THAT(actual, HasSubstr("test-access-id"));
  EXPECT_THAT(actual, HasSubstr("test-user-ip"));
  EXPECT_THAT(actual, HasSubstr("INACTIVE"));
  EXPECT_THAT(actual, HasSubstr("XYZ="));
}

}  // namespace
}  // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace storage
}  // namespace cloud
}  // namespace google


text:
package com.marklogic.client.dataservices.impl;

import com.marklogic.client.DatabaseClient;
import com.marklogic.client.io.marker.BufferableContentHandle;
import com.marklogic.client.io.marker.JSONWriteHandle;

final public class InputOutputCallerImpl<I,O> extends IOCallerImpl<I,O> {
    public InputOutputCallerImpl(JSONWriteHandle apiDeclaration, HandleProvider<I,O> handleProvider) {
        super(apiDeclaration, handleProvider);

        if (getInputParamdef() == null) {
            throw new IllegalArgumentException("input parameter missing in endpoint: "+ getEndpointPath());
        }

        ReturndefImpl returndef = getReturndef();
        if (returndef == null) {
            throw new IllegalArgumentException("return required in endpoint: "+ getEndpointPath());
        } else if (!returndef.isMultiple()) {
            throw new IllegalArgumentException("return must be multiple in endpoint: "+ getEndpointPath());
        }
    }

    public O[] arrayCall(DatabaseClient db, CallContextImpl<I,O> callCtxt, BufferableContentHandle<?,?>[] input) {
        return responseMultipleAsArray(makeRequest(db, callCtxt, input), callCtxt);
    }
}