text:
"""Demonstration-suitable implementation of the face layer of RPC Framework."""

from grpc.framework.base import util as _base_util
from grpc.framework.base.packets import implementations as _tickets_implementations
from grpc.framework.face import implementations
from grpc.framework.foundation import logging_pool

_POOL_SIZE_LIMIT = 20

_MAXIMUM_TIMEOUT = 90

class LinkedPair(object):
  """A Server and Stub that are linked to one another.

  Attributes:
    server: A Server.
    stub: A Stub.
  """

  def shut_down(self):
    """Shuts down this object and releases its resources."""
    raise NotImplementedError()

class _LinkedPair(LinkedPair):

  def __init__(self, server, stub, front, back, pools):
    self.server = server
    self.stub = stub
    self._front = front
    self._back = back
    self._pools = pools

  def shut_down(self):
    _base_util.wait_for_idle(self._front)
    _base_util.wait_for_idle(self._back)

    for pool in self._pools:
      pool.shutdown(wait=True)

def server_and_stub(
    default_timeout,
    inline_value_in_value_out_methods=None,
    inline_value_in_stream_out_methods=None,
    inline_stream_in_value_out_methods=None,
    inline_stream_in_stream_out_methods=None,
    event_value_in_value_out_methods=None,
    event_value_in_stream_out_methods=None,
    event_stream_in_value_out_methods=None,
    event_stream_in_stream_out_methods=None,
    multi_method=None):
  """Creates a Server and Stub linked together for use."""
  front_work_pool = logging_pool.pool(_POOL_SIZE_LIMIT)
  front_transmission_pool = logging_pool.pool(_POOL_SIZE_LIMIT)
  front_utility_pool = logging_pool.pool(_POOL_SIZE_LIMIT)
  back_work_pool = logging_pool.pool(_POOL_SIZE_LIMIT)
  back_transmission_pool = logging_pool.pool(_POOL_SIZE_LIMIT)
  back_utility_pool = logging_pool.pool(_POOL_SIZE_LIMIT)
  stub_pool = logging_pool.pool(_POOL_SIZE_LIMIT)
  pools = (
      front_work_pool, front_transmission_pool, front_utility_pool,
      back_work_pool, back_transmission_pool, back_utility_pool,
      stub_pool)

  servicer = implementations.servicer(
      back_work_pool,
      inline_value_in_value_out_methods=inline_value_in_value_out_methods,
      inline_value_in_stream_out_methods=inline_value_in_stream_out_methods,
      inline_stream_in_value_out_methods=inline_stream_in_value_out_methods,
      inline_stream_in_stream_out_methods=inline_stream_in_stream_out_methods,
      event_value_in_value_out_methods=event_value_in_value_out_methods,
      event_value_in_stream_out_methods=event_value_in_stream_out_methods,
      event_stream_in_value_out_methods=event_stream_in_value_out_methods,
      event_stream_in_stream_out_methods=event_stream_in_stream_out_methods,
      multi_method=multi_method)

  front = _tickets_implementations.front(
      front_work_pool, front_transmission_pool, front_utility_pool)
  back = _tickets_implementations.back(
      servicer, back_work_pool, back_transmission_pool, back_utility_pool,
      default_timeout, _MAXIMUM_TIMEOUT)
  front.join_rear_link(back)
  back.join_fore_link(front)

  stub = implementations.stub(front, stub_pool)

  return _LinkedPair(implementations.server(), stub, front, back, pools)


text:
from trt_layer_auto_scan_test import TrtLayerAutoScanTest
from program_config import TensorConfig, ProgramConfig
import unittest
import numpy as np
import paddle.inference as paddle_infer
from functools import partial
from typing import Any, Dict, List

class TrtConvertSoftmaxTest(TrtLayerAutoScanTest):
    def is_program_valid(self, program_config: ProgramConfig) -> bool:
        inputs = program_config.inputs
        weights = program_config.weights
        outputs = program_config.outputs

        attrs = [
            program_config.ops[i].attrs for i in range(len(program_config.ops))
        ]

        # The input dimension should be less than or equal to the set axis.
        if len(inputs['softmax_input'].shape) <= attrs[0]['axis']:
            return False

        return True

    def sample_program_configs(self):
        def generate_input1(attrs: List[Dict[str, Any]], batch):
            if self.dims == 4:
                return np.ones([batch, 3, 24, 24]).astype(np.float32)
            elif self.dims == 3:
                return np.ones([batch, 3, 24]).astype(np.float32)
            elif self.dims == 2:
                return np.ones([batch, 32]).astype(np.float32)

        for dims in [2, 3, 4]:
            for batch in [1, 2, 4]:
                for axis in [-1, 0, 1, 2, 3]:
                    self.dims = dims
                    dics = [{"axis": axis}, {}]
                    ops_config = [
                        {
                            "op_type": "softmax",
                            "op_inputs": {"X": ["softmax_input"]},
                            "op_outputs": {"Out": ["softmax_out"]},
                            "op_attrs": dics[0],
                        }
                    ]
                    ops = self.generate_op_config(ops_config)
                    program_config = ProgramConfig(
                        ops=ops,
                        weights={},
                        inputs={
                            "softmax_input": TensorConfig(
                                data_gen=partial(generate_input1, dics, batch)
                            )
                        },
                        outputs=["softmax_out"],
                    )

                    yield program_config

    def sample_predictor_configs(
        self, program_config
    ) -> (paddle_infer.Config, List[int], float):
        def generate_dynamic_shape(attrs):
            if self.dims == 4:
                self.dynamic_shape.min_input_shape = {
                    "softmax_input": [1, 3, 24, 24]
                }
                self.dynamic_shape.max_input_shape = {
                    "softmax_input": [4, 3, 48, 48]
                }
                self.dynamic_shape.opt_input_shape = {
                    "softmax_input": [1, 3, 24, 48]
                }
            elif self.dims == 3:
                self.dynamic_shape.min_input_shape = {
                    "softmax_input": [1, 3, 24]
                }
                self.dynamic_shape.max_input_shape = {
                    "softmax_input": [4, 3, 48]
                }
                self.dynamic_shape.opt_input_shape = {
                    "softmax_input": [1, 3, 48]
                }
            elif self.dims == 2:
                self.dynamic_shape.min_input_shape = {"softmax_input": [1, 32]}
                self.dynamic_shape.max_input_shape = {"softmax_input": [4, 64]}
                self.dynamic_shape.opt_input_shape = {"softmax_input": [1, 32]}

        def clear_dynamic_shape():
            self.dynamic_shape.min_input_shape = {}
            self.dynamic_shape.max_input_shape = {}
            self.dynamic_shape.opt_input_shape = {}

        def generate_trt_nodes_num(attrs, dynamic_shape):
            return 1, 2

        attrs = [
            program_config.ops[i].attrs for i in range(len(program_config.ops))
        ]
        # for static_shape
        clear_dynamic_shape()
        if attrs[0]['axis'] == 0:
            pass
        else:
            self.trt_param.precision = paddle_infer.PrecisionType.Float32
            yield self.create_inference_config(), generate_trt_nodes_num(
                attrs, False
            ), 1e-5
            self.trt_param.precision = paddle_infer.PrecisionType.Half
            yield self.create_inference_config(), generate_trt_nodes_num(
                attrs, False
            ), 1e-3

        # for dynamic_shape
        generate_dynamic_shape(attrs)
        self.trt_param.precision = paddle_infer.PrecisionType.Float32
        yield self.create_inference_config(), generate_trt_nodes_num(
            attrs, True
        ), 1e-5
        self.trt_param.precision = paddle_infer.PrecisionType.Half
        yield self.create_inference_config(), generate_trt_nodes_num(
            attrs, True
        ), 1e-3

    def test(self):
        self.run_test()

if __name__ == "__main__":
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
.DEFAULT_GOAL := run
SHELL := bash
.SHELLFLAGS := -euo pipefail -c
.DELETE_ON_ERROR:
MAKEFLAGS += --warn-undefined-variables
MAKEFLAGS += --no-builtin-rules

_FLAGS ?= ""
_POSTS := building-a-blog.md \
		 zero-to-code-monkey.md \
		 audible-literacy-filter.md \
		 language-use-on-github.md \
		 soft-deletion-in-django.md \
		 license-your-code.md \
		 testing-django-fields.md \
		 podcasts-for-developers.md \
		 decade-of-cap.md \
		 getting-started-with-go.md \
		 lazy-loading-data-with-swiftui-and-combine.md \
		 recipes/garam-masala.md \
		 recipes/bakers-percentages.md \
		 recipes/sourdough-starter.md \
		 recipes/focaccia.md \
		 recipes/chicken-kebabs.md \
		 recipes/methi-murgh.md \
		 grit.md \
		 recipes/waffles.md \
		 recipes/hokkaido-milk-bread.md \
		 recipes/pizza.md \
		 automating-gmail-with-appsscript.md \
		 recipes/coriander-mint-chutney.md \
		 recipes/methi-dal.md \
		 sourdough.md \
		 recipes/pancakes.md \
		 go-time-protobuf-grpc.md

.PHONY: help
help: ## Describe useful make targets
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "%-30s %s\n", $$1, $$2}'

.PHONY: clean
clean: ## Delete intermediate build artifacts
	rm -rf tmp cmd/serve/static cmd/serve/recipes
	rm -f cmd/serve/favicon.ico cmd/serve/*.html

.PHONY: upgrade
upgrade: ## Upgrade Go dependencies
	go get -u -t ./...
	go mod tidy -v

.PHONY: run
run: build tmp/serve ## Run on :8080
	@./tmp/serve

.PHONY: deploy
deploy: INITIAL = $(strip $(shell gcloud config get-value account))
deploy: WANT := akshay@akshayshah.org
deploy: PROJECT := blog-276404/blog
deploy: ## Deploy to GCP
	# Gross, but ensures that I don't forget to run `make clean`.
	$(MAKE) clean
	$(MAKE) build
ifneq ($(WANT),$(INITIAL))
	gcloud config set account $(WANT)
endif
	gcloud auth configure-docker us-central1-docker.pkg.dev
	docker build -t us-central1-docker.pkg.dev/$(PROJECT)/blog:latest .
	docker push us-central1-docker.pkg.dev/$(PROJECT)/blog:latest
	gcloud run deploy blog \
		--image=us-central1-docker.pkg.dev/$(PROJECT)/blog:latest \
		--port=8080 \
		--concurrency=512 \
		--cpu=2 \
		--ingress=all \
		--max-instances=5 \
		--min-instances=default \
		--memory=512Mi \
		--platform=managed \
		--timeout=30s \
		--use-http2 \
		--allow-unauthenticated \
		--cpu-throttling \
		--region=us-central1
ifneq ($(WANT),$(INITIAL))
	gcloud config set account $(INITIAL)
endif

define render-post
	@echo "Rendering $<..."
	@mkdir -p $(@D)
	@tmp/build -style style.css $(_FLAGS) $< > $@
endef

define post-template
build: cmd/serve/$(basename $1).html
cmd/serve/$(basename $1).html: $1 tmp/build page.html style.css
	$$(render-post)
endef

.PHONY: build
build:
	@rm -rf cmd/serve/static && cp -R static cmd/serve
	@cp -p favicon.ico cmd/serve/favicon.ico

tmp/build: go.mod cmd/build/main.go
	@go build -o tmp/build ./cmd/build

tmp/serve: build go.mod cmd/serve/main.go
	@go build -o tmp/serve ./cmd/serve

build: cmd/serve/404.html
cmd/serve/404.html: _FLAGS = -nodates
cmd/serve/404.html: 404.md tmp/build style.css
	$(render-post)

tmp/index.md: index.md style.css tmp/build $(_POSTS)
	@mkdir -p $(@D)
	@tmp/build -recipes recipes -style style.css -index $(_POSTS) > $@

build: cmd/serve/index.html
cmd/serve/index.html: _FLAGS = -nodates -nohome
cmd/serve/index.html: tmp/index.md style.css tmp/build
	$(render-post)

build: cmd/serve/colophon.html
cmd/serve/colophon.html: colophon.md tmp/build page.html style.css
	$(render-post)

build: cmd/serve/license.html
cmd/serve/license.html: _FLAGS = -nolicense -nodates
cmd/serve/license.html: license.md tmp/build page.html style.css
	$(render-post)

$(foreach post,$(_POSTS),$(eval $(call post-template,$(post))))


text:
<?php

use Faker\Factory as Faker;
use Illuminate\Database\Seeder;

class ArticlesTableSeeder extends Seeder
{
    public function run()
    {
        $faker = Faker::create('zh_CN');

        $userIds = \App\User::lists('id');
        $tagIds = \App\Tag::lists('id');
        $categoryIds = \App\Category::lists('id');

        foreach (range(1, 150) as $index) {
            $article = \App\Article::create([
                'title' => $faker->sentence,
                'body' => $faker->paragraph(20),
                'click' => $faker->numberBetween(100, 9000),
                'slug' => $faker->unique()->slug,
                'category_id' => $faker->randomElement($categoryIds),
                'user_id' => $faker->randomElement($userIds),
                'original' => $faker->optional(0.5)->url,
                'created_at' => $faker->dateTimeThisYear(),
                'updated_at' => $faker->dateTimeThisYear(),
                'deleted_at' => $faker->optional(0.1)->dateTimeThisYear(),
            ]);

            $tags = $faker->randomElements($tagIds, 3);

            $article->tags()->sync($tags);
        }
    }
}


text:
package com.forerunnergames.tools.common;

import ch.fourmilab.randomx.RandomHotBits;

import com.google.common.collect.Lists;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

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

/**
 * Utility class for random-number-related functionality.
 */
public final class Randomness
{
  // @formatter:off
  private static final Logger log = LoggerFactory.getLogger (Randomness.class);
  private static final int SEED_BYTES = 8; // The number of bytes used to seed the pseudo random number generator.
  private static final int RESEED_THRESHOLD = 10000; // The number of random numbers that can be generated before reseeding.
  private static final RandomHotBits TRNG = new RandomHotBits (); // True random number generator, used for seeding only, and only in RELEASE mode.
  private static long reseedCounter = 0; // Keeps track of how many random numbers have been generated for reseeding purposes.
  private static SecureRandom csprng; // Cryptographically secure pseudo random number generator.
  private static Mode currentMode;
  // @formatter:on

  // Initialize the random number generator.
  static
  {
    setModeTo (Mode.DEBUG);
  }

  /**
   * The default mode is DEBUG.
   */
  public enum Mode
  {
    /**
     * Uses system entropy to seed a cryptographically-secure random number generator.
     */
    DEBUG,

    /**
     * Uses HotBits entropy (https://www.fourmilab.ch/hotbits) to seed a cryptographically-secure random number
     * generator. WARNING: HotBits will attempt to connect to and download the entropy from a remote server, so internet
     * access is required, and the remote server must be online & functioning. If obtaining HotBits entropy fails, it
     * will automatically fall back to using system entropy, with a log entry explaining what went wrong.
     */
    RELEASE
  }

  /**
   * Checks whether the specified mode is set.
   *
   * @param mode
   *          The mode to check, must not be null.
   */
  public static boolean isMode (final Mode mode)
  {
    Arguments.checkIsNotNull (mode, "mode");

    return mode.equals (currentMode);
  }

  /**
   * Sets the specified mode. Idempotent - nothing will happen if the specified mode has already been set.
   *
   * @param mode
   *          The mode to set, must not be null.
   *
   * @see #isMode
   */
  public static void setModeTo (final Mode mode)
  {
    Arguments.checkIsNotNull (mode, "mode");

    if (isMode (mode)) return;

    currentMode = mode;

    createCsprng ();

    switch (mode)
    {
      case DEBUG:
      {
        reseedCsprngWithSystemEntropy ();

        break;
      }
      case RELEASE:
      {
        reseedCsprngWithHotBitsEntropy ();

        break;
      }
    }
  }

  /**
   * Gets a random integer in the range [inclusiveLowerBound, inclusiveUpperBound] using a cryptographically secure
   * pseudo random number generator.
   *
   * @param inclusiveLowerBound
   *          The inclusive lower bound, must be >= 0 and <= inclusiveUpperBound and < Integer.MAX_VALUE.
   * @param inclusiveUpperBound
   *          The inclusive upper bound, must be >= 0 and >= inclusiveLowerBound and < Integer.MAX_VALUE.
   */
  public static int getRandomIntegerFrom (int inclusiveLowerBound, int inclusiveUpperBound)
  {
    Arguments.checkIsNotNegative (inclusiveLowerBound, "inclusiveLowerBound");
    Arguments.checkIsNotNegative (inclusiveUpperBound, "inclusiveUpperBound");
    Arguments.checkUpperExclusiveBound (inclusiveLowerBound, Integer.MAX_VALUE, "inclusiveLowerBound",
                                        "Integer.MAX_VALUE");
    Arguments.checkUpperExclusiveBound (inclusiveUpperBound, Integer.MAX_VALUE, "inclusiveUpperBound",
                                        "Integer.MAX_VALUE");
    Arguments.checkUpperInclusiveBound (inclusiveLowerBound, inclusiveUpperBound, "inclusiveLowerBound",
                                        "inclusiveUpperBound");

    final long n = (long) inclusiveUpperBound - inclusiveLowerBound + 1;

    assert n > 0;
    assert n <= Integer.MAX_VALUE;

    checkCsprngUsage ();

    final long randomNumber = (long) inclusiveLowerBound + csprng.nextInt ((int) n);

    updateCsprngUsage (1);

    assert randomNumber >= inclusiveLowerBound;
    assert randomNumber <= inclusiveUpperBound;

    return (int) randomNumber;
  }

  /**
   * Gets a random double in the range [0.0, 1.0) using a cryptographically secure pseudo random number generator.
   */
  public static double getRandomDouble ()
  {
    checkCsprngUsage ();

    final double randomNumber = csprng.nextDouble ();

    updateCsprngUsage (1);

    return randomNumber;
  }

  /**
   * Obtains a random element from the specified collection using a cryptographically secure pseudo random number
   * generator.
   *
   * @param <T>
   *          The element type of the specified collection.
   * @param collection
   *          The collection to obtain a random element from, must not be null, must not contain null elements, must not
   *          be empty.
   *
   * @return A random element from the specified collection.
   */
  public static <T> T getRandomElementFrom (final Collection <T> collection)
  {
    Arguments.checkIsNotNull (collection, "collection");
    Arguments.checkHasNoNullElements (collection, "collection");
    Preconditions.checkIsFalse (collection.isEmpty (), "Cannot get random element from an empty collection.");

    return shuffle (collection).get (0);
  }

  /**
   * Obtains a random element from the specified elements using a cryptographically secure pseudo random number
   * generator.
   *
   * @param <T>
   *          The elements' type.
   * @param elements
   *          The elements to obtain a random element from, must not be null, must not contain null elements, must not
   *          be empty.
   *
   * @return A random element from the specified elements.
   */
  @SafeVarargs
  public static <T> T getRandomElementFrom (final T... elements)
  {
    Arguments.checkIsNotNull (elements, "elements");
    Arguments.checkHasNoNullElements (elements, "elements");
    Preconditions.checkIsTrue (elements.length > 0, "Cannot get random element from empty varargs elements.");

    return shuffle (elements).get (0);
  }

  /**
   * Shuffles a copy of the specified iterable using a cryptographically secure pseudo random number generator.
   *

   * NOTE: The original iterable will not be modified.
   *
   * @param <T>
   *          The element type of the specified iterable.
   * @param iterable
   *          The iterable to be shuffled, must not be null, may be immutable / unmodifiable, may contain null elements.
   *
   * @return A shuffled, mutable copy of the original iterable.
   */
  public static <T> List <T> shuffle (final Iterable <T> iterable)
  {
    Arguments.checkIsNotNull (iterable, "iterable");

    checkCsprngUsage ();

    final List <T> listCopy = Lists.newArrayList (iterable);

    Collections.shuffle (listCopy, csprng);

    updateCsprngUsage (listCopy.size ());

    return listCopy;
  }

  /**
   * Shuffles a copy of the specified elements using a cryptographically secure pseudo random number generator.
   *

   * NOTE: The original element array will not be modified.
   *
   * @param <T>
   *          The elements' type.
   * @param elements
   *          The elements to be shuffled, must not be null, may contain null elements.
   *
   * @return A shuffled, mutable copy of the original elements.
   */
  @SafeVarargs
  public static <T> List <T> shuffle (final T... elements)
  {
    Arguments.checkIsNotNull (elements, "elements");

    return shuffle (Arrays.asList (elements));
  }

  private static void createCsprng ()
  {
    try
    {
      csprng = SecureRandom.getInstance ("SHA1PRNG", "SUN");
    }
    catch (final NoSuchProviderException e)
    {
      try
      {
        final Provider[] providers = Security.getProviders ();

        if (providers == null || providers.length == 0)
        {
          throw new RuntimeException ("Cannot create random number generator.", e);
        }

        final Provider provider = providers [0];

        log.warn ("Cannot find SUN provider, trying default (preferred) provider: {}.", provider);

        csprng = SecureRandom.getInstance ("SHA1PRNG", provider);
      }
      catch (final NoSuchAlgorithmException e1)
      {
        throw new RuntimeException ("Cannot create random number generator.", e);
      }
    }
    catch (final NoSuchAlgorithmException e)
    {
      throw new RuntimeException ("Cannot create random number generator.", e);
    }
  }

  private static void reseedCsprngWithSystemEntropy ()
  {
    csprng.setSeed (generateSystemEntropySeed ());
  }

  private static byte[] generateSystemEntropySeed ()
  {
    return csprng.generateSeed (SEED_BYTES);
  }

  private static void reseedCsprngWithHotBitsEntropy ()
  {
    csprng.setSeed (generateHotBitsEntropySeed ());
  }

  private static byte[] generateHotBitsEntropySeed ()
  {
    try
    {
      final byte[] trueRandomEntropySeed = new byte [SEED_BYTES];

      for (int i = 0; i < trueRandomEntropySeed.length; ++i)
      {
        trueRandomEntropySeed [i] = TRNG.nextByte ();
      }

      return trueRandomEntropySeed;
    }
    catch (final RuntimeException e)
    {
      log.warn ("Could not obtain HotBits entropy! Falling back to a system entropy source.", e);

      return generateSystemEntropySeed ();
    }
  }

  private static void checkCsprngUsage ()
  {
    if (shouldReseedCsprng ()) reseedCsprng ();
  }

  private static boolean shouldReseedCsprng ()
  {
    return reseedCounter > RESEED_THRESHOLD;
  }

  private static void reseedCsprng ()
  {
    reseedCounter = 0;

    switch (currentMode)
    {
      case DEBUG:
      {
        reseedCsprngWithSystemEntropy ();

        break;
      }
      case RELEASE:
      {
        reseedCsprngWithHotBitsEntropy ();

        break;
      }
    }
  }

  private static void updateCsprngUsage (final int timesUsed)
  {
    reseedCounter += timesUsed;
  }
}


text:
<html>
<body>
This inspection detects reflective access to classes which aren't visible due to Java 9 module accessibility rules.
</body>
</html>


text:
class Mimabox
  # Because it will be marshal to JSON and unmarshal back,
  # thus its keys are strings, not symbols.
  def self.make(fields)
    raise(ArgumentError, 'Title is required', caller) unless fields.key?('title')

    {
      'title' => fields['title'],
      'username' => fields['username'] || '',
      'password' => fields['password'] || '',
      'website' => fields['website'] || '',
      'notes' => fields['notes'] || '',
      'fav' => fields.key?('fav') && fields['fav'] != 0 ? 1 : 0
    }
  end
end


text:
require 'rails_helper'

RSpec.describe CustomDevise::RegistrationsController, type: :controller do

end


text:
package com.drew.metadata.adobe;

import com.drew.lang.BufferBoundsException;
import com.drew.lang.BufferReader;
import com.drew.lang.annotations.NotNull;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataReader;

/**
 * Decodes Adobe formatted data stored in JPEG files, normally in the APPE (App14) segment.
 *
 * @author Philip, Drew Noakes http://drewnoakes.com
 */
public class AdobeJpegReader implements MetadataReader
{
    public void extract(@NotNull byte[] data, @NotNull Metadata metadata)
    {
        final Directory directory = metadata.getOrCreateDirectory(AdobeJpegDirectory.class);

        if (data.length != 12) {
            directory.addError(String.format("Adobe JPEG data is expected to be 12 bytes long, not %d.", data.length));
            return;
        }

        try {
            BufferReader reader = new BufferReader(data);
            reader.setMotorolaByteOrder(false);

            if (!reader.getString(0, 5).equals("Adobe")) {
                directory.addError("Invalid Adobe JPEG data header.");
                return;
            }

            directory.setInt(AdobeJpegDirectory.TAG_DCT_ENCODE_VERSION, reader.getUInt16(5));
            directory.setInt(AdobeJpegDirectory.TAG_APP14_FLAGS0, reader.getUInt16(7));
            directory.setInt(AdobeJpegDirectory.TAG_APP14_FLAGS1, reader.getUInt16(9));
            directory.setInt(AdobeJpegDirectory.TAG_COLOR_TRANSFORM, reader.getByte(11));
        } catch (BufferBoundsException ex) {
            directory.addError("Exif data segment ended prematurely");
        }
    }
}


text:
'use strict';

var utils = require('./utils');

module.exports = function(name, config) {
  if (typeof name !== 'string') {
    config = name;
    name = undefined;
  }

  return function plugin(app) {
    if (!utils.isValid(app)) return;

    // if `name` is not passed, get the project name
    if (typeof name === 'undefined') {
      name = utils.project(process.cwd());
    }

    var opts = utils.extend({}, config, app.options.store);
    this.define('store', utils.store(name, opts));

    /**
     * Bubble up a few events to `app`
     */

    this.store.on('set', function(key, val) {
      app.emit('store.set', key, val);
      app.emit('store', 'set', key, val);
    });

    this.store.on('get', function(key, val) {
      app.emit('store.get', key, val);
      app.emit('store', 'get', key, val);
    });

    this.store.on('del', function(key, val) {
      app.emit('store.del', key, val);
      app.emit('store', 'del', key, val);
    });

    return plugin;
  };
};


text:
<x:widget extends="Example" controller="CheckTreeExample">
	<template>
		<div style="position: relative;height: 320px;width: 350px;overflow: auto;border: 1px solid gray;">
			<x:widget extends="FolderTree">
				<assign name="records">$tree_example.records</assign>
				<include name="node_body_content">
					<checkbox style="float: right">
						<x:assign name="is_checked">node.is_checked</x:assign>
						<x:assign name="is_indeterminate">node.is_indeterminate</x:assign>
						<x:roles>$tree_example._checkbox</x:roles>
					</checkbox>
					{> $tree.FolderTree$node_body_content}
				</include>
				<script x:equiv="options" type="lava/options">
					{
						meta_storage_columns: ["is_expanded"],
						refresher: {type: 'Collapse'}
					}
				</script>
			</x:widget>
		</div>
	</template>
	<assign name="records">#ExamplesApp.tree_records</assign>
</x:widget>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <litepal>

        <dbname value="cool_weather" />

        <version value="1" />

        <list>
            <mapping class="com.coolweather.android.db.Province" />
            <mapping class="com.coolweather.android.db.City" />
            <mapping class="com.coolweather.android.db.County" />
        </list>
    </litepal>

</resources>


text:
<?php

namespace Opifer\CmsBundle\Controller\Backend;

use APY\DataGridBundle\Grid\Action\RowAction;
use APY\DataGridBundle\Grid\Source\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Opifer\CmsBundle\Entity\Site;
use Opifer\CmsBundle\Form\Type\SiteType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

class SiteController extends Controller
{
    /**
     * @return Response
     */
    public function indexAction()
    {
        $this->denyAccessUnlessGranted('SITE_INDEX');

        $source = new Entity(Site::class);

        $editAction = new RowAction('edit', 'opifer_cms_site_edit');
        $editAction->setRouteParameters(['id']);

        $deleteAction = new RowAction('delete', 'opifer_cms_site_delete');
        $deleteAction->setRouteParameters(['id']);

        $grid = $this->get('grid');
        $grid->setId('sites')
            ->setSource($source)
            ->addRowAction($editAction)
            ->addRowAction($deleteAction);

        return $grid->getGridResponse('@OpiferCms/Backend/Site/index.html.twig');
    }

    /**
     * @param Request $request
     *
     * @return RedirectResponse|Response
     */
    public function createAction(Request $request)
    {
        $this->denyAccessUnlessGranted('SITE_CREATE');

        $site = new Site();

        $form = $this->createForm(SiteType::class, $site);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            foreach ($form->getData()->getDomains() as $domain) {
                $domain->setSite($site);

                $em->persist($domain);
            }

            $em->persist($site);
            $em->flush();

            return $this->redirectToRoute('opifer_cms_site_edit', ['id' => $site->getId()]);
        }

        return $this->render('@OpiferCms/Backend/Site/create.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    /**
     * @param Request $request
     * @param int     $id
     *
     * @return RedirectResponse|Response
     */
    public function editAction(Request $request, $id)
    {
        $this->denyAccessUnlessGranted('SITE_EDIT');

        $em = $this->getDoctrine()->getManager();
        $site = $em->getRepository(Site::class)->find($id);

        $originalDomains = new ArrayCollection();
        foreach ($site->getDomains() as $domain) {
            $originalDomains->add($domain);
        }

        $form = $this->createForm(SiteType::class, $site);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            // Remove deleted domains
            foreach ($originalDomains as $domain) {
                if (false === $site->getDomains()->contains($domain)) {
                    $em->remove($domain);
                }
            }

            // Add new domain
            foreach ($form->getData()->getDomains() as $domain) {
                $domain->setSite($site);
            }
            $em->persist($domain);

            $em->flush();

            return $this->redirectToRoute('opifer_cms_site_edit', ['id' => $site->getId()]);
        }

        return $this->render('@OpiferCms/Backend/Site/edit.html.twig', [
            'form' => $form->createView(),
            'site' => $site,
        ]);
    }

    /**
     * @param int $id
     *
     * @return RedirectResponse
     */
    public function deleteAction($id)
    {
        $this->denyAccessUnlessGranted('SITE_DELETE');

        $em = $this->getDoctrine()->getManager();
        $site = $em->getRepository(Site::class)->find($id);

        $em->remove($site);
        $em->flush();

        return $this->redirectToRoute('opifer_cms_site_index');
    }
}


text:
> ZBJCalendar is a simple way to create a calendar view. The concept of ZBJCalendar is UICollectionView or UITableView.

> As we know, UICollectionView and UITableView set up the corresponding relations between cell and indexPath. Differently, ZBJCalendar set up the corresponding relations between cell and date, this is important to understand ZBJCalendar.

## Requirements

 * iOS7 or later

## Installation with CocoaPods
`pod 'ZBJCalendar'`

## Installation with Carthage
`github "wanggang316/ZBJCalendar"`

## Architecture

### ZBJCalendarView

This is the main class of ZBJCalendar, an instance of this is a calendar view.

You can find some familiar properties and new properties:

 * `dataSource` is `<ZBJCalendarDataSource>` protocol property which  used to custom cells or headers
 * `delegate` is `<ZBJCalendarDelegate>` protocol property which used to handle the display and behaviour of the day cells.
 * `firstDate` and `lastDate` use to set the calendar's start date and end date.
 * `selectionMode` is a enum of `ZBJSelectionMode` which express the single selection or mutable selection or can't be select.

Also, it contains some familiar methods like:
 * `- (void)registerCellClass:(id)clazz withReuseIdentifier:(NSString *)identifier;`
 * `- (void)reloadData;`
 * `- (id)cellAtDate:(NSDate *)date;`
 * `- (void)reloadCellsAtDates:(NSSet<NSDate *> *)dates;`

#### <ZBJCalendarDataSource>

A protocol to custom the cell data model object. It supplies the cell and supplementary view's information about appearance and data.

* `- (void)calendarView:(ZBJCalendarView *)calendarView configureCell:(id)cell forDate:(NSDate *)date;`
* `- (void)calendarView:(ZBJCalendarView *)calendarView configureSectionHeaderView:(id)headerView firstDateOfMonth:(NSDate *)firstDateOfMonth;`
* `- (void)calendarView:(ZBJCalendarView *)calendarView configureSectionFooterView:(id)headerView lastDateOfMonth:(NSDate *)lastDateOfMonth;`
* `- (void)calendarView:(ZBJCalendarView *)calendarView configureWeekDayLabel:(UILabel *)dayLabel atWeekDay:(NSInteger)weekDay;`

#### <ZBJCalendarDelegate>

A protocol use to handle the display and behaviour of ZBJCalendar.

* `- (BOOL)calendarView:(ZBJCalendarView *)calendarView shouldSelectDate:(NSDate *)date;`
* `- (void)calendarView:(ZBJCalendarView *)calendarView didSelectDate:(NSDate *)date ofCell:(id)cell;`

### ZBJCalendarWeekView

ZBJCalendar provider a week view by this class, you can change it's style by implement <ZBJCalendarDataSource>

### NSDate+ZBJAddition

This category provide utility methods for `NSDate`.

### NSDate+IndexPath

 This category provide methods used to corresponding relations between indexpath and date.

## Examples

![show](./screenshots/00.png)

## License

ZBJCalendar is released under the MIT license.


text:
<?php

namespace Accompli\Task;

use Accompli\AccompliEvents;
use Accompli\Chrono\Repository;
use Accompli\Deployment\Connection\ConnectionAdapterProcessExecutor;
use Accompli\Deployment\Release;
use Accompli\EventDispatcher\Event\LogEvent;
use Accompli\EventDispatcher\Event\PrepareReleaseEvent;
use Accompli\EventDispatcher\EventDispatcherInterface;
use Accompli\Exception\TaskCommandExecutionException;
use Psr\Log\LogLevel;

/**
 * RepositoryCheckoutTask.
 *
 * @author Niels Nijens <nijens.niels@gmail.com>
 */
class RepositoryCheckoutTask extends AbstractConnectedTask
{
    /**
     * The URL of the repository.
     *
     * @var string
     */
    private $repositoryUrl;

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            AccompliEvents::PREPARE_RELEASE => array(
                array('onPrepareReleaseConstructReleaseInstance', 10),
                array('onPrepareReleaseCheckoutRepository', 0),
            ),
        );
    }

    /**
     * Constructs a new RepositoryCheckoutTask.
     *
     * @param string $repositoryUrl
     */
    public function __construct($repositoryUrl)
    {
        $this->repositoryUrl = $repositoryUrl;
    }

    /**
     * Creates a Release instance when not already available.
     *
     * @param PrepareReleaseEvent $event
     */
    public function onPrepareReleaseConstructReleaseInstance(PrepareReleaseEvent $event)
    {
        if (($event->getRelease() instanceof Release) === false) {
            $release = new Release($event->getVersion());

            $event->getWorkspace()->addRelease($release);
            $event->setRelease($release);
        }
    }

    /**
     * Creates a checkout of the repository for the release.
     *
     * @param PrepareReleaseEvent      $event
     * @param string                   $eventName
     * @param EventDispatcherInterface $eventDispatcher
     *
     * @throws TaskRuntimeException when the checkout of the repository has failed.
     */
    public function onPrepareReleaseCheckoutRepository(PrepareReleaseEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
    {
        $context = array('repositoryUrl' => $this->repositoryUrl, 'version' => $event->getRelease()->getVersion(), 'event.task.action' => TaskInterface::ACTION_IN_PROGRESS);

        $connection = $this->ensureConnection($event->getRelease()->getWorkspace()->getHost());
        $processExecutor = new ConnectionAdapterProcessExecutor($connection);

        $eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, 'Creating checkout of repository "{repositoryUrl}" for version "{version}".', $eventName, $this, $context));

        $repository = new Repository($this->repositoryUrl, $event->getRelease()->getPath(), $processExecutor);
        if ($repository->checkout($event->getRelease()->getVersion())) {
            $context['event.task.action'] = TaskInterface::ACTION_COMPLETED;
            $context['output.resetLine'] = true;

            $eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, 'Created checkout of repository "{repositoryUrl}" for version "{version}".', $eventName, $this, $context));
        } else {
            throw new TaskCommandExecutionException(sprintf('Failed to checkout version "%s" from repository "%s".', $event->getRelease()->getVersion(), $this->repositoryUrl), $processExecutor->getLastProcessExecutionResult(), $this);
        }
    }
}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_CUSTOM_SCROLLBAR_PART_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_CUSTOM_SCROLLBAR_PART_H_

#include "third_party/blink/renderer/core/layout/layout_replaced.h"
#include "third_party/blink/renderer/core/scroll/scroll_types.h"

namespace blink {

class CustomScrollbar;
class ScrollableArea;

class CORE_EXPORT LayoutCustomScrollbarPart final : public LayoutReplaced {
 public:
  static LayoutCustomScrollbarPart* CreateAnonymous(Document*,
                                                    ScrollableArea*,
                                                    CustomScrollbar* = nullptr,
                                                    ScrollbarPart = kNoPart);

  const char* GetName() const override {
    NOT_DESTROYED();
    return "LayoutCustomScrollbarPart";
  }

  PaintLayerType LayerTypeRequired() const override {
    NOT_DESTROYED();
    return kNoPaintLayer;
  }

  // Computes thickness of the scrollbar (which defines thickness of all parts).
  // For kScrollbarBGPart only. This can be called during style update.
  // Percentage size will be ignored.
  int ComputeThickness() const;

  // Computes size of the part in the direction of the scrollbar orientation.
  // This doesn't apply to kScrollbarBGPart because its length is not determined
  // by the style of the part of itself. For kThumbPart this returns the
  // minimum length of the thumb. The length may depend on the size of the
  // containing box, so this function can only be called after the size is
  // available.
  int ComputeLength() const;

  LayoutUnit MarginTop() const override;
  LayoutUnit MarginBottom() const override;
  LayoutUnit MarginLeft() const override;
  LayoutUnit MarginRight() const override;

  bool IsOfType(LayoutObjectType type) const override {
    NOT_DESTROYED();
    return type == kLayoutObjectCustomScrollbarPart ||
           LayoutReplaced::IsOfType(type);
  }
  ScrollableArea* GetScrollableArea() const {
    NOT_DESTROYED();
    return scrollable_area_;
  }

  LayoutCustomScrollbarPart(ScrollableArea*, CustomScrollbar*, ScrollbarPart);

 private:
  void UpdateFromStyle() override;
  void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
  void ImageChanged(WrappedImagePtr, CanDeferInvalidation) override;

  // A scrollbar part's Location() and PhysicalLocation() are relative to the
  // scrollbar (instead of relative to any LayoutBox ancestor), and both are
  // in physical coordinates.
  LayoutBox* LocationContainer() const override {
    NOT_DESTROYED();
    return nullptr;
  }

  // A scrollbar part is not in the layout tree and is not laid out like other
  // layout objects. CustomScrollbar will call scrollbar parts' SetFrameRect()
  // from its SetFrameRect() when needed.
  void UpdateLayout() override {
    NOT_DESTROYED();
    NOTREACHED();
  }

  // Have all padding getters return 0. The important point here is to avoid
  // resolving percents against the containing block, since scroll bar corners
  // don't always have one (so it would crash). Scroll bar corners are not
  // actually laid out, and they don't have child content, so what we return
  // here doesn't really matter.
  LayoutUnit PaddingTop() const override {
    NOT_DESTROYED();
    return LayoutUnit();
  }
  LayoutUnit PaddingBottom() const override {
    NOT_DESTROYED();
    return LayoutUnit();
  }
  LayoutUnit PaddingLeft() const override {
    NOT_DESTROYED();
    return LayoutUnit();
  }
  LayoutUnit PaddingRight() const override {
    NOT_DESTROYED();
    return LayoutUnit();
  }

  void SetNeedsPaintInvalidation();

  void RecordPercentLengthStats() const;

  int ComputeSize(SizeType size_type,
                  const Length& length,
                  int container_size) const;
  int ComputeWidth(int container_width) const;
  int ComputeHeight(int container_height) const;

  UntracedMember<ScrollableArea> scrollable_area_;
  UntracedMember<CustomScrollbar> scrollbar_;

  ScrollbarPart part_;
};

template <>
struct DowncastTraits<LayoutCustomScrollbarPart> {
  static bool AllowFrom(const LayoutObject& object) {
    return object.IsLayoutCustomScrollbarPart();
  }
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_CUSTOM_SCROLLBAR_PART_H_


text:
/**
 * @file 支持的自选形状
 * @author mengke01(kekee000@gmail.com)
 */

define(
    function (require) {
        return {
            circle: require('./circle'),
            rect: require('./rect'),
            roundrect: require('./roundrect'),
            arrow: require('./arrow'),
            star: require('./star'),
            triangle: require('./triangle'),
            heart: require('./heart'),
            tel: require('./tel'),
            drop: require('./drop')
        };
    }
);


text:
package control

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"runtime"
	"strings"

	"golang.org/x/net/context"

	yaml "github.com/cloudfoundry-incubator/candiedyaml"
	"github.com/rancher/os/log"

	"github.com/codegangsta/cli"
	dockerClient "github.com/docker/engine-api/client"
	composeConfig "github.com/docker/libcompose/config"
	"github.com/docker/libcompose/project/options"
	"github.com/rancher/os/cmd/power"
	"github.com/rancher/os/compose"
	"github.com/rancher/os/config"
	"github.com/rancher/os/docker"
)

type Images struct {
	Current   string   `yaml:"current,omitempty"`
	Available []string `yaml:"available,omitempty"`
}

func osSubcommands() []cli.Command {
	return []cli.Command{
		{
			Name:   "upgrade",
			Usage:  "upgrade to latest version",
			Action: osUpgrade,
			Flags: []cli.Flag{
				cli.BoolFlag{
					Name:  "stage, s",
					Usage: "Only stage the new upgrade, don't apply it",
				},
				cli.StringFlag{
					Name:  "image, i",
					Usage: "upgrade to a certain image",
				},
				cli.BoolFlag{
					Name:  "force, f",
					Usage: "do not prompt for input",
				},
				cli.BoolFlag{
					Name:  "no-reboot",
					Usage: "do not reboot after upgrade",
				},
				cli.BoolFlag{
					Name:  "kexec, k",
					Usage: "reboot using kexec",
				},
				cli.StringFlag{
					Name:  "append",
					Usage: "append additional kernel parameters",
				},
				cli.BoolFlag{
					Name:  "upgrade-console",
					Usage: "upgrade console even if persistent",
				},
				cli.BoolFlag{
					Name:  "debug",
					Usage: "Run installer with debug output",
				},
			},
		},
		{
			Name:   "list",
			Usage:  "list the current available versions",
			Action: osMetaDataGet,
		},
		{
			Name:   "version",
			Usage:  "show the currently installed version",
			Action: osVersion,
		},
	}
}

// TODO: this and the getLatestImage should probably move to utils/network and be suitably cached.
func getImages() (*Images, error) {
	upgradeURL, err := getUpgradeURL()
	if err != nil {
		return nil, err
	}

	var body []byte

	if strings.HasPrefix(upgradeURL, "/") {
		body, err = ioutil.ReadFile(upgradeURL)
		if err != nil {
			return nil, err
		}
	} else {
		u, err := url.Parse(upgradeURL)
		if err != nil {
			return nil, err
		}

		q := u.Query()
		q.Set("current", config.Version)
		u.RawQuery = q.Encode()
		upgradeURL = u.String()

		resp, err := http.Get(upgradeURL)
		if err != nil {
			return nil, err
		}
		defer resp.Body.Close()
		body, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, err
		}
	}

	return parseBody(body)
}

func osMetaDataGet(c *cli.Context) error {
	images, err := getImages()
	if err != nil {
		log.Fatal(err)
	}

	client, err := docker.NewSystemClient()
	if err != nil {
		log.Fatal(err)
	}

	cfg := config.LoadConfig()
	runningName := cfg.Rancher.Upgrade.Image + ":" + config.Version

	foundRunning := false
	for i := len(images.Available) - 1; i >= 0; i-- {
		image := images.Available[i]
		_, _, err := client.ImageInspectWithRaw(context.Background(), image, false)
		local := "local"
		if dockerClient.IsErrImageNotFound(err) {
			local = "remote"
		}
		available := "available"
		if image == images.Current {
			available = "latest"
		}
		var running string
		if image == runningName {
			foundRunning = true
			running = "running"
		}
		fmt.Println(image, local, available, running)
	}
	if !foundRunning {
		fmt.Println(config.Version, "running")
	}

	return nil
}

func getLatestImage() (string, error) {
	images, err := getImages()
	if err != nil {
		return "", err
	}

	return images.Current, nil
}

func osUpgrade(c *cli.Context) error {
	if runtime.GOARCH != "amd64" {
		log.Fatalf("ros install / upgrade only supported on 'amd64', not '%s'", runtime.GOARCH)
	}

	image := c.String("image")

	if image == "" {
		var err error
		image, err = getLatestImage()
		if err != nil {
			log.Fatal(err)
		}
		if image == "" {
			log.Fatal("Failed to find latest image")
		}
	}
	if c.Args().Present() {
		log.Fatalf("invalid arguments %v", c.Args())
	}
	if err := startUpgradeContainer(
		image,
		c.Bool("stage"),
		c.Bool("force"),
		!c.Bool("no-reboot"),
		c.Bool("kexec"),
		c.Bool("upgrade-console"),
		c.Bool("debug"),
		c.String("append"),
	); err != nil {
		log.Fatal(err)
	}

	return nil
}

func osVersion(c *cli.Context) error {
	fmt.Println(config.Version)
	return nil
}

func startUpgradeContainer(image string, stage, force, reboot, kexec, debug bool, upgradeConsole bool, kernelArgs string) error {
	command := []string{
		"-t", "rancher-upgrade",
		"-r", config.Version,
	}

	if kexec {
		command = append(command, "--kexec")
	}
	if debug {
		command = append(command, "--debug")
	}

	kernelArgs = strings.TrimSpace(kernelArgs)
	if kernelArgs != "" {
		command = append(command, "-a", kernelArgs)
	}

	if upgradeConsole {
		if err := config.Set("rancher.force_console_rebuild", true); err != nil {
			log.Fatal(err)
		}
	}

	fmt.Printf("Upgrading to %s\n", image)
	confirmation := "Continue"
	imageSplit := strings.Split(image, ":")
	if len(imageSplit) > 1 && imageSplit[1] == config.Version+config.Suffix {
		confirmation = fmt.Sprintf("Already at version %s. Continue anyway", imageSplit[1])
	}
	if !force && !yes(confirmation) {
		os.Exit(1)
	}

	container, err := compose.CreateService(nil, "os-upgrade", &composeConfig.ServiceConfigV1{
		LogDriver:  "json-file",
		Privileged: true,
		Net:        "host",
		Pid:        "host",
		Image:      image,
		Labels: map[string]string{
			config.ScopeLabel: config.System,
		},
		Command: command,
	})
	if err != nil {
		return err
	}

	client, err := docker.NewSystemClient()
	if err != nil {
		return err
	}

	// Only pull image if not found locally
	if _, _, err := client.ImageInspectWithRaw(context.Background(), image, false); err != nil {
		if err := container.Pull(context.Background()); err != nil {
			return err
		}
	}

	if !stage {
		// If there is already an upgrade container, delete it
		// Up() should to this, but currently does not due to a bug
		if err := container.Delete(context.Background(), options.Delete{}); err != nil {
			return err
		}

		if err := container.Up(context.Background(), options.Up{}); err != nil {
			return err
		}

		if err := container.Log(context.Background(), true); err != nil {
			return err
		}

		if err := container.Delete(context.Background(), options.Delete{}); err != nil {
			return err
		}

		if reboot && (force || yes("Continue with reboot")) {
			log.Info("Rebooting")
			power.Reboot()
		}
	}

	return nil
}

func parseBody(body []byte) (*Images, error) {
	update := &Images{}
	err := yaml.Unmarshal(body, update)
	if err != nil {
		return nil, err
	}

	return update, nil
}

func getUpgradeURL() (string, error) {
	cfg := config.LoadConfig()
	return cfg.Rancher.Upgrade.URL, nil
}


text:
using System;
using System.Windows.Forms;

namespace GBAHL.Tests
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        /// <summary>
        /// Gets or sets the current game file.
        /// </summary>
        public static string GameFilePath { get; set; }
    }
}


text:
import { $bind } from './directives/$bind';
import { $content } from './directives/$content';
import { $if } from './directives/$if';
import { $init } from './directives/$init';
import { $repeat } from './directives/$repeat';
import { $template } from './directives/$template';
import { MaybePromise } from 'maybe-promise';

/* @ngInject */
export class JsonBinder implements jsonBinding.IJsonBinder {

    constructor(private $parse?: jsonBinding.IParseService) {
        if (!this.$parse) {
            let expressions = require('angular-expressions');
            this.$parse = expressions.compile;
        }
    }

    private templates: Record<string, any> = {};
    registerTemplate(name: string, template: any) {
        this.templates[name] = template;
    }

    static DefaultDirectives = [
        $bind,
        $content,
        $if,
        $init,
        $repeat,
        $template,
    ];

    private directives: jsonBinding.IDirective[] = JsonBinder.DefaultDirectives.slice();
    private isDirectiveSorted = false;
    registerDirective(directive: jsonBinding.IDirective) {
        this.directives.push(directive);
        this.isDirectiveSorted = false;
    }

    newScope(isolate: boolean, parent?: any) {
        let result: any = {};
        if (!isolate) {
            Object.assign(result, parent);
        }
        result.$parent = parent;
        result.$root = parent && parent.$root || parent;
        return result;
    }

    private static EXPR_REGEX = /{{(.*?)}}/g;
    interpolate(text: string, $scope: any) {
        return text.replace(JsonBinder.EXPR_REGEX, (_, expr) => this.$parse(expr)($scope));
    }

    parse(expr: string) {
        return this.$parse(expr);
    }

    getTemplate(name: string) {
        return this.templates[name];
    }

    bind(template: any, $scope: any) {
        if (!this.isDirectiveSorted) {
           this.directives.sort((a, b) => (b.priority || 0) - (a.priority || 0));
           this.isDirectiveSorted = true;
        }
        let type = typeof template;
        switch (type) {
            case 'string':
                return this.interpolate(template, $scope);
            case 'object':
                return template instanceof Array
                    ? this._bindArray(template, $scope)
                    : this._bindObject(template, $scope);
            default:
                return template;
        }
    }

    private _bindObject(template: Record<string, any>, $scope: any): any {
        if (template.constructor !== Object) {
            return template;
        }

        //link directive
        for (let directive of this.directives) {
            let value = template[directive.name];
            if (value !== void(0)) {
                let cloned = Object.assign({}, template);
                delete cloned[directive.name];
                let result = directive.link.call(this, value, cloned, $scope);
                return this.bind(result, $scope);
            }
        }

        //evaluate all members
        let keys = Object.keys(template);
        let results: Record<string, any> = {};
        let maybe = new MaybePromise(results);
        for (let key of keys) {
            let interpolatedKey = this.interpolate(key, $scope);
            let value = template[key];
            let result = this.bind(value, $scope);

            maybe = maybe.chain(_ => result).chain(r => this.assignObject(results, interpolatedKey, r));
        }
        return maybe.value();
    }

    private assignObject(results: Record<string, any>, key: string, result: any) {
        if (result !== void(0)) {
            results[key] = result;
        }
        return results;
    }

    private _bindArray(template: any[], $scope: any) {
        let results: any[] = [];
        let maybe = new MaybePromise(results);
        for (let item of template) {
            let result = this.bind(item, $scope);

            maybe = maybe.chain(_ => result).chain(r => this.pushArray(results, item, r));
        }
        return maybe.value();
    }

    private pushArray(results: any[], item: any, result: any) {
        if (!(item instanceof Array) && result instanceof Array) {
            for (let r of result) {
                if (r !== void(0)) {
                    results.push(r);
                }
            }
        } else if (result !== void(0)) {
            results.push(result);
        }
        return results;
    }
}


text:
import React, { Component } from 'react';
import SunBurst from 'grommet/components/SunBurst';
import Box from 'grommet/components/Box';
import Legend from 'grommet/components/Legend';
import Value from 'grommet/components/Value';
import InteractiveExample from '../../../components/InteractiveExample';

SunBurst.displayName = 'SunBurst';

const PROPS_SCHEMA = {
  size: { options: ['small', 'medium', 'large'] }
};

const CONTENTS_SCHEMA = {
  Legend: { value: (
    <Legend series={[
      { label: 'on target', colorIndex: 'neutral-1' },
      { label: 'over', colorIndex: 'neutral-2' },
      { label: 'under', colorIndex: 'neutral-3' }
    ]} />
  ), initial: true }
};

const DATA = [
  { label: 'root-1', value: 50, colorIndex: 'neutral-1', children: [
    { label: 'sub-1', value: 20, colorIndex: 'neutral-1', total: 10, children: [
      { label: 'leaf-1', value: 5, colorIndex: 'neutral-1' },
      { label: 'leaf-2', value: 1, colorIndex: 'neutral-1' }
    ] },
    { label: 'sub-2', value: 20, colorIndex: 'neutral-1' },
    { label: 'sub-3', value: 10, colorIndex: 'neutral-1' }
  ]},
  { label: 'root-2', value: 30, colorIndex: 'neutral-2', children: [
    { label: 'sub-4', value: 15, colorIndex: 'neutral-2' },
    { label: 'sub-5', value: 10, colorIndex: 'neutral-1' },
    { label: 'sub-6', value: 5, colorIndex: 'neutral-3' }
  ]},
  { label: 'root-3', value: 20, colorIndex: 'neutral-3', children: [
    { label: 'sub-7', value: 10, colorIndex: 'neutral-1' },
    { label: 'sub-8', value: 7, colorIndex: 'neutral-1' },
    { label: 'sub-9', value: 3, colorIndex: 'neutral-3' }
  ]}
];

function seriesForPath (path) {
  path = path.slice(0);
  let data = { children: DATA };
  let series = [];
  while (path.length > 0) {
    data = data.children[path.shift()];
    series.push({
      colorIndex: data.colorIndex,
      label: data.label,
      value: data.value
    });
  }
  return series;
}

export default class SunBurstExamplesDoc extends Component {

  constructor () {
    super();
    this.state = { contents: {}, elementProps: {} };
  }

  _onClick (path) {
    const series = seriesForPath(path);
    const text = series.map(data => `${data.label} ${data.value}`).join(', ');
    alert(text);
  }

  render () {
    const { active, contents, elementProps } = this.state;
    let label;
    if (active) {
      const series = seriesForPath(active).map(data => ({
        ...data, value: <Value value={data.value} size='small' />
      }));
      label = (
        <Legend series={series} />
      );
    }
    let element = (
      <SunBurst data={DATA} active={active} label={label}
        onActive={active => this.setState({ active })}
        onClick={this._onClick}
        {...elementProps} />
    );
    if (contents.Legend) {
      element = (
        <Box direction='row' align='center' pad={{ between: 'medium'}}>
          {element}
          {contents.Legend}
        </Box>
      );
    }
    return (
      <InteractiveExample contextLabel='SunBurst' contextPath='/docs/sun-burst'
        preamble={`import SunBurst from 'grommet/components/SunBurst';`}
        propsSchema={PROPS_SCHEMA}
        contentsSchema={CONTENTS_SCHEMA}
        element={element}
        onChange={(elementProps, contents) => {
          this.setState({ elementProps, contents });
        }} />
    );
  }
};


text:
package org.arquillian.extension.recorder.screenshot;

import java.io.File;
import org.arquillian.extension.recorder.Configuration;

/**
 * Screenshooter configuration for every screenshooter extension implementation.
 *
 * @author Stefan Miklosovic
 *
 */
public abstract class ScreenshooterConfiguration extends Configuration<ScreenshooterConfiguration> {

    private String rootFolder = "target";

    private String screenshoType = ScreenshotType.PNG.toString();

    private String takeBeforeTest = "false";

    private String takeAfterTest = "false";

    private String takeWhenTestFailed = "false";

    private String takeWhenTestPassed = "false";

    /**
     * By default set to "target"
     *
     * @return root folder where all screenshots will be placed. Directory structure is left on the extension itself
     */
    public File getRootFolder() {
        return new File(getProperty("rootFolder", rootFolder));
    }

    /**
     * By default set to PNG.
     *
     * @return type of image we want to have our screenshots of, consult {@link ImageType}
     */
    public String getScreenshotType() {
        return getProperty("screenshoType", screenshoType);
    }

    /**
     * By default set to "false".
     *
     * @return
     */
    public String getTakeBeforeTest() {
        return getProperty("takeBeforeTest", takeBeforeTest);
    }

    /**
     * By default set to "false".
     *
     * @return
     */
    public String getTakeAfterTest() {
        return getProperty("takeAfterTest", takeAfterTest);
    }

    /**
     * By default set to "false".
     *
     * @return
     */
    public String getTakeWhenTestFailed() {
        return getProperty("takeWhenTestFailed", takeWhenTestFailed);
    }

    /**
     * By default set to "false".
     *
     * @return
     */
    public String getTakeWhenTestPassed() {
        return getProperty("takeWhenTestPassed", takeWhenTestPassed);
    }

    @Override
    public void validate() throws ScreenshooterConfigurationException {
        try {
            if (!getRootFolder().exists()) {
                getRootFolder().mkdir();
            } else {
                if (!getRootFolder().isDirectory()) {
                    throw new ScreenshooterConfigurationException("Root directory you specified is not a directory.");
                }
                if (!getRootFolder().canWrite()) {
                    throw new ScreenshooterConfigurationException(
                        "You can not write to '" + getRootFolder().getAbsolutePath() + "'.");
                }
            }
        } catch (SecurityException ex) {
            throw new ScreenshooterConfigurationException(
                "You are not permitted to operate on specified resource: " + getRootFolder().getAbsolutePath() + "'.");
        }
    }

}


text:
package gov.nih.nci.cabig.ctms.audit.exception;

/**
 * Exception for unexpected, unhandlable runtime conditions while audting. E.g,
 * an InvocationTargetException when it is not expected that the invoked method
 * will throw an exception.
 *
 * @author Saurabh Agrawal
 */
public class AuditSystemException extends RuntimeException {

    /**
     * Instantiates a new audit system exception.
     *
     * @param message
     *            the message
     */
    public AuditSystemException(String message) {
        super(message);
    }

    /**
     * Instantiates a new audit system exception.
     *
     * @param message
     *            the message
     * @param cause
     *            the cause
     */
    public AuditSystemException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Instantiates a new audit system exception.
     *
     * @param cause
     *            the cause
     */
    public AuditSystemException(Throwable cause) {
        super(cause);
    }
}