text:
[![Apps Using](https://img.shields.io/badge/Apps%20Using-%3E%203,000-00BFFF.svg?style=plastic)](https://cocoapods.org/pods/PYSearch)
[![Total Downloads](https://img.shields.io/badge/Total%20Downloads-%3E%2060,000-00BFFF.svg?style=plastic)](https://cocoapods.org/pods/PYSearch)

[![Build Status](https://travis-ci.org/ko1o/PYSearch.svg?branch=master)](https://travis-ci.org/ko1o/PYSearch)
[![Pod Version](http://img.shields.io/cocoapods/v/PYSearch.svg?style=flat)](http://cocoadocs.org/docsets/PYSearch/)
[![Pod Platform](https://img.shields.io/badge/platform-iOS%207%2B-blue.svg?style=flat)](http://cocoadocs.org/docsets/PYSearch/)
[![Pod License](http://img.shields.io/cocoapods/l/PYSearch.svg?style=flat)](https://opensource.org/licenses/MIT)

- 🔍 An elegant search controller for iOS.

## QQ chat room

## Features
- [x] Support a variety of hot search style
- [x] Support a variety of search history style
- [x] Support a variety of search results display mode
- [x] Support a variety of search view controller display mode
- [x] Support search suggestions
- [x] Support search history (record) cache
- [x] Support callback using delegate or block completion search
- [x] Support CocoaPods
- [x] Support localization
- [x] Support vertical and horizontal screen on iPhone and iPad

## Requirements
* iOS 7.0 or later
* Xcode 7.0 or later

## Architecture
### Main
- `PYSearch`
- `PYSearchConst`
- `PYSearchViewController`
- `PYSearchSuggestionViewController`

### Category
- `UIColor+PYSearchExtension`
- `UIView+PYSearchExtension`
- `NSBundle+PYSearchExtension`

## Contents
* Getting Started
  * [Renderings](#Renderings)
  * [Styles](#Styles)

* Usage
  * [How to use](#Howtouse)
  * [Details (See the example program PYSearchExample for details)](#Details)
  * [Custom](#Custom)

* [Hope](#Hope)

## Renderings

## Styles

#### Hot search style

#### Search history style

## How to use
* Use CocoaPods:
  - `pod "PYSearch"`
  - Import the main file:`#import <PYSearch.h>`
* Manual import:
  - Drag All files in the `PYSearch` folder to project
  - Import the main file:`#import "PYSearch.h"`

## Details (See the example program PYSearchExample for details)
```objc
    // 1. Create hotSearches array
    NSArray *hotSeaches = @[@"Java", @"Python", @"Objective-C", @"Swift", @"C", @"C++", @"PHP", @"C#", @"Perl", @"Go", @"JavaScript", @"R", @"Ruby", @"MATLAB"];
    // 2. Create searchViewController
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:hotSeaches searchBarPlaceholder:@"Search programming language" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        // Call this Block when completion search automatically
        // Such as: Push to a view controller
        [searchViewController.navigationController pushViewController:[[UIViewController alloc] init] animated:YES];

    }];
    // 3. present the searchViewController
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    [self presentViewController:nav  animated:NO completion:nil];

```

## Custom

* Custom search suggestions display
```objc
// 1. Set dataSource
searchViewController.dataSource = self;
// 2. Implement dataSource method
```

* Custom search result dispaly
```objc
// 1. Set searchResultShowMode
searchViewController.searchResultShowMode = PYSearchResultShowModeEmbed;
// 2. Set searchResultController
searchViewController.searchResultController = [[UIViewController alloc] init];
```

* Set hotSearchStyle(default is PYHotSearchStyleNormalTag)
```objc
// Set hotSearchStyle
searchViewController.hotSearchStyle = PYHotSearchStyleColorfulTag;
```

* Set searchHistoryStyle(default is PYSearchHistoryStyleCell)
```objc
// Set searchHistoryStyle
searchViewController.searchHistoryStyle = PYSearchHistoryStyleBorderTag;
```

* Set searchHistoriesCachePath(default is PYSEARCH_SEARCH_HISTORY_CACHE_PATH)
```objc
// Set searchHistoriesCachePath
searchViewController.searchHistoriesCachePath = @"The cache path";
```

* Set searchHistoriesCount(default is 20)
```objc
// Set searchHistoriesCount
searchViewController. searchHistoriesCount = 6;
```

* Set searchResultShowMode(default is PYSearchResultShowModeCustom)
```objc
// Set searchResultShowMode
searchViewController.searchResultShowMode = PYSearchResultShowModeEmbed;
```

* Set searchSuggestionHidden(deafult is NO)
```objc
// Set searchSuggestionHidden
searchViewController.searchSuggestionHidden = YES;
```

## Hope

- If you have any questions during the process or want more interfaces to customize,you can [issues me](https://github.com/iphone5solo/PYSearch/issues/new)!
- Instead of giving me star, it is better to throw a bug to me!
- If you want to participate in the maintenance of this project or have a good design style, welcome to pull request!
- If you feel slightly discomfort in use, please contact me QQ:499491531 or Email:499491531@qq.com.
- Hope to improve this project together, let it become more powerful, able to meet the needs of most users!

## Licenses
All source code is licensed under the MIT License.


text:
package com.schooner.MemCached;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.BufferOverflowException;

/**
 * {@link SockOutputStream} is a outputstream based on socket. There will be a
 * big buffer in the socket, which is 1Mb in default, you can put all bytes into
 * this buffer easily, when it is full, it will flush the bytes into the socket.<br>
 * Don't make the buffer too much small, or else you will have problem in
 * memcached set operation.
 *
 * @author Xingen Wang
 * @since 2.5.0
 * @see OutputStream
 * @see SchoonerSockIO
 */
public final class SockOutputStream extends OutputStream {
	private int count = 0;
	private SchoonerSockIO sock;

	/**
	 * get byte count, how many wrote.
	 *
	 * @return
	 */
	public final int getCount() {
		return count;
	}

	/**
	 * reset the count;
	 */
	public final void resetCount() {
		this.count = 0;
	}

	/**
	 * get channel of this stream.
	 *
	 * @return channel specified with this stream.
	 */
	public final SchoonerSockIO getSock() {
		return sock;
	}

	/**
	 * Constructor with SockIO.
	 *
	 * @param sock
	 *            specified socket for this outputstream.
	 */
	public SockOutputStream(final SchoonerSockIO sock) {
		this.sock = sock;
	}

	/**
	 * write buffered bytes into socket channel.
	 *
	 * @throws IOException
	 *             error happened.
	 */
	private final void writeToChannel() throws IOException {
		sock.writeBuf.flip();
		sock.getChannel().write(sock.writeBuf);
		sock.writeBuf.clear();
	}

	@Override
	public final void write(int b) throws IOException {
		try {
			sock.writeBuf.put((byte) b);
		} catch (BufferOverflowException e) {
			writeToChannel();
			sock.writeBuf.put((byte) b);
		}
		count++;
	}

	@Override
	public final void write(byte[] b) throws IOException {
		write(b, 0, b.length);
	}

	@Override
	public final void write(byte[] b, int off, int len) throws IOException {
		if (len == 0)
			return;
		if (sock.writeBuf.remaining() >= len)
			sock.writeBuf.put(b, off, len);
		else {
			int written = 0;
			int w1 = 0;
			int tRemain = 0;
			while ((tRemain = len - written) > 0) {
				w1 = sock.writeBuf.remaining();
				w1 = w1 < tRemain ? w1 : tRemain;
				if (w1 == 0)
					writeToChannel();
				else
					sock.writeBuf.put(b, off, w1);
				written += w1;
			}
		}
		count += len;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package ucar.nc2.dataset;

import ucar.ma2.Array;
import ucar.ma2.ArrayChar;
import ucar.ma2.DataType;
import ucar.ma2.Index;
import ucar.ma2.IndexIterator;
import ucar.ma2.InvalidRangeException;
import ucar.ma2.MAMath;
import ucar.ma2.Range;
import ucar.ma2.Section;
import ucar.nc2.Group;
import ucar.nc2.constants.AxisType;
import ucar.nc2.constants.CF;
import ucar.nc2.util.NamedObject;
import ucar.unidata.util.Format;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * A 1-dimensional Coordinate Axis. Its values must be monotonic.
 *

 * If this is char valued, it will have rank 2, otherwise it will have rank 1.
 *

 * If string or char valued, only getCoordName() can be called.
 *

 * If the coordinates are regularly spaced, isRegular() is true, and the values are equal to
 * getStart() + i * getIncrement().
 *

 * This will also set "cell bounds" for this axis. By default, the cell bounds are midway between the coordinates
 * values,
 * and are therefore contiguous, and can be accessed though getCoordEdge(i).
 * The only way the bounds can be set is if the coordinate variable has an attribute "bounds" that points to another
 * variable
 * bounds(ncoords,2). These contain the cell bounds, and must be ascending or descending as the coordinate values are.
 * In
 * this case isContiguous() is true when bounds1(i+1) == bounds2(i) for all i.
 *
 * @author john caron
 * @see CoordinateAxis#fromVariableDS
 */

public class CoordinateAxis1D extends CoordinateAxis {
  private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(CoordinateAxis1D.class);

  /**
   * Create a 1D coordinate axis from an existing Variable
   *
   * @param ncd the containing dataset
   * @param vds wrap this VariableDS, which is not changed.
   * @deprecated Use CoordinateAxis1D.builder()
   */
  @Deprecated
  public CoordinateAxis1D(NetcdfDataset ncd, VariableDS vds) {
    super(ncd, vds);
    vds.setCaching(true);
  }

  /**
   * Copy constructor
   *
   * @param ncd ok to reparent
   * @param org copy from here
   * @deprecated Use CoordinateAxis1D.toBuilder()
   */
  @Deprecated
  CoordinateAxis1D(NetcdfDataset ncd, CoordinateAxis1D org) {
    super(ncd, org);
    this.orgName = org.orgName;
    this.cache.reset(); // decouple cache
    org.setCaching(true);

    // copy rest of state
    this.increment = org.getIncrement();
    this.isAscending = org.isAscending;
    this.isInterval = org.isInterval();
    this.isRegular = org.isRegular();

    if (isNumeric()) {
      this.coords = org.getCoordValues();
      this.edge = org.getCoordEdges();
    }

    this.names = org.names;

    if (isInterval) {
      this.bound1 = org.getBound1();
      this.bound2 = org.getBound2();
    }

    this.wasBoundsDone = org.wasBoundsDone;
    this.wasCalcRegular = org.wasCalcRegular;
    this.wasRead = org.wasRead;
  }

  /**
   * Constructor when theres no underlying variable. You better set the values too!
   *
   * @param ds the containing dataset.
   * @param group the containing group; if null, use rootGroup
   * @param shortName axis name.
   * @param dataType data type
   * @param dims list of dimension names
   * @param units units of coordinates, preferably udunit compatible.
   * @param desc long name.
   * @deprecated Use CoordinateAxis1D.builder()
   */
  @Deprecated
  public CoordinateAxis1D(NetcdfDataset ds, Group group, String shortName, DataType dataType, String dims, String units,
      String desc) {

    super(ds, group, shortName, dataType, dims, units, desc);
  }

  /**
   * Create a new CoordinateAxis1D as a section of this CoordinateAxis1D.
   *
   * @param r the section range
   * @return a new CoordinateAxis1D as a section of this CoordinateAxis1D
   * @throws InvalidRangeException if IllegalRange
   */
  public CoordinateAxis1D section(Range r) throws InvalidRangeException {
    Section section = Section.builder().appendRange(r).build();
    CoordinateAxis1D result = (CoordinateAxis1D) section(section);
    int len = r.length();

    // deal with the midpoints, bounds
    if (isNumeric()) {
      double[] new_mids = new double[len];
      for (int idx = 0; idx < len; idx++) {
        int old_idx = r.element(idx);
        new_mids[idx] = coords[old_idx];
      }
      result.coords = new_mids;

      if (isInterval) {
        double[] new_bound1 = new double[len];
        double[] new_bound2 = new double[len];
        double[] new_edge = new double[len + 1];
        for (int idx = 0; idx < len; idx++) {
          int old_idx = r.element(idx);
          new_bound1[idx] = bound1[old_idx];
          new_bound2[idx] = bound2[old_idx];
          new_edge[idx] = bound1[old_idx];
          new_edge[idx + 1] = bound2[old_idx]; // all but last are overwritten
        }
        result.bound1 = new_bound1;
        result.bound2 = new_bound2;
        result.edge = new_edge;

      } else {
        double[] new_edge = new double[len + 1];
        for (int idx = 0; idx < len; idx++) {
          int old_idx = r.element(idx);
          new_edge[idx] = edge[old_idx];
          new_edge[idx + 1] = edge[old_idx + 1]; // all but last are overwritten
        }
        result.edge = new_edge;
      }
    }

    if (names != null) {
      String[] new_names = new String[len];
      for (int idx = 0; idx < len; idx++) {
        int old_idx = r.element(idx);
        new_names[idx] = names[old_idx];
      }
      result.names = new_names;
    }

    result.wasCalcRegular = false;
    result.calcIsRegular();

    return result;
  }

  // for section and slice

  @Override
  protected CoordinateAxis1D copy() {
    return new CoordinateAxis1D(this.ncd, this);
  }

  @Override
  public CoordinateAxis copyNoCache() {
    CoordinateAxis1D axis = new CoordinateAxis1D(ncd, getParentGroupOrRoot(), getShortName(), getDataType(),
        getDimensionsString(), getUnitsString(), getDescription());

    // other state
    axis.axisType = this.axisType;
    axis.boundaryRef = this.boundaryRef;
    axis.isContiguous = this.isContiguous;
    axis.positive = this.positive;

    axis.cache.reset(); // decouple cache
    return axis;
  }

  /**
   * Get the list of names, to be used for user selection.
   * The ith one refers to the ith coordinate.
   *
   * @return List of ucar.nc2.util.NamedObject, or empty list.
   * @deprecated will move in ver 6
   */
  @Deprecated
  public List<NamedObject> getNames() {
    int n = getDimension(0).getLength();
    List<NamedObject> names = new ArrayList<>(n);
    for (int i = 0; i < n; i++)
      names.add(new ucar.nc2.util.NamedAnything(getCoordName(i), getShortName() + " " + getUnitsString()));
    return names;
  }

  /**
   * The "name" of the ith coordinate. If nominal, this is all there is to a coordinate.
   * If numeric, this will return a String representation of the coordinate.
   *
   * @param index which one ?
   * @return the ith coordinate value as a String
   */
  public String getCoordName(int index) {
    if (!wasRead)
      doRead();
    if (isNumeric())
      return Format.d(getCoordValue(index), 5, 8);
    else
      return names[index];
  }

  /**
   * Get the ith coordinate value. This is the value of the coordinate axis at which
   * the data value is associated. These must be strictly monotonic.
   *
   * @param index which coordinate. Between 0 and getNumElements()-1 inclusive.
   * @return coordinate value.
   * @throws UnsupportedOperationException if !isNumeric()
   */
  public double getCoordValue(int index) {
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis1D.getCoordValue() on non-numeric");
    if (!wasRead)
      doRead();
    return coords[index];
  }

  @Override
  public double getMinValue() {
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis1D.getCoordValue() on non-numeric");
    if (!wasRead)
      doRead();

    return Math.min(coords[0], coords[coords.length - 1]);
  }

  @Override
  public double getMaxValue() {
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis1D.getCoordValue() on non-numeric");
    if (!wasRead)
      doRead();

    return Math.max(coords[0], coords[coords.length - 1]);
  }

  public double getMinEdgeValue() {
    if (edge == null)
      return getMinValue();
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis1D.getCoordValue() on non-numeric");
    if (!wasRead)
      doRead();

    return Math.min(edge[0], edge[edge.length - 1]);
  }

  public double getMaxEdgeValue() {
    if (edge == null)
      return getMaxValue();
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis1D.getCoordValue() on non-numeric");
    if (!wasRead)
      doRead();

    return Math.max(edge[0], edge[edge.length - 1]);
  }

  /**
   * Get the ith coordinate edge. Exact only if isContiguous() is true, otherwise use getBound1() and getBound2().
   * This is the value where the underlying grid element switches
   * from "belonging to" coordinate value i-1 to "belonging to" coordinate value i.
   * In some grids, this may not be well defined, and so should be considered an
   * approximation or a visualization hint.
   *

   *
   *

   *  Coordinate edges must be strictly monotonic:
   *    coordEdge(0) < coordValue(0) < coordEdge(1) < coordValue(1) ...
   *    ... coordEdge(i) < coordValue(i) < coordEdge(i+1) < coordValue(i+1) ...
   *    ... coordEdge(n-1) < coordValue(n-1) < coordEdge(n)
   *

   *
   * @param index which coordinate. Between 0 and getNumElements() inclusive.
   * @return coordinate edge.
   * @throws UnsupportedOperationException if !isNumeric()
   */
  public double getCoordEdge(int index) {
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis1D.getCoordEdge() on non-numeric");
    if (!wasBoundsDone)
      makeBounds();
    return edge[index];
  }

  /**
   * Get the coordinate values as a double array.
   *
   * @return coordinate value.
   * @throws UnsupportedOperationException if !isNumeric()
   */
  public double[] getCoordValues() {
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis1D.getCoordValues() on non-numeric");
    if (!wasRead)
      doRead();
    return coords.clone();
  }

  /**
   * Get the coordinate edges as a double array.
   * Exact only if isContiguous() is true, otherwise use getBound1() and getBound2().
   *
   * @return coordinate edges.
   * @throws UnsupportedOperationException if !isNumeric()
   */
  public double[] getCoordEdges() {
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis1D.getCoordEdges() on non-numeric");
    if (!wasBoundsDone)
      makeBounds();
    return edge.clone();
  }

  @Override
  public boolean isContiguous() {
    if (!wasBoundsDone)
      makeBounds(); // this sets isContiguous
    return isContiguous;
  }

  ///////////////////////////////////////////////

  /**
   * If this coordinate has interval values.
   * If so, then one should use getBound1, getBound2, and not getCoordEdges()
   *
   * @return true if coordinate has interval values
   */
  public boolean isInterval() {
    if (!wasBoundsDone)
      makeBounds(); // this sets isInterval
    return isInterval;
  }

  /**
   * Get the coordinate bound1 as a double array.
   * bound1[i] # coordValue[i] # bound2[i], where # is < if increasing (bound1[i] < bound1[i+1])
   * else < if decreasing.
   *
   * @return coordinate bound1.
   * @throws UnsupportedOperationException if !isNumeric()
   */
  public double[] getBound1() {
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis1D.getBound1() on non-numeric");
    if (!wasBoundsDone)
      makeBounds();
    if (bound1 == null)
      makeBoundsFromEdges();
    assert bound1 != null;
    return bound1.clone();
  }

  /**
   * Get the coordinate bound1 as a double array.
   * bound1[i] # coordValue[i] # bound2[i], where # is < if increasing (bound1[i] < bound1[i+1])
   * else < if decreasing.
   *
   * @return coordinate bound2.
   * @throws UnsupportedOperationException if !isNumeric()
   */
  public double[] getBound2() {
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis1D.getBound2() on non-numeric");
    if (!wasBoundsDone)
      makeBounds();
    if (bound2 == null)
      makeBoundsFromEdges();
    assert bound2 != null;
    return bound2.clone();
  }

  /**
   * Get the coordinate bounds for the ith coordinate.
   * Can use this for isContiguous() true or false.
   *
   * @param i coordinate index
   * @return double[2] edges for ith coordinate
   */
  public double[] getCoordBounds(int i) {
    if (!wasBoundsDone)
      makeBounds();

    double[] e = new double[2];
    if (isContiguous()) {
      e[0] = getCoordEdge(i);
      e[1] = getCoordEdge(i + 1);
    } else {
      e[0] = bound1[i];
      e[1] = bound2[i];
    }
    return e;
  }

  public double getCoordBoundsMidpoint(int i) {
    double[] bounds = getCoordBounds(i);
    return (bounds[0] + bounds[1]) / 2;
  }

  /**
   * Given a coordinate value, find what grid element contains it.
   * This means that
   *
   *

   * edge[i] <= value < edge[i+1] (if values are ascending)
   * edge[i] > value >= edge[i+1] (if values are descending)
   *

   *
   * @param coordVal position in this coordinate system
   * @return index of grid point containing it, or -1 if outside grid area
   */
  public int findCoordElement(double coordVal) {
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis.findCoordElement() on non-numeric");

    if (isRegular())
      return findCoordElementRegular(coordVal, false);
    if (isContiguous())
      return findCoordElementIrregular(coordVal, false);
    else
      return findCoordElementNonContiguous(coordVal, false);
  }

  /**
   * Given a coordinate position, find what grid element contains it, or is closest to it.
   *
   * @param coordVal position in this coordinate system
   * @return index of grid point containing it, or best estimate of closest grid interval.
   */
  public int findCoordElementBounded(double coordVal) {
    if (!isNumeric())
      throw new UnsupportedOperationException("CoordinateAxis.findCoordElementBounded() on non-numeric");

    // the scalar or len-1 case:
    if (this.getSize() == 1)
      return 0;

    if (isRegular())
      return findCoordElementRegular(coordVal, true);
    if (isContiguous())
      return findCoordElementIrregular(coordVal, true);
    else
      return findCoordElementNonContiguous(coordVal, true);
  }

  /**
   * @deprecated use findCoordElement(coordVal)
   */
  public int findCoordElement(double coordVal, int lastIndex) {
    return findCoordElement(coordVal);
  }

  //////////////////////////////////////////////////////////////////
  // following is from Jon Blower's ncWMS
  // faster routines for coordValue -> index search
  // significantly modified

  /**
   * Optimize the regular case
   * Gets the index of the given point. Uses index = (value - start) / stride,
   * hence this is faster than an exhaustive search.
   * from jon blower's ncWMS.
   *
   * @param coordValue The value along this coordinate axis
   * @param bounded if false and not in range, return -1, else nearest index
   * @return the index that is nearest to this point, or -1 if the point is
   *         out of range for the axis
   */
  private int findCoordElementRegular(double coordValue, boolean bounded) {
    int n = (int) this.getSize();

    // the scalar or len-1 case:
    if (this.getSize() == 1) {
      return 0;
    }

    /*
     * if (axisType == AxisType.Lon) {
     * double maxValue = this.start + this.increment * n;
     * if (betweenLon(coordValue, this.start, maxValue)) {
     * double distance = LatLonPointImpl.getClockwiseDistanceTo(this.start, coordValue);
     * double exactNumSteps = distance / this.increment;
     * // This axis might wrap, so we make sure that the returned index is within range
     * return ((int) Math.round(exactNumSteps)) % (int) this.getSize();
     *
     * } else if (coordValue < this.start) {
     * return bounded ? 0 : -1;
     * } else {
     * return bounded ? n - 1 : -1;
     * }
     * }
     */

    double distance = coordValue - this.start;
    double exactNumSteps = distance / this.increment;
    int index = (int) Math.round(exactNumSteps);
    if (index < 0)
      return bounded ? 0 : -1;
    else if (index >= n)
      return bounded ? n - 1 : -1;
    return index;
  }

  private boolean betweenLon(double lon, double lonBeg, double lonEnd) {
    while (lon < lonBeg)
      lon += 360;
    return (lon >= lonBeg) && (lon <= lonEnd);
  }

  /**
   * Performs a binary search to find the index of the element of the array
   * whose value is contained in the interval, so must be contiguous.
   *
   * @param target The value to search for
   * @param bounded if false, and not in range, return -1, else nearest index
   * @return the index of the element in values whose value is closest to target,
   *         or -1 if the target is out of range
   */
  private int findCoordElementIrregular(double target, boolean bounded) {
    int n = (int) this.getSize();
    int low = 0;
    int high = n;

    if (isAscending) {
      // Check that the point is within range
      if (target < this.edge[low])
        return bounded ? 0 : -1;
      else if (target > this.edge[high])
        return bounded ? n - 1 : -1;

      // do a binary search to find the nearest index
      int mid;
      while (high > low + 1) {
        mid = (low + high) / 2;
        double midVal = this.edge[mid];
        if (midVal == target)
          return mid;
        else if (midVal < target)
          low = mid;
        else
          high = mid;
      }

      return low;

    } else {

      // Check that the point is within range
      if (target > this.edge[low])
        return bounded ? 0 : -1;
      else if (target < this.edge[high])
        return bounded ? n - 1 : -1;

      // do a binary search to find the nearest index
      int mid;
      while (high > low + 1) {
        mid = (low + high) / 2;
        double midVal = this.edge[mid];
        if (midVal == target)
          return mid;
        else if (midVal < target)
          high = mid;
        else
          low = mid;
      }

      return high - 1;
    }
  }

  /**
   * Given a coordinate position, find what grid element contains it.
   * Only use if isContiguous() == false
   * This algorithm does a linear search in the bound1[] amd bound2[] array.
   *

   * This means that
   *
   *

   * edge[i] <= pos < edge[i+1] (if values are ascending)
   * edge[i] > pos >= edge[i+1] (if values are descending)
   *

   *
   * @param target The value to search for
   * @param bounded if false, and not in range, return -1, else nearest index
   * @return the index of the element in values whose value is closest to target,
   *         or -1 if the target is out of range
   */
  private int findCoordElementNonContiguous(double target, boolean bounded) {

    double[] bounds1 = getBound1();
    double[] bounds2 = getBound2();
    int n = bounds1.length;

    if (isAscending) {
      // Check that the point is within range
      if (target < bounds1[0])
        return bounded ? 0 : -1;
      else if (target > bounds2[n - 1])
        return bounded ? n - 1 : -1;

      int[] idx = findSingleHit(bounds1, bounds2, target);
      if (idx[0] == 0 && !bounded)
        return -1; // no hits
      if (idx[0] == 1)
        return idx[1]; // one hit

      // multiple hits = choose closest to the midpoint i guess
      return findClosest(coords, target);

    } else {

      // Check that the point is within range
      if (target > bounds1[0])
        return bounded ? 0 : -1;
      else if (target < bounds2[n - 1])
        return bounded ? n - 1 : -1;

      int[] idx = findSingleHit(bounds2, bounds1, target);
      if (idx[0] == 0 && !bounded)
        return -1; // no hits
      if (idx[0] == 1)
        return idx[1];

      // multiple hits = choose closest to the midpoint i guess
      return findClosest(getCoordValues(), target);
    }
  }

  // return index if only one match, else -1
  private int[] findSingleHit(double[] low, double[] high, double target) {
    int hits = 0;
    int idxFound = -1;
    int n = low.length;
    for (int i = 0; i < n; i++) {
      if ((low[i] <= target) && (target <= high[i])) {
        hits++;
        idxFound = i;
      }
    }
    return new int[] {hits, idxFound};
  }

  // return index of closest value to target
  private int findClosest(double[] values, double target) {
    double minDiff = Double.MAX_VALUE;
    int idxFound = -1;
    int n = values.length;
    for (int i = 0; i < n; i++) {
      double diff = Math.abs(values[i] - target);
      if (diff < minDiff) {
        minDiff = diff;
        idxFound = i;
      }
    }
    return idxFound;
  }

  ///////////////////////////////////////////////////////////////////////////////
  // check if Regular

  /**
   * Get starting value if isRegular()
   *
   * @return starting value if isRegular()
   */
  public double getStart() {
    calcIsRegular();
    return start;
  }

  /**
   * Get increment value if isRegular()
   *
   * @return increment value if isRegular()
   */
  public double getIncrement() {
    calcIsRegular();
    return increment;
  }

  /**
   * If true, then value(i) = getStart() + i * getIncrement().
   *
   * @return if evenly spaced.
   */
  public boolean isRegular() {
    calcIsRegular();
    return isRegular;
  }

  private void calcIsRegular() {
    if (wasCalcRegular)
      return;
    if (!wasRead)
      doRead();

    if (!isNumeric())
      isRegular = false;
    else if (getSize() < 2)
      isRegular = true;
    else {
      start = getCoordValue(0);
      int n = (int) getSize();
      increment = (getCoordValue(n - 1) - getCoordValue(0)) / (n - 1);
      isRegular = true;
      for (int i = 1; i < getSize(); i++)
        if (!ucar.nc2.util.Misc.nearlyEquals(getCoordValue(i) - getCoordValue(i - 1), increment, 5.0e-3)) {
          isRegular = false;
          break;
        }
    }
    wasCalcRegular = true;
  }

  ///////////////////////////////////////////////////////////////////////////////

  private void doRead() {
    if (isNumeric()) {
      readValues();
      wasRead = true;

      if (getSize() < 2)
        isAscending = true;
      else
        isAscending = getCoordValue(0) < getCoordValue(1);
      // calcIsRegular(); */
    } else if (getDataType() == DataType.STRING) {
      readStringValues();
      wasRead = true;
    } else {
      readCharValues();
      wasRead = true;
    }
  }

  // LOOK turns longitude coordinate into monotonic, dealing with possible wrap.
  /** @deprecated do not use. */
  @Deprecated
  public void correctLongitudeWrap() {
    // correct non-monotonic longitude coords
    if (axisType != AxisType.Lon) {
      return;
    }

    if (!wasRead)
      doRead();
    if (!wasBoundsDone)
      makeBounds();

    boolean monotonic = true;
    for (int i = 0; i < coords.length - 1; i++)
      monotonic &= isAscending ? coords[i] < coords[i + 1] : coords[i] > coords[i + 1];

    if (!monotonic) {
      boolean cross = false;
      if (isAscending) {
        for (int i = 0; i < coords.length; i++) {
          if (cross)
            coords[i] += 360;
          if (!cross && (i < coords.length - 1) && (coords[i] > coords[i + 1]))
            cross = true;
        }
      } else {
        for (int i = 0; i < coords.length; i++) {
          if (cross)
            coords[i] -= 360;
          if (!cross && (i < coords.length - 1) && (coords[i] < coords[i + 1]))
            cross = true;
        }
      }

      // LOOK - need to make sure we get stuff from the cache
      Array cachedData = Array.factory(DataType.DOUBLE, getShape(), coords);
      if (getDataType() != DataType.DOUBLE)
        cachedData = MAMath.convert(cachedData, getDataType());
      setCachedData(cachedData);

      if (!isInterval) {
        makeEdges();
      }
    }

  }

  // only used if String

  private void readStringValues() {
    int count = 0;
    Array data;
    try {
      data = read();
    } catch (IOException ioe) {
      log.error("Error reading string coordinate values ", ioe);
      throw new IllegalStateException(ioe);
    }

    names = new String[(int) data.getSize()];
    IndexIterator ii = data.getIndexIterator();
    while (ii.hasNext())
      names[count++] = (String) ii.getObjectNext();
  }

  private void readCharValues() {
    int count = 0;
    ArrayChar data;
    try {
      data = (ArrayChar) read();
    } catch (IOException ioe) {
      log.error("Error reading char coordinate values ", ioe);
      throw new IllegalStateException(ioe);
    }
    ArrayChar.StringIterator iter = data.getStringIterator();
    names = new String[iter.getNumElems()];
    while (iter.hasNext())
      names[count++] = iter.next();
  }

  protected void readValues() {
    Array data;
    try {
      // setUseNaNs(false); // missing values not allowed LOOK not true for point data !!
      data = read();
      // if (!hasCachedData()) setCachedData(data, false); //cache data for subsequent reading
    } catch (IOException ioe) {
      log.error("Error reading coordinate values ", ioe);
      throw new IllegalStateException(ioe);
    }

    coords = (double[]) data.get1DJavaArray(DataType.DOUBLE);
    // IndexIterator iter = data.getIndexIterator();
    // while (iter.hasNext())
    // coords[count++] = iter.getDoubleNext();
  }

  /**
   * Calculate bounds, set isInterval, isContiguous
   */
  private void makeBounds() {
    if (!wasRead)
      doRead();
    if (isNumeric()) {
      if (!makeBoundsFromAux()) {
        makeEdges();
      }
    }
    wasBoundsDone = true;
  }

  private boolean makeBoundsFromAux() {
    String boundsVarName = attributes().findAttributeString(CF.BOUNDS, null);
    if (boundsVarName == null) {
      return false;
    }
    VariableDS boundsVar = (VariableDS) getParentGroupOrRoot().findVariableLocal(boundsVarName);
    if (null == boundsVar)
      return false;
    if (2 != boundsVar.getRank())
      return false;

    if (getDimension(0) != boundsVar.getDimension(0))
      return false;
    if (2 != boundsVar.getDimension(1).getLength())
      return false;

    Array data;
    try {
      // LOOK this seems bogus
      boundsVar.removeEnhancement(NetcdfDataset.Enhance.ConvertMissing); // Don't convert missing values to NaN.
      data = boundsVar.read();
    } catch (IOException e) {
      log.warn("CoordinateAxis1D.hasBounds read failed ", e);
      return false;
    }

    assert (data.getRank() == 2) && (data.getShape()[1] == 2) : "incorrect shape data for variable " + boundsVar;

    // extract the bounds
    int n = shape[0];
    double[] value1 = new double[n];
    double[] value2 = new double[n];
    Index ima = data.getIndex();
    for (int i = 0; i < n; i++) {
      ima.set0(i);
      value1[i] = data.getDouble(ima.set1(0));
      value2[i] = data.getDouble(ima.set1(1));
    }

    /*
     * flip if needed
     * boolean firstLower = true; // in the first interval, is lower < upper ?
     * for (int i = 0; i < value1.length; i++) {
     * if (Misc.nearlyEquals(value1[i], value2[i])) continue; // skip when lower == upper
     * firstLower = value1[i] < value2[i];
     * break;
     * }
     * // check first against last : lower, unless all lower equal then upper
     * boolean goesUp = (n < 2) || value1[n - 1] > value1[0] || (Misc.nearlyEquals(value1[n - 1], value2[0]) && value2[n
     * - 1] > value2[0]);
     * if (goesUp != firstLower) {
     * double[] temp = value1;
     * value1 = value2;
     * value2 = temp;
     * }
     */

    // decide if they are contiguous
    boolean contig = true;
    for (int i = 0; i < n - 1; i++) {
      if (!ucar.nc2.util.Misc.nearlyEquals(value1[i + 1], value2[i]))
        contig = false;
    }

    if (contig) {
      edge = new double[n + 1];
      edge[0] = value1[0];
      for (int i = 1; i < n + 1; i++)
        edge[i] = value2[i - 1];
    } else { // what does edge mean when not contiguous ??
      edge = new double[n + 1];
      edge[0] = value1[0];
      for (int i = 1; i < n; i++)
        edge[i] = (value1[i] + value2[i - 1]) / 2;
      edge[n] = value2[n - 1];
      isContiguous = false;
    }

    bound1 = value1;
    bound2 = value2;
    isInterval = true;

    return true;
  }

  private void makeEdges() {
    int size = (int) getSize();
    edge = new double[size + 1];
    if (size < 1) {
      return;
    }
    if (size == 1) {
      // if the axis size is one, edges are the same as the coord
      edge[0] = coords[0];
      edge[1] = coords[0];
      return;
    }
    for (int i = 1; i < size; i++) {
      edge[i] = (coords[i - 1] + coords[i]) / 2;
    }
    edge[0] = coords[0] - (edge[1] - coords[0]);
    edge[size] = coords[size - 1] + (coords[size - 1] - edge[size - 1]);
    isContiguous = true;
  }

  private void makeBoundsFromEdges() {
    int size = (int) getSize();
    if (size == 0)
      return;

    bound1 = new double[size];
    bound2 = new double[size];
    for (int i = 0; i < size; i++) {
      bound1[i] = edge[i];
      bound2[i] = edge[i + 1];
    }

    // flip if needed
    if (bound1[0] > bound2[0]) {
      double[] temp = bound1;
      bound1 = bound2;
      bound2 = temp;
    }
  }

  ////////////////////////////////////////////////////////////////////////////////////////////
  // These are all calculated, I think?
  protected boolean wasRead; // have the data values been read
  private boolean wasBoundsDone; // have we created the bounds arrays if exists ?
  private boolean isInterval; // is this an interval coordinates - then should use bounds
  private boolean isAscending;

  // read in on doRead()
  protected double[] coords; // coordinate values, must be between edges
  private String[] names; // only set if String or char values

  // defer making until asked, use makeBounds()
  private double[] edge; // n+1 edges, edge[k] < midpoint[k] < edge[k+1]
  private double[] bound1, bound2; // may be contiguous or not

  private boolean wasCalcRegular; // have we checked if the data is regularly spaced ?
  private boolean isRegular;
  private double start, increment;

  protected CoordinateAxis1D(Builder<?> builder, Group parentGroup) {
    super(builder, parentGroup);
  }

  public Builder<?> toBuilder() {
    return addLocalFieldsToBuilder(builder());
  }

  // Add local fields to the passed - in builder.
  protected Builder<?> addLocalFieldsToBuilder(Builder<? extends Builder<?>> b) {
    return (Builder<?>) super.addLocalFieldsToBuilder(b);
  }

  /**
   * Get Builder for this class that allows subclassing.
   *
   * @see "https://community.oracle.com/blogs/emcmanus/2010/10/24/using-builder-pattern-subclasses"
   */
  public static Builder<?> builder() {
    return new Builder2();
  }

  private static class Builder2 extends Builder<Builder2> {
    @Override
    protected Builder2 self() {
      return this;
    }
  }

  public static abstract class Builder<T extends Builder<T>> extends CoordinateAxis.Builder<T> {
    private boolean built;

    protected abstract T self();

    public CoordinateAxis1D build(Group parentGroup) {
      if (built)
        throw new IllegalStateException("already built");
      built = true;
      return new CoordinateAxis1D(this, parentGroup);
    }
  }

}


text:
<?php

/**
 * @class Spriter
 * @author Christian Stuff <christian.stuff@namics.com>
 */
class Spriter {
	public static $version = "1.2.2";

	public $hasGenerated = false;

	protected $srcDirectory;
	protected $spriteDirectory;
	protected $cssDirectory;
	protected $spriteFilepath;
	protected $spriteFilename;
	protected $spriteChecksum = false;
	protected $tileMargin = 0;
	protected $retina = array( 1 );
	protected $retinaDelimiter = "@";
	protected $cssFileExtension = "css"; // deprecated
	protected $namespace = "icon-";
	protected $globalTemplate;
	protected $eachTemplate;
	protected $eachHoverTemplate;
	protected $ratioTemplate;
	protected $timestamp;
	protected $forceGenerate = false;
	protected $ignoreHover = false;
	protected $hoverSuffix = "-hover";

	protected $targets = array();

	private $icons = array();

	public function __construct( $config = array() ) {
		if ( is_array( $config ) ) {
			// config
			foreach ( $config as $key => $val ) {
				if ( property_exists( $this, $key ) ) {
					$this->$key = $val;
				}
			}
			// validation & defaults
			$this->validate();
			if ( !in_array( 1, $this->retina ) ) {
				$this->retina[] = 1;
			}
			$this->checkDefaultTemplates();
			// setup & generation
			$this->setupIcons();
			if ( $this->hasChanged() || $this->forceGenerate ) {
				$this->timestamp = date( 'YmdHis', time() );
				$this->generateChecksum();
				$this->generateSprite();
				$this->generateCSS();
				$this->hasGenerated = true;
			}
		}
		else {
			$this->error( self::INVALID_CONFIG );
		}
	}

	private function checkDefaultTemplates() {
		$defaultGlobal    = file_get_contents( __DIR__ . "/templates/default-global.tpl" );
		$defaultEach      = file_get_contents( __DIR__ . "/templates/default-each.tpl" );
		$defaultEachHover = file_get_contents( __DIR__ . "/templates/default-each-hover.tpl" );
		$defaultRatio     = file_get_contents( __DIR__ . "/templates/default-ratio.tpl" );

		if ( empty( $this->targets ) ) {
			if ( empty( $this->globalTemplate ) ) {
				$this->globalTemplate = $defaultGlobal;
			}
			if ( empty( $this->eachTemplate ) ) {
				$this->eachTemplate = $defaultEach;
			}
			if ( empty( $this->eachHoverTemplate ) ) {
				$this->eachHoverTemplate = $defaultEachHover;
			}
			if ( empty( $this->ratioTemplate ) && count( $this->retina ) > 1 ) {
				$this->ratioTemplate = $defaultRatio;
			}
		}
		else {
			for ( $i = 0; $i < count( $this->targets ); $i ++ ) {
				if ( empty( $this->targets[ $i ]['globalTemplate'] ) ) {
					$this->targets[ $i ]['globalTemplate'] = $defaultGlobal;
				}
				if ( empty( $this->targets[ $i ]['eachTemplate'] ) ) {
					$this->targets[ $i ]['eachTemplate'] = $defaultEach;
				}
				if ( empty( $this->targets[ $i ]['eachHoverTemplate'] ) ) {
					$this->targets[ $i ]['eachHoverTemplate'] = $defaultEachHover;
				}
				if ( empty( $this->targets[ $i ]['ratioTemplate'] ) && count( $this->retina ) > 1 ) {
					$this->targets[ $i ]['ratioTemplate'] = $defaultRatio;
				}
			}
		}
	}

	private function hasChanged() {
		// Check if the generated sprite files exist
		foreach ( $this->retina as $ratio ) {
			if ( !file_exists( $this->getSpriteFilename( $ratio ) ) ) {
				return true;
			}
		}

		// Check if the generated css file exists
		foreach ( $this->targets as $target ) {
			if ( !file_exists( $target['cssDirectory'] . "/" . $target['cssFilename'] ) ) {
				return true;
			}
		}

		// Checksum comparison
		if ( file_exists( __DIR__ . "/" . $this->getChecksumName() ) ) {
			$lastChecksum = file_get_contents( __DIR__ . "/" . $this->getChecksumName() );

			if ( $lastChecksum !== $this->getChecksum() ) {
				return true;
			}
		}
		else {
			return true;
		}

		return false;
	}

	private function setupIcons() {
		if ( $handle = opendir( $this->srcDirectory ) ) {
			while ( false !== ( $file = readdir( $handle ) ) ) {
				if ( $file != "." && $file != ".." && in_array( pathinfo( $file, PATHINFO_EXTENSION ), array(
						"gif",
						"jpg",
						"jpeg",
						"png"
					) )
				) {
					$fullPath   = $this->srcDirectory . "/" . $file;
					$size       = getimagesize( $fullPath );
					$path_parts = pathinfo( $fullPath );
					array_push( $this->icons, new Icon(
						$file,
						$path_parts['filename'],
						$size[0],
						$size[1]
					) );
				}
			}
			// Get the hover indicated icons
			if ( !$this->ignoreHover ) {
				foreach ( $this->icons as $icon ) {
					$hoverIcon = $this->searchHoverIcon( $icon->name );
					if ( $hoverIcon != null ) {
						$icon->hoverIcon = $hoverIcon;
						$icon->hasHover  = true;
					}
				}
			}
		}
		Icon::sort( $this->icons );
	}

	private function searchHoverIcon( $name ) {
		$hoverName = $name . $this->hoverSuffix;
		foreach ( $this->icons as $icon ) {
			if ( $icon->name == $hoverName ) {
				return $icon;
			}
		}

		return null;
	}

	private function createTransparentImage( $width, $height ) {
		$img   = imagecreatetruecolor( $width, $height );
		$white = imagecolorexactalpha( $img, 255, 255, 255, 127 );
		imagefill( $img, 0, 0, $white );
		imagealphablending( $img, false );
		$bg = imagecolorallocate( $img, 0, 0, 0 );
		imagecolortransparent( $img, $bg );
		imagesavealpha( $img, true );

		return $img;
	}

	private function generateSprite() {
		$canvas   = array( 1, 1 );
		$free     = array();
		$maxRatio = 1.0;

		$tileMargin = $this->tileMargin;

		if ( is_array( $this->retina ) && count( $this->retina ) > 1 ) {
			$maxRatio = max( $this->retina );
		}

		foreach ( $this->icons as $icon ) {
			if ( $canvas[0] == 1 && $canvas[1] == 1 ) {
				$icon->x = 0;
				$icon->y = 0;
				$canvas  = array( $icon->width, $icon->height );
			}
			else {
				for ( $i = 0; $i < count( $free ); $i ++ ) {
					if ( $free[ $i ]['width'] >= $icon->width && $free[ $i ]['height'] >= $icon->height ) {
						// icon fits in free area
						$icon->x = $free[ $i ]['x'];
						$icon->y = $free[ $i ]['y'];

						if ( $icon->height + $tileMargin < $free[ $i ]['height'] ) {
							array_push( $free, array(
								'x'      => $free[ $i ]['x'],
								'y'      => $free[ $i ]['y'] + $icon->height + $tileMargin,
								'width'  => $free[ $i ]['width'],
								'height' => $free[ $i ]['height'] - $icon->height - $tileMargin
							) );
						}

						$free[ $i ]['x']      = $free[ $i ]['x'] + $icon->width + $tileMargin;
						$free[ $i ]['width']  = $free[ $i ]['width'] - $icon->width - $tileMargin;
						$free[ $i ]['height'] = $icon->height;
						if ( $free[ $i ]['width'] <= 0 ) {
							array_splice( $free, $i, 1 );
						}
						break;
					}
				}

				if ( is_null( $icon->x ) && is_null( $icon->y ) ) {
					// icon needs new space
					if ( $canvas[1] >= $canvas[0] ) {
						// increase canvas width
						$canvas  = array( $canvas[0] + $icon->width + $tileMargin, $canvas[1] );
						$icon->x = $canvas[0] - $icon->width;
						$icon->y = 0;

						if ( $canvas[1] > $icon->height ) {
							array_push( $free, array(
								'x'      => $canvas[0] - $icon->width,
								'y'      => $icon->height + $tileMargin,
								'width'  => $icon->width,
								'height' => $canvas[1] - $icon->height - $tileMargin
							) );
						}
					}
					else {
						// increase canvas height
						$canvas  = array( $canvas[0], $canvas[1] + $icon->height + $tileMargin );
						$icon->x = 0;
						$icon->y = $canvas[1] - $icon->height;

						if ( $canvas[0] > $icon->width ) {
							array_push( $free, array(
								'x'      => $icon->width + $tileMargin,
								'y'      => $canvas[1] - $icon->height,
								'width'  => $canvas[0] - $icon->width - $tileMargin,
								'height' => $icon->height
							) );
						}
					}
				}
			}
		}

		if ( is_array( $this->retina ) ) {
			foreach ( $this->retina as $ratio ) {
				if ( is_numeric( $ratio ) ) {
					$retina_width  = $canvas[0] * $ratio / $maxRatio;
					$retina_height = $canvas[1] * $ratio / $maxRatio;
					$retina        = self::createTransparentImage( $retina_width, $retina_height );
					foreach ( $this->icons as $i ) {
						$path_parts = pathinfo( $this->srcDirectory . "/" . $i->file );
						$icon_img   = null;
						switch ( $path_parts['extension'] ) {
							case "png":
								$icon_img = imagecreatefrompng( $this->srcDirectory . "/" . $i->file );
								break;
							case "jpg":
							case "jpeg":
								$icon_img = imagecreatefromjpeg( $this->srcDirectory . "/" . $i->file );
								break;
							case "gif":
								$icon_img = imagecreatefromgif( $this->srcDirectory . "/" . $i->file );
								break;
						}
						if ( is_null( $icon_img ) ) {
							continue;
						}
						imagecopyresampled( $retina, $icon_img, (int) ( $i->x * $ratio / $maxRatio ), (int) ( $i->y * $ratio / $maxRatio ), 0, 0, $i->width * $ratio / $maxRatio, $i->height * $ratio / $maxRatio, $i->width, $i->height );
					}
					imagepng( $retina, $this->getSpriteFilename( $ratio ), 9 );
					if ( $ratio == 1 ) {
						$this->width  = imagesx( $retina );
						$this->height = imagesy( $retina );
					}
				}
			}
		}
	}

	private function generateCSS() {

		if ( empty( $this->targets ) ) {
			array_push( $this->targets, array(
				"cssDirectory"      => $this->cssDirectory,
				"cssFilename"       => $this->spriteFilename . "." . $this->cssFileExtension,
				"globalTemplate"    => $this->globalTemplate,
				"eachTemplate"      => $this->eachTemplate,
				"eachHoverTemplate" => $this->eachHoverTemplate,
				"ratioTemplate"     => $this->ratioTemplate
			) );
		}

		for ( $i = 0; $i < count( $this->targets ); $i ++ ) {
			$target = $this->targets[ $i ];

			$result = "";

			$replacements = array(
				"{{spriteFilepath}}"  => $this->spriteFilepath,
				"{{spriteFilename}}"  => $this->spriteFilename,
				"{{sprite}}"          => $this->spriteFilepath . "/" . $this->spriteFilename . ".png?" . $this->timestamp,
				"{{width}}"           => $this->width . "px",
				"{{height}}"          => $this->height . "px",
				"{{namespace}}"       => $this->namespace,
				"{{checksum}}"        => $this->spriteChecksum,
				"{{timestamp}}"       => $this->timestamp,

				"{{spriteDirectory}}" => $this->spriteFilepath // deprecated
			);

			$result .= str_replace(
				array_keys( $replacements ),
				array_values( $replacements ),
				$target['globalTemplate']
			);

			foreach ( $this->icons as $icon ) {
				$result .= $icon->generateCSSRule( $this->namespace, $target['eachTemplate'], $this->retina );
				if ( !$this->ignoreHover && $icon->hasHover ) {
					$result .= $icon->generateHoverCSSRule( $this->namespace, $target['eachHoverTemplate'], $this->retina );
				}
			}

			if ( isset( $target['ratioTemplate'] ) && !empty( $target['ratioTemplate'] ) && is_array( $this->retina ) && count( $this->retina ) > 1 ) {
				$ratios = "";
				foreach ( $this->retina as $ratio ) {
					if ( $ratio > 1 ) {
						$replacements = array(
							"{{spriteFilepath}}"  => $this->spriteFilepath,
							"{{spriteFilename}}"  => $this->spriteFilename,
							"{{sprite}}"          => $this->spriteFilepath . "/" . $this->spriteFilename . $this->retinaDelimiter . $ratio . "x.png?" . $this->timestamp,
							"{{ratio}}"           => $ratio,
							"{{ratioFrag}}"       => $ratio . "/1",
							"{{width}}"           => $this->width . "px",
							"{{height}}"          => $this->height . "px",
							"{{delimiter}}"       => $this->retinaDelimiter,
							"{{namespace}}"       => $this->namespace,
							"{{checksum}}"        => $this->spriteChecksum,
							"{{timestamp}}"       => $this->timestamp,

							"{{spriteDirectory}}" => $this->spriteFilepath, // deprecated
						);
						$ratios       = str_replace(
							                array_keys( $replacements ),
							                array_values( $replacements ),
							                $target['ratioTemplate']
						                ) . "\n" . $ratios;
					}
				}
				$result .= $ratios;
			}

			file_put_contents( $target['cssDirectory'] . "/" . $target['cssFilename'], $result );
		}
	}

	private function getChecksum() {
		$content = "";

		if ( $this->spriteChecksum === false ) {
			foreach ( $this->icons as $icon ) {
				$content .= $icon->file . file_get_contents( $this->srcDirectory . "/" . $icon->file );
			}
			$this->spriteChecksum = sha1( $content );
		}

		return $this->spriteChecksum;
	}

	private function generateChecksum() {
		file_put_contents( __DIR__ . "/" . $this->getChecksumName(), $this->getChecksum() );
	}

	private function getChecksumName() {
		return ".checksum-" . $this->spriteFilename;
	}

	private function getSpriteFilename( $ratio = 1 ) {
		return $this->spriteDirectory . "/" . $this->spriteFilename . ( $ratio > 1 ? $this->retinaDelimiter . $ratio . "x" : "" ) . ".png";
	}

	private function validate() {
		if ( !isset( $this->srcDirectory ) ) {
			$this->error( sprintf( self::MISSING_PROP, 'srcDirectory' ) );
		}
		if ( !isset( $this->spriteDirectory ) ) {
			$this->error( sprintf( self::MISSING_PROP, 'spriteDirectory' ) );
		}
		if ( !isset( $this->spriteFilepath ) ) {
			$this->error( sprintf( self::MISSING_PROP, 'spriteFilepath' ) );
		}
		if ( !isset( $this->spriteFilename ) ) {
			$this->error( sprintf( self::MISSING_PROP, 'spriteFilename' ) );
		}
	}

	private function error( $msg ) {
		throw new Exception( $msg );
	}

	/** error messages **/
	const INVALID_CONFIG = "Spriter: invalid initialization. Please check the documentation.";
	const MISSING_PROP = "Spriter: missing mandatory property \"%s\"";
}


text:
import { NestedOptionHost } from '../../core/nested-option';
import { DxoAnimationConfig } from './base/animation-config';
export declare class DxoAnimationComponent extends DxoAnimationConfig {
    protected readonly _optionPath: string;
    constructor(parentOptionHost: NestedOptionHost, optionHost: NestedOptionHost);
}
export declare class DxoAnimationModule {
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace IronVelocity.Compilation.AST
{
    public class InterpolatedStringExpression : VelocityExpression
    {
        public IImmutableList<Expression> Parts { get; set; }

        public override Type Type => typeof(string);
        public override VelocityExpressionType VelocityExpressionType => VelocityExpressionType.InterpolatedString;

        public InterpolatedStringExpression(IImmutableList<Expression> parts)
        {
            Parts = parts;
        }

        public override Expression Reduce()
        {
            if (Parts.Count == 0)
                return Expression.Constant(string.Empty);
            if (Parts.Count == 1)
            {
                var element = Parts[0];
                if (element.Type != typeof(void))
                {
                    Expression nullValue = null;
                    var reference = element as ReferenceExpression;
                    if (reference != null && !reference.IsSilent)
                        nullValue = Expression.Constant(reference.Raw);

                    if (element.Type == typeof(string))
                        return element;

                    var toStringExpr = Expression.Call(element, MethodHelpers.ToStringMethodInfo);

                    if (!TypeHelper.IsNullableType(element.Type))
                        return toStringExpr;

                    return Expression.Condition(
                        Expression.Equal(element, Expression.Default(element.Type))
                        , nullValue ?? Expression.Constant(string.Empty)
                        , toStringExpr);
                }
            }
            //If we don't have any void expressions (i.e. Macros), use String.Concat as it produces less IL and so JIT compiles faster
            //TODO: This optimisation doesn't work as it fails with unsilenced null references.
            /*
            else if (Parts.All(x => x.Type != typeof(void) ))
            {
                var objParts = Parts.Select(x => VelocityExpressions.ConvertIfNeeded(x, typeof(object)));
                return Expression.Call(_stringConcatMethodInfo, Expression.NewArrayInit(typeof(object),objParts));

            }*/

            //Create a new scope, in which the Output parameter points to a different StringBuilder
            //So we can get the result, without writing it to the output stream.
            var outputParam = Constants.OutputParameter;
            var stringWriter = Expression.Parameter(typeof(StringWriter), "interpolatedStringWriter");

            return new TemporaryVariableScopeExpression(
                stringWriter,
                    new TemporaryVariableScopeExpression(
                        outputParam,
                        Expression.Block(
                            Expression.Assign(stringWriter, Expression.New(stringWriter.Type)),
                            Expression.Assign(outputParam, Expression.New(MethodHelpers.OutputConstructor, stringWriter)),
                            new RenderedBlock(Parts),
                            Expression.Call(stringWriter, MethodHelpers.ToStringMethodInfo)
                        )
                    )
                );
        }

        public InterpolatedStringExpression Update(ImmutableList<Expression> parts)
        {
            return parts == Parts
                ? this
                : new InterpolatedStringExpression(parts);
        }
    }
}


text:
<?php

declare (strict_types=1);
namespace Ssch\TYPO3Rector\Rector\v10\v0;

use PhpParser\Node;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\PropertyFetch;
use PHPStan\Type\ObjectType;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Ssch\TYPO3Rector\Helper\Typo3NodeResolver;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
 * @changelog https://docs.typo3.org/c/typo3/cms-core/master/en-us/Changelog/10.0/Deprecation-88559-TSFE-sys_language_isocode.html
 * @see \Ssch\TYPO3Rector\Tests\Rector\v10\v0\UseTwoLetterIsoCodeFromSiteLanguageRector\UseTwoLetterIsoCodeFromSiteLanguageRectorTest
 */
final class UseTwoLetterIsoCodeFromSiteLanguageRector extends \Rector\Core\Rector\AbstractRector
{
    /**
     * @var \Ssch\TYPO3Rector\Helper\Typo3NodeResolver
     */
    private $typo3NodeResolver;
    public function __construct(\Ssch\TYPO3Rector\Helper\Typo3NodeResolver $typo3NodeResolver)
    {
        $this->typo3NodeResolver = $typo3NodeResolver;
    }
    /**
     * @return array<class-string<Node>>
     */
    public function getNodeTypes() : array
    {
        return [\PhpParser\Node\Expr\PropertyFetch::class];
    }
    /**
     * @param PropertyFetch $node
     */
    public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
    {
        if (!$this->isObjectType($node, new \PHPStan\Type\ObjectType('TYPO3\\CMS\\Frontend\\Controller\\TypoScriptFrontendController')) && !$this->typo3NodeResolver->isPropertyFetchOnAnyPropertyOfGlobals($node, \Ssch\TYPO3Rector\Helper\Typo3NodeResolver::TYPO_SCRIPT_FRONTEND_CONTROLLER)) {
            return null;
        }
        if (!$this->isName($node->name, 'sys_language_isocode')) {
            return null;
        }
        $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE);
        // Check if we have an assigment to the property, if so do not change it
        if ($parentNode instanceof \PhpParser\Node\Expr\Assign && $parentNode->var instanceof \PhpParser\Node\Expr\PropertyFetch) {
            return null;
        }
        return $this->nodeFactory->createMethodCall($this->nodeFactory->createMethodCall($node->var, 'getLanguage'), 'getTwoLetterIsoCode');
    }
    /**
     * @codeCoverageIgnore
     */
    public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
    {
        return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('The usage of the propery sys_language_isocode is deprecated. Use method getTwoLetterIsoCode of SiteLanguage', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE'
if ($GLOBALS['TSFE']->sys_language_isocode) {
    $GLOBALS['LANG']->init($GLOBALS['TSFE']->sys_language_isocode);
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
if ($GLOBALS['TSFE']->getLanguage()->getTwoLetterIsoCode()) {
    $GLOBALS['LANG']->init($GLOBALS['TSFE']->getLanguage()->getTwoLetterIsoCode());
}
CODE_SAMPLE
)]);
    }
}


text:
'''
Tests the data i/o functions and package.

.. moduleauthor:: Chris Fournier <chris.m.fournier@gmail.com>
'''
from __future__ import absolute_import
import os
import unittest
from segeval.data import Dataset, load_nested_folders_dict, FILETYPE_JSON, DataIOError
from segeval.data.samples import (HEARST_1997_STARGAZER, COMPLETE_AGREEMENT,
                                  LARGE_DISAGREEMENT)

class TestDataset(unittest.TestCase):

    '''
    Test data i/o functions and package.
    '''

    def test_dataset(self):
        '''
        Test dataset property creation and independence.
        '''
        prop = 'test'
        dataset_a = Dataset()
        dataset_a.properties[prop] = False
        dataset_b = Dataset()
        self.assertFalse(prop in dataset_b.properties)

    def test_add(self):
        '''
        Test ``Dataset.add()``.
        '''
        # Output complete and large disagreement, then merge
        self.assertEqual(set(['an5', 'an6']), LARGE_DISAGREEMENT.coders)
        large_disagreement = LARGE_DISAGREEMENT.copy()
        self.assertEqual(set(['an5', 'an6']), large_disagreement.coders)
        large_disagreement += COMPLETE_AGREEMENT
        self.assertEqual(6, len(large_disagreement.coders))
        self.assertEqual(4, len(large_disagreement))
        self.assertEqual(6, len(large_disagreement['item1']))

    def test_coders(self):
        '''
        Test ``Dataset.add()``.
        '''
        self.assertEqual(
            set(['an4', 'an1', 'an2', 'an3']), COMPLETE_AGREEMENT.coders)

    def test_dataset_property(self):
        '''
        Test dataset property creation and independence.
        '''
        prop = 'test'
        dataset = Dataset(properties={prop: True})
        self.assertTrue(prop in dataset.properties)
        self.assertTrue(dataset.properties[prop])

    def test_add_coders(self):
        '''
        Test dataset property creation and independence.
        '''
        dataset_a = Dataset({'item1': {'a': [2]}})
        dataset_b = Dataset({'item1': {'b': [2]}})
        dataset_c = Dataset({'item1': {'a': [2], 'b': [2]}})

        self.assertNotEqual(dataset_a, dataset_b)
        self.assertEqual(dataset_a + dataset_b, dataset_c)
        self.assertNotEqual(dataset_a, dataset_b)
        self.assertNotEqual(dataset_a, dataset_c)
        self.assertNotEqual(dataset_b, dataset_c)

    def test_add_codings(self):
        '''
        Test dataset property creation and independence.
        '''
        dataset_a = Dataset({'item1': {'a': [2]}})
        dataset_b = Dataset({'item2': {'a': [2]}})
        dataset_c = Dataset({'item1': {'a': [2]},
                             'item2': {'a': [2]}})

        self.assertNotEqual(dataset_a, dataset_b)
        self.assertEqual(dataset_a + dataset_b, dataset_c)
        self.assertNotEqual(dataset_a, dataset_b)
        self.assertNotEqual(dataset_a, dataset_c)
        self.assertNotEqual(dataset_b, dataset_c)

    def test_add_duplicate_codings(self):
        '''
        Test dataset property creation and independence.
        '''
        dataset_a = Dataset({'item1': {'a': [2]}})
        dataset_b = Dataset({'item1': {'a': [2]}})
        exception = False
        try:
            dataset_a + dataset_b
        except DataIOError:
            exception = True
        self.assertTrue(exception, 'Did not throw DataIOError')

class TestUtils(unittest.TestCase):

    '''
    Test data merge functions.
    '''

    test_data_dir = os.path.split(__file__)[0]

    def test_load_nested_folders_dict(self):
        '''
        Test nested folder dict construction.
        '''
        data_dir = os.path.abspath(os.path.join(self.test_data_dir, '../'))
        dataset = load_nested_folders_dict(data_dir, FILETYPE_JSON)
        self.assertEqual(dataset['data,stargazer'],
                         HEARST_1997_STARGAZER['stargazer'])


text:
package com.ECS.client.jax;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b14140
 * Generated source version: 2.2
 *
 */
@WebService(name = "AWSECommerceServicePortType", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@XmlSeeAlso({
    ObjectFactory.class
})
public interface AWSECommerceServicePortType {

    /**
     *
     * @param body
     * @return
     *     returns com.ECS.client.jax.ItemSearchResponse
     */
    @WebMethod(operationName = "ItemSearch", action = "http://soap.amazon.com/ItemSearch")
    @WebResult(name = "ItemSearchResponse", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
    public ItemSearchResponse itemSearch(
        @WebParam(name = "ItemSearch", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
        ItemSearch body);

    /**
     *
     * @param body
     * @return
     *     returns com.ECS.client.jax.ItemLookupResponse
     */
    @WebMethod(operationName = "ItemLookup", action = "http://soap.amazon.com/ItemLookup")
    @WebResult(name = "ItemLookupResponse", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
    public ItemLookupResponse itemLookup(
        @WebParam(name = "ItemLookup", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
        ItemLookup body);

    /**
     *
     * @param body
     * @return
     *     returns com.ECS.client.jax.BrowseNodeLookupResponse
     */
    @WebMethod(operationName = "BrowseNodeLookup", action = "http://soap.amazon.com/BrowseNodeLookup")
    @WebResult(name = "BrowseNodeLookupResponse", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
    public BrowseNodeLookupResponse browseNodeLookup(
        @WebParam(name = "BrowseNodeLookup", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
        BrowseNodeLookup body);

    /**
     *
     * @param body
     * @return
     *     returns com.ECS.client.jax.SimilarityLookupResponse
     */
    @WebMethod(operationName = "SimilarityLookup", action = "http://soap.amazon.com/SimilarityLookup")
    @WebResult(name = "SimilarityLookupResponse", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
    public SimilarityLookupResponse similarityLookup(
        @WebParam(name = "SimilarityLookup", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
        SimilarityLookup body);

    /**
     *
     * @param body
     * @return
     *     returns com.ECS.client.jax.CartGetResponse
     */
    @WebMethod(operationName = "CartGet", action = "http://soap.amazon.com/CartGet")
    @WebResult(name = "CartGetResponse", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
    public CartGetResponse cartGet(
        @WebParam(name = "CartGet", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
        CartGet body);

    /**
     *
     * @param body
     * @return
     *     returns com.ECS.client.jax.CartCreateResponse
     */
    @WebMethod(operationName = "CartCreate", action = "http://soap.amazon.com/CartCreate")
    @WebResult(name = "CartCreateResponse", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
    public CartCreateResponse cartCreate(
        @WebParam(name = "CartCreate", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
        CartCreate body);

    /**
     *
     * @param body
     * @return
     *     returns com.ECS.client.jax.CartAddResponse
     */
    @WebMethod(operationName = "CartAdd", action = "http://soap.amazon.com/CartAdd")
    @WebResult(name = "CartAddResponse", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
    public CartAddResponse cartAdd(
        @WebParam(name = "CartAdd", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
        CartAdd body);

    /**
     *
     * @param body
     * @return
     *     returns com.ECS.client.jax.CartModifyResponse
     */
    @WebMethod(operationName = "CartModify", action = "http://soap.amazon.com/CartModify")
    @WebResult(name = "CartModifyResponse", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
    public CartModifyResponse cartModify(
        @WebParam(name = "CartModify", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
        CartModify body);

    /**
     *
     * @param body
     * @return
     *     returns com.ECS.client.jax.CartClearResponse
     */
    @WebMethod(operationName = "CartClear", action = "http://soap.amazon.com/CartClear")
    @WebResult(name = "CartClearResponse", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
    public CartClearResponse cartClear(
        @WebParam(name = "CartClear", targetNamespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", partName = "body")
        CartClear body);

}


text:
using Microsoft.AspNetCore.Mvc;

namespace BrillionCore.UI.Site.Components
{
	[ViewComponent(Name = "Navigation")]
	public class NavigationViewComponent : ViewComponent
	{
		public IViewComponentResult Invoke()
		{
			return View(viewName: "NavigationViewComponent");
		}
	}
}


text:
describe("Follwers", function(){
	var scope, controller, templateCache, location;
	beforeEach( module("puzzle.followers", "followers/followers.tpl.html") );
	beforeEach(inject(function($rootScope, $controller, $templateCache, $location){
		scope = $rootScope.$new();
		controller = $controller;
		templateCache = $templateCache;
		location = $location;
	}));

	it("should accept the follwers twitter handle", inject(function($state){
		expect(function(){
			$state.transitionTo('followers', {handle: 'testHandle'});
		}).not.toThrow();
		scope.$apply();
		expect($state.current.controller).toBe("FollowersController");
	}));
	describe("fetch followers", function(){
		var response, handle, url;
		beforeEach(function(){
			response = ['firefox','chrome'];
			handle = 'twitter';
			url = "/" + handle + "/followers";
		});
		it("should fetch the followers", inject(function(followersFactory, $httpBackend){
			$httpBackend.expectGET(url).respond(response);
			followersFactory.fetchFollowers(handle);
			$httpBackend.flush();
			var user = followersFactory.getUser();
			expect(user.name).toBe(handle);
			expect(user.followers).toBe(response);
		}));
		it("should populate user's followers details", inject(function(followersFactory, $httpBackend, $stateParams){
			expect(scope.user).toBeUndefined();
			$httpBackend.expectGET(url).respond(response);
			$stateParams.handle = handle;
			var followersController = controller("FollowersController", {$scope: scope, $stateParams: $stateParams});
			$httpBackend.flush();
			expect(scope.user.name).toBe(handle);
			expect(scope.user.followers).toBe(response);
		}));
	});
	describe("show followers", function(){
		var compile;
		beforeEach(inject(function($compile){
			compile = $compile;
		}));
		it("should show followers details", function(){
			scope.user = {
				name: 'twitter',
				followers: ['firefox', 'chrome']
			};
			var template = templateCache.get('followers/followers.tpl.html');
			var element = compile(template)(scope);
			scope.$apply();
			expect(element.html()).toContain(scope.user.name);
			expect(element.html()).toContain(scope.user.followers[0]);
		});
		it("should show option to change twitter handle", function(){
			var template = "<select-handle></select-handle>";
			var html = (compile(template)(scope)).html();
			expect(html).toContain("input");
		});
		it("should change the twitter handle on click of the button", inject(function($state){
			var template = "<select-handle></select-handle>";
			var element = (compile(template)(scope));
			element.scope().handle = "firefox";
			scope.$apply();
			spyOn($state, 'transitionTo');
			element.find("button").triggerHandler("click");
			expect($state.transitionTo).toHaveBeenCalled();
		}));
	});

})
;


text: to jest przykładowy tekst


text:
const userProjects = {
  // filter projects to remove user if blocked, and deletes unwanted fields
  filterProjects: (user, projects, returnFields) => {
    const filteredProjects = projects;
    // site admins cannot be blocked at all
    // lab admins cannot be blocked from their own labs project
    const canBlock = (currUser, item) => {
      if (currUser.privilege === 'siteAdmin') {
        return false;
      } else if (
        currUser.privilege === 'labAdmin' &&
        currUser.lab === item.lab
      ) {
        return false;
      }
      return true;
    };

    // remove project if user does not have permission
    filteredProjects.forEach((project, index) => {
      const userExclude = project.userPermission.findIndex((specialUser) => {
        return (
          specialUser.email === user.email &&
          specialUser.permission === 'n'
        );
      });
      if (
        userExclude > -1 &&
        canBlock(user, project.userPermission[userExclude])
      ) {
        filteredProjects.splice(index, 1);
      }
    });
    // format projects to only return desired fields
    return filteredProjects.map((project) => {
      const newProject = project;
      Object.keys(newProject).forEach((key) => {
        if (
          returnFields &&
          !returnFields.project.includes(key)
        ) {
          delete newProject[key];
        }
      });
      return newProject;
    });
  },
  // project query object
  query: (user) => {
    let queryObj = {};
    if (user.privilege === 'siteAdmin') {
      queryObj = {};
    } else if (user.privilege === 'labAdmin') {
      queryObj = {
        $or: [
          { creatorEmail: user.email }, // created the project
          { // project is in the same lab
            $and: [
              { lab: user.lab },
            ],
          },
          { // anyone can view this project
            $and: [
              { permission: { $in: ['ar', 'aw'] } },
            ],
          },
          { // user has been explicitly added
            userPermission: { $elemMatch: { email: user.email, permission: { $ne: 'n' } } },
          },
        ],
      };
    } else {
      queryObj = {
        $or: [
          { creatorEmail: user.email }, // created the project
          { // project is in the same lab
            $and: [
              { lab: user.lab },
              { permission: { $in: ['lr', 'lw'] } },
            ],
          },
          { // anyone can view this project
            $and: [
              { permission: { $in: ['ar', 'aw'] } },
            ],
          },
          { // user has been explicitly added
            userPermission: { $elemMatch: { email: user.email, permission: { $ne: 'n' } } },
          },
        ],
      };
    }
    const returnObj = {};
    return { queryObj, returnObj };
  },
};
module.exports = userProjects;


text:
/* @flow */
import Box from '../../common/DemoBox';
import responsiveInstructions from '../../common/responsiveInstructions';

export default {
  id: 'responsive',
  title: 'Responsive',
  description: `Many of the properties for Box can be responsive:

${responsiveInstructions}

The code in the example below exhibits the following behavior:

1. When the viewport is less than 800px wide, it will have a right margin of
50px.
1. When the viewport is between 800px and 1024px (the 'wide' breakpoint theme
variable), it will have a right margin of 100px.
1. When the viewport is at least 1024px wide, it will have a right margin of
150px.`,
  scope: { Box },
  source: `
    <Box
      breakpoints={[800, 'wide']}
      marginRight={[50, 100, 150]}>
      A
    </Box>`
};


text:
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.IO.Json;
using Neo.Network.RPC.Models;
using System.Numerics;

namespace Neo.UnitTests.Network.RPC.Models
{
    [TestClass]
    public class UT_RpcNep5Balance
    {
        private RpcNep5Balance balance;

        [TestInitialize]
        public void Setup()
        {
            balance = new RpcNep5Balance();
        }

        [TestMethod]
        public void TestAssetHash()
        {
            balance.AssetHash = UInt160.Zero;
            balance.AssetHash.Should().Be(UInt160.Zero);
        }

        [TestMethod]
        public void TestAmount()
        {
            balance.Amount = BigInteger.Zero;
            balance.Amount.Should().Be(BigInteger.Zero);
        }

        [TestMethod]
        public void TestLastUpdatedBlock()
        {
            balance.LastUpdatedBlock = 0;
            balance.LastUpdatedBlock.Should().Be(0);
        }

        [TestMethod]
        public void TestToJson()
        {
            balance.AssetHash = UInt160.Zero;
            balance.Amount = BigInteger.Zero;
            balance.LastUpdatedBlock = 0;
            var json = balance.ToJson();
            json["asset_hash"].AsString().Should().Be("0x0000000000000000000000000000000000000000");
            json["amount"].AsNumber().Should().Be(0);
            json["last_updated_block"].AsNumber().Should().Be(0);
        }

        [TestMethod]
        public void TestFromJson()
        {
            var json = new JObject();
            json["asset_hash"] = "0x0000000000000000000000000000000000000000";
            json["amount"] = "0";
            json["last_updated_block"] = "0";
            var rpcNep5Balance = RpcNep5Balance.FromJson(json);
            rpcNep5Balance.AssetHash.Should().Be(UInt160.Zero);
            rpcNep5Balance.Amount.Should().Be(BigInteger.Zero);
            rpcNep5Balance.LastUpdatedBlock.Should().Be(0);
        }
    }
}


text:
using System.Dynamic;
using System.Web.Mvc;

namespace Spark.Web.Mvc
{
	public class DynamicViewDataDictionary : DynamicObject
	{
		private readonly ViewDataDictionary _viewData;

		public DynamicViewDataDictionary( ViewDataDictionary viewData )
		{
			_viewData = viewData;
		}

		public override bool TryGetMember( GetMemberBinder binder, out object result )
		{
			result = _viewData[binder.Name];
			return true;
		}

		public override bool TrySetMember( SetMemberBinder binder, object value )
		{
			_viewData[binder.Name] = value;
			return true;
		}
	}
}


text:
<?php
namespace Vda\Query;

use Vda\Util\Type;

class SourceAlias extends Alias implements ISource
{
    public function __construct(Select $select, $alias)
    {
        parent::__construct($select, $alias);
    }

    public function getFields()
    {
        $result = array();

        return array_map(array($this, 'convertExpression'), $this->getExpression()->getFields());
    }

    public function getField($name)
    {
        return $this->convertExpression($this->getExpression()->getField($name));
    }

    public function getName()
    {
        return $this->getAlias();
    }

    private function convertExpression($f)
    {
        if ($f instanceof Alias) {
            return new Field(Type::DYNAMIC, $f->getAlias(), $f->getAlias(), $this);
        } elseif ($f instanceof Field) {
            return new Field($f->getType(), $f->getName(), $f->getPropertyName(), $this);
        }

        //TODO throw an UnexpectedValueException here?
        return new Field(Type::DYNAMIC, null, null, $this);
    }
}


text:
require 'spec_helper'

describe Update do
  describe "validations" do
    it{ should validate_presence_of :project_id }
    it{ should validate_presence_of :user_id }
    it{ should validate_presence_of :comment }
    it{ should validate_presence_of :comment_html }
  end

  describe "associations" do
    it{ should belong_to :user }
    it{ should belong_to :project }
  end

  describe ".visible_to" do
    let(:project) { create(:project) }
    let(:user) {}

    before do
      @exclusive_update = create(:update, exclusive: true, project: project)
      @update = create(:update, project: project)
    end

    subject { Update.visible_to(user) }

    context "when user is a contribution" do
      let(:user) { create(:contribution, state: 'confirmed', project: project).user }

      it { should have(2).itens }
    end

    context "when user is not a contribution" do
      let(:user) { create(:contribution, state: 'pending', project: project).user }

      it { should eq([@update]) }
    end

    context "when user is a project owner" do
      let(:user) { project.user }

      it { should have(2).itens }
    end

    context "when user is an admin" do
      let(:user) { create(:user, admin: true) }

      it { should have(2).itens }
    end

    context "when user is a guest" do
      it { should eq([@update]) }
    end
  end

  describe ".create" do
    subject{ create(:update, comment: "this is a comment\n") }
    its(:comment_html){ should == "
this is a comment
" }
  end

  describe "#email_comment_html" do
    subject{ create(:update, comment: "this is a comment\nhttp://vimeo.com/6944344\nhttp://catarse.me/assets/catarse/logo164x54.png").email_comment_html }
    it{ should == "
this is a comment
\nhttp://vimeo.com/6944344
\n
" }
  end

  describe "#update_number" do
    let(:project){ create(:project) }
    let(:update){ create(:update, project: project) }
    subject{ update.update_number }
    before do
      create(:update, project: project)
      update
      create(:update, project: project)
    end
    it{ should == 2 }
  end

  describe "#notify_contributors" do
    before do
      Notification.unstub(:notify)
      Notification.unstub(:notify_once)
      @project = create(:project)
      contribution = create(:contribution, state: 'confirmed', project: @project)
      create(:contribution, state: 'confirmed', project: @project, user: contribution.user)
      @project.reload
      ActionMailer::Base.deliveries = []
      @update = Update.create!(user: @project.user, project: @project, title: "title", comment: "this is a comment\nhttp://vimeo.com/6944344\nhttp://catarse.me/assets/catarse/logo164x54.png")
      Notification.should_receive(:notify_once).with(
        :updates,
        contribution.user,
        {update_id: @update.id, user_id: contribution.user.id},
        {
          project: @update.project,
          project_update: @update,
          origin_email: @update.project.user.email,
          origin_name: @update.project.user.display_name
        }
      ).once.and_call_original
    end

    it 'should call Notification.notify once' do
      @update.notify_contributors
    end
  end
end


text:
package org.apereo.portal.portlet.om;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apereo.portal.IBasicEntity;
import org.apereo.portal.io.xml.IPortalData;

/** A portlet definition is equivalent to a published ChannelDefinition. */
public interface IPortletDefinition extends IBasicEntity, IPortalData {

    String EDITABLE_PARAM = "editable";
    String CONFIGURABLE_PARAM = "configurable";
    String HAS_HELP_PARAM = "hasHelp";
    String HAS_ABOUT_PARAM = "hasAbout";

    String DISTINGUISHED_GROUP = IPortletDefinition.class.getName();

    /**
     * The name of the portlet parameter that if present represents an alternative URL that ought to
     * be used to "maximize" the defined portlet.
     *
     *
This is useful for portlets that when maximized ought to instead be the external URL or
     * web application that they're representing in the portal.
     */
    String ALT_MAX_LINK_PARAM = "alternativeMaximizedLink";

    /** A portlet parameter that specifies a target for the flyout, eg : _blank */
    String TARGET_PARAM = "target";

    /** @return The unique identifier for this portlet definition. */
    IPortletDefinitionId getPortletDefinitionId();

    /** @return The List of PortletPreferences, will not be null */
    List<IPortletPreference> getPortletPreferences();

    /**
     * @param portletPreferences The List of PortletPreferences, null clears the preferences but
     *     actually sets an empty list
     * @return true if the portlet preferences changed
     */
    boolean setPortletPreferences(List<IPortletPreference> portletPreferences);

    PortletLifecycleState getLifecycleState();

    String getFName();

    String getName();

    String getDescription();

    IPortletDescriptorKey getPortletDescriptorKey();

    String getTitle();

    /** @return Default timeout in ms, -1 means no timeout. */
    int getTimeout();
    /**
     * @return Optional timeout for action requests in ms, if null {@link #getTimeout()} should be
     *     used, -1 means no timeout.
     */
    Integer getActionTimeout();
    /**
     * @return Optional timeout for event requests in ms, if null {@link #getTimeout()} should be
     *     used, -1 means no timeout.
     */
    Integer getEventTimeout();
    /**
     * @return Optional timeout for render requests in ms, if null {@link #getTimeout()} should be
     *     used, -1 means no timeout.
     */
    Integer getRenderTimeout();
    /**
     * @return Optional timeout for resource requests in ms, if null {@link #getTimeout()} should be
     *     used, -1 means no timeout.
     */
    Integer getResourceTimeout();

    IPortletType getType();

    int getPublisherId();

    int getApproverId();

    Date getPublishDate();

    Date getApprovalDate();

    int getExpirerId();

    Date getExpirationDate();

    /** @return a READ-ONLY copy of the parameters */
    Set<IPortletDefinitionParameter> getParameters();

    IPortletDefinitionParameter getParameter(String key);

    Map<String, IPortletDefinitionParameter> getParametersAsUnmodifiableMap();

    // I18n
    String getName(String locale);

    String getDescription(String locale);

    String getTitle(String locale);

    /**
     * Returns the alternative maximized link (URL) associated with this portlet definition, or null
     * if none.
     *
     *
Syntactic sugar for parsing potential alternative maximized link as a preferable
     * alternative to directly parsing the portlet parameters elsewhere.
     *
     * @return String representing alternative max URL, or null if none.
     * @since 4.2
     */
    String getAlternativeMaximizedLink();

    /**
     * Syntactic sugar for getting the target parameter from the portlet parameters.
     *
     * @return the target tab/window
     */
    String getTarget();

    // Setter methods
    void setFName(String fname);

    void setName(String name);

    void setDescription(String descr);

    void setTitle(String title);

    /** @param timeout The default timeout value in ms, -1 means no timeout. */
    void setTimeout(int timeout);

    /**
     * @param actionTimeout Optional timeout for action requests in ms, if null {@link
     *     #getTimeout()} will be used, -1 means no timeout.
     */
    void setActionTimeout(Integer actionTimeout);
    /**
     * @param eventTimeout Optional timeout for event requests in ms, if null {@link #getTimeout()}
     *     will be used, -1 means no timeout.
     */
    void setEventTimeout(Integer eventTimeout);
    /**
     * @param renderTimeout Optional timeout for render requests in ms, if null {@link
     *     #getTimeout()} will be used, -1 means no timeout.
     */
    void setRenderTimeout(Integer renderTimeout);
    /**
     * @param resourceTimeout Optional timeout for resource requests in ms, if null {@link
     *     #getTimeout()} will be used, -1 means no timeout.
     */
    void setResourceTimeout(Integer resourceTimeout);

    void setType(IPortletType channelType);

    void setPublisherId(int publisherId);

    void setApproverId(int approvalId);

    void setPublishDate(Date publishDate);

    void setApprovalDate(Date approvalDate);

    void setExpirerId(int expirerId);

    void setExpirationDate(Date expirationDate);

    void setParameters(Set<IPortletDefinitionParameter> parameters);

    void addLocalizedTitle(String locale, String chanTitle);

    void addLocalizedName(String locale, String chanName);

    void addLocalizedDescription(String locale, String chanDesc);

    /** @return a portlet rating */
    Double getRating();

    /** @param rating sets portlet rating */
    void setRating(Double rating);

    /** @return Number of users that rated this portlet */
    Long getUsersRated();

    /** @param usersRated sets number of users that rated this portlet */
    void setUsersRated(Long usersRated);

    /**
     * Adds a parameter to this channel definition
     *
     * @param parameter the channel parameter to add
     */
    void addParameter(IPortletDefinitionParameter parameter);

    void addParameter(String name, String value);

    /**
     * Removes a parameter from this channel definition
     *
     * @param parameter the channel parameter to remove
     */
    void removeParameter(IPortletDefinitionParameter parameter);

    /**
     * Removes a parameter from this channel definition
     *
     * @param name the parameter name
     */
    void removeParameter(String name);

    /** @return Hash code based only on the fname of the portlet definition */
    @Override
    int hashCode();

    /**
     * Equals must be able to compare against any other {@link IPortletDefinition} and the
     * comparison must only use the fname
     */
    @Override
    boolean equals(Object o);
}