text:
package org.apache.solr.search;

import java.util.Arrays;

/**
 * DocSlice implements DocList as an array of docids and optional scores.
 *
 *
 * @since solr 0.9
 */
public class DocSlice extends DocSetBase implements DocList {
  final int offset;    // starting position of the docs (zero based)
  final int len;       // number of positions used in arrays
  final int[] docs;    // a slice of documents (docs 0-100 of the query)

  final float[] scores;  // optional score list
  final int matches;
  final float maxScore;

  /**
   * Primary constructor for a DocSlice instance.
   *
   * @param offset  starting offset for this range of docs
   * @param len     length of results
   * @param docs    array of docids starting at position 0
   * @param scores  array of scores that corresponds to docs, may be null
   * @param matches total number of matches for the query
   */
  public DocSlice(int offset, int len, int[] docs, float[] scores, int matches, float maxScore) {
    this.offset=offset;
    this.len=len;
    this.docs=docs;
    this.scores=scores;
    this.matches=matches;
    this.maxScore=maxScore;
  }

  @Override
  public DocList subset(int offset, int len) {
    if (this.offset == offset && this.len==len) return this;

    // if we didn't store enough (and there was more to store)
    // then we can't take a subset.
    int requestedEnd = offset + len;
    if (requestedEnd > docs.length && this.matches > docs.length) return null;
    int realEndDoc = Math.min(requestedEnd, docs.length);
    int realLen = Math.max(realEndDoc-offset,0);
    if (this.offset == offset && this.len == realLen) return this;
    return new DocSlice(offset, realLen, docs, scores, matches, maxScore);
  }

  @Override
  public boolean hasScores() {
    return scores!=null;
  }

  @Override
  public float maxScore() {
    return maxScore;
  }

  @Override
  public int offset()  { return offset; }
  @Override
  public int size()    { return len; }
  @Override
  public int matches() { return matches; }

  @Override
  public long memSize() {
    return (docs.length<<2)
            + (scores==null ? 0 : (scores.length<<2))
            + 24;
  }

  @Override
  public boolean exists(int doc) {
    int end = offset+len;
    for (int i=offset; i<end; i++) {
      if (docs[i]==doc) return true;
    }
    return false;
  }

  // Hmmm, maybe I could have reused the scorer interface here...
  // except that it carries Similarity baggage...
  @Override
  public DocIterator iterator() {
    return new DocIterator() {
      int pos=offset;
      final int end=offset+len;
      @Override
      public boolean hasNext() {
        return pos < end;
      }

      @Override
      public Integer next() {
        return nextDoc();
      }

      /**
       * The remove  operation is not supported by this Iterator.
       */
      @Override
      public void remove() {
        throw new UnsupportedOperationException("The remove  operation is not supported by this Iterator.");
      }

      @Override
      public int nextDoc() {
        return docs[pos++];
      }

      @Override
      public float score() {
        return scores[pos-1];
      }
    };
  }

  @Override
  public DocSet intersection(DocSet other) {
    if (other instanceof SortedIntDocSet || other instanceof HashDocSet) {
      return other.intersection(this);
    }
    HashDocSet h = new HashDocSet(docs,offset,len);
    return h.intersection(other);
  }

  @Override
  public int intersectionSize(DocSet other) {
    if (other instanceof SortedIntDocSet || other instanceof HashDocSet) {
      return other.intersectionSize(this);
    }
    HashDocSet h = new HashDocSet(docs,offset,len);
    return h.intersectionSize(other);
  }

  @Override
  public boolean intersects(DocSet other) {
    if (other instanceof SortedIntDocSet || other instanceof HashDocSet) {
      return other.intersects(this);
    }
    HashDocSet h = new HashDocSet(docs,offset,len);
    return h.intersects(other);
  }

  @Override
  protected DocSlice clone() {
    try {
      // DocSlice is not currently mutable
      DocSlice slice = (DocSlice) super.clone();
    } catch (CloneNotSupportedException e) {}
    return null;
  }
}


text:
package com.cw.jerrbase.util;

import android.app.Activity;
import android.app.Fragment;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.cw.jerrbase.BaseApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @version V1.0
 * @ClassName: ${CLASS_NAME}
 * @Description: (图片工具类)
 * @create by: chenwei
 * @date 2016/7/26 9:34
 */
public class ImageUtil {

    /**
     * 压缩图片的临时存放路径
     */
    public static final String tempPath = getImageCacheFile().getAbsolutePath() + "/" + "temp.png";

    /**
     * 应用缓存根目录
     */
    private static final String APP_CACHE_DIR = "cache";
    /**
     * 图片缓存目录
     */
    private static final String IMAGE_CACHE_DIR = "image";
    /**
     * 图片缓存目录
     */
    private static final String VIDEO_CACHE_DIR = "video";
    /**
     * 文件缓存目录
     */
    private static final String FILE_CACHE_DIR = "file";
    /**
     * 异常信息目录
     */
    private static final String CRASH_CACHE_DIR = "crash";

    /**
     * 获取图片缓存路径
     *
     * @param imageName 图片名
     * @return 图片路径
     */
    public static String getImageCachPath(String imageName) {
        return getImageCacheFile().getAbsolutePath() + "/" + imageName + ".png";
    }

    /**
     * 获取视频缓存路径
     *
     * @return
     */
    public static String getVideoCachePath() {
        return getVideoCacheFile().getAbsolutePath();
    }

    /**
     * 获取异常信息路径
     *
     * @param logName 文件名
     * @return log文件
     */
    public static String getCrashPath(String logName) {
        return getCrashFile().getAbsolutePath() + "/crash" + logName + ".txt";
    }

    /**
     * 获取图片缓存目录
     *
     * @return File
     */
    public static File getImageCacheFile() {
        File result = null;
        if (getCacheRootFile() != null) {
            result = new File(
                    getCacheRootFile().getAbsoluteFile() + "/" + APP_CACHE_DIR + "/" + IMAGE_CACHE_DIR);
        } else {
            result = BaseApplication.getInstance().getFilesDir();
        }
        if (!result.exists())
            result.mkdirs();
        return result;
    }

    /**
     * 获取视频缓存目录
     * @return
     */
    public static File getVideoCacheFile() {
        File result = null;
        if (getCacheRootFile() != null) {
            result = new File(
                    getCacheRootFile().getAbsoluteFile() + "/" + APP_CACHE_DIR + "/" + VIDEO_CACHE_DIR);
        } else {
            result = BaseApplication.getInstance().getFilesDir();
        }
        if (!result.exists())
            result.mkdirs();
        return result;
    }

    /**
     * 获取文件缓存目录
     *
     * @return File
     */
    public static File getFileCacheFile() {
        File result = null;
        if (getCacheRootFile() != null) {
            result = new File(
                    getCacheRootFile().getAbsoluteFile() + "/" + APP_CACHE_DIR + "/" + FILE_CACHE_DIR);
        } else {
            result = BaseApplication.getInstance().getFilesDir();
        }
        if (!result.exists())
            result.mkdirs();
        return result;
    }

    /**
     * 获取异常信息目录
     *
     * @return File
     */
    public static File getCrashFile() {
        File result = null;
        if (getCacheRootFile() != null) {
            result = new File(
                    getCacheRootFile().getAbsoluteFile() + "/" + APP_CACHE_DIR + "/" + CRASH_CACHE_DIR);
        } else {
            result = BaseApplication.getInstance().getFilesDir();
        }
        if (!result.exists())
            result.mkdirs();
        return result;
    }

    /**
     * 获取缓存根目录 有SDcard放在/mnt/sdcard/Android目录下
     * <p/>
     * 没有sdcard 放在 data/data/packagename/file 目录下
     *
     * @return
     */
    public static File getCacheRootFile() {
        File result = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// SD卡已经挂载
            result = BaseApplication.getInstance().getExternalFilesDir(null);
        } else {
            result = BaseApplication.getInstance().getFilesDir();
        }
        return result;
    }

    /**
     * 压缩图片
     *
     * @param filePath   原图片路径
     * @param targetPath 目标图片路径
     * @param quality    质量
     * @return
     */
    public static String compressImage(String filePath, String targetPath, int quality) {
        Bitmap bm = getSmallBitmap(filePath);//获取一定尺寸的图片
        int degree = readPictureDegree(filePath);//获取相片拍摄角度
        if (degree != 0) {//旋转照片角度,防止头像横着显示
            bm = rotateBitmap(bm, degree);
        }
        File outputFile = new File(targetPath);
        try {
            if (!outputFile.exists()) {
                outputFile.getParentFile().mkdirs();
                //outputFile.createNewFile();
            } else {
                outputFile.delete();
            }
            FileOutputStream out = new FileOutputStream(outputFile);
            bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
        } catch (Exception e) {
        }
        return outputFile.getPath();
    }

    /**
     * 根据路径获得图片信息并按比例压缩,返回bitmap
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只解析图片边沿,获取宽高
        BitmapFactory.decodeFile(filePath, options);
        // 计算缩放比
        options.inSampleSize = calculateInSampleSize(options, 800, 800);
        // 完整解析图片返回bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    /**
     * 获取照片角度
     *
     * @param path
     * @return
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转照片
     *
     * @param bitmap
     * @param degress
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

    /**
     * 获取手机中uri的真实路径(选取手机相册返回的uri统一经过此方法获得图片路径)
     *
     * @param context The context.
     * @param uri     The Uri to query.
     * @author paulburke
     */
    public static String getPathFromUri(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * 清除用户上传图片时保存的临时文件
     */
    public static void clearTempImage() {
        if (getImageCacheFile().exists())
            deleteAllFiles(getImageCacheFile());
    }

    /**
     * 删除指定目录下的所有文件
     *
     * @param root
     */
    public static void deleteAllFiles(File root) {
        File files[] = root.listFiles();
        if (files != null)
            for (File f : files) {
                if (f.isDirectory()) { // 判断是否为文件夹
                    deleteAllFiles(f);
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                } else {
                    if (f.exists()) { // 判断是否存在
                        deleteAllFiles(f);
                        try {
                            f.delete();
                        } catch (Exception e) {
                        }
                    }
                }
            }
    }

    /**
     * 打开照相机(Activity)
     *
     * @param mContext      activity
     * @param cameraImgPath 拍照存储路径
     * @param requestCode   请求码
     */
    public static void openCameraActivity(Activity mContext, String cameraImgPath, int requestCode) {
        Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri picUri = Uri.fromFile(new File(cameraImgPath));
        photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
        mContext.startActivityForResult(photoIntent, requestCode);
    }

    /**
     * 打开照相机(Fragment)
     *
     * @param mContext      fragment
     * @param cameraImgPath 拍照存储路径
     * @param requestCode   请求码
     */
    public static void openCameraFragment(Fragment mContext, String cameraImgPath, int requestCode) {
        Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri picUri = Uri.fromFile(new File(cameraImgPath));
        photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
        mContext.startActivityForResult(photoIntent, requestCode);
    }

    /**
     * 打开相册(Activity)
     *
     * @param mContext    activity
     * @param requestCode 请求码
     */
    public static void openAlbumActivity(Activity mContext, int requestCode) {
        Intent iconIntent = new Intent(Intent.ACTION_GET_CONTENT);
        iconIntent.addCategory(Intent.CATEGORY_OPENABLE);
        iconIntent.setType("image/*");
        String[] mimeTypes = {"image/jpg", "image/jpeg", "image/png"};
        iconIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        mContext.startActivityForResult(iconIntent, requestCode);
    }

    /**
     * 打开相册(Fragment)
     *
     * @param mContext    fragment
     * @param requestCode 请求码
     */
    public static void openAlbumFragment(Fragment mContext, int requestCode) {
        Intent iconIntent = new Intent(Intent.ACTION_GET_CONTENT);
        iconIntent.addCategory(Intent.CATEGORY_OPENABLE);
        iconIntent.setType("image/*");
        mContext.startActivityForResult(iconIntent, requestCode);
    }
}

redpajama_set_name: RedPajamaGithub


text:
export RED='\x1b[0;31m'
export GREEN='\x1b[38;5;22m'
export CYAN='\x1b[36m'
export YELLOW='\x1b[33m'
export NO_COLOR='\x1b[0m'

if [ -z "${LOG_TITLE}" ]; then
  LOG_TITLE=''
fi
if [ -z "${LOG_LEVEL}" ]; then
  LOG_LEVEL="INFO"
fi

debug() {
  if [[ "${LOG_LEVEL}" == "DEBUG" ]]; then
    local log_title
    if [ -n "${LOG_TITLE}" ]; then
     log_title="(${LOG_TITLE})"
    else
     log_title=''
    fi
    echo -e "${GREEN}[DEBUG]${log_title} ${NO_COLOR}$1"
  fi
}

info() {
  if [[ "${LOG_LEVEL}" == "DEBUG" ]] ||\
     [[ "${LOG_LEVEL}" == "INFO" ]]; then
    local log_title
    if [ -n "${LOG_TITLE}" ]; then
     log_title="(${LOG_TITLE})"
    else
     log_title=''
    fi
    echo -e "${CYAN}[INFO] ${log_title} ${NO_COLOR}$1"
  fi
}

warn() {
  if [[ "${LOG_LEVEL}" == "DEBUG" ]] ||\
     [[ "${LOG_LEVEL}" == "INFO" ]] ||\
     [[ "${LOG_LEVEL}" == "WARN" ]]; then
    local log_title
    if [ -n "${LOG_TITLE}" ]; then
     log_title="(${LOG_TITLE})"
    else
     log_title=''
    fi
    echo -e "${YELLOW}[WARN] ${log_title} ${NO_COLOR}$1"
  fi
}

error() {
  if [[ "${LOG_LEVEL}" == "DEBUG" ]] ||\
     [[ "${LOG_LEVEL}" == "INFO" ]] ||\
     [[ "${LOG_LEVEL}" == "WARN" ]] ||\
     [[ "${LOG_LEVEL}" == "ERROR" ]]; then
    local log_title
    if [ -n "${LOG_TITLE}" ]; then
     log_title="(${LOG_TITLE})"
    else
     log_title=''
    fi
    echo -e "${RED}[ERROR]${log_title} ${NO_COLOR}$1"
  fi
}

detect_node_os()
{
  local pod="$1"

  OS=`kubectl exec -i $pod -- nsenter --mount=/proc/1/ns/mnt -- bash -c 'grep -E "^ID_LIKE=" /etc/os-release | cut -d= -f2'`
  if [[ -z "${OS}" ]]; then
    OS=`kubectl exec -i $pod -- nsenter --mount=/proc/1/ns/mnt -- bash -c 'grep -E "^ID=" /etc/os-release | cut -d= -f2'`
  fi
  echo "$OS"
}

set_packages_and_check_cmd()
{
  case $OS in
  *"debian"* | *"ubuntu"* )
    CHECK_CMD='dpkg -l | grep -w'
    PACKAGES=(nfs-common open-iscsi)
    ;;
  *"centos"* | *"fedora"* | *"rocky"* | *"ol"* )
    CHECK_CMD='rpm -q'
    PACKAGES=(nfs-utils iscsi-initiator-utils)
    ;;
  *"suse"* )
    CHECK_CMD='rpm -q'
    PACKAGES=(nfs-client open-iscsi)
    ;;
  *"arch"* )
    CHECK_CMD='pacman -Q'
    PACKAGES=(nfs-utils open-iscsi)
    ;;
  *)
    CHECK_CMD=''
    PACKAGES=()
    warn "Stop the environment check because '$OS' is not supported in the environment check script."
    exit 1
    ;;
   esac
}

check_dependencies() {
  local targets=($@)

  local allFound=true
  for ((i=0; i<${#targets[@]}; i++)); do
    local target=${targets[$i]}
    if [ "$(which $target)" == "" ]; then
      allFound=false
      error "Not found: $target"
    fi
  done
  if [ "$allFound" == "false" ]; then
    error "Please install missing dependencies."
    exit 2
  else
    info "Required dependencies are installed."
  fi
}

create_ds() {
cat <<EOF > $TEMP_DIR/environment_check.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  labels:
    app: longhorn-environment-check
  name: longhorn-environment-check
spec:
  selector:
    matchLabels:
      app: longhorn-environment-check
  template:
    metadata:
      labels:
        app: longhorn-environment-check
    spec:
      hostPID: true
      containers:
      - name: longhorn-environment-check
        image: alpine:3.12
        args: ["/bin/sh", "-c", "sleep 1000000000"]
        volumeMounts:
        - name: mountpoint
          mountPath: /tmp/longhorn-environment-check
          mountPropagation: Bidirectional
        securityContext:
          privileged: true
      volumes:
      - name: mountpoint
        hostPath:
            path: /tmp/longhorn-environment-check
EOF
  kubectl create -f $TEMP_DIR/environment_check.yaml > /dev/null
}

cleanup() {
  info "Cleaning up longhorn-environment-check pods..."
  kubectl delete -f $TEMP_DIR/environment_check.yaml > /dev/null
  rm -rf $TEMP_DIR
  info "Cleanup completed."
}

wait_ds_ready() {
  while true; do
    local ds=$(kubectl get ds/longhorn-environment-check -o json)
    local numberReady=$(echo $ds | jq .status.numberReady)
    local desiredNumberScheduled=$(echo $ds | jq .status.desiredNumberScheduled)

    if [ "$desiredNumberScheduled" == "$numberReady" ] && [ "$desiredNumberScheduled" != "0" ]; then
      info "All longhorn-environment-check pods are ready ($numberReady/$desiredNumberScheduled)."
      return
    fi

    info "Waiting for longhorn-environment-check pods to become ready ($numberReady/$desiredNumberScheduled)..."
    sleep 3
  done
}

check_mount_propagation() {
  local allSupported=true
  local pods=$(kubectl -l app=longhorn-environment-check get po -o json)

  local ds=$(kubectl get ds/longhorn-environment-check -o json)
  local desiredNumberScheduled=$(echo $ds | jq .status.desiredNumberScheduled)

  for ((i=0; i<desiredNumberScheduled; i++)); do
    local pod=$(echo $pods | jq .items[$i])
    local nodeName=$(echo $pod | jq -r .spec.nodeName)
    local mountPropagation=$(echo $pod | jq -r '.spec.containers[0].volumeMounts[] | select(.name=="mountpoint") | .mountPropagation')

    if [ "$mountPropagation" != "Bidirectional" ]; then
      allSupported=false
      error "node $nodeName: MountPropagation is disabled"
    fi
  done

  if [ "$allSupported" != "true" ]; then
    error "MountPropagation is disabled on at least one node. As a result, CSI driver and Base image cannot be supported."
    exit 1
  else
    info "MountPropagation is enabled."
  fi
}

check_package_installed() {
  local pods=$(kubectl get pods -o name | grep longhorn-environment-check)

  local allFound=true

  for pod in ${pods}; do
    OS=`detect_node_os $pod`
    if [ x"$OS" == x"" ]; then
      error "Unable to detect OS on node $node."
      exit 2
    fi

    set_packages_and_check_cmd "$OS"

    for ((i=0; i<${#PACKAGES[@]}; i++)); do
      local package=${PACKAGES[$i]}

      kubectl exec -i $pod -- nsenter --mount=/proc/1/ns/mnt -- timeout 30 bash -c "$CHECK_CMD $package" > /dev/null 2>&1
      if [ $? != 0 ]; then
        allFound=false
        node=`kubectl get ${pod} --no-headers -o=custom-columns=:.spec.nodeName`
        error "$package is not found in $node."
      fi
    done
  done

  if [ "$allFound" == "false" ]; then
    error "Please install missing packages."
    exit 2
  else
    info "Required packages are installed."
  fi
}

check_multipathd() {
  local pods=$(kubectl get pods -o name | grep longhorn-environment-check)
  local allNotFound=true

  for pod in ${pods}; do
    kubectl exec -t $pod -- nsenter --mount=/proc/1/ns/mnt -- bash -c "systemctl status --no-pager multipathd.service" > /dev/null 2>&1
    if [ $? = 0 ]; then
      allNotFound=false
      node=`kubectl get ${pod} --no-headers -o=custom-columns=:.spec.nodeName`
      warn "multipathd is running on $node."
    fi
  done

  if [ "$allNotFound" == "false" ]; then
    warn "multipathd would probably result in the Longhorn volume mount failure. Please refer to https://longhorn.io/kb/troubleshooting-volume-with-multipath for more information."
  fi
}

check_iscsid() {
  local pods=$(kubectl get pods -o name | grep longhorn-environment-check)
  local allFound=true

  for pod in ${pods}; do
    kubectl exec -t $pod -- nsenter --mount=/proc/1/ns/mnt -- bash -c "systemctl status --no-pager iscsid.service" > /dev/null 2>&1

    if [ $? != 0 ]; then
      allFound=false
      node=`kubectl get ${pod} --no-headers -o=custom-columns=:.spec.nodeName`
      error "iscsid is not running on $node."
    fi
  done

  if [ "$allFound" == "false" ]; then
    exit 2
  fi
}

DEPENDENCIES=(kubectl jq mktemp)
check_dependencies ${DEPENDENCIES[@]}

TEMP_DIR=$(mktemp -d)

trap cleanup EXIT
create_ds
wait_ds_ready
check_package_installed
check_iscsid
check_multipathd
check_mount_propagation

exit 0


text:
.btn-amazon-inversed {
  background-color: #f29e37;
  border-color: #f29e37;
  color: white; }
  .btn-amazon-inversed:hover, .btn-amazon-inversed:focus, .btn-amazon-inversed:active, .btn-amazon-inversed.active {
    background-color: transparent;
    color: #f29e37; }

.btn-delicious-inversed {
  background-color: #3271cb;
  border-color: #3271cb;
  color: white; }
  .btn-delicious-inversed:hover, .btn-delicious-inversed:focus, .btn-delicious-inversed:active, .btn-delicious-inversed.active {
    background-color: transparent;
    color: #3271cb; }

.btn-digg-inversed {
  background-color: #164673;
  border-color: #164673;
  color: white; }
  .btn-digg-inversed:hover, .btn-digg-inversed:focus, .btn-digg-inversed:active, .btn-digg-inversed.active {
    background-color: transparent;
    color: #164673; }

.btn-disqus-inversed {
  background-color: #2e9fff;
  border-color: #2e9fff;
  color: white; }
  .btn-disqus-inversed:hover, .btn-disqus-inversed:focus, .btn-disqus-inversed:active, .btn-disqus-inversed.active {
    background-color: transparent;
    color: #2e9fff; }

.btn-eventbrite-inversed {
  background-color: #ff5616;
  border-color: #ff5616;
  color: white; }
  .btn-eventbrite-inversed:hover, .btn-eventbrite-inversed:focus, .btn-eventbrite-inversed:active, .btn-eventbrite-inversed.active {
    background-color: transparent;
    color: #ff5616; }

.btn-eventful-inversed {
  background-color: #376095;
  border-color: #376095;
  color: white; }
  .btn-eventful-inversed:hover, .btn-eventful-inversed:focus, .btn-eventful-inversed:active, .btn-eventful-inversed.active {
    background-color: transparent;
    color: #376095; }

.btn-intensedebate-inversed {
  background-color: #0099e1;
  border-color: #0099e1;
  color: white; }
  .btn-intensedebate-inversed:hover, .btn-intensedebate-inversed:focus, .btn-intensedebate-inversed:active, .btn-intensedebate-inversed.active {
    background-color: transparent;
    color: #0099e1; }

.btn-lanyrd-inversed {
  background-color: #2e6ac2;
  border-color: #2e6ac2;
  color: white; }
  .btn-lanyrd-inversed:hover, .btn-lanyrd-inversed:focus, .btn-lanyrd-inversed:active, .btn-lanyrd-inversed.active {
    background-color: transparent;
    color: #2e6ac2; }

.btn-pinboard-inversed {
  background-color: #0000ff;
  border-color: #0000ff;
  color: white; }
  .btn-pinboard-inversed:hover, .btn-pinboard-inversed:focus, .btn-pinboard-inversed:active, .btn-pinboard-inversed.active {
    background-color: transparent;
    color: #0000ff; }

.btn-songkick-inversed {
  background-color: #ff0050;
  border-color: #ff0050;
  color: white; }
  .btn-songkick-inversed:hover, .btn-songkick-inversed:focus, .btn-songkick-inversed:active, .btn-songkick-inversed.active {
    background-color: transparent;
    color: #ff0050; }

.btn-stumbleupon-inversed {
  background-color: #eb4924;
  border-color: #eb4924;
  color: white; }
  .btn-stumbleupon-inversed:hover, .btn-stumbleupon-inversed:focus, .btn-stumbleupon-inversed:active, .btn-stumbleupon-inversed.active {
    background-color: transparent;
    color: #eb4924; }

.btn-gmail-inversed {
  background-color: #db4038;
  border-color: #db4038;
  color: white; }
  .btn-gmail-inversed:hover, .btn-gmail-inversed:focus, .btn-gmail-inversed:active, .btn-gmail-inversed.active {
    background-color: transparent;
    color: #db4038; }

.btn-google-inversed {
  background-color: #4e6cf7;
  border-color: #4e6cf7;
  color: white; }
  .btn-google-inversed:hover, .btn-google-inversed:focus, .btn-google-inversed:active, .btn-google-inversed.active {
    background-color: transparent;
    color: #4e6cf7; }

.btn-evernote-inversed {
  background-color: #6bb130;
  border-color: #6bb130;
  color: white; }
  .btn-evernote-inversed:hover, .btn-evernote-inversed:focus, .btn-evernote-inversed:active, .btn-evernote-inversed.active {
    background-color: transparent;
    color: #6bb130; }

.btn-grooveshark-inversed {
  background-color: #e97a2f;
  border-color: #e97a2f;
  color: white; }
  .btn-grooveshark-inversed:hover, .btn-grooveshark-inversed:focus, .btn-grooveshark-inversed:active, .btn-grooveshark-inversed.active {
    background-color: transparent;
    color: #e97a2f; }

.btn-instapaper-inversed {
  background-color: #222222;
  border-color: #222222;
  color: white; }
  .btn-instapaper-inversed:hover, .btn-instapaper-inversed:focus, .btn-instapaper-inversed:active, .btn-instapaper-inversed.active {
    background-color: transparent;
    color: #222222; }

.btn-itunes-inversed {
  background-color: #525152;
  border-color: #525152;
  color: white; }
  .btn-itunes-inversed:hover, .btn-itunes-inversed:focus, .btn-itunes-inversed:active, .btn-itunes-inversed.active {
    background-color: transparent;
    color: #525152; }

.btn-opentable-inversed {
  background-color: #990000;
  border-color: #990000;
  color: white; }
  .btn-opentable-inversed:hover, .btn-opentable-inversed:focus, .btn-opentable-inversed:active, .btn-opentable-inversed.active {
    background-color: transparent;
    color: #990000; }

.btn-logmein-inversed {
  background-color: #000000;
  border-color: #000000;
  color: white; }
  .btn-logmein-inversed:hover, .btn-logmein-inversed:focus, .btn-logmein-inversed:active, .btn-logmein-inversed.active {
    background-color: transparent;
    color: #000000; }

.btn-ninetyninedesigns-inversed {
  background-color: #072243;
  border-color: #072243;
  color: white; }
  .btn-ninetyninedesigns-inversed:hover, .btn-ninetyninedesigns-inversed:focus, .btn-ninetyninedesigns-inversed:active, .btn-ninetyninedesigns-inversed.active {
    background-color: transparent;
    color: #072243; }

.btn-paypal-inversed {
  background-color: #32689a;
  border-color: #32689a;
  color: white; }
  .btn-paypal-inversed:hover, .btn-paypal-inversed:focus, .btn-paypal-inversed:active, .btn-paypal-inversed.active {
    background-color: transparent;
    color: #32689a; }

.btn-pocket-inversed {
  background-color: #de5a5f;
  border-color: #de5a5f;
  color: white; }
  .btn-pocket-inversed:hover, .btn-pocket-inversed:focus, .btn-pocket-inversed:active, .btn-pocket-inversed.active {
    background-color: transparent;
    color: #de5a5f; }

.btn-scribd-inversed {
  background-color: #231c1a;
  border-color: #231c1a;
  color: white; }
  .btn-scribd-inversed:hover, .btn-scribd-inversed:focus, .btn-scribd-inversed:active, .btn-scribd-inversed.active {
    background-color: transparent;
    color: #231c1a; }

.btn-spotify-inversed {
  background-color: #60af00;
  border-color: #60af00;
  color: white; }
  .btn-spotify-inversed:hover, .btn-spotify-inversed:focus, .btn-spotify-inversed:active, .btn-spotify-inversed.active {
    background-color: transparent;
    color: #60af00; }

.btn-statusnet-inversed {
  background-color: #829d25;
  border-color: #829d25;
  color: white; }
  .btn-statusnet-inversed:hover, .btn-statusnet-inversed:focus, .btn-statusnet-inversed:active, .btn-statusnet-inversed.active {
    background-color: transparent;
    color: #829d25; }

.btn-stripe-inversed {
  background-color: #2f7ed6;
  border-color: #2f7ed6;
  color: white; }
  .btn-stripe-inversed:hover, .btn-stripe-inversed:focus, .btn-stripe-inversed:active, .btn-stripe-inversed.active {
    background-color: transparent;
    color: #2f7ed6; }

.btn-yahoo-inversed {
  background-color: #a200c2;
  border-color: #a200c2;
  color: white; }
  .btn-yahoo-inversed:hover, .btn-yahoo-inversed:focus, .btn-yahoo-inversed:active, .btn-yahoo-inversed.active {
    background-color: transparent;
    color: #a200c2; }

.btn-yelp-inversed {
  background-color: #e60010;
  border-color: #e60010;
  color: white; }
  .btn-yelp-inversed:hover, .btn-yelp-inversed:focus, .btn-yelp-inversed:active, .btn-yelp-inversed.active {
    background-color: transparent;
    color: #e60010; }

.btn-wikipedia-inversed {
  background-color: #111111;
  border-color: #111111;
  color: white; }
  .btn-wikipedia-inversed:hover, .btn-wikipedia-inversed:focus, .btn-wikipedia-inversed:active, .btn-wikipedia-inversed.active {
    background-color: transparent;
    color: #111111; }

.btn-wordpress-inversed {
  background-color: #464646;
  border-color: #464646;
  color: white; }
  .btn-wordpress-inversed:hover, .btn-wordpress-inversed:focus, .btn-wordpress-inversed:active, .btn-wordpress-inversed.active {
    background-color: transparent;
    color: #464646; }

.btn-ycombinator-inversed {
  background-color: #ff6600;
  border-color: #ff6600;
  color: white; }
  .btn-ycombinator-inversed:hover, .btn-ycombinator-inversed:focus, .btn-ycombinator-inversed:active, .btn-ycombinator-inversed.active {
    background-color: transparent;
    color: #ff6600; }

.btn-bitcoin-inversed {
  background-color: #eb9737;
  border-color: #eb9737;
  color: white; }
  .btn-bitcoin-inversed:hover, .btn-bitcoin-inversed:focus, .btn-bitcoin-inversed:active, .btn-bitcoin-inversed.active {
    background-color: transparent;
    color: #eb9737; }

.btn-cloudapp-inversed {
  background-color: #312c2a;
  border-color: #312c2a;
  color: white; }
  .btn-cloudapp-inversed:hover, .btn-cloudapp-inversed:focus, .btn-cloudapp-inversed:active, .btn-cloudapp-inversed.active {
    background-color: transparent;
    color: #312c2a; }

.btn-creativecommons-inversed {
  background-color: #000000;
  border-color: #000000;
  color: white; }
  .btn-creativecommons-inversed:hover, .btn-creativecommons-inversed:focus, .btn-creativecommons-inversed:active, .btn-creativecommons-inversed.active {
    background-color: transparent;
    color: #000000; }

.btn-dropbox-inversed {
  background-color: #007ee5;
  border-color: #007ee5;
  color: white; }
  .btn-dropbox-inversed:hover, .btn-dropbox-inversed:focus, .btn-dropbox-inversed:active, .btn-dropbox-inversed.active {
    background-color: transparent;
    color: #007ee5; }

.btn-html5-inversed {
  background-color: #ff3617;
  border-color: #ff3617;
  color: white; }
  .btn-html5-inversed:hover, .btn-html5-inversed:focus, .btn-html5-inversed:active, .btn-html5-inversed.active {
    background-color: transparent;
    color: #ff3617; }

.btn-ie-inversed {
  background-color: #00a1d9;
  border-color: #00a1d9;
  color: white; }
  .btn-ie-inversed:hover, .btn-ie-inversed:focus, .btn-ie-inversed:active, .btn-ie-inversed.active {
    background-color: transparent;
    color: #00a1d9; }

.btn-podcast-inversed {
  background-color: #9365ce;
  border-color: #9365ce;
  color: white; }
  .btn-podcast-inversed:hover, .btn-podcast-inversed:focus, .btn-podcast-inversed:active, .btn-podcast-inversed.active {
    background-color: transparent;
    color: #9365ce; }

.btn-rss-inversed {
  background-color: #ff7f25;
  border-color: #ff7f25;
  color: white; }
  .btn-rss-inversed:hover, .btn-rss-inversed:focus, .btn-rss-inversed:active, .btn-rss-inversed.active {
    background-color: transparent;
    color: #ff7f25; }

.btn-skype-inversed {
  background-color: #00a2ed;
  border-color: #00a2ed;
  color: white; }
  .btn-skype-inversed:hover, .btn-skype-inversed:focus, .btn-skype-inversed:active, .btn-skype-inversed.active {
    background-color: transparent;
    color: #00a2ed; }

.btn-steam-inversed {
  background-color: #000000;
  border-color: #000000;
  color: white; }
  .btn-steam-inversed:hover, .btn-steam-inversed:focus, .btn-steam-inversed:active, .btn-steam-inversed.active {
    background-color: transparent;
    color: #000000; }

.btn-windows-inversed {
  background-color: #48bbef;
  border-color: #48bbef;
  color: white; }
  .btn-windows-inversed:hover, .btn-windows-inversed:focus, .btn-windows-inversed:active, .btn-windows-inversed.active {
    background-color: transparent;
    color: #48bbef; }

.btn-android-inversed {
  background-color: #a4c639;
  border-color: #a4c639;
  color: white; }
  .btn-android-inversed:hover, .btn-android-inversed:focus, .btn-android-inversed:active, .btn-android-inversed.active {
    background-color: transparent;
    color: #a4c639; }

.btn-appstore-inversed {
  background-color: #000000;
  border-color: #000000;
  color: white; }
  .btn-appstore-inversed:hover, .btn-appstore-inversed:focus, .btn-appstore-inversed:active, .btn-appstore-inversed.active {
    background-color: transparent;
    color: #000000; }

.btn-googleplay-inversed {
  background-color: #b9c13e;
  border-color: #b9c13e;
  color: white; }
  .btn-googleplay-inversed:hover, .btn-googleplay-inversed:focus, .btn-googleplay-inversed:active, .btn-googleplay-inversed.active {
    background-color: transparent;
    color: #b9c13e; }

.btn-macstore-inversed {
  background-color: #007dcb;
  border-color: #007dcb;
  color: white; }
  .btn-macstore-inversed:hover, .btn-macstore-inversed:focus, .btn-macstore-inversed:active, .btn-macstore-inversed.active {
    background-color: transparent;
    color: #007dcb; }

.btn-appnet-inversed {
  background-color: #3178bd;
  border-color: #3178bd;
  color: white; }
  .btn-appnet-inversed:hover, .btn-appnet-inversed:focus, .btn-appnet-inversed:active, .btn-appnet-inversed.active {
    background-color: transparent;
    color: #3178bd; }

.btn-blogger-inversed {
  background-color: #ee5a22;
  border-color: #ee5a22;
  color: white; }
  .btn-blogger-inversed:hover, .btn-blogger-inversed:focus, .btn-blogger-inversed:active, .btn-blogger-inversed.active {
    background-color: transparent;
    color: #ee5a22; }

.btn-bitbucket-inversed {
  background-color: #205081;
  border-color: #205081;
  color: white; }
  .btn-bitbucket-inversed:hover, .btn-bitbucket-inversed:focus, .btn-bitbucket-inversed:active, .btn-bitbucket-inversed.active {
    background-color: transparent;
    color: #205081; }

.btn-dribbble-inversed {
  background-color: #ea4c89;
  border-color: #ea4c89;
  color: white; }
  .btn-dribbble-inversed:hover, .btn-dribbble-inversed:focus, .btn-dribbble-inversed:active, .btn-dribbble-inversed.active {
    background-color: transparent;
    color: #ea4c89; }

.btn-facebook-inversed {
  background-color: #4863ae;
  border-color: #4863ae;
  color: white; }
  .btn-facebook-inversed:hover, .btn-facebook-inversed:focus, .btn-facebook-inversed:active, .btn-facebook-inversed.active {
    background-color: transparent;
    color: #4863ae; }

.btn-flattr-inversed {
  background-color: #8aba42;
  border-color: #8aba42;
  color: white; }
  .btn-flattr-inversed:hover, .btn-flattr-inversed:focus, .btn-flattr-inversed:active, .btn-flattr-inversed.active {
    background-color: transparent;
    color: #8aba42; }

.btn-flickr-inversed {
  background-color: #ff0084;
  border-color: #ff0084;
  color: white; }
  .btn-flickr-inversed:hover, .btn-flickr-inversed:focus, .btn-flickr-inversed:active, .btn-flickr-inversed.active {
    background-color: transparent;
    color: #ff0084; }

.btn-foursquare-inversed {
  background-color: #0072b1;
  border-color: #0072b1;
  color: white; }
  .btn-foursquare-inversed:hover, .btn-foursquare-inversed:focus, .btn-foursquare-inversed:active, .btn-foursquare-inversed.active {
    background-color: transparent;
    color: #0072b1; }

.btn-github-inversed {
  background-color: #171515;
  border-color: #171515;
  color: white; }
  .btn-github-inversed:hover, .btn-github-inversed:focus, .btn-github-inversed:active, .btn-github-inversed.active {
    background-color: transparent;
    color: #171515; }

.btn-googleplus-inversed {
  background-color: #dd4a38;
  border-color: #dd4a38;
  color: white; }
  .btn-googleplus-inversed:hover, .btn-googleplus-inversed:focus, .btn-googleplus-inversed:active, .btn-googleplus-inversed.active {
    background-color: transparent;
    color: #dd4a38; }

.btn-gowalla-inversed {
  background-color: #ff720a;
  border-color: #ff720a;
  color: white; }
  .btn-gowalla-inversed:hover, .btn-gowalla-inversed:focus, .btn-gowalla-inversed:active, .btn-gowalla-inversed.active {
    background-color: transparent;
    color: #ff720a; }

.btn-instagram-inversed {
  background-color: #3f729b;
  border-color: #3f729b;
  color: white; }
  .btn-instagram-inversed:hover, .btn-instagram-inversed:focus, .btn-instagram-inversed:active, .btn-instagram-inversed.active {
    background-color: transparent;
    color: #3f729b; }

.btn-klout-inversed {
  background-color: #e34a25;
  border-color: #e34a25;
  color: white; }
  .btn-klout-inversed:hover, .btn-klout-inversed:focus, .btn-klout-inversed:active, .btn-klout-inversed.active {
    background-color: transparent;
    color: #e34a25; }

.btn-lastfm-inversed {
  background-color: #dc1a23;
  border-color: #dc1a23;
  color: white; }
  .btn-lastfm-inversed:hover, .btn-lastfm-inversed:focus, .btn-lastfm-inversed:active, .btn-lastfm-inversed.active {
    background-color: transparent;
    color: #dc1a23; }

.btn-linkedin-inversed {
  background-color: #0083a8;
  border-color: #0083a8;
  color: white; }
  .btn-linkedin-inversed:hover, .btn-linkedin-inversed:focus, .btn-linkedin-inversed:active, .btn-linkedin-inversed.active {
    background-color: transparent;
    color: #0083a8; }

.btn-meetup-inversed {
  background-color: #ff0026;
  border-color: #ff0026;
  color: white; }
  .btn-meetup-inversed:hover, .btn-meetup-inversed:focus, .btn-meetup-inversed:active, .btn-meetup-inversed.active {
    background-color: transparent;
    color: #ff0026; }

.btn-myspace-inversed {
  background-color: #000000;
  border-color: #000000;
  color: white; }
  .btn-myspace-inversed:hover, .btn-myspace-inversed:focus, .btn-myspace-inversed:active, .btn-myspace-inversed.active {
    background-color: transparent;
    color: #000000; }

.btn-pinterest-inversed {
  background-color: #c91618;
  border-color: #c91618;
  color: white; }
  .btn-pinterest-inversed:hover, .btn-pinterest-inversed:focus, .btn-pinterest-inversed:active, .btn-pinterest-inversed.active {
    background-color: transparent;
    color: #c91618; }

.btn-quora-inversed {
  background-color: #a82400;
  border-color: #a82400;
  color: white; }
  .btn-quora-inversed:hover, .btn-quora-inversed:focus, .btn-quora-inversed:active, .btn-quora-inversed.active {
    background-color: transparent;
    color: #a82400; }

.btn-reddit-inversed {
  background-color: #ff5700;
  border-color: #ff5700;
  color: white; }
  .btn-reddit-inversed:hover, .btn-reddit-inversed:focus, .btn-reddit-inversed:active, .btn-reddit-inversed.active {
    background-color: transparent;
    color: #ff5700; }

.btn-plurk-inversed {
  background-color: #cf682f;
  border-color: #cf682f;
  color: white; }
  .btn-plurk-inversed:hover, .btn-plurk-inversed:focus, .btn-plurk-inversed:active, .btn-plurk-inversed.active {
    background-color: transparent;
    color: #cf682f; }

.btn-smashing-inversed {
  background-color: #ff4f27;
  border-color: #ff4f27;
  color: white; }
  .btn-smashing-inversed:hover, .btn-smashing-inversed:focus, .btn-smashing-inversed:active, .btn-smashing-inversed.active {
    background-color: transparent;
    color: #ff4f27; }

.btn-soundcloud-inversed {
  background-color: #ff4500;
  border-color: #ff4500;
  color: white; }
  .btn-soundcloud-inversed:hover, .btn-soundcloud-inversed:focus, .btn-soundcloud-inversed:active, .btn-soundcloud-inversed.active {
    background-color: transparent;
    color: #ff4500; }

.btn-stackoverflow-inversed {
  background-color: #f18436;
  border-color: #f18436;
  color: white; }
  .btn-stackoverflow-inversed:hover, .btn-stackoverflow-inversed:focus, .btn-stackoverflow-inversed:active, .btn-stackoverflow-inversed.active {
    background-color: transparent;
    color: #f18436; }

.btn-tumblr-inversed {
  background-color: #374a61;
  border-color: #374a61;
  color: white; }
  .btn-tumblr-inversed:hover, .btn-tumblr-inversed:focus, .btn-tumblr-inversed:active, .btn-tumblr-inversed.active {
    background-color: transparent;
    color: #374a61; }

.btn-twitter-inversed {
  background-color: #46c0fb;
  border-color: #46c0fb;
  color: white; }
  .btn-twitter-inversed:hover, .btn-twitter-inversed:focus, .btn-twitter-inversed:active, .btn-twitter-inversed.active {
    background-color: transparent;
    color: #46c0fb; }

.btn-viadeo-inversed {
  background-color: #e7732e;
  border-color: #e7732e;
  color: white; }
  .btn-viadeo-inversed:hover, .btn-viadeo-inversed:focus, .btn-viadeo-inversed:active, .btn-viadeo-inversed.active {
    background-color: transparent;
    color: #e7732e; }

.btn-vimeo-inversed {
  background-color: #00a2cd;
  border-color: #00a2cd;
  color: white; }
  .btn-vimeo-inversed:hover, .btn-vimeo-inversed:focus, .btn-vimeo-inversed:active, .btn-vimeo-inversed.active {
    background-color: transparent;
    color: #00a2cd; }

.btn-vk-inversed {
  background-color: #45688e;
  border-color: #45688e;
  color: white; }
  .btn-vk-inversed:hover, .btn-vk-inversed:focus, .btn-vk-inversed:active, .btn-vk-inversed.active {
    background-color: transparent;
    color: #45688e; }

.btn-weibo-inversed {
  background-color: #d7584d;
  border-color: #d7584d;
  color: white; }
  .btn-weibo-inversed:hover, .btn-weibo-inversed:focus, .btn-weibo-inversed:active, .btn-weibo-inversed.active {
    background-color: transparent;
    color: #d7584d; }

.btn-xing-inversed {
  background-color: #0a5d5e;
  border-color: #0a5d5e;
  color: white; }
  .btn-xing-inversed:hover, .btn-xing-inversed:focus, .btn-xing-inversed:active, .btn-xing-inversed.active {
    background-color: transparent;
    color: #0a5d5e; }

.btn-youtube-inversed {
  background-color: #ff0000;
  border-color: #ff0000;
  color: white; }
  .btn-youtube-inversed:hover, .btn-youtube-inversed:focus, .btn-youtube-inversed:active, .btn-youtube-inversed.active {
    background-color: transparent;
    color: #ff0000; }

.btn-csgo-inversed {
  background-color: #b67300;
  border-color: #b67300;
  color: white; }
  .btn-csgo-inversed:hover, .btn-csgo-inversed:focus, .btn-csgo-inversed:active, .btn-csgo-inversed.active {
    background-color: transparent;
    color: #b67300; }

.btn-dota2-inversed {
  background-color: #c33d2b;
  border-color: #c33d2b;
  color: white; }
  .btn-dota2-inversed:hover, .btn-dota2-inversed:focus, .btn-dota2-inversed:active, .btn-dota2-inversed.active {
    background-color: transparent;
    color: #c33d2b; }

.btn-gm-inversed {
  background-color: #1194f0;
  border-color: #1194f0;
  color: white; }
  .btn-gm-inversed:hover, .btn-gm-inversed:focus, .btn-gm-inversed:active, .btn-gm-inversed.active {
    background-color: transparent;
    color: #1194f0; }

.btn-lol-inversed {
  background-color: #d79922;
  border-color: #d79922;
  color: white; }
  .btn-lol-inversed:hover, .btn-lol-inversed:focus, .btn-lol-inversed:active, .btn-lol-inversed.active {
    background-color: transparent;
    color: #d79922; }

.btn-minecraft-inversed {
  background-color: #94c864;
  border-color: #94c864;
  color: white; }
  .btn-minecraft-inversed:hover, .btn-minecraft-inversed:focus, .btn-minecraft-inversed:active, .btn-minecraft-inversed.active {
    background-color: transparent;
    color: #94c864; }

.btn-tf2-inversed {
  background-color: #b35215;
  border-color: #b35215;
  color: white; }
  .btn-tf2-inversed:hover, .btn-tf2-inversed:focus, .btn-tf2-inversed:active, .btn-tf2-inversed.active {
    background-color: transparent;
    color: #b35215; }

.btn-quake-inversed {
  background-color: #cd1800;
  border-color: #cd1800;
  color: white; }
  .btn-quake-inversed:hover, .btn-quake-inversed:focus, .btn-quake-inversed:active, .btn-quake-inversed.active {
    background-color: transparent;
    color: #cd1800; }

.btn-wot-inversed {
  background-color: #ff4005;
  border-color: #ff4005;
  color: white; }
  .btn-wot-inversed:hover, .btn-wot-inversed:focus, .btn-wot-inversed:active, .btn-wot-inversed.active {
    background-color: transparent;
    color: #ff4005; }


text:
<?php

namespace ML\HydraBundle\Mapping;

/**
 * Operation annotation
 *
 * The operation annotation is used to document the semantics of controller
 * methods. It allows to specify the type of the operation and the expected
 * data. The type of data the operation returns is typically documented by
 * the "@return" annotation. It is also possible to document the status
 * codes ("status_codes") that may be returned.
 *
 * If "iri" is set, the annotation represents an externally defined
 * operation.
 *
 * This annotation should not be confused with the {@link Operations}
 * annotation which is used to associate available operations to an element.
 *
 * @Annotation
 * @Target("METHOD")
 *
 * @author Markus Lanthaler <mail@markus-lanthaler.com>
 */
class Operation
{
    /**
     * @var string
     */
    public $iri = null;

    /**
     * @var string
     */
    public $type = null;

    /**
     * @var string
     */
    public $expect = null;

    /**
     * @var array
     */
    public $status_codes = array();

    /**
     * Get the IRI (fragment)
     *
     * @return string The IRI fragment
     */
    public function getIri()
    {
        if (null === $this->iri) {
            return null;
        }

        // Is it an absolute IRI?
        if (strpos($this->iri, ':')) {
            return $this->iri;
        }

        if ('#' === $this->iri[0]) {
            return substr($this->iri, 1);
        }

        return $this->iri;
    }
}


text:
#pragma once

#include <boost/utility.hpp>
#include "clanlib/core/system.h"

class CL_GraphicContext;
class CL_ProgramObject;
class CL_Rect;

namespace Gfx
{

class ShaderImpl;
class Shader : public boost::noncopyable
{
	public:
		Shader();
		virtual ~Shader();

		void initialize(CL_GraphicContext &p_gc);
		void destroy();

		void begin(CL_GraphicContext &p_gc);
		void end(CL_GraphicContext &p_gc);

		void setBoundRect(const CL_Rect &p_boundRect);

	protected:

		virtual const CL_String &getFragmentShaderResourceName() = 0;
		virtual const CL_String &getVertexShaderResourceName() = 0;

		virtual const CL_Rect &getDrawRect(const CL_Rect &p_requested);

		virtual void setUniforms(CL_ProgramObject &p_program);

	private:
		CL_SharedPtr<ShaderImpl> m_impl;
		friend class ShaderImpl;
};

}


text:
module Zucy
  module Routing
    class Route
      attr_reader :klass_name, :request, :method_name
      def initialize(request, klass_and_method)
        @klass_name, @method_name = klass_and_method
        @request = request
      end

      def klass
        klass_name.constantize
      end

      def dispatch
        klass.new(request).send(method_name)
      end
    end
  end
end


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

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: vmware_guest_find
short_description: Find the folder path(s) for a VM by name or UUID
description:
    - Find the folder path(s) for a VM by name or UUID
version_added: 2.4
author:
    - James Tanner <tanner.jc@gmail.com>
notes:
    - Tested on vSphere 6.5
requirements:
    - "python >= 2.6"
    - PyVmomi
options:
   name:
        description:
            - Name of the VM to work with.
            - This is required if uuid is not supplied.
   uuid:
        description:
            - UUID of the instance to manage if known, this is VMware's BIOS UUID.
            - This is required if name is not supplied.
   datacenter:
        description:
            - Destination datacenter for the find operation.
        required: True
extends_documentation_fragment: vmware.documentation
'''

EXAMPLES = '''
- name: Find Guest's Folder using name
  vmware_guest_find:
    hostname: 192.168.1.209
    username: administrator@vsphere.local
    password: vmware
    validate_certs: no
    name: testvm
  register: vm_folder

- name: Find Guest's Folder using UUID
  vmware_guest_find:
    hostname: 192.168.1.209
    username: administrator@vsphere.local
    password: vmware
    validate_certs: no
    uuid: 38c4c89c-b3d7-4ae6-ae4e-43c5118eae49
  register: vm_folder
'''

RETURN = """
"""

import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.vmware import (
    connect_to_api,
    gather_vm_facts,
    get_all_objs,
    compile_folder_path_for_object,
    vmware_argument_spec,
    find_datacenter_by_name
)

try:
    import pyVmomi
    from pyVmomi import vim

    HAS_PYVMOMI = True
except ImportError:
    HAS_PYVMOMI = False

class PyVmomiHelper(object):
    def __init__(self, module):
        if not HAS_PYVMOMI:
            module.fail_json(msg='pyvmomi module required')

        self.datacenter = None
        self.folders = None
        self.foldermap = {
            'fvim_by_path': {},
            'path_by_fvim': {},
            'path_by_vvim': {},
            'paths': {},
            'uuids': {}
        }
        self.module = module
        self.params = module.params
        self.content = connect_to_api(self.module)

    def getvm_folder_paths(self, name=None, uuid=None):

        results = []

        if not self.folders:
            self.getfolders()

        # compare the folder path of each VM against the search path
        vmList = get_all_objs(self.content, [vim.VirtualMachine])
        for item in vmList.items():
            vobj = item[0]
            if not isinstance(vobj.parent, vim.Folder):
                continue
            # Match by name or uuid
            if vobj.config.name == name or vobj.config.uuid == uuid:
                folderpath = compile_folder_path_for_object(vobj)
                results.append(folderpath)

        return results

    def gather_facts(self, vm):
        return gather_vm_facts(self.content, vm)

    def _build_folder_tree(self, folder):

        tree = {'virtualmachines': [],
                'subfolders': {},
                'vimobj': folder,
                'name': folder.name}

        children = None
        if hasattr(folder, 'childEntity'):
            children = folder.childEntity

        if children:
            for child in children:
                if child == folder or child in tree:
                    continue
                if isinstance(child, vim.Folder):
                    ctree = self._build_folder_tree(child)
                    tree['subfolders'][child] = dict.copy(ctree)
                elif isinstance(child, vim.VirtualMachine):
                    tree['virtualmachines'].append(child)
        else:
            if isinstance(folder, vim.VirtualMachine):
                return folder
        return tree

    def _build_folder_map(self, folder, inpath='/'):

        """ Build a searchable index for vms+uuids+folders """
        if isinstance(folder, tuple):
            folder = folder[1]

        thispath = os.path.join(inpath, folder['name'])

        if thispath not in self.foldermap['paths']:
            self.foldermap['paths'][thispath] = []

        # store object by path and store path by object
        self.foldermap['fvim_by_path'][thispath] = folder['vimobj']
        self.foldermap['path_by_fvim'][folder['vimobj']] = thispath

        for item in folder.items():
            k = item[0]
            v = item[1]

            if k == 'name':
                pass
            elif k == 'subfolders':
                for x in v.items():
                    self._build_folder_map(x, inpath=thispath)
            elif k == 'virtualmachines':
                for x in v:
                    # Apparently x.config can be None on corrupted VMs
                    if x.config is None:
                        continue
                    self.foldermap['uuids'][x.config.uuid] = x.config.name
                    self.foldermap['paths'][thispath].append(x.config.uuid)

                    if x not in self.foldermap['path_by_vvim']:
                        self.foldermap['path_by_vvim'][x] = thispath

    def getfolders(self):
        if not self.datacenter:
            self.datacenter = find_datacenter_by_name(self.content, self.params['datacenter'])

        if self.datacenter is None:
            self.module.fail_json(msg="Unable to find datacenter %(datacenter)s" % self.params)

        self.folders = self._build_folder_tree(self.datacenter.vmFolder)
        self._build_folder_map(self.folders)

def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        name=dict(type='str'),
        uuid=dict(type='str'),
        datacenter=dict(type='str', required=True)
    )

    module = AnsibleModule(argument_spec=argument_spec,
                           required_one_of=[['name', 'uuid']])
    pyv = PyVmomiHelper(module)
    # Check if the VM exists before continuing
    folders = pyv.getvm_folder_paths(
        name=module.params['name'],
        uuid=module.params['uuid']
    )

    # VM already exists
    if folders:
        try:
            module.exit_json(folders=folders)
        except Exception as exc:
            module.fail_json(msg="Folder enumeration failed with exception %s" % to_native(exc))
    else:
        msg = "Unable to find folders for VM "
        if module.params['name']:
            msg += "%(name)s" % module.params
        elif module.params['uuid']:
            msg += "%(uuid)s" % module.params
        module.fail_json(msg=msg)

if __name__ == '__main__':
    main()


text:
/**
 * User Model.
 *
 * @module server/models/User
 */

const bcrypt = require('bcryptjs');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

const { Schema } = mongoose;
const { Types } = Schema;

const schema = new Schema({
  firstName: {
    type: Types.String,
    trim: true,
    required: true,
  },
  lastName: {
    type: Types.String,
    trim: true,
    required: true,
  },
  email: {
    type: Types.String,
    lowercase: true,
    trim: true,
    required: true,
  },
  password: {
    type: Types.String,
    trim: true,
    required: true,
    set(password) { return bcrypt.hashSync(password, 8); },
  },
  habits: [
    {
      type: Types.ObjectId,
      ref: 'Habit',
    },
  ],
}, {
  collection: 'users',
});

schema.methods.comparePassword = function comparePassword(password) {
  return bcrypt.compareSync(password, this.password);
};

const User = mongoose.model('User', schema);

module.exports = User;


text:
CKEditor Chart Plugin
=====================

This is a proof-of-concept plugin that adds support for injecting charts into CKEditor.
To render charts, the [Chart.js](http://www.chartjs.org/) library is used.
The plugin serves as an example of using external JavaScript libraries in CKEditor, using the [widgets feature](http://docs.ckeditor.com/#!/guide/widget_sdk_intro). It has lots of comments inside to help you understand how it was built.

## Live Demo

View [live demo](http://wwalc.github.io/chart/).

## Installation

1. Put the plugin into the CKEditor "plugins" folder.
2. Enable the plugin with `config.extraPlugins`.
3. Add the `Chart` button to the toolbar if it will not appear automatically.

CKEDITOR.replace( 'editor1', {
    extraPlugins: 'chart'
}

In case of any problems with installation, there is [an online sample](http://wwalc.github.io/chart/sample.html) available that should help you get started.

## Rendering charts on a website

Chart created in CKEditor is represented as a simple `<div>` element with data attributes. This is by design, because such a simplified form allows you to re-edit the chart in the future. It ensures that your content will be future-proof, allowing you to to use different styling for charts embed on your website when you redesign it or to use the future major versions of Chart.js library with different API/features.

To convert `<div>` elements into charts, include `chart.min.js` and `widget2chart.js` on your website. See the [online sample](http://wwalc.github.io/chart/sample.html).

## Configuration Options

### config.chart_height

The default chart height (in pixels) in the Edit Chart dialog window.

	config.chart_height = 400;

### config.chart_maxItems

The number of rows (items to enter) in the Edit Chart dialog window.

	config.chart_maxItems = 12;

### config.chart_colors

Colors used to draw charts. See Bar chart data structure and
Pie chart data structure.

config.chart_colors =
{
	// Colors for Bar/Line chart.
	fillColor: 'rgba(151,187,205,0.5)',
	strokeColor: 'rgba(151,187,205,0.8)',
	highlightFill: 'rgba(151,187,205,0.75)',
	highlightStroke: 'rgba(151,187,205,1)',
	// Colors for Doughnut/Pie/PolarArea charts.
	data: [ '#B33131', '#B66F2D', '#B6B330', '#71B232', '#33B22D', '#31B272', '#2DB5B5', '#3172B6', '#3232B6', '#6E31B2', '#B434AF', '#B53071' ]
}

### config.chart_configBar

Chart.js configuration to use for Bar charts.

	config.chart_configBar = { animation: false };

### config.chart_configDoughnut

Chart.js configuration to use for Doughnut charts.

	config.chart_configDoughnut = { animateRotate: false };

### config.chart_configLine

Chart.js configuration to use for Line charts.

	config.chart_configLine = { animation: false };

### config.chart_configPie

Chart.js configuration to use for Pie charts.

	config.chart_configPie = { animateRotate: false };

### config.chart_configPolarArea

Chart.js configuration to use for PolarArea charts.

	config.chart_configPolarArea = { animateRotate: false };

## Screenshot

![Charts in CKEditor](http://s10.postimg.org/efvmb3fmh/chartjs.png)

## The future of this plugin

For now, this is a proof-of-concept plugin. However if you would like to leave any feedback, fill a future request, report a bug etc., feel free to do so.

## Browser compatibility

Any modern browser should be supported. **IE8 is not supported.**

### License

Licensed under the GPL, LGPL and MPL licenses, at your choice.

For full details about the license, please check the LICENSE.md file.


text:
package com.airbnb.aerosolve.core.function;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;

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

@Slf4j
public class FunctionUtil {
  public static float[] fitPolynomial(float[] data) {
    int numCoeff = 6;
    int iterations = numCoeff * 4;
    float[] initial = new float[numCoeff];

    float[] initialStep = new float[numCoeff];
    Arrays.fill(initialStep, 1.0f);
    return optimize(1.0 / 512.0, iterations, initial, initialStep,
        new ImmutablePair<Float, Float>(-10.0f, 10.0f), data);
  }

  public static float evaluatePolynomial(float[] coeff, float[] data, boolean overwrite) {
    int len = data.length;
    float err = 0;
    long count = 0;
    for (int i = 0; i < len; i++) {
      float t = (float) i / (len - 1);
      float tinv = 1 - t;
      float diracStart = (i == 0) ? coeff[0] : 0;
      float diracEnd = (i == len - 1) ? coeff[1] : 0;
      double eval = coeff[2] * tinv * tinv * tinv +
          coeff[3] * 3.0 * tinv * tinv * t +
          coeff[4] * 3.0 * tinv * t * t +
          coeff[5] * t * t * t +
          diracStart +
          diracEnd;
      if (data[i] != 0.0) {
        err += Math.abs(eval - data[i]);
        count++;
      }
      if (overwrite) {
        data[i] = (float) eval;
      }
    }
    return err / count;
  }

  // CyclicCoordinateDescent
  public static float[] optimize(double tolerance, int iterations,
                                 float[] initial, float[] initialStep,
                                 Pair<Float, Float> bounds, float[] data) {
    float[] best = initial;
    float bestF = evaluatePolynomial(best, data, false);
    int maxDim = initial.length;
    for (int i = 0; i < iterations; ++i) {
      for (int dim = 0; dim < maxDim; ++dim) {
        float step = initialStep[dim];
        while (step > tolerance) {
          float[] left = best.clone();
          left[dim] = Math.max(bounds.getLeft(), best[dim] - step);
          float leftF = evaluatePolynomial(left, data, false);
          float[] right = best.clone();
          right[dim] = Math.min(bounds.getRight(), best[dim] + step);
          float rightF = evaluatePolynomial(right, data, false);
          if (leftF < bestF) {
            best = left;
            bestF = leftF;
          }
          if (rightF < bestF) {
            best = right;
            bestF = rightF;
          }
          step *= 0.5;
        }
      }
    }
    return best;
  }

  public static float[] toFloat(List<Double> list) {
    float[] result = new float[list.size()];
    for (int i = 0; i < result.length; i++) {
      result[i] = list.get(i).floatValue();
    }
    return result;
  }

  /*
 * @param  tolerance if fitted array's deviation from weights is less than tolerance
 *         use the fitted, otherwise keep original weights.
 * @param  weights the curve you want to smooth
 * @return double errAndCoeff in the weights
   */
  public static double smooth(double tolerance, boolean toleranceIsPercentage, float[] weights) {
    // TODO use apache math's PolynomialCurveFitter
    float[] best = FunctionUtil.fitPolynomial(weights);
    double errAndCoeff = FunctionUtil.evaluatePolynomial(best, weights, false);
    if (toleranceIsPercentage) {
      double absMean = getAbsMean(weights);
      return smoothInternal(errAndCoeff, tolerance * absMean, best, weights) / absMean;
    } else {
      return smoothInternal(errAndCoeff, tolerance, best, weights);
    }
  }

  private static double smoothInternal(
      double errAndCoeff, double tolerance, float[] best, float[] weights) {
    if (errAndCoeff < tolerance) {
      FunctionUtil.evaluatePolynomial(best, weights, true);
    }
    return errAndCoeff;
  }

  public static double getAbsMean(float[] weights) {
    double sum = 0;
    for (float f : weights) {
      sum += Math.abs(f);
    }
    return  sum / weights.length;
  }
}


text:
import hbs from 'htmlbars-inline-precompile';
import { test, moduleForComponent } from 'ember-qunit';

moduleForComponent('spinner-button', 'SpinnerButtonComponent', {
  integration: true
});

test('does not display a spinner when isSpinning is false', function (assert) {
  this.render(hbs`
    {{#spinner-button isSpinning=false}}
      Click me
    {{/spinner-button}}
  `);

  assert.equal(this.$('.spin-spinner').length, 0);
});

test('does display a spinner when isSpinning is true', function (assert) {
  this.render(hbs`
    {{#spinner-button isSpinning=true}}
      Click me
    {{/spinner-button}}
  `);

  assert.equal(this.$('.spin-spinner').length, 1);
});

test('sends the action when clicked when isSpinning is false', function (assert) {
  this.render(hbs`
    {{#spinner-button id="my_button" action='dummyAction' isSpinning=false}}
      Click me
    {{/spinner-button}}
  `);

  this.set('actions.dummyAction', () => {
    assert.ok(true, 'external Action was called!');
  });

  this.$('#my_button').click();
});

test('fires the action bound to onclick when clicked when isSpinning is false', function (assert) {
  this.set('actions.dummyAction', () => {
    assert.ok(true, 'external Action was called!');
  });

  this.render(hbs`
    {{#spinner-button id="my_button" onclick=(action 'dummyAction') isSpinning=false}}
      Click me
    {{/spinner-button}}
  `);

  this.$('#my_button').click();
});


text:
import pygame
from pygame.locals import *

from Colors import *

class Arena:
	def __init__(self,surface,color):
		self.layer = surface
		self.color = color

	''' CREATING BORDERS '''
	def create_Left(self):
		pygame.draw.rect(self.layer,self.color,[0,0,10,499]) #Left Goal
	def create_Right(self):
		pygame.draw.rect(self.layer,self.color,[700,500,-10,-499]) #Right Goal
	def create_Top(self):
		pygame.draw.rect(self.layer,self.color,[700,0,-699,10]) #Top
	def create_Bottom(self):
		pygame.draw.rect(self.layer,self.color,[0,500,699,-10]) #Bottom
	def create_Arena(self):
		self.create_Left()
		self.create_Bottom()
		self.create_Right()
		self.create_Top()


text:
#pragma once
#include <aws/appsync/AppSync_EXPORTS.h>
#include <aws/appsync/AppSyncRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace AppSync
{
namespace Model
{

  /**
   */
  class AWS_APPSYNC_API DeleteTypeRequest : public AppSyncRequest
  {
  public:
    DeleteTypeRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DeleteType"; }

    Aws::String SerializePayload() const override;

    /**
     *
The API ID.

     */
    inline const Aws::String& GetApiId() const{ return m_apiId; }

    /**
     *
The API ID.

     */
    inline bool ApiIdHasBeenSet() const { return m_apiIdHasBeenSet; }

    /**
     *
The API ID.

     */
    inline void SetApiId(const Aws::String& value) { m_apiIdHasBeenSet = true; m_apiId = value; }

    /**
     *
The API ID.

     */
    inline void SetApiId(Aws::String&& value) { m_apiIdHasBeenSet = true; m_apiId = std::move(value); }

    /**
     *
The API ID.

     */
    inline void SetApiId(const char* value) { m_apiIdHasBeenSet = true; m_apiId.assign(value); }

    /**
     *
The API ID.

     */
    inline DeleteTypeRequest& WithApiId(const Aws::String& value) { SetApiId(value); return *this;}

    /**
     *
The API ID.

     */
    inline DeleteTypeRequest& WithApiId(Aws::String&& value) { SetApiId(std::move(value)); return *this;}

    /**
     *
The API ID.

     */
    inline DeleteTypeRequest& WithApiId(const char* value) { SetApiId(value); return *this;}

    /**
     *
The type name.

     */
    inline const Aws::String& GetTypeName() const{ return m_typeName; }

    /**
     *
The type name.

     */
    inline bool TypeNameHasBeenSet() const { return m_typeNameHasBeenSet; }

    /**
     *
The type name.

     */
    inline void SetTypeName(const Aws::String& value) { m_typeNameHasBeenSet = true; m_typeName = value; }

    /**
     *
The type name.

     */
    inline void SetTypeName(Aws::String&& value) { m_typeNameHasBeenSet = true; m_typeName = std::move(value); }

    /**
     *
The type name.

     */
    inline void SetTypeName(const char* value) { m_typeNameHasBeenSet = true; m_typeName.assign(value); }

    /**
     *
The type name.

     */
    inline DeleteTypeRequest& WithTypeName(const Aws::String& value) { SetTypeName(value); return *this;}

    /**
     *
The type name.

     */
    inline DeleteTypeRequest& WithTypeName(Aws::String&& value) { SetTypeName(std::move(value)); return *this;}

    /**
     *
The type name.

     */
    inline DeleteTypeRequest& WithTypeName(const char* value) { SetTypeName(value); return *this;}

  private:

    Aws::String m_apiId;
    bool m_apiIdHasBeenSet;

    Aws::String m_typeName;
    bool m_typeNameHasBeenSet;
  };

} // namespace Model
} // namespace AppSync
} // namespace Aws


text:
:+1::star_struck: Wow, thanks for taking the time to contribute! :tada::+1:

The following is a set of guidelines for contributing to [picocli](https://github.com/remkop/picocli). These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request.

##  It is okay to raise an issue to ask a question
If you have a question about picocli, feel free to raise an issue for it.

##  Helpful problem reports look like this
A helpful issue (problem report) is one that saves the maintainer time.
Try to include these elements:

* How to reproduce the problem
* What is the expected behaviour
* What do you actually see

If you can provide code that reproduces the problem, great!
If this code is in the form of a failing unit test, even better!

##  Issues or pull requests?
As a rule of thumb, it may be good to raise an issue first before providing a pull request.

It is a good idea to check we all have the same understanding that there actually is a problem to solve, and for complex pull requests it may save time when we discuss in advance what shape the solution should take.

That said, for bugfixes and documentation fixes, reporting the issue and providing a pull request to fix it in one PR is perfectly fine.
When in doubt, maybe raise an issue first.

##  Conventions for pull requests
If there is a corresponding GitHub issue, please mention the issue number in the pull request title.

Ideally prefix commit comments with either the pull request number, or the associated GitHub issue number.

##  Java version
The project is built with Java 8, and different artifacts target different versions of Java.
See the table below.

Artifact | Target Java Version
------------ | -------------
`picocli` | Java 5
`picocli-codegen` | Java 6
`picocli-groovy` | Java 5
`picocli-shell-jline2` | Java 5
`picocli-shell-jline3` | Java 8
`picocli-spring-boot-starter` | Java 8

Please be aware that pull requests can only use language features that are supported in the above version of Java.

##  Building

```
git clone https://github.com/remkop/picocli.git
cd picocli
gradlew publishToMavenLocal
```

That should publish `picocli-4.7.0-SNAPSHOT` to your local .m2 Maven cache. You can then try this in a project that uses the `info.picocli:picocli:4.7.0-SNAPSHOT` dependency.


text:
/*

    A `fluid.express.middleware` component that sets one or more HTTP headers based on the content of `options.headers`.

    See the documentation for more details:

    https://github.com/fluid-project/fluid-express/blob/master/docs/headerMiddleware.md

 */
"use strict";
var fluid = require("infusion");

fluid.registerNamespace("fluid.express.middleware.headerSetter");

/**
 *
 * @param {Object} that - The middleware component itself.
 * @param {Any} err - An optional error to pass along to the next piece of middleware in the chain.
 * @param {Object} req - The Express request object.
 * @param {Object} res - The Express response object.
 * @param {Function} next - The function to be executed next in the middleware chain.
 *
 * A middleware function that adds one or more headers before launching the next middleware function in the chain.
 *
 */
fluid.express.middleware.headerSetter.addHeaders = function (that, err, req, res, next) {
    fluid.each(that.options.headers, function (headerOptions) {
        var templateData = fluid.model.transformWithRules({ that: that, request: req }, headerOptions.dataRules);
        var fieldValue = fluid.stringTemplate(headerOptions.template, templateData);

        res.setHeader(headerOptions.fieldName, fieldValue);
    });

    // Ensure that the presence (or absence) of an error is correctly conveyed to the next piece of middleware.
    next.apply(null, fluid.makeArray(err));
};

fluid.defaults("fluid.express.middleware.headerSetter.base", {
    mergePolicy: {
        "headers": "nomerge"
    }
});

fluid.defaults("fluid.express.middleware.headerSetter", {
    gradeNames: ["fluid.express.middleware.headerSetter.base", "fluid.express.middleware"],
    invokers: {
        middleware: {
            funcName: "fluid.express.middleware.headerSetter.addHeaders",
            args:     ["{that}", null, "{arguments}.0", "{arguments}.1", "{arguments}.2"] // err, req, res, next
        }
    }

});

fluid.defaults("fluid.express.middleware.headerSetter.error", {
    gradeNames: ["fluid.express.middleware.headerSetter.base", "fluid.express.middleware.error"],
    invokers: {
        middleware: {
            funcName: "fluid.express.middleware.headerSetter.addHeaders",
            args:     ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2", "{arguments}.3"] // err, req, res, next
        }
    }
});


text:
<?php

  srand();

  $starts     = array("Experiential truth ", "The physical world ", "Non-judgment ", "Quantum physics ");
  $middles    = array("nurtures ", "projects onto ", "imparts reality to ", "constructs with ");
  $qualifiers = array("abundance of ", "the barrier of ", "self-righteous ", "potential ");
  $finishes   = array("marvel.", "choices.", "creativity.", "actions.");

  function random_from($uarray) { return $uarray[rand(0, count($uarray)-1)]; }

  echo implode(" ", array(random_from($starts), random_from($middles), random_from($qualifiers), random_from($finishes) ));

?>


text:
'use strict';

// Import the interface to Tessel hardware
const tessel = require('tessel');

// Turn one of the LEDs on to start.
tessel.led[2].on();

// Blink!
setInterval(() => {
  tessel.led[2].toggle();
  tessel.led[3].toggle();
}, 100);

console.log("I'm blinking! (Press CTRL + C to stop)");


text:
// This file contains methods that modify the path/node in some ways.

import { path as pathCache } from "../cache";
import PathHoister from "./lib/hoister";
import NodePath from "./index";
import * as t from "babel-types";

/**
 * Insert the provided nodes before the current one.
 */

export function insertBefore(nodes) {
  this._assertUnremoved();

  nodes = this._verifyNodeList(nodes);

  if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) {
    return this.parentPath.insertBefore(nodes);
  } else if (
    this.isNodeType("Expression") ||
    (this.parentPath.isForStatement() && this.key === "init")
  ) {
    if (this.node) nodes.push(this.node);
    this.replaceExpressionWithStatements(nodes);
  } else {
    this._maybePopFromStatements(nodes);
    if (Array.isArray(this.container)) {
      return this._containerInsertBefore(nodes);
    } else if (this.isStatementOrBlock()) {
      if (this.node) nodes.push(this.node);
      this._replaceWith(t.blockStatement(nodes));
    } else {
      throw new Error("We don't know what to do with this node type. " +
        "We were previously a Statement but we can't fit in here?");
    }
  }

  return [this];
}

export function _containerInsert(from, nodes) {
  this.updateSiblingKeys(from, nodes.length);

  const paths = [];

  for (let i = 0; i < nodes.length; i++) {
    const to = from + i;
    const node = nodes[i];
    this.container.splice(to, 0, node);

    if (this.context) {
      const path = this.context.create(this.parent, this.container, to, this.listKey);

      // While this path may have a context, there is currently no guarantee that the context
      // will be the active context, because `popContext` may leave a final context in place.
      // We should remove this `if` and always push once #4145 has been resolved.
      if (this.context.queue) path.pushContext(this.context);
      paths.push(path);
    } else {
      paths.push(NodePath.get({
        parentPath: this.parentPath,
        parent: this.parent,
        container: this.container,
        listKey: this.listKey,
        key: to
      }));
    }
  }

  const contexts = this._getQueueContexts();

  for (const path of paths) {
    path.setScope();
    path.debug(() => "Inserted.");

    for (const context of contexts) {
      context.maybeQueue(path, true);
    }
  }

  return paths;
}

export function _containerInsertBefore(nodes) {
  return this._containerInsert(this.key, nodes);
}

export function _containerInsertAfter(nodes) {
  return this._containerInsert(this.key + 1, nodes);
}

export function _maybePopFromStatements(nodes) {
  const last = nodes[nodes.length - 1];
  const isIdentifier = t.isIdentifier(last) ||
    (t.isExpressionStatement(last) && t.isIdentifier(last.expression));

  if (isIdentifier && !this.isCompletionRecord()) {
    nodes.pop();
  }
}

/**
 * Insert the provided nodes after the current one. When inserting nodes after an
 * expression, ensure that the completion record is correct by pushing the current node.
 */

export function insertAfter(nodes) {
  this._assertUnremoved();

  nodes = this._verifyNodeList(nodes);

  if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) {
    return this.parentPath.insertAfter(nodes);
  } else if (
    this.isNodeType("Expression") ||
    (this.parentPath.isForStatement() && this.key === "init")
  ) {
    if (this.node) {
      const temp = this.scope.generateDeclaredUidIdentifier();
      nodes.unshift(t.expressionStatement(t.assignmentExpression("=", temp, this.node)));
      nodes.push(t.expressionStatement(temp));
    }
    this.replaceExpressionWithStatements(nodes);
  } else {
    this._maybePopFromStatements(nodes);
    if (Array.isArray(this.container)) {
      return this._containerInsertAfter(nodes);
    } else if (this.isStatementOrBlock()) {
      if (this.node) nodes.unshift(this.node);
      this._replaceWith(t.blockStatement(nodes));
    } else {
      throw new Error("We don't know what to do with this node type. " +
        "We were previously a Statement but we can't fit in here?");
    }
  }

  return [this];
}

/**
 * Update all sibling node paths after `fromIndex` by `incrementBy`.
 */

export function updateSiblingKeys(fromIndex, incrementBy) {
  if (!this.parent) return;

  const paths = pathCache.get(this.parent);
  for (let i = 0; i < paths.length; i++) {
    const path = paths[i];
    if (path.key >= fromIndex) {
      path.key += incrementBy;
    }
  }
}

export function _verifyNodeList(nodes) {
  if (!nodes) {
    return [];
  }

  if (nodes.constructor !== Array) {
    nodes = [nodes];
  }

  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    let msg;

    if (!node) {
      msg = "has falsy node";
    } else if (typeof node !== "object") {
      msg = "contains a non-object node";
    } else if (!node.type) {
      msg = "without a type";
    } else if (node instanceof NodePath) {
      msg = "has a NodePath when it expected a raw object";
    }

    if (msg) {
      const type = Array.isArray(node) ? "array" : typeof node;
      throw new Error(`Node list ${msg} with the index of ${i} and type of ${type}`);
    }
  }

  return nodes;
}

export function unshiftContainer(listKey, nodes) {
  this._assertUnremoved();

  nodes = this._verifyNodeList(nodes);

  // get the first path and insert our nodes before it, if it doesn't exist then it
  // doesn't matter, our nodes will be inserted anyway
  const path = NodePath.get({
    parentPath: this,
    parent: this.node,
    container: this.node[listKey],
    listKey,
    key: 0
  });

  return path.insertBefore(nodes);
}

export function pushContainer(listKey, nodes) {
  this._assertUnremoved();

  nodes = this._verifyNodeList(nodes);

  // get an invisible path that represents the last node + 1 and replace it with our
  // nodes, effectively inlining it

  const container = this.node[listKey];
  const path = NodePath.get({
    parentPath: this,
    parent: this.node,
    container: container,
    listKey,
    key: container.length
  });

  return path.replaceWithMultiple(nodes);
}

/**
 * Hoist the current node to the highest scope possible and return a UID
 * referencing it.
 */

export function hoist(scope = this.scope) {
  const hoister = new PathHoister(this, scope);
  return hoister.run();
}


text:
package de.htwg.zeta.server.routing.authentication

import scala.concurrent.Future

import com.mohiva.play.silhouette.api.HandlerResult
import play.api.mvc.AnyContent
import play.api.mvc.Request

/**
 */
class UnAuthenticatedWebSocket(
    override val dependencies: AbstractWebSocket.Dependencies
) extends AbstractWebSocketAPI[Request[AnyContent]] {

  override protected[authentication] def handleRequest[T](request: Request[AnyContent])
    (buildFlow: (Request[AnyContent]) => Future[HandlerResult[T]]): Future[HandlerResult[T]] = {
    silhouette.UnsecuredRequestHandler(buildFlow)(request)
  }
}


text:
BEGIN
  EXECUTE IMMEDIATE 'DROP TABLE ndt_log';
EXCEPTION WHEN OTHERS THEN NULL;
END;
/

CREATE TABLE ndt_log (
  log_date DATE NOT NULL,
  log_level VARCHAR2(20) NOT NULL,
  originator VARCHAR2(128),
  log_msg VARCHAR2(512)
)
/

CREATE OR REPLACE PACKAGE ndt_common
  AUTHID DEFINER
  /*******************************************************************************
   * Copyright (c) 2015 Persinity Inc.
   *******************************************************************************/
IS

  -- Logs a message. Does not affect caller on logging failure.
  ERROR CONSTANT PLS_INTEGER := 1;
  INFO CONSTANT PLS_INTEGER := 2;
  DEBUG CONSTANT PLS_INTEGER := 3;
  SUBTYPE log_level IS PLS_INTEGER RANGE 1..3 NOT NULL;
  PROCEDURE log(i_level log_level, i_originator VARCHAR2, i_msg VARCHAR2);

END;
/

CREATE OR REPLACE PACKAGE BODY ndt_common
  /*******************************************************************************
   * Copyright (c) 2015 Persinity Inc.
   *******************************************************************************/
IS
  CONS_TYPE_REF CONSTANT CHAR(1) := 'R';
  CONS_ENABLED CONSTANT CHAR(7) := 'ENABLED';
  CONS_DISABLED CONSTANT CHAR(8) := 'DISABLED';

  PROCEDURE log(i_level log_level, i_originator VARCHAR2, i_msg VARCHAR2) IS
    PRAGMA AUTONOMOUS_TRANSACTION;
    l_msg VARCHAR2(512);
    l_originator VARCHAR2(128);
  BEGIN
    l_originator := SUBSTR(i_originator, 1, 128);
    l_msg := SUBSTR(i_msg, 1, 512);
    -- TODO get rid of the hardcoded schema ndt as this package can be used on destination or custom env.
    INSERT INTO ndt_log (log_date, log_level, originator, log_msg) VALUES (SYSDATE, DECODE(i_level, 1, 'ERROR', 2, 'INFO', 3, 'DEBUG'), l_originator, l_msg);
    COMMIT;
  EXCEPTION WHEN OTHERS THEN
    ROLLBACK;
  END;

END;
/


text:
//
//  IBGLView.m
//  icedcoffee-tests-ios
//
//  Created by Tobias Lensing on 8/4/12.
//  Copyright (C) 2016 Tobias Lensing. All rights reserved.
//

#import "IBGLView.h"

@implementation IBGLView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sticta curvata Ach.

### Remarks
null


text:
require 'spec_helper'
describe 'nova::compute::neutron' do

  context 'with default parameters' do
    it { is_expected.to contain_nova_config('libvirt/vif_driver').with_value('nova.virt.libvirt.vif.LibvirtGenericVIFDriver')}
    it { is_expected.to contain_nova_config('DEFAULT/force_snat_range').with(:value => '0.0.0.0/0') }
  end

  context 'when overriding params' do
    let :params do
      {:libvirt_vif_driver => 'foo' }
    end
    it { is_expected.to contain_nova_config('libvirt/vif_driver').with_value('foo')}
    it { is_expected.to contain_nova_config('DEFAULT/force_snat_range').with_ensure(:absent) }
  end

  context 'when overriding with a removed libvirt_vif_driver param' do
    let :params do
      {:libvirt_vif_driver => 'nova.virt.libvirt.vif.LibvirtOpenVswitchDriver' }
    end

    it_raises 'a Puppet::Error', /nova.virt.libvirt.vif.LibvirtOpenVswitchDriver as vif_driver is removed from Icehouse/
  end

  context 'with force_snat_range parameter set to false' do
    let :params do
      { :force_snat_range => false, }
    end
    it { is_expected.to contain_nova_config('DEFAULT/force_snat_range').with_ensure('absent') }
  end

  context 'with force_snat_range parameter set to 10.0.0.0/24' do
    let :params do
      { :force_snat_range => '10.0.0.0/24', }
    end

    it { is_expected.to contain_nova_config('DEFAULT/force_snat_range').with_value('10.0.0.0/24') }
  end

  context 'with force_snat_range parameter set to fe80::/64' do
    let :params do
      { :force_snat_range => 'fe80::/64', }
    end

    it { is_expected.to contain_nova_config('DEFAULT/force_snat_range').with_value('fe80::/64') }
  end

  context 'with force_snat_range parameter set ip without mask' do
    let :params do
      { :force_snat_range => '10.0.0.0', }
    end

    it_raises 'a Puppet::Error', /force_snat_range should be IPv4 or IPv6 CIDR notation/
  end

end


text:
import * as types from './actionTypes'

export const addScene = (data) => ({
    type: types.ADD_SCENE,
    data
})


text:
<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

/**
 * @group DDC-1655
 * @group DDC-1640
 * @group DDC-1556
 */
class DDC1655Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    public function setUp()
    {
        parent::setUp();

        try {
            $this->_schemaTool->createSchema(
                [
                $this->_em->getClassMetadata(DDC1655Foo::class),
                $this->_em->getClassMetadata(DDC1655Bar::class),
                $this->_em->getClassMetadata(DDC1655Baz::class),
                ]
            );
        } catch(\Exception $e) {
        }
    }

    public function testPostLoadOneToManyInheritance()
    {
        $cm = $this->_em->getClassMetadata(DDC1655Foo::class);
        $this->assertEquals(["postLoad" => ["postLoad"]], $cm->lifecycleCallbacks);

        $cm = $this->_em->getClassMetadata(DDC1655Bar::class);
        $this->assertEquals(["postLoad" => ["postLoad", "postSubLoaded"]], $cm->lifecycleCallbacks);

        $baz = new DDC1655Baz();
        $foo = new DDC1655Foo();
        $foo->baz = $baz;
        $bar = new DDC1655Bar();
        $bar->baz = $baz;

        $this->_em->persist($foo);
        $this->_em->persist($bar);
        $this->_em->persist($baz);
        $this->_em->flush();
        $this->_em->clear();

        $baz = $this->_em->find(get_class($baz), $baz->id);
        foreach ($baz->foos as $foo) {
            $this->assertEquals(1, $foo->loaded, "should have loaded callback counter incremented for " . get_class($foo));
        }
    }

    /**
     * Check that post load is not executed several times when the entity
     * is rehydrated again although its already known.
     */
    public function testPostLoadInheritanceChild()
    {
        $bar = new DDC1655Bar();

        $this->_em->persist($bar);
        $this->_em->flush();
        $this->_em->clear();

        $bar = $this->_em->find(get_class($bar), $bar->id);
        $this->assertEquals(1, $bar->loaded);
        $this->assertEquals(1, $bar->subLoaded);

        $bar = $this->_em->find(get_class($bar), $bar->id);
        $this->assertEquals(1, $bar->loaded);
        $this->assertEquals(1, $bar->subLoaded);

        $dql = "SELECT b FROM " . __NAMESPACE__ . "\DDC1655Bar b WHERE b.id = ?1";
        $bar = $this->_em->createQuery($dql)->setParameter(1, $bar->id)->getSingleResult();

        $this->assertEquals(1, $bar->loaded);
        $this->assertEquals(1, $bar->subLoaded);

        $this->_em->refresh($bar);

        $this->assertEquals(2, $bar->loaded);
        $this->assertEquals(2, $bar->subLoaded);
    }
}

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorMap({
 *    "foo" = "DDC1655Foo",
 *    "bar" = "DDC1655Bar"
 * })
 * @HasLifecycleCallbacks
 */
class DDC1655Foo
{
    /** @Id @GeneratedValue @Column(type="integer") */
    public $id;

    public $loaded = 0;

    /**
     * @ManyToOne(targetEntity="DDC1655Baz", inversedBy="foos")
     */
    public $baz;

    /**
     * @PostLoad
     */
    public function postLoad()
    {
        $this->loaded++;
    }
}

/**
 * @Entity
 * @HasLifecycleCallbacks
 */
class DDC1655Bar extends DDC1655Foo
{
    public $subLoaded;

    /**
     * @PostLoad
     */
    public function postSubLoaded()
    {
        $this->subLoaded++;
    }
}

/**
 * @Entity
 */
class DDC1655Baz
{
    /** @Id @GeneratedValue @Column(type="integer") */
    public $id;

    /**
     * @OneToMany(targetEntity="DDC1655Foo", mappedBy="baz")
     */
    public $foos = [];
}


text:
<!doctype html>
<html>
<head>
  <title>Shuttle</title>
  <meta name="viewport" content="width=device-width">
  <script src="../../../polymer/polymer.js" shadow="native"></script>
  <script src="https://uitoolkit.googleplex.com/schedule.js"></script>
  <script src="mock_schedule.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
  <link rel="import" href="shuttle-app.html">
  <link rel="stylesheet" href="../../../polymer-ui-elements/basic.css">
  <style>
    shuttle-app {
      -webkit-user-select: none;
    }
  </style>
</head>
<body class="polymer-ui-body-text">
  <shuttle-app class="polymer-ui-fit" theme="polymer-ui-light-theme"></shuttle-app>
</body>
</html>