text:
package localdisk

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"camlistore.org/pkg/blobref"
	"camlistore.org/pkg/blobserver"
)

func (ds *DiskStorage) ReceiveBlob(blobRef *blobref.BlobRef, source io.Reader) (blobGot blobref.SizedBlobRef, err error) {
	pname := ds.partition
	if pname != "" {
		err = fmt.Errorf("refusing upload directly to queue partition %q", pname)
		return
	}
	hashedDirectory := ds.blobDirectory(pname, blobRef)
	err = os.MkdirAll(hashedDirectory, 0700)
	if err != nil {
		return
	}

	tempFile, err := ioutil.TempFile(hashedDirectory, BlobFileBaseName(blobRef)+".tmp")
	if err != nil {
		return
	}

	success := false // set true later
	defer func() {
		if !success {
			log.Println("Removing temp file: ", tempFile.Name())
			os.Remove(tempFile.Name())
		}
	}()

	hash := blobRef.Hash()
	written, err := io.Copy(io.MultiWriter(hash, tempFile), source)
	if err != nil {
		return
	}
	if err = tempFile.Sync(); err != nil {
		return
	}
	if err = tempFile.Close(); err != nil {
		return
	}
	if !blobRef.HashMatches(hash) {
		err = blobserver.ErrCorruptBlob
		return
	}
	stat, err := os.Lstat(tempFile.Name())
	if err != nil {
		return
	}
	if stat.Size() != written {
		err = fmt.Errorf("temp file %q size %d didn't match written size %d", tempFile.Name(), stat.Size(), written)
		return
	}

	fileName := ds.blobPath("", blobRef)
	if err = os.Rename(tempFile.Name(), fileName); err != nil {
		return
	}

	stat, err = os.Lstat(fileName)
	if err != nil {
		return
	}
	if stat.Size() != written {
		err = errors.New("Written size didn't match.")
		return
	}

	for _, mirror := range ds.mirrorPartitions {
		pname := mirror.partition
		if pname == "" {
			panic("expected partition name")
		}
		partitionDir := ds.blobDirectory(pname, blobRef)

		// Prevent the directory from being unlinked by
		// enumerate code, which cleans up.
		defer keepDirectoryLock(partitionDir).Unlock()
		defer keepDirectoryLock(filepath.Dir(partitionDir)).Unlock()
		defer keepDirectoryLock(filepath.Dir(filepath.Dir(partitionDir))).Unlock()

		if err = os.MkdirAll(partitionDir, 0700); err != nil {
			return blobref.SizedBlobRef{}, fmt.Errorf("localdisk.receive: MkdirAll(%q) after lock on it: %v", partitionDir, err)
		}
		partitionFileName := ds.blobPath(pname, blobRef)
		pfi, err := os.Stat(partitionFileName)
		if err == nil && !pfi.IsDir() {
			log.Printf("Skipped dup on partition %q", pname)
		} else {
			if err = linkOrCopy(fileName, partitionFileName); err != nil && !linkAlreadyExists(err) {
				log.Fatalf("got link or copy error %T %#v", err, err)
				return blobref.SizedBlobRef{}, err
			}
			log.Printf("Mirrored blob %s to partition %q", blobRef, pname)
		}
	}

	blobGot = blobref.SizedBlobRef{BlobRef: blobRef, Size: stat.Size()}
	success = true

	hub := ds.GetBlobHub()
	hub.NotifyBlobReceived(blobRef)
	for _, mirror := range ds.mirrorPartitions {
		mirror.GetBlobHub().NotifyBlobReceived(blobRef)
	}
	return
}

func linkAlreadyExists(err error) bool {
	if os.IsExist(err) {
		return true
	}
	if le, ok := err.(*os.LinkError); ok && os.IsExist(le.Err) {
		return true
	}
	return false
}

// Used by Windows (receive_windows.go) and when a posix filesystem doesn't
// support a link operation (e.g. Linux with an exfat external USB disk).
func copyFile(src, dst string) error {
	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	dstFile, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer dstFile.Close()

	_, err = io.Copy(dstFile, srcFile)
	return err
}

redpajama_set_name: RedPajamaGithub


text:
package util

import "time"

// Ticker repeatedly calls cb with a delay in between calls. It stops doing This
// When a element is sent to the done channel.
func Ticker(cb func(), delay time.Duration, done chan bool) {
	for {
		select {
		case <-done:
			return

		default:
			cb()
			time.Sleep(delay)
		}
	}
}


text:
const { standardAction } = require('./utils/actions')

module.exports = {
  getLabel: ({ tasks }) => {
    const { curfewHours } = tasks
    return curfewHours === 'DONE' ? 'Confirmed' : 'Not completed'
  },

  getRoAction: ({ tasks }) => {
    const { curfewHours } = tasks
    return standardAction(curfewHours, '/hdc/curfew/curfewHours/')
  },
}


text:
import unittest
import geopy

class TestFormat(unittest.TestCase):

    def test_format(self):
        d = geopy.point.Point.parse_degrees('-13', '19', 0)
        s = geopy.format.format_degrees(d)
        self.assertEqual("-13 19\' 0.0\"", s)

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


text:
"""Utilities to normalize a stream of tensors (typically observations)."""

import tensorflow as tf

class Normalizer(tf.Module):
  """Normalizes tensors by tracking their element-wise mean and variance."""

  def __init__(self, eps=0.001, clip_range=(-5, 5)):
    """Initialize the normalizer.

    Args:
      eps: A constant added to the standard deviation of data before
        normalization.
      clip_range: Normalized values are clipped to this range.
    """
    super(Normalizer, self).__init__()
    self.eps = eps
    self.clip_range = clip_range
    self.initialized = False

  def build(self, input_shape):
    assert not self.initialized
    self.initialized = True

    size = input_shape[-1]
    def get_variable(name, initial_value, local):
      if local:
        # ON_READ causes the replicated variable to act as independent variables
        # for each replica. The variable only gets aggregated if it is read
        # in cross-replica context, which may happen e.g. when the normalizer
        # is checkpointed.
        return tf.Variable(name=name,
                           initial_value=initial_value,
                           trainable=False,
                           dtype=tf.float32,
                           synchronization=tf.VariableSynchronization.ON_READ,
                           aggregation=tf.VariableAggregation.MEAN)
      else:  # mirrored variable, same value on each replica
        return tf.Variable(name=name,
                           initial_value=initial_value,
                           trainable=False,
                           dtype=tf.float32)
    # local accumulators
    self.steps_acc = get_variable('steps_acc', 0, local=True)
    self.sum_acc = get_variable('sum_acc', tf.zeros(shape=[size]), local=True)
    self.sumsq_acc = get_variable('sumsq_acc', tf.zeros(shape=[size]),
                                  local=True)
    # mirrored variables
    self.steps = get_variable('steps', 0, local=False)
    self.sum = get_variable('sum', tf.zeros(shape=[size]), local=False)
    self.sumsq = get_variable('sumsq', tf.zeros(shape=[size]), local=False)
    self.mean = get_variable('mean', tf.zeros(shape=[size]), local=False)
    self.std = get_variable('std', tf.zeros(shape=[size]), local=False)

  def update(self, input_, only_accumulate=False):
    """Update normalization statistics.

    Args:
      input_: A tensor. All dimensions apart from the last one are treated
        as batch dimensions.
      only_accumulate: If True, only local accumulators are updated and the
        normalization is not affected. Use this option if running on TPU.
        In this case, you need to call `finish_update` method in cross-replica
        context later to update the normalization.
    """
    if not self.initialized:
      self.build(input_.shape)

    # reshape to 2 dimensions
    shape = input_.shape
    input_ = tf.reshape(input_, [tf.reduce_prod(shape[:-1]), shape[-1]])
    assert len(input_.shape) == 2

    # update local accumulators
    self.steps_acc.assign_add(float(input_.shape[0]))
    self.sum_acc.assign_add(tf.reduce_sum(input_, axis=0))
    self.sumsq_acc.assign_add(tf.reduce_sum(tf.square(input_), axis=0))

    if not only_accumulate:
      self.finish_update()

  def finish_update(self):
    """Update the normalization (mean and std) based on local accumulators.

    You only need to call this method manually if `update` was called with
    `only_accumulate=True` (usually on a TPU). This method needs to be called
    in cross-replica context (i.e. not inside Strategy.run).
    """
    # sum the accumulators accross all replicas
    step_increment, sum_increment, sumsq_increment = (
        tf.distribute.get_replica_context().all_reduce(
            tf.distribute.ReduceOp.SUM,
            [self.steps_acc, self.sum_acc, self.sumsq_acc]))

    # zero the accumulators
    self.steps_acc.assign(tf.zeros_like(self.steps_acc))
    self.sum_acc.assign(tf.zeros_like(self.sum_acc))
    self.sumsq_acc.assign(tf.zeros_like(self.sumsq_acc))

    # update the normalization
    self.steps.assign_add(step_increment)
    self.sum.assign_add(sum_increment)
    self.sumsq.assign_add(sumsq_increment)
    self.mean.assign(self.sum / self.steps)
    self.std.assign(tf.sqrt(tf.maximum(
        0., (self.sumsq / self.steps) - tf.square(self.mean))))

  def __call__(self, input_):
    """Normalize the tensor.

    Args:
      input_: tensor to be normalizer. All dimensions apart from the last one
        are treated as batch dimensions.

    Returns:
      a tensor of the same shape and dtype as input_.
    """
    if not self.initialized:
      self.build(input_.shape)
    # reshape to 2 dimensions
    shape = input_.shape
    input_ = tf.reshape(input_, [tf.reduce_prod(shape[:-1]), shape[-1]])
    assert len(input_.shape) == 2
    # normalize
    input_ -= self.mean[tf.newaxis, :]
    input_ /= self.std[tf.newaxis, :] + self.eps
    input_ = tf.clip_by_value(input_, *self.clip_range)
    # reshape to the original shape
    return tf.reshape(input_, shape)

  def get_logs(self):
    logs = dict()
    for key, var in [('mean', self.mean), ('std', self.std)]:
      for i in range(var.shape[0]):
        logs['%s/%d' % (key, i)] = var[i]
    return logs

class NormalizeObservationsWrapper(tf.Module):
  """Wrapper which adds observation normalization to a policy.

  Works for V-trace and SAC policies.
  """

  def __init__(self, policy, normalizer):
    self.policy = policy
    self.normalizer = normalizer

  def _norm_env_output(self, env_outputs):
    flat = tf.nest.flatten(env_outputs.observation)
    normalized = self.normalizer(tf.concat(values=flat, axis=-1))
    normalized = tf.split(normalized, [t.shape[-1] for t in flat], axis=-1)
    normalized = tf.nest.pack_sequence_as(env_outputs.observation, normalized)
    for a, b in zip(tf.nest.flatten(flat), tf.nest.flatten(normalized)):
      assert a.shape == b.shape
    return env_outputs._replace(observation=normalized)

  @tf.function
  def initial_state(self, *args, **kwargs):
    return self.policy.initial_state(*args, **kwargs)

  # Not clear why, but if "@tf.function" declarator is placed directly onto
  # __call__, training fails with "uninitialized variable *baseline".
  # when running on multiple learning tpu cores.

  @tf.function
  def get_action(self, *args, **kwargs):
    return self.__call__(*args, **kwargs)

  def __call__(self, prev_actions, env_outputs, *args,
               is_training=False, **kwargs):
    if is_training:
      flat = tf.nest.flatten(env_outputs.observation)
      self.normalizer.update(tf.concat(values=flat, axis=-1),
                             only_accumulate=True)

    return self.policy(prev_actions, self._norm_env_output(env_outputs), *args,
                       is_training=is_training, **kwargs)

  def end_of_training_step_callback(self):
    self.normalizer.finish_update()

  # The methods below are only used by SAC policies.
  def get_Q(self, prev_action, env_output, *args, **kwargs):
    return self.policy.get_Q(
        prev_action, self._norm_env_output(env_output), *args, **kwargs)

  def get_V(self, prev_action, env_output, *args, **kwargs):
    return self.policy.get_V(
        prev_action, self._norm_env_output(env_output), *args, **kwargs)

  def get_action_params(self, prev_action, env_output, *args, **kwargs):
    return self.policy.get_action_params(
        prev_action, self._norm_env_output(env_output), *args, **kwargs)


text:
package com.alibaba.wasmWeex.uitest.TC_AG;
import com.alibaba.wasmWeex.WXPageActivity;
import com.alibaba.wasmWeex.util.TestFlow;
import java.util.TreeMap;
import org.junit.Before;
import org.junit.Test;

public class AG_Switch_Switch_Checked extends TestFlow {
	public AG_Switch_Switch_Checked() {
		super(WXPageActivity.class);
	}

	@Before
	public void setUp() throws InterruptedException {
		super.setUp();
		TreeMap testMap = new <String, Object> TreeMap();
		testMap.put("testComponet", "AG_Switch");
		testMap.put("testChildCaseInit", "AG_Switch_Switch_Checked");
		testMap.put("step1",new TreeMap(){
			{
				put("click", "true");
				put("screenshot", "AG_Switch_Switch_Checked_01_true");
			}
		});
		testMap.put("step2",new TreeMap(){
			{
				put("click", "false");
				put("screenshot", "AG_Switch_Switch_Checked_02_false");
			}
		});
		super.setTestMap(testMap);
	}

	@Test
	public void doTest(){
		super.testByTestMap();
	}

}


text:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { FormModaldemoComponent } from './form-modaldemo.component';

@NgModule( {
  imports: [
    RouterModule.forChild( [
      { path: '', component: FormModaldemoComponent }
    ] )
  ],
  exports: [
    RouterModule
  ]
} )
export class FormModalDemoRoutingModule {
}


text:
id: bad87fee1348bd9bec908846
title: Create a Bootstrap Row
challengeType: 0
videoUrl: ''
localeTitle: 创建一个Bootstrap行
---

## Description

现在我们将为内联元素创建一个Bootstrap行。在h3标记下创建一个div元素,其中包含一个row类。

## Instructions

## Tests

```yml
tests:
  - text: 在<code>h3</code>元素下面添加一个<code>div</code>元素。
    testString: 'assert(($("div").length > 1) && ($("div.row h3.text-primary").length == 0) && ($("div.row + h3.text-primary").length == 0) && ($("h3.text-primary + div.row").length > 0), "Add a <code>div</code> element below your <code>h3</code> element.");'
  - text: 你的<code>div</code>元素应该有类<code>row</code>
    testString: 'assert($("div").hasClass("row"), "Your <code>div</code> element should have the class <code>row</code>");'
  - text: 你的<code>row div</code>应该嵌套在<code>container-fluid div</code>
    testString: 'assert($("div.container-fluid div.row").length > 0, "Your <code>row div</code> should be nested inside the <code>container-fluid div</code>");'
  - text: 确保你的<code>div</code>元素有一个结束标记。
    testString: 'assert(code.match(/<\/div>/g) && code.match(/<div/g) && code.match(/<\/div>/g).length === code.match(/<div/g).length, "Make sure your <code>div</code> element has a closing tag.");'

```

## Challenge Seed

```html
<div class="container-fluid">
  <h3 class="text-primary text-center">jQuery Playground</h3>

</div>

```

## Solution

```js
// solution required
```


text:
package weapons.client.gui;

import java.util.HashMap;
import java.util.Map;

import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;

import org.lwjgl.opengl.GL11;

public class GuiBase extends GuiContainer{
	private Map<String, Integer[]> thetooltips = new HashMap<String, Integer[]>();
	private Map<String, String[]> thesubtooltips = new HashMap<String, String[]>();
	public GuiBase(Container par1Container)
	{
		super(par1Container);
	}
	public void addTooltip(String tooltip, int x, int y, int maxx, int maxy){
		Integer[] mouse = new Integer[4];
		mouse[0] = x;
		mouse[1] = y;
		mouse[2] = maxx;
		mouse[3] = maxy;
		thetooltips.put(tooltip, mouse);
	}
	public void addsubtooltip(String tooltip, String[] infotooltip){
		if(thetooltips.containsKey(tooltip) && infotooltip.length > 0){
			thesubtooltips.put(tooltip, infotooltip);
		}
	}
	public void updateToolTipText(String newtooltip, String oldtooltip){
		if(thetooltips.containsKey(oldtooltip)){
			Integer[] mouse = thetooltips.get(oldtooltip);
			thetooltips.remove(oldtooltip);
			thetooltips.put(newtooltip, mouse);
		}
	}
	public void updateSubToolTipText(String oldtooltip, String tooltip, String[] subtooltips){
		if(thetooltips.containsKey(tooltip) && subtooltips.length > 0 && thesubtooltips.containsKey(oldtooltip)){
			thesubtooltips.remove(oldtooltip);
			thesubtooltips.put(tooltip, subtooltips);
		}
	}
	public void updateToolTipBounds(String tooltip, int x, int y, int maxx, int maxy){
		Integer[] mouse = new Integer[4];
		mouse[0] = x;
		mouse[1] = y;
		mouse[2] = maxx;
		mouse[3] = maxy;
		thetooltips.remove(tooltip);
		thetooltips.put(tooltip, mouse);
	}
	/**
	 * Draws the screen and all the components in it.
	 */
	@Override
	public void drawScreen(int mouseX, int mouseY, float par3) {
		super.drawScreen(mouseX, mouseY, par3);
		int xoff = (width - xSize) / 2;
		int yoff = (height - ySize) / 2;
		mouseX -= xoff;
		mouseY -= yoff;
		int left = this.guiLeft;
		int top = this.guiTop;

		GL11.glDisable(GL11.GL_LIGHTING);
		GL11.glDisable(GL11.GL_DEPTH_TEST);
		GL11.glPushMatrix();
		GL11.glTranslatef((float) left, (float) top, 0.0F);
		GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
		RenderHelper.disableStandardItemLighting();

		InventoryPlayer playerInv = this.mc.thePlayer.inventory;

		if (playerInv.getItemStack() == null) {
			if (isMouseOver(mouseX, mouseY)) {
				String[] tips;
				String tip = getTip(mouseX, mouseY);
				if(thesubtooltips.containsKey(tip)){
					tips = new String[thesubtooltips.get(tip).length + 1];
					tips[0] = tip;
					int tipcount = 0;
					for(String addingtip : thesubtooltips.get(tip)){
						tipcount ++;
						tips[tipcount] = addingtip;
					}
					drawToolTips(tips, mouseX, mouseY);
				}
				else{
					tips = new String[1];
					tips[0] = tip;
					drawToolTips(tips, mouseX, mouseY);
				}
			}
		}
		GL11.glPopMatrix();
		GL11.glEnable(GL11.GL_LIGHTING);
		GL11.glEnable(GL11.GL_DEPTH_TEST);
	}
	private boolean isMouseOver(int x, int y){
		for (String key : thetooltips.keySet()) {
			Integer[] mousepoints = thetooltips.get(key);
			int startX = mousepoints[0];
			int startY = mousepoints[1];
			int endX = mousepoints[2];
			int endY = mousepoints[3];
			int xlenght = endX - startX;
			int ylenght = endY - startY;
			for(int i = 0; i < xlenght; i++){
				for(int k = 0; k < ylenght; k++){
					if(x == (startX + i) && y == (startY + k)){
						return true;
					}
				}
			}
		}
		return false;
	}
	private String getTip(int x, int y){
		for (String key : thetooltips.keySet()) {
			Integer[] mousepoints = thetooltips.get(key);
			int startX = mousepoints[0];
			int startY = mousepoints[1];
			int endX = mousepoints[2];
			int endY = mousepoints[3];
			int xlenght = endX - startX;
			int ylenght = endY - startY;
			for(int i = 0; i < xlenght; i++){
				for(int k = 0; k < ylenght; k++){
					if(x == (startX + i) && y == (startY + k)){
						return key;
					}
				}
			}
		}
		return "";
	}
	private void drawToolTips(String[] toolTips, int mouseX, int mouseY) {
		mouseX += 2;
		mouseY -= 2;
		int x = 0;
		int iteration = 0;
		for (String tip : toolTips){
			iteration ++;
			if(this.fontRenderer.getStringWidth(tip) > x){
				x = this.fontRenderer.getStringWidth(tip);
			}
		}
		int var15 = -267386864;
		int var16 = 1347420415;
		@SuppressWarnings("unused")
		int var17 = (var16 & 16711422) >> 1 | var16 & -16777216;
		this.drawGradientRect(mouseX - 1, mouseY - 5, mouseX + x + 9, mouseY + (toolTips.length * 12) - 1, var15, var15);
		this.drawGradientRect(mouseX + x + 7, mouseY - 5, mouseX + x + 8, mouseY + (toolTips.length * 12) - 1, var16, var16);
		this.drawGradientRect(mouseX, mouseY - 5, mouseX + 1, mouseY + (toolTips.length * 12) - 1, var16, var16);
		this.drawGradientRect(mouseX + 1, mouseY - 5, mouseX + x + 7, mouseY - 4, var16, var16);
		this.drawGradientRect(mouseX + 1, mouseY + (toolTips.length * 12) - 2, mouseX + x + 7, mouseY + (toolTips.length * 12) - 1, var16, var16);
		this.drawGradientRect(mouseX, mouseY + (toolTips.length * 12) - 1, mouseX + x + 8, mouseY + (toolTips.length * 12), var15, var15);
		this.drawGradientRect(mouseX, mouseY - 6, mouseX + x + 8, mouseY - 5, var15, var15);
		iteration = 0;
		for (String tip : toolTips){
			iteration ++;
			if(iteration < 2){
				this.fontRenderer.drawStringWithShadow(tip, mouseX + 5, mouseY, -1);
			}
			else{
				this.fontRenderer.drawStringWithShadow(tip, mouseX + 5, mouseY + (iteration * 6), -1);
			}
		}
	}
	protected void drawGuiContainerBackgroundLayer(float f, int i, int j){}
}


text:
package org.springframework.boot.cli.compiler.dependencies;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.maven.model.Model;
import org.springframework.boot.cli.compiler.dependencies.Dependency.Exclusion;

/**
 * {@link DependencyManagement} derived from a Maven {@link Model}
 *
 * @author Andy Wilkinson
 * @since 1.3.0
 */
public class MavenModelDependencyManagement implements DependencyManagement {

	private final List<Dependency> dependencies;

	private final Map<String, Dependency> byArtifactId = new LinkedHashMap<String, Dependency>();

	public MavenModelDependencyManagement(Model model) {
		this.dependencies = extractDependenciesFromModel(model);
		for (Dependency dependency : this.dependencies) {
			this.byArtifactId.put(dependency.getArtifactId(), dependency);
		}
	}

	private static List<Dependency> extractDependenciesFromModel(Model model) {
		List<Dependency> dependencies = new ArrayList<Dependency>();
		for (org.apache.maven.model.Dependency mavenDependency : model
				.getDependencyManagement().getDependencies()) {
			List<Exclusion> exclusions = new ArrayList<Exclusion>();
			for (org.apache.maven.model.Exclusion mavenExclusion : mavenDependency
					.getExclusions()) {
				exclusions.add(new Exclusion(mavenExclusion.getGroupId(), mavenExclusion
						.getArtifactId()));
			}
			Dependency dependency = new Dependency(mavenDependency.getGroupId(),
					mavenDependency.getArtifactId(), mavenDependency.getVersion(),
					exclusions);
			dependencies.add(dependency);
		}
		return dependencies;
	}

	@Override
	public List<Dependency> getDependencies() {
		return this.dependencies;
	}

	@Override
	public String getSpringBootVersion() {
		return find("spring-boot").getVersion();
	}

	@Override
	public Dependency find(String artifactId) {
		return this.byArtifactId.get(artifactId);
	}
}


text:
require "logger"
require "sinatra"
require "json"
require "thread"

module NSICloudooo
  class Server < Sinatra::Application

    def self.prepare
      @@done = Hash.new
    end

    post "/" do
      content_type :json
      incoming = JSON.parse(request.body.read)
      filename = incoming["filename"]
      filename = File.basename(incoming["doc_link"]) if incoming.has_key? "doc_link"
      callback = incoming["callback"] || nil
      metadata = incoming['metadata']
      unless metadata.nil?
        return {doc_key: incoming["sam_uid"]}.to_json
      end
      verb = incoming["verb"] || nil
      if filename.include? "secs"
        seconds = filename.split(".")[0].delete("secs").to_i
        sleep seconds-1
      elsif filename.include? "queue error"
        return 503
      end
      {
        doc_key: "key for document #{filename}",
        callback: callback,
        verb: verb,
      }.to_json
    end

    get "/" do
      content_type :json
      incoming = JSON.parse(request.body.read)
      if incoming.has_key?("key") && incoming["key"].include?("secs")
        unless @@done.has_key? incoming["key"]
          @@done[incoming["key"]] = true
          return {done: false}.to_json
        else
          return {done: true}.to_json
        end
      elsif incoming.has_key? "doc_key"
        if incoming.has_key? "metadata"
          return {"metadata_key" => "metadata for #{incoming['doc_key']}"}.to_json
        end
        return {:images => [], :files => [], :thumbnail => ['thumbnail key',]}.to_json
      end
    return 404 if incoming["key"].include? "dont"
    end
  end

  class FakeServerManager

    # Start the nsi.cloudooo fake server
    #
    # @param [Fixnum] port the port where the fake server will listen
    #   * make sure there's not anything else listenning on this port
    def start_server(port=9886)
      @thread = Thread.new do
        Server.prepare
        Server.run! :port => port
      end
      sleep(1)
      self
    end

    # Stop the SAM fake server
    def stop_server
      @thread.kill
      self
    end
  end
end


text:
Eigenvalue solvers
==================

.. meta::
   :description: Computing the eigenvalues and eigenvectors of a tight-binding Hamiltonian matrix

Solvers were first introduced in the :doc:`bands` section and then used throughout the tutorial to
present the results of the various models we constructed. This section will take a more detailed
look at the concrete :func:`.lapack` and :func:`.arpack` eigenvalue solvers and their common
:class:`.Solver` interface.

.. only:: html

    :nbexport:`Download this page as a Jupyter notebook <self>`

LAPACK
------

The :class:`.Solver` class establishes the interface of a solver within pybinding, but it does not
contain a concrete diagonalization routine. For this reason we never instantiate the plain solver,
only its implementations such as :func:`.solver.lapack`.

The LAPACK implementation works on dense matrices which makes it well suited only for small
systems. However, a great advantage of this solver is that it always solves for all eigenvalues
and eigenvectors of a Hamiltonian matrix. This makes it perfect for calculating the entire band
structure of the bulk or nanoribbons, as has been shown several times in this tutorial.

Internally, this solver uses the :func:`scipy.linalg.eigh` function for dense Hermitian matrices.
See the :func:`.solver.lapack` API reference for more details.

ARPACK
------

The :func:`.solver.arpack` implementation works on sparse matrices which makes it suitable for
large systems. However, only a small subset of the total eigenvalues and eigenvectors can be
calculated. This tutorial already contains a few examples where the ARPACK solver was used, and
one more is presented below.

Internally, the :func:`scipy.sparse.linalg.eigsh` function is used to solve large sparse Hermitian
matrices. The first argument to :func:`.solver.arpack` must be the pybinding :class:`.Model`, but
the following arguments are the same as :func:`~scipy.sparse.linalg.eigsh`, so the solver routine
can be tweaked as desired. Rather than reproduce the full list of options here, we refer you to
the scipy :func:`~scipy.sparse.linalg.eigsh` reference documentation. Here, we will focus on the
specific features of solvers within pybinding.

Solver interface
----------------

No matter which concrete solver is used, they all share a common :class:`.Solver` interface.
The two primary properties are :attr:`~.Solver.eigenvalues` and :attr:`~.Solver.eigenvectors`.
These are the raw results of the exact diagonalization of the Hamiltonian matrix.

    >>> from pybinding.repository import graphene
    >>> model = pb.Model(graphene.monolayer())
    >>> model.hamiltonian.todense()
    [[ 0.0 -2.8]
     [-2.8  0.0]]
    >>> solver = pb.solver.lapack(model)
    >>> solver.eigenvalues
    [-2.8 2.8]
    >>> solver.eigenvectors
    [[-0.707 -0.707]
     [-0.707  0.707]]

The properties contain just the raw data. However, :class:`.Solver` also offers a few convenient
calculation methods. We'll demonstrate these on a simple rectangular graphene system.

.. plot::
    :context: close-figs

    from pybinding.repository import graphene

    model = pb.Model(
        graphene.monolayer(),
        pb.rectangle(x=3, y=1.2)
    )
    model.plot()

First, we'll take a look at the :meth:`~.Solver.calc_eigenvalues` method. While its job is
essentially the same as the :attr:`~.Solver.eigenvalues` property, there is one key difference:
the property returns a raw array, while the method returns an :class:`.Eigenvalues` result object.
These objects have convenient functions built in and they know how to plot their data:

.. plot::
    :context: close-figs
    :alt: Energy states of a graphene quantum dot

    solver = pb.solver.arpack(model, k=20)  # for the 20 lowest energy eigenvalues
    eigenvalues = solver.calc_eigenvalues()
    eigenvalues.plot()

The basic plot just shows the state number and energy of each eigenstate, but we can also do
something more interesting. If we pass a position argument to :meth:`~.Solver.calc_eigenvalues`
it will calculate the probability density :math:`|\Psi(\vec{r})|^2` at that position for each
eigenstate and we can view the result using :meth:`.Eigenvalues.plot_heatmap`:

.. plot::
    :context: close-figs
    :alt: Energy states of a graphene quantum dot with probability heatmap

    eigenvalues = solver.calc_eigenvalues(map_probability_at=[0.1, 0.6])  # position in [nm]
    eigenvalues.plot_heatmap(show_indices=True)
    pb.pltutils.colorbar()

In this case we are interested in the probability density at `[x, y] = [0.1, 0.6]`, i.e. a lattice
site at the top zigzag edge of our system. Note that the given position does not need to be
precise: the probability will be computed for the site closest to the given coordinates. From the
figure we can see that the probability at the edge is highest for the two zero-energy states:
numbers 9 and 10. We can take a look at the spatial map of state 9 using the
:meth:`~.Solver.calc_probability` method:

.. plot::
    :context: close-figs
    :alt: Spatial map of the probability density of a graphene quantum dot

    probability_map = solver.calc_probability(9)
    probability_map.plot()

The result object in this case is a :class:`.StructureMap` with the probability density
:math:`|\Psi(\vec{r})|^2` as its data attribute. As expected, the most prominent states are at
the zigzag edges of the system.

An alternative way to get a spatial map of the system is via the local density of states (LDOS).
The :meth:`~.Solver.calc_spatial_ldos` method makes this easy. The LDOS map is requested for a
specific energy value instead of a state number and it considers multiple states within a Gaussian
function with the specified broadening:

.. plot::
    :context: close-figs
    :alt: Spatial LDOS of a graphene quantum dot

    ldos_map = solver.calc_spatial_ldos(energy=0, broadening=0.05)  # [eV]
    ldos_map.plot()

The total density of states can be calculated with :meth:`~.Solver.calc_dos`:

.. plot::
    :context: close-figs
    :alt: Total density of states (DOS) of a graphene quantum dot

    dos = solver.calc_dos(energies=np.linspace(-1, 1, 200), broadening=0.05)  # [eV]
    dos.plot()

Our example system is quite small so the DOS does not resemble bulk graphene. The zero-energy peak
stands out as the signature of the zigzag edge states.

.. _manual_band_calculation:

For periodic systems, the wave vector can be controlled using :meth:`.Solver.set_wave_vector`.
This allows us to compute the eigenvalues at various points in k-space. For example:

.. plot::
    :context: close-figs
    :alt: Graphene band structure

    from math import pi

    model = pb.Model(
        graphene.monolayer(),
        pb.translational_symmetry()
    )
    solver = pb.solver.lapack(model)

    kx_lim = pi / graphene.a
    kx_path = np.linspace(-kx_lim, kx_lim, 100)
    ky_outer = 0
    ky_inner = 2*pi / (3*graphene.a_cc)

    outer_bands = []
    for kx in kx_path:
        solver.set_wave_vector([kx, ky_outer])
        outer_bands.append(solver.eigenvalues)

    inner_bands = []
    for kx in kx_path:
        solver.set_wave_vector([kx, ky_inner])
        inner_bands.append(solver.eigenvalues)

    for bands in [outer_bands, inner_bands]:
        result = pb.results.Bands(kx_path, bands)
        result.plot()

This example shows the basic principle of iterating over a path in k-space in order to calculate
the band structure. However, this is made much easier with the :meth:`.Solver.calc_bands` method.
This was already covered in the :doc:`bands` section and will not be repeated here. But keep in
mind that this calculation does not need to be done manually, :meth:`.Solver.calc_bands` is the
preferred way.

Further reading
---------------

Take a look at the :mod:`.solver` and :mod:`.results` reference pages for more detailed
information. More solver examples are available throughout this tutorial.


text:
@interface LQSViewController : UIViewController

@property (nonatomic) LYRClient *layerClient;

@property (weak, nonatomic) IBOutlet UIButton *sendButton;
@property (nonatomic, retain) IBOutlet UITextView *inputTextView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, weak) IBOutlet UILabel *typingIndicatorLabel;

@end


text:
package com.wq.exception;

/**
 * Mana异常
 *
 * @author wangqing
 * @since 1.0.0
 */
public class ManaException extends Exception {

    public ManaException(String msg) {
        super(msg);
    }

    public ManaException(String msg,Throwable e) {
        super(msg,e);
    }
}


text:
class InsertSlugMigrations < ActiveRecord::Migration
  def change
    return say("Skipping slug creation in test environment") if Rails.env.test?

    OLD_SLUGS.each do |s|
      execute "INSERT INTO slug_migrations (slug, created_at, updated_at, content_id) VALUES ('#{s}', now(), now(), '#{SecureRandom.uuid}')"
    end
  end

  OLD_SLUGS = [
    "/service-manual/communications/blogs.html",
    "/service-manual/communications/increasing-digital-takeup.html",
    "/service-manual/communications.html",
    "/service-manual/web-ops.html",
    "/service-manual/developers.html",
    "/service-manual/agile/writing-user-stories.html",
    "/service-manual/agile/quality.html",
    "/service-manual/agile/training-and-learning.html",
    "/service-manual/agile/running-retrospectives.html",
    "/service-manual/agile.html",
    "/service-manual/agile/what-agile-looks-like.html",
    "/service-manual/agile/continuous-delivery.html",
    "/service-manual/agile/features-of-agile.html",
    "/service-manual/digital-by-default/awarding-the-standard.html",
    "/service-manual/digital-by-default/self-certification.html",
    "/service-manual/digital-by-default/scope-of-the-standard.html",
    "/service-manual/digital-by-default.html",
    "/service-manual/digital-by-default/assessments-at-gds.html",
    "/service-manual/digital-by-default/failure-to-meet-the-standard.html",
    "/service-manual/digital-by-default/maintaining-the-standard.html",
    "/service-manual/feedback.html",
    "/service-manual/governance/governing-the-discovery-phase.html",
    "/service-manual/governance/seeing-progress.html",
    "/service-manual/governance/introduction-to-governance-for-service-delivery.html",
    "/service-manual/governance/governing-the-beta-phase.html",
    "/service-manual/governance/setting-up-the-right-reporting.html",
    "/service-manual/governance/self-assurance-by-agile-teams.html",
    "/service-manual/governance/governing-the-alpha-phase.html",
    "/service-manual/governance/what-to-expect-from-the-show-and-tell.html",
    "/service-manual/governance/funding-your-digital-service.html",
    "/service-manual/governance/when-to-scale-up.html",
    "/service-manual/governance/governing-the-live-phase.html",
    "/service-manual/governance/scaling-a-service-team.html",
    "/service-manual/governance/governing-a-service-after-scaling-up.html",
    "/service-manual/governance/governance-principles.html",
    "/service-manual/governance/how-delivery-teams-manage-their-work.html",
    "/service-manual/governance/assurance-for-digital-services.html",
    "/service-manual/governance.html",
    "/service-manual/governance/assurance-from-those-outside-the-service-team.html",
    "/service-manual/governance/governance-across-the-life-of-a-service.html",
    "/service-manual/chief-technology-officers.html",
    "/service-manual/measurement/completion-rate.html",
    "/service-manual/measurement/performance-platform.html",
    "/service-manual/measurement/other-kpis.html",
    "/service-manual/measurement/user-satisfaction.html",
    "/service-manual/measurement.html",
    "/service-manual/measurement/using-data.html",
    "/service-manual/measurement/cost-per-transaction.html",
    "/service-manual/measurement/digital-takeup.html",
    "/service-manual/domain-names/how-they-work.html",
    "/service-manual/domain-names/https.html",
    "/service-manual/domain-names/service-subdomain-names.html",
    "/service-manual/domain-names/asset-hosts.html",
    "/service-manual/domain-names/email.html",
    "/service-manual/domain-names.html",
    "/service-manual/domain-names/setting-up.html",
    "/service-manual/the-team/content-designer.html",
    "/service-manual/the-team/working-with-specialists.html",
    "/service-manual/the-team/working-environment.html",
    "/service-manual/the-team/service-manager.html",
    "/service-manual/the-team/recruitment/job-descriptions.html",
    "/service-manual/the-team/recruitment/hub.html",
    "/service-manual/the-team/recruitment/scs-orgdesign.html",
    "/service-manual/the-team/recruitment.html",
    "/service-manual/the-team/recruitment/performance-analyst-jd.html",
    "/service-manual/the-team/accessibility.html",
    "/service-manual/the-team/learning-and-development/service-manager-induction.html",
    "/service-manual/the-team/learning-and-development/open-programme.html",
    "/service-manual/the-team/learning-and-development/foundation-day.html",
    "/service-manual/the-team/learning-and-development.html",
    "/service-manual/the-team/web-operations.html",
    "/service-manual/the-team/developer.html",
    "/service-manual/the-team/user-researcher.html",
    "/service-manual/the-team/designer.html",
    "/service-manual/the-team.html",
    "/service-manual/the-team/digital-leader.html",
    "/service-manual/the-team/delivery-manager.html",
    "/service-manual/browse.html",
    "/service-manual/technology/service-integration.html",
    "/service-manual/technology/architecture.html",
    "/service-manual/technology/security-as-enabler.html",
    "/service-manual/technology/end-user-devices.html",
    "/service-manual/technology/government-as-a-platform.html",
    "/service-manual/technology/code-of-practice.html",
    "/service-manual/technology/spending-controls.html",
    "/service-manual/technology/open-data.html",
    "/service-manual/technology.html",
    "/service-manual/technology/culture-that-supports-change.html",
    "/service-manual/digital-by-default-26-points.html",
    "/service-manual/operations/devops.html",
    "/service-manual/operations/penetration-testing.html",
    "/service-manual/operations/hosting.html",
    "/service-manual/operations/managing-user-support.html",
    "/service-manual/operations/load-and-performance-testing.html",
    "/service-manual/operations/web-operations-stories.html",
    "/service-manual/operations/uptime-and-availability.html",
    "/service-manual/operations/cloud-security.html",
    "/service-manual/operations/service-management.html",
    "/service-manual/operations/monitoring.html",
    "/service-manual/operations.html",
    "/service-manual/operations/helpdesk.html",
    "/service-manual/operations/operating-servicegovuk-subdomains.html",
    "/service-manual/user-researchers.html",
    "/service-manual/user-centred-design/resources/elements.html",
    "/service-manual/user-centred-design/resources/header-footer.html",
    "/service-manual/user-centred-design/resources/sass-repositories.html",
    "/service-manual/user-centred-design/resources/patterns/summary-pages.html",
    "/service-manual/user-centred-design/resources/patterns/alpha-beta.html",
    "/service-manual/user-centred-design/resources/patterns/knowledge-based-authentication.html",
    "/service-manual/user-centred-design/resources/patterns/form-structure.html",
    "/service-manual/user-centred-design/resources/patterns/usernames.html",
    "/service-manual/user-centred-design/resources/patterns/dates.html",
    "/service-manual/user-centred-design/resources/patterns/feedback-pages.html",
    "/service-manual/user-centred-design/resources/patterns/confirmation-pages.html",
    "/service-manual/user-centred-design/resources/patterns/create-user-account.html",
    "/service-manual/user-centred-design/resources/patterns/email-addresses.html",
    "/service-manual/user-centred-design/resources/patterns/gender-and-sex.html",
    "/service-manual/user-centred-design/resources/patterns/create-password.html",
    "/service-manual/user-centred-design/resources/patterns/help-text.html",
    "/service-manual/user-centred-design/resources/patterns/names.html",
    "/service-manual/user-centred-design/resources/patterns/email-confirmation-loop.html",
    "/service-manual/user-centred-design/resources/patterns/national-insurance-number.html",
    "/service-manual/user-centred-design/resources/patterns.html",
    "/service-manual/user-centred-design/resources/patterns/create-username.html",
    "/service-manual/user-centred-design/resources/patterns/progress-indicators.html",
    "/service-manual/user-centred-design/resources/patterns/start-pages.html",
    "/service-manual/user-centred-design/resources/patterns/addresses.html",
    "/service-manual/user-centred-design/resources/shared-asset-libraries.html",
    "/service-manual/user-centred-design/resources/captcha.html",
    "/service-manual/user-centred-design/resources/creating-accessible-PDFs.html",
    "/service-manual/user-centred-design/data-visualisation.html",
    "/service-manual/user-centred-design/how-users-read.html",
    "/service-manual/user-centred-design/card-sorting.html",
    "/service-manual/user-centred-design/choosing-appropriate-formats.html",
    "/service-manual/user-centred-design/accessibility.html",
    "/service-manual/user-centred-design/user-research/user-research-tools.html",
    "/service-manual/user-centred-design/user-research/community-user-groups.html",
    "/service-manual/user-centred-design/user-research/discussion-guides.html",
    "/service-manual/user-centred-design/user-research/accessibility-testing.html",
    "/service-manual/user-centred-design/user-research/multivariate-testing.html",
    "/service-manual/user-centred-design/user-research/user-research-briefs.html",
    "/service-manual/user-centred-design/user-research/expert-review.html",
    "/service-manual/user-centred-design/user-research/same-day-user-testing.html",
    "/service-manual/user-centred-design/user-research/ethnographic-research.html",
    "/service-manual/user-centred-design/user-research/guerrilla-testing.html",
    "/service-manual/user-centred-design/user-research/focus-groups-mini-groups-interviews.html",
    "/service-manual/user-centred-design/user-research/user-research-surveys.html",
    "/service-manual/user-centred-design/user-research/online-research-panels.html",
    "/service-manual/user-centred-design/user-research/sentiment-analysis.html",
    "/service-manual/user-centred-design/user-research/sampling-methodologies.html",
    "/service-manual/user-centred-design/user-research.html",
    "/service-manual/user-centred-design/user-research/survey-design.html",
    "/service-manual/user-centred-design/user-research/online-omnibus-survey.html",
    "/service-manual/user-centred-design/user-research/lab-based-user-testing.html",
    "/service-manual/user-centred-design/user-research/remote-usability.html",
    "/service-manual/user-centred-design/browsers-and-devices.html",
    "/service-manual/user-centred-design/working-with-prototypes.html",
    "/service-manual/user-centred-design/user-needs.html",
    "/service-manual/user-centred-design.html",
    "/service-manual/user-centred-design/user-centred-design-alpha-beta.html",
    "/service-manual/user-centred-design/print-forms.html",
    "/service-manual/user-centred-design/service-user-experience.html",
    "/service-manual/themes.html",
    "/service-manual/phases/live.html",
    "/service-manual/phases/retirement.html",
    "/service-manual/phases/ideal-alphas.html",
    "/service-manual/phases/alpha.html",
    "/service-manual/phases.html",
    "/service-manual/phases/discovery.html",
    "/service-manual/phases/beta.html",
    "/service-manual/cards.html",
    "/service-manual/assisted-digital/assisted-digital-user-research.html",
    "/service-manual/assisted-digital.html",
    "/service-manual/assisted-digital/action-plan.html",
    "/service-manual/performance-analysts.html",
    "/service-manual/start.html",
    "/service-manual/designers.html",
    "/service-manual/making-software/code-testing.html",
    "/service-manual/making-software/apis.html",
    "/service-manual/making-software/logins.html",
    "/service-manual/making-software/dependency-management.html",
    "/service-manual/making-software/open-standards-and-licensing.html",
    "/service-manual/making-software/information-security.html",
    "/service-manual/making-software/cookies.html",
    "/service-manual/making-software/development-environment.html",
    "/service-manual/making-software/exploratory-testing.html",
    "/service-manual/making-software/sandbox-and-staging-servers.html",
    "/service-manual/making-software/release-strategies.html",
    "/service-manual/making-software/choosing-technology.html",
    "/service-manual/making-software/testing-in-agile.html",
    "/service-manual/making-software/deployment.html",
    "/service-manual/making-software/progressive-enhancement.html",
    "/service-manual/making-software/version-control.html",
    "/service-manual/making-software/standalone-apps.html",
    "/service-manual/making-software/analytics-tools.html",
    "/service-manual/making-software.html",
    "/service-manual/making-software/open-source.html",
    "/service-manual/making-software/configuration-management.html",
    "/service-manual/identity-assurance.html",
    "/service-manual/service-managers.html",
    "/service-manual/content-designers/privacy-note-template-for-services.html",
    "/service-manual/content-designers.html",
    "/service-manual/technical-architects.html",
  ].freeze
end


text:
static struct lkl_mutex* mut = NULL;

void secondary(void* arg) {
	UNUSED(arg);
	// Cannot use wait()/sleep() operations
	volatile int i = 0;
	while (i < 10000000L)
		i++;
	lkl_host_ops.mutex_unlock(mut);
}

int main() {
	// Check mutex_alloc
	mut = lkl_host_ops.mutex_alloc();
	if (mut == NULL) {
		fprintf(stderr, "Failed to mutex_alloc\n");
		return 1;
	}

	// Check non-blocking mutex_lock
	lkl_host_ops.mutex_lock(mut);

	// Check blocking mutex_lock and ordering
	lkl_thread_t thread = lkl_host_ops.thread_create(&secondary, NULL);
	if (thread == 0) {
		fprintf(stderr, "Failed to thread_create\n");
		return 2;
	}

	lkl_host_ops.mutex_lock(mut);

	// Check mutex_free
	lkl_host_ops.mutex_free(mut);

	return 0;
}


text:
package hrv.lib.hrv.calc.parameter;

import hrv.lib.hrv.RRData;

public class ModeCalculator implements HRVDataProcessor {

	@Override
	public HRVParameter process(RRData data) {

		double[] a = data.getValueAxis();
		double maxValue = 0;
		var maxCount = 0;

		// For each element in a calculate the occurrences of that element in a.
		for (double anA : a) {
			var count = 0;
			for (double anA1 : a) {

				// Because the elements are of floating point precision they are
				// almost never the same.
				// Therefore they have to be in a certain range.
				if (!((anA1 > anA * 1.05) || (anA1 < anA * 0.95)))
					++count;
			}
			if (count > maxCount) {
				maxCount = count;
				maxValue = anA;
			}
		}

		return new HRVParameter(HRVParameterEnum.MODE, maxValue, "non");
	}

	@Override
	public boolean validData(RRData data) {
		return true;
	}
}


text:
root=`pwd`
version=$1
home=~
force=$2

         #--with-cc="gcc46" \
ngx-build $force $version \
          --with-ld-opt="-L$PCRE_LIB -Wl,-rpath,$PCRE_LIB:/usr/local/lib" \
          --add-module=$root/../echo-nginx-module \
          --add-module=$root/../ndk-nginx-module \
          --add-module=$root/../lua-nginx-module \
          --add-module=$root/../set-misc-nginx-module \
          --add-module=$root/../form-input-nginx-module \
          --add-module=$root/../rds-json-nginx-module \
          --add-module=$root/../headers-more-nginx-module \
          --add-module=$root $opts \
            --with-debug \
          || exit 1
          #--with-debug || exit 1
          #--add-module=$home/work/ngx_http_auth_request-0.1 #\
          #--with-rtsig_module
          #--with-cc-opt="-g3 -O0"
          #--add-module=$root/../echo-nginx-module \
  #--without-http_ssi_module  # we cannot disable ssi because echo_location_async depends on it (i dunno why?!)


text:
package foo.bar;

import javax.annotation.Generated;

@Generated("com.github.rocksteady.builder2.BuildableProcessor")
public abstract class B2GenericExtendedBuilder<Builder extends B2GenericExtendedBuilder<Builder, D, E>, D, E> {

    @SuppressWarnings("unchecked")
    private final Builder builder = (Builder) this;

    private final GenericExtended<D, E> buildable;

    public B2GenericExtendedBuilder(GenericExtended<D, E> buildable) {
        this.buildable = buildable;
    }
}


text:
SimpleForm.setup do |config|
  config.wrappers :inline, tag: :div, class: 'form-group', error_class: 'has-error',
                  label_html: { class: 'sr-only' } do |b|
    b.use :html5
    b.use :min_max
    b.use :placeholder

    b.optional :pattern
    b.optional :readonly

    b.use :label
    b.use :input
  end

  config.wrappers :inline_checkbox, tag: :div, class: "form-group", error_class: "has-error" do |b|
    b.use :html5
    b.optional :readonly

    b.wrapper tag: :div, class: 'checkbox' do |c|
      c.wrapper tag: :label do |a|
        a.use :input
        a.use :label_text
      end
    end
  end

  config.wrappers :inline_radio, tag: :div, class: "form-group", error_class: "has-error" do |b|
    b.use :html5
    b.optional :readonly

    b.wrapper tag: :div, class: 'radio' do |c|
      c.wrapper tag: :label do |a|
        a.use :input
        a.use :label_text
      end
    end
  end
end


text:
$LOAD_PATH << File.dirname(__FILE__)
require 'test_helper'

class GeographyColumnTests < ActiveRecordSpatialTestCase
  def setup
    load_models(:foo_geography)
  end

  def test_geography_columns_detected
    assert_equal(0, FooGeography.geometry_columns.length)
    assert_equal(2, FooGeography.geography_columns.length)

    FooGeography.geography_columns.each do |column|
      assert_kind_of(ActiveRecordSpatial::GeographyColumn, column)
    end
  end

  def test_srid_for
    assert_equal(ActiveRecordSpatial::UNKNOWN_SRIDS[:geography], FooGeography.srid_for(:the_geom))
    assert_equal(4326, FooGeography.srid_for(:the_other_geom))
  end

  def test_coord_dimension_for
    assert_nil(FooGeography.coord_dimension_for(:the_geom))
    assert_equal(2, FooGeography.coord_dimension_for(:the_other_geom))
  end

  def test_geography_column_by_name
    assert_kind_of(ActiveRecordSpatial::GeographyColumn, FooGeography.geography_column_by_name(:the_geom))
    assert_kind_of(ActiveRecordSpatial::GeographyColumn, FooGeography.geography_column_by_name(:the_other_geom))
  end

  def test_spatial_ref_sys
    assert_nil(FooGeography.geography_column_by_name(:the_geom).spatial_ref_sys)
    assert_kind_of(ActiveRecordSpatial::SpatialRefSys, FooGeography.geography_column_by_name(:the_other_geom).spatial_ref_sys)
    assert_equal(4326, FooGeography.geography_column_by_name(:the_other_geom).spatial_ref_sys.srid)
  end
end


text:
```
title: "Part VI: Zoom and Cameras"
```

When you run your game now, you'll notice that everything is really, really small. We're going to make it more visible by applying some zoom to our game so that we can get a better look at the action. This is a pretty quick change:

Open the Main.hx file. This class initializes your game, and there are a few things here that you could play with, if you want. We just need to change a couple of the parameters.

Change gameWidth and gameHeight to 320 and 240 (half of their original values). You could also change zoom from -1 to 2 if you wanted, but since it's at  -1, it will auto-calculate the zoom based on the difference between your game's size and the window dimension (which is defined in Project.xml).

If you ran the game right now, everything would be zoomed in, but the player would run off the screen pretty quick - we need to tell the camera to follow the player around.

So, open the PlayState again.

In the create function, after you add the player and before super.create(), add:

FlxG.camera.follow(_player, FlxCamera.STYLE_TOPDOWN, 1);

This simply tells the camera to follow the player using the Topdown style, with a lerp of 1 (which helps the camera move a little smoother). Note: we 'skipped' over the offset parameter, this is a neat feature in Haxe which you can read about here and here.

That's it! Test out the game and see how it looks!

Next, let's give the player something to pickup around the map!


text:
<?php

namespace PHPCR\Tests\SameNameSiblings;

/**
 * Test for deleting same name siblings (SNS).
 *
 * At this point, we are only testing for the ability to delete existing SNS;
 * creating or manipulating them is not supported.
 */
class DeleteMethodsTest extends \PHPCR\Test\BaseCase
{
    public static function setupBeforeClass($fixtures = '22_SameNameSiblings/delete')
    {
        parent::setupBeforeClass($fixtures);
    }

    public function setUp()
    {
        $this->renewSession(); // get rid of cache from previous tests
        parent::setUp();
    }

    /**
     * Call session->removeItem() with multiple items before session->save().
     */
    public function testRemoveItemMultiple()
    {
        $parentPath = '/tests_write_manipulation_delete_sns/testRemoveSnsBySession';
        $childNames = array('child', 'child[2]', 'child[3]');

        $parent = $this->getParentNode($this->session, $parentPath);

        foreach ($childNames as $childName) {
            $this->assertTrue($parent->hasNode($childName));
            $this->session->removeItem($parentPath.'/'.$childName);
            $this->assertFalse($parent->hasNode($childName), 'Node was not removed');
        }

        $this->saveAndRenewSession();

        foreach ($childNames as $childName) {
            $this->assertFalse($this->session->nodeExists($parentPath.'/'.$childName));
        }
    }

    /**
     * Call node->remove() with multiple items before session->save().
     *
     * \PHPCR\ItemInterface::remove
     */
    public function testRemoveNode()
    {
        $parentPath = '/tests_write_manipulation_delete_sns/testRemoveSnsByNode';
        $childNames = array('child', 'child[2]', 'child[3]');

        $parent = $this->getParentNode($this->session, $parentPath);

        foreach ($childNames as $childName) {
            $this->assertTrue($parent->hasNode($childName));
            $child = $parent->getNode($childName);
            $this->assertInstanceOf('PHPCR\NodeInterface', $child);
            $child->remove();
            $this->assertFalse($parent->hasNode($childName), 'Node was not removed');
        }

        $this->saveAndRenewSession();

        foreach ($childNames as $childName) {
            $this->assertFalse($this->session->nodeExists($parentPath.'/'.$childName));
        }
    }

    /**
     * Delete 6 nodes from a set of 12, and check that the correct ones remain
     * (using a property to track individual nodes as they get renamed).
     */
    public function testDeleteManyNodes()
    {
        $parentPath = '/tests_write_manipulation_delete_sns/testRemoveManyNodes';
        $childrenAtStart = array(
            'child'     => '1',
            'child[2]'  => '2',
            'child[3]'  => '3',
            'child[4]'  => '4',
            'child[5]'  => '5',
            'child[6]'  => '6',
            'child[7]'  => '7',
            'child[8]'  => '8',
            'child[9]'  => '9',
            'child[10]' => '10',
            'child[11]' => '11',
            'child[12]' => '12',
        );
        $childrenToDelete = array(
            'child',
            'child[2]',
            'child[3]',
            'child[6]',
            'child[10]',
            'child[11]',
        );
        $childrenAtEnd = array(
            'child'     => '4',
            'child[2]'  => '5',
            'child[3]'  => '7',
            'child[4]'  => '8',
            'child[5]'  => '9',
            'child[6]'  => '12',
        );

        $parent = $this->getParentNode($this->session, $parentPath);

        foreach ($childrenAtStart as $childName => $childNumber) {
            $this->assertTrue($parent->hasNode($childName), "Child $childNumber not found.");
        }

        foreach ($childrenToDelete as $childName) {
            $this->session->removeItem($parentPath.'/'.$childName);
            $this->assertFalse($parent->hasNode($childName), 'Node was not removed');
        }

        $this->saveAndRenewSession();

        $parent = $this->session->getNode($parentPath);
        $this->assertCount(count($childrenAtEnd), $parent->getNodes());

        foreach ($parent->getNodes() as $node) {
            $child = each($childrenAtEnd);
            $this->assertEquals($parentPath.'/'.$child['key'], $node->getPath());
            $this->assertEquals($child['value'], $node->getProperty('childNumber')->getValue());
        }
    }

    /**
     * @param $session
     * @param $parentPath
     *
     * @return mixed
     */
    private function getParentNode($session, $parentPath)
    {
        $parent = $session->getNode($parentPath);
        $this->assertInstanceOf('PHPCR\NodeInterface', $parent);

        return $parent;
    }
}


text:
<?php

namespace spectrum\reports;
require_once __DIR__ . '/../init.php';

abstract class Test extends \spectrum\Test
{
	protected function setUp()
	{
		parent::setUp();
		\spectrum\core\plugins\Manager::registerPlugin('reports', '\spectrum\reports\Plugin', 'firstAccess');
	}

	protected function tearDown()
	{
		parent::tearDown();
		\spectrum\core\plugins\Manager::unregisterPlugin('reports');
	}
}


text:
package org.gsm.oneapi.sms;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URLEncoder;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.gsm.oneapi.endpoints.ServiceEndpoints;
import org.gsm.oneapi.endpoints.ServiceEndpointsInterface;
import org.gsm.oneapi.foundation.CommandLineOptions;
import org.gsm.oneapi.foundation.FormParameters;
import org.gsm.oneapi.foundation.JSONRequest;
import org.gsm.oneapi.responsebean.RequestError;
import org.gsm.oneapi.responsebean.sms.InboundSMSMessageNotification;
import org.gsm.oneapi.responsebean.sms.InboundSMSMessageNotificationWrapper;
import org.gsm.oneapi.responsebean.sms.RetrieveSMSResponse;
import org.gsm.oneapi.responsebean.sms.SMSMessageReceiptSubscriptionResponse;
import org.gsm.oneapi.server.OneAPIServlet;

/**
 * The main API interface for the OneAPI SMS Retrieve methods
 */
public class SMSRetrieve {
	static Logger logger=Logger.getLogger(SMSRetrieve.class);

	ServiceEndpointsInterface endPoints=null;
	String authorisationHeader=null;

	public static boolean dumpRequestAndResponse=false;

	private static JSONRequest<RetrieveSMSResponse> retrieveSMSprocessor=new JSONRequest<RetrieveSMSResponse>(new RetrieveSMSResponse());
	private static JSONRequest<SMSMessageReceiptSubscriptionResponse> smsMessageReceiptSubscriptionProcessor=new JSONRequest<SMSMessageReceiptSubscriptionResponse>(new SMSMessageReceiptSubscriptionResponse());

	/**
	 Creates a new instance of the Receive SMS API main interface. Requires endPoints to define the URL targets of the various Receive SMS network calls and authorisationHeader containing the username/password used for HTTP Basic authorisation with the OneAPI server.

	@param  endPoints  contains a set of service/ call specific endpoints
	@param  authorisationHeader Base 64 encoded username/ password

	@see org.gsm.oneapi.endpoints.ServiceEndpoints
	@see org.gsm.oneapi.foundation.JSONRequest#getAuthorisationHeader(String, String)
	 */
	public SMSRetrieve(ServiceEndpointsInterface endPoints, String authorisationHeader) {
		this.endPoints=endPoints;
		this.authorisationHeader=authorisationHeader;
	}

	/**
	 Creates a new instance of the Receive SMS API main interface. Requires endPoints to define the URL targets of the various Receive SMS network calls and the username/password used for HTTP Basic authorisation with the OneAPI server.

	@param  endPoints  contains a set of service/ call specific endpoints
	@param  username is the account name allocated for use of the service
	@param  password is the corresponding authentication password

	@see org.gsm.oneapi.endpoints.ServiceEndpoints
	 */
	public SMSRetrieve(ServiceEndpointsInterface endPoints, String username, String password) {
		String authorisationHeader=null;
		if (username!=null && password!=null) {
			authorisationHeader=JSONRequest.getAuthorisationHeader(username, password);
		}
		this.authorisationHeader=authorisationHeader;
		this.endPoints=endPoints;
	}

	/**
	 Can be used to update the service endpoints

	@param  endPoints  contains a set of service/ call specific endpoints

	@see org.gsm.oneapi.endpoints.ServiceEndpoints
	 */
	public void setEndpoints(ServiceEndpoints endPoints) {
		this.endPoints=endPoints;
	}

	/**
	 Can be used to update the service authorisation header

	@param  authorisationHeader Base 64 encoded username/ password

	@see org.gsm.oneapi.foundation.JSONRequest#getAuthorisationHeader(String, String)
	 */
	public void setAuthorisationHeader(String authorisationHeader) {
		this.authorisationHeader=authorisationHeader;
	}

	/**
	 Retrieve SMS messages sent to your Web application

	@param registrationId (mandatory) is agreed with your network operator for receiving messages
	@param maxBatchSize (mandatory) is the maximum number of messages to retrieve in this request

	@see RetrieveSMSResponse
	*/
	public RetrieveSMSResponse retrieveMessages(String registrationId, int maxBatchSize) {
		RetrieveSMSResponse response=new RetrieveSMSResponse();

		if (registrationId!=null && maxBatchSize>=0) {

        	int responseCode=0;
            String contentType = null;

            try {
				logger.debug("endpoint="+endPoints.getRetrieveSMSEndpoint());
				String endpoint=endPoints.getRetrieveSMSEndpoint().replaceAll("\\{registrationId\\}", URLEncoder.encode(registrationId, "utf-8")).replaceAll("\\{maxBatchSize\\}", String.valueOf(maxBatchSize));

				if (dumpRequestAndResponse) JSONRequest.dumpRequestVariables(endpoint, authorisationHeader, null);

				HttpURLConnection con = JSONRequest.setupConnection(endpoint, authorisationHeader);

	        	responseCode=con.getResponseCode();
	            contentType = con.getContentType();

	            response.setHTTPResponseCode(responseCode);
	            response.setContentType(contentType);

	            response=retrieveSMSprocessor.getResponse(con, OneAPIServlet.OK);
			} catch (Exception e) {
				logger.error("Exception "+e.getMessage()+" "+e.getLocalizedMessage());
				e.printStackTrace();
				response.setHTTPResponseCode(responseCode);
				response.setContentType(contentType);

				response.setRequestError(new RequestError(RequestError.SERVICEEXCEPTION, "SVCJAVA", e.getMessage(), e.getClass().getName()));
			}
		}
		return response;
	}

	/**
	 Start subscribing to notifications of SMS messages sent to your application

	@param destinationAddress (mandatory) is the address/ MSISDN, or code agreed with the operator, to which people may send an SMS to your application
	@param notifyURL (mandatory) is the URL to which you would like a notification of message receipts sent
	@param criteria (optional) is case-insensitve text to match against the first word of the message, ignoring any leading whitespace. This allows you to reuse a short code among various applications, each of which can register their own subscription with different criteria
	@param notificationFormat (optional) is the content type that notifications will be sent in Ð for OneAPI v1.0 only JSON is supported
	@param clientCorrelator (optional) uniquely identifies this create subscription request. If there is a communication failure during the request, using the same clientCorrelator when retrying the request allows the operator to avoid creating a duplicate subscription
	@param callbackData (optional) is a function name or other data that you would like included when the POST is sent to your application

	@see SMSMessageReceiptSubscriptionResponse
	*/
	public SMSMessageReceiptSubscriptionResponse subscribeToReceiptNotifications(String destinationAddress, String notifyURL, String criteria, String notificationFormat, String clientCorrelator, String callbackData) {
		SMSMessageReceiptSubscriptionResponse response=new SMSMessageReceiptSubscriptionResponse();

		if (destinationAddress!=null && notifyURL!=null) {
			FormParameters formParameters=new FormParameters();
			formParameters.put("destinationAddress", destinationAddress);
			formParameters.put("notifyURL", notifyURL);
			formParameters.put("criteria", criteria);
			formParameters.put("notificationFormat", notificationFormat);
			formParameters.put("clientCorrelator", clientCorrelator);
			formParameters.put("callbackData", callbackData);

	    	int responseCode=0;
	        String contentType = null;

			try {
				String endpoint=endPoints.getSMSReceiptSubscriptionsEndpoint();

				if (dumpRequestAndResponse) JSONRequest.dumpRequestVariables(endpoint, authorisationHeader, formParameters);

				HttpURLConnection con = JSONRequest.setupConnection(endpoint, authorisationHeader);
		        con.setDoOutput(true);
		        OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());

		        String requestBody=JSONRequest.formEncodeParams(formParameters);
		        out.write(requestBody);
		        out.close();

	        	responseCode=con.getResponseCode();
	            contentType = con.getContentType();

	            response=smsMessageReceiptSubscriptionProcessor.getResponse(con, OneAPIServlet.CREATED);
			} catch (Exception e) {
				response.setHTTPResponseCode(responseCode);
				response.setContentType(contentType);

				response.setRequestError(new RequestError(RequestError.SERVICEEXCEPTION, "SVCJAVA", e.getMessage(), e.getClass().getName()));

				logger.error("Exception "+e.getMessage()+" "+e.getLocalizedMessage());
			}
		}
		return response;
	}

	/**
	 Stop subscribing to message receipt notifications for all your received SMS

	@param subscriptionId (mandatory) contains the subscriptionId of a previously created SMS message receipt subscription

	*/
	public int cancelReceiptNotifications(String subscriptionId)  {
		int responseCode=0;

		if (subscriptionId!=null) {

			try {
				logger.debug("endpoint="+endPoints.getCancelSMSReceiptSubscriptionEndpoint());
				String endpoint=endPoints.getCancelSMSReceiptSubscriptionEndpoint().replaceAll("\\{subscriptionId\\}", URLEncoder.encode(subscriptionId, "utf-8"));

				if (dumpRequestAndResponse) JSONRequest.dumpRequestVariables(endpoint, authorisationHeader, null);

				HttpURLConnection con = JSONRequest.setupConnection(endpoint, authorisationHeader);

				con.setRequestMethod("DELETE");

	        	responseCode=con.getResponseCode();
			} catch (Exception e) {
				logger.error("Exception "+e.getMessage()+" "+e.getLocalizedMessage());
				e.printStackTrace();
			}
		}
		return responseCode;
	}

	/**
	 * Utility function to process a received JSON formatted message received notification into a usable class instance of InboundSMSMessageNotification
	 * @param request the HttpServletRequest - make sure the input stream has not been read before calling
	 * @return InboundSMSMessageNotification
	 */
	public static InboundSMSMessageNotification convertInboundSMSMessageNotification(HttpServletRequest request) {
		InboundSMSMessageNotification inboundSMSMessageNotification=null;
		if (request.getContentType()!=null && request.getContentType().equalsIgnoreCase("application/json")) {
			try {
				ServletInputStream inputStream=request.getInputStream();

				ByteArrayOutputStream baos = new ByteArrayOutputStream();
	            int i;
	            while ((i = (byte) inputStream.read()) != -1) baos.write(i);

	            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

	            ObjectMapper mapper=new ObjectMapper();

	            InboundSMSMessageNotificationWrapper wrapper=mapper.readValue(bais, InboundSMSMessageNotificationWrapper.class);
	            if (wrapper!=null) inboundSMSMessageNotification=wrapper.getInboundSMSMessageNotification();
			} catch (java.io.IOException e) {
				logger.error("IOException "+e.getMessage());
			}
		}
		return inboundSMSMessageNotification;
	}

	public static void main(String[] args) {
		BasicConfigurator.configure();

		dumpRequestAndResponse=true;

		ServiceEndpoints serviceEndpoints=CommandLineOptions.getServiceEndpoints(args);

		String username=CommandLineOptions.getUsername(args);
		String password=CommandLineOptions.getPassword(args);

		if (username==null) username="Fred.Jones";
		if (password==null) password="1234";
		if (serviceEndpoints==null) serviceEndpoints=new ServiceEndpoints();

		logger.debug("Demonstration of inbound SMS API");

		String authorisationHeader=JSONRequest.getAuthorisationHeader(username, password);

		SMSRetrieve me=new SMSRetrieve(serviceEndpoints, authorisationHeader);

		logger.debug("SMS receive endpoint="+serviceEndpoints.getRetrieveSMSEndpoint());
		RetrieveSMSResponse retrieveResponse=me.retrieveMessages("3456", 2);
		if (retrieveResponse!=null) {
			logger.debug("Have SMS retrieve response:\n"+retrieveResponse.toString());
		} else {
			logger.debug("No response obtained");
		}

		String notifyURL="http://test.com/notifyThis/Message="+JSONRequest.urlEncode("This is encoded");

		logger.debug("Register a message receipt notification endpoint="+serviceEndpoints.getSMSReceiptSubscriptionsEndpoint());

		SMSMessageReceiptSubscriptionResponse receiptSubscription=me.subscribeToReceiptNotifications("3456", notifyURL, "Vote%", "JSON", "12345", "doSomething()");
		if (receiptSubscription!=null) {
			logger.debug("SMSMessageReceiptSubscriptionResponse="+receiptSubscription.toString());
		} else {
			logger.debug("No response obtained");
		}

		logger.debug("Cancel message receipt notification endpoint="+serviceEndpoints.getCancelSMSReceiptSubscriptionEndpoint());

		int cancelSubscriptionResponse=me.cancelReceiptNotifications("sub789");
		logger.debug("Cancel receipt subscription response code="+cancelSubscriptionResponse);

	}

}


text:
FROM jrnt30/nodejs-grunt-bower

WORKDIR /app
ADD package.json /app/
RUN npm install
ADD . /app

CMD []
ENTRYPOINT ["/nodejs/bin/npm", "start"]


text:
define("arale/sticky/1.3.1/sticky-debug", [ "$-debug" ], function(require, exports, module, undefined) {
    var $ = require("$-debug"), doc = $(document), stickyPrefix = [ "-webkit-", "-ms-", "-o-", "-moz-", "" ], guid = 0, ua = (window.navigator.userAgent || "").toLowerCase(), isIE = ua.indexOf("msie") !== -1, isIE6 = ua.indexOf("msie 6") !== -1;
    var isPositionStickySupported = checkPositionStickySupported(), isPositionFixedSupported = checkPositionFixedSupported();
    // Sticky
    // position: sticky simulator
    function Sticky(options) {
        this.options = options || {};
        this.elem = $(this.options.element);
        this.callback = options.callback || function() {};
        this.position = options.position;
        this._stickyId = guid++;
    }
    Sticky.prototype._prepare = function() {
        // save element's origin position
        var offset = this.elem.offset();
        this._originTop = offset.top;
        this._originLeft = offset.left;
        // if is fixed, force to call this_supportFixed
        if (this.position.top === Number.MAX_VALUE) {
            this._callFix = true;
            this.position.top = this._originTop;
        }
        // save element's origin style
        this._originStyles = {
            position: null,
            top: null,
            bottom: null,
            left: null
        };
        for (var style in this._originStyles) {
            if (this._originStyles.hasOwnProperty(style)) {
                this._originStyles[style] = this.elem.css(style);
            }
        }
    };
    Sticky.prototype.render = function() {
        var self = this;
        // only bind once
        if (!this.elem.length || this.elem.data("bind-sticked")) {
            return this;
        }
        this._prepare();
        // if other element change height in one page,
        // or if resize window,
        // need adjust sticky element's status
        this.adjust = function() {
            self._restore();
            var offset = self.elem.offset();
            self._originTop = offset.top;
            self._originLeft = offset.left;
            scrollFn.call(self);
        };
        var scrollFn;
        if (sticky.isPositionStickySupported && !this._callFix) {
            scrollFn = this._supportSticky;
            // set position: sticky directly
            var tmp = "";
            for (var i = 0; i < stickyPrefix.length; i++) {
                tmp += "position:" + stickyPrefix[i] + "sticky;";
            }
            if (this.position.top !== undefined) {
                tmp += "top: " + this.position.top + "px;";
            }
            if (this.position.bottom !== undefined) {
                tmp += "bottom: " + this.position.bottom + "px;";
            }
            this.elem[0].style.cssText += tmp;
            this.adjust = function() {
                scrollFn.call(self);
            };
        } else if (sticky.isPositionFixedSupported) {
            scrollFn = this._supportFixed;
        } else {
            scrollFn = this._supportAbsolute;
            // ie6
            // avoid floatImage Shake for IE6
            // see: https://github.com/lifesinger/lifesinger.
            //      github.com/blob/master/lab/2009/ie6sticked_position_v4.html
            $("").appendTo("head");
        }
        // first run after document ready
        scrollFn.call(this);
        // stickyX is event namespace
        $(window).on("scroll.sticky" + this._stickyId, function() {
            if (!self.elem.is(":visible")) return;
            scrollFn.call(self);
        });
        $(window).on("resize.sticky" + this._stickyId, debounce(function() {
            self.adjust();
        }, 120));
        this.elem.data("bind-sticked", true);
        return this;
    };
    Sticky.prototype._getTopBottom = function(scrollTop, offsetTop) {
        var top;
        var bottom;
        // top is true when the distance from element to top of window <= position.top
        if (this.position.top !== undefined) {
            top = offsetTop - scrollTop <= this.position.top;
        }
        // bottom is true when the distance is from bottom of element to bottom of window <= position.bottom
        if (this.position.bottom !== undefined) {
            bottom = scrollTop + $(window).height() - offsetTop - this.elem.outerHeight() <= this.position.bottom;
        }
        return {
            top: top,
            bottom: bottom
        };
    };
    Sticky.prototype._supportFixed = function() {
        var _sticky = this.elem.data("sticked");
        var distance = this._getTopBottom(doc.scrollTop(), this._originTop);
        if (!_sticky && (distance.top !== undefined && distance.top || distance.bottom !== undefined && distance.bottom)) {
            this._addPlaceholder();
            this.elem.css($.extend({
                position: "fixed",
                left: this._originLeft
            }, distance.top ? {
                top: this.position.top
            } : {
                bottom: this.position.bottom
            }));
            this.elem.data("sticked", true);
            this.callback.call(this, true);
        } else if (_sticky && !distance.top && !distance.bottom) {
            this._restore();
        }
    };
    Sticky.prototype._supportAbsolute = function() {
        var scrollTop = doc.scrollTop();
        var _sticky = this.elem.data("sticked");
        var distance = this._getTopBottom(scrollTop, this.elem.offset().top);
        if (distance.top || distance.bottom || this._callFix) {
            // sticky status change only one time
            if (!_sticky) {
                this._addPlaceholder();
                this.elem.data("sticked", true);
                this.callback.call(this, true);
            }
            // update element's position
            this.elem.css({
                position: "absolute",
                top: this._callFix ? this._originTop + scrollTop : distance.top ? this.position.top + scrollTop : scrollTop + $(window).height() - this.position.bottom - this.elem.outerHeight()
            });
        } else if (_sticky && !distance.top && !distance.bottom) {
            this._restore();
        }
    };
    Sticky.prototype._supportSticky = function() {
        // sticky status change for callback
        var _sticky = this.elem.data("sticked");
        var distance = this._getTopBottom(doc.scrollTop(), this.elem.offset().top);
        if (!_sticky && (distance.top !== undefined && distance.top || distance.bottom !== undefined && distance.bottom)) {
            this.elem.data("sticked", true);
            this.callback.call(this, true);
        } else if (_sticky && !distance.top && !distance.bottom) {
            // don't need restore style and remove placeholder
            this.elem.data("sticked", false);
            this.callback.call(this, false);
        }
    };
    Sticky.prototype._restore = function() {
        this._removePlaceholder();
        // set origin style
        this.elem.css(this._originStyles);
        this.elem.data("sticked", false);
        this.callback.call(this, false);
    };
    // need placeholder when: 1) position: static or relative, but expect for display != block
    Sticky.prototype._addPlaceholder = function() {
        var need = false;
        var position = this.elem.css("position");
        if (position === "static" || position === "relative") {
            need = true;
        }
        if (this.elem.css("display") !== "block") {
            need = false;
        }
        if (need) {
            this._placeholder = $('

');
            this._placeholder.width(this.elem.outerWidth(true)).height(this.elem.outerHeight(true)).css("float", this.elem.css("float")).insertAfter(this.elem);
        }
    };
    Sticky.prototype._removePlaceholder = function() {
        // remove placeholder if has
        this._placeholder && this._placeholder.remove();
    };
    Sticky.prototype.destroy = function() {
        this._restore();
        this.elem.data("bind-sticked", false);
        $(window).off("scroll.sticky" + this._stickyId);
        $(window).off("resize.sticky" + this._stickyId);
    };
    // APIs
    // ---
    module.exports = sticky;
    function sticky(elem, position, callback) {
        if (!$.isPlainObject(position)) {
            position = {
                top: position
            };
        }
        if (position.top === undefined && position.bottom === undefined) {
            position.top = 0;
        }
        return new Sticky({
            element: elem,
            position: position,
            callback: callback
        }).render();
    }
    // sticky.stick(elem, position, callback)
    sticky.stick = sticky;
    // sticky.fix(elem)
    sticky.fix = function(elem) {
        return new Sticky({
            element: elem,
            // position.top is Number.MAX_VALUE means fixed
            position: {
                top: Number.MAX_VALUE
            }
        }).render();
    };
    // for tc
    sticky.isPositionStickySupported = isPositionStickySupported;
    sticky.isPositionFixedSupported = isPositionFixedSupported;
    // Helper
    // ---
    function checkPositionFixedSupported() {
        return !isIE6;
    }
    function checkPositionStickySupported() {
        if (isIE) return false;
        var container = doc[0].body;
        if (doc[0].createElement && container && container.appendChild && container.removeChild) {
            var isSupported, el = doc[0].createElement("div"), getStyle = function(st) {
                if (window.getComputedStyle) {
                    return window.getComputedStyle(el).getPropertyValue(st);
                } else {
                    return el.currentStyle.getAttribute(st);
                }
            };
            container.appendChild(el);
            for (var i = 0; i < stickyPrefix.length; i++) {
                el.style.cssText = "position:" + stickyPrefix[i] + "sticky;visibility:hidden;";
                if (isSupported = getStyle("position").indexOf("sticky") !== -1) break;
            }
            el.parentNode.removeChild(el);
            return isSupported;
        }
    }
    // https://github.com/jashkenas/underscore/blob/master/underscore.js#L699
    function getTime() {
        return (Date.now || function() {
            return new Date().getTime();
        })();
    }
    function debounce(func, wait, immediate) {
        var timeout, args, context, timestamp, result;
        return function() {
            context = this;
            args = arguments;
            timestamp = getTime();
            var later = function() {
                var last = getTime() - timestamp;
                if (last < wait) {
                    timeout = setTimeout(later, wait - last);
                } else {
                    timeout = null;
                    if (!immediate) result = func.apply(context, args);
                }
            };
            var callNow = immediate && !timeout;
            if (!timeout) {
                timeout = setTimeout(later, wait);
            }
            if (callNow) result = func.apply(context, args);
            return result;
        };
    }
});


text:
#ifndef FS_NFS_DELEGATION_H
#define FS_NFS_DELEGATION_H

#if defined(CONFIG_NFS_V4)
/*
 * NFSv4 delegation
 */
struct nfs_delegation {
	struct list_head super_list;
	struct rpc_cred *cred;
	struct inode *inode;
	nfs4_stateid stateid;
	int type;
#define NFS_DELEGATION_NEED_RECLAIM 1
	long flags;
	loff_t maxsize;
	__u64 change_attr;
};

int nfs_inode_set_delegation(struct inode *inode, struct rpc_cred *cred, struct nfs_openres *res);
void nfs_inode_reclaim_delegation(struct inode *inode, struct rpc_cred *cred, struct nfs_openres *res);
int __nfs_inode_return_delegation(struct inode *inode);
int nfs_async_inode_return_delegation(struct inode *inode, const nfs4_stateid *stateid);

struct inode *nfs_delegation_find_inode(struct nfs4_client *clp, const struct nfs_fh *fhandle);
void nfs_return_all_delegations(struct super_block *sb);
void nfs_expire_all_delegations(struct nfs4_client *clp);
void nfs_handle_cb_pathdown(struct nfs4_client *clp);

void nfs_delegation_mark_reclaim(struct nfs4_client *clp);
void nfs_delegation_reap_unclaimed(struct nfs4_client *clp);

/* NFSv4 delegation-related procedures */
int nfs4_proc_delegreturn(struct inode *inode, struct rpc_cred *cred, const nfs4_stateid *stateid);
int nfs4_open_delegation_recall(struct dentry *dentry, struct nfs4_state *state);
int nfs4_lock_delegation_recall(struct nfs4_state *state, struct file_lock *fl);

static inline int nfs_have_delegation(struct inode *inode, int flags)
{
	flags &= FMODE_READ|FMODE_WRITE;
	smp_rmb();
	if ((NFS_I(inode)->delegation_state & flags) == flags)
		return 1;
	return 0;
}

static inline int nfs_inode_return_delegation(struct inode *inode)
{
	int err = 0;

	if (NFS_I(inode)->delegation != NULL)
		err = __nfs_inode_return_delegation(inode);
	return err;
}
#else
static inline int nfs_have_delegation(struct inode *inode, int flags)
{
	return 0;
}

static inline int nfs_inode_return_delegation(struct inode *inode)
{
	return 0;
}
#endif

#endif


text:
#ifndef LengthFunctions_h
#define LengthFunctions_h

#include "LayoutTypes.h"

namespace WebCore {

class RenderView;
struct Length;

int minimumIntValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
int intValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
LayoutUnit minimumValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
LayoutUnit valueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
float floatValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0);
float floatValueForLength(const Length&, float maximumValue, RenderView* = 0);

} // namespace WebCore

#endif // LengthFunctions_h


text:
<!DOCTYPE html>

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">

<title>Table of Contents - Opinio</title>

<link type="text/css" media="screen" href="./rdoc.css" rel="stylesheet">

Table of Contents - Opinio

Pages

    README

Opinio

Description

Intallation

Usage

Customization

Views

Behaviour

Opinio Model

Opinio Subjectum

Pretty Urls

Customize destroy conditions

Testing

Contribution

TODO

Classes/Modules

    Opinio

    Opinio::Controllers

    Opinio::Controllers::Extensions

    Opinio::Controllers::Extensions::ClassMethods

    Opinio::Controllers::Extensions::InstanceMethods

    Opinio::Controllers::Helpers

    Opinio::Controllers::InternalHelpers

    Opinio::Controllers::Replies

    Opinio::Engine

    Opinio::Generators

    Opinio::Generators::InstallGenerator

    Opinio::Generators::ViewsGenerator

    Opinio::OpinioModel

    Opinio::OpinioModel::ClassMethods

    Opinio::OpinioModel::RepliesSupport

    Opinio::OpinioModel::Sanitizing

    Opinio::OpinioModel::Validations

    Opinio::OpinioModel::Validations::IntervalMethods

    Opinio::OpinioSubjectum

    Opinio::OpinioSubjectum::ClassMethods

    Opinio::Orm

    Opinio::Orm::ActiveRecord

    Opinio::Orm::ActiveRecord::Schema

    Opinio::Schema

    Opinio::Version

    ActionDispatch

    ActionDispatch::Routing

    ActionDispatch::Routing::Mapper

    Create

    NoSanitizerComment

    Object

Methods

::check_custom_identifiers — Opinio

::included — Opinio::OpinioModel::Sanitizing

::included — Opinio::Controllers::Extensions

::included — Opinio::OpinioModel

::included — Opinio::OpinioModel::RepliesSupport

::included — Opinio::OpinioSubjectum

::next_migration_number — Opinio::Generators::InstallGenerator

::opinio_identifier — Opinio

::set_destroy_conditions — Opinio

::setup — Opinio

#add_dependency_gem — Opinio::Generators::InstallGenerator

#apply_opinio_schema — Opinio::Schema

#apply_opinio_schema — Opinio::Orm::ActiveRecord::Schema

#can_destroy_opinio? — Opinio::Controllers::Extensions::InstanceMethods

#comments_for — Opinio::Controllers::Helpers

#copy_views — Opinio::Generators::ViewsGenerator

#custom_resource_identifier — Opinio::Controllers::InternalHelpers

#generate_initializer — Opinio::Generators::InstallGenerator

#generate_migration — Opinio::Generators::InstallGenerator

#generate_model — Opinio::Generators::InstallGenerator

#generate_route — Opinio::Generators::InstallGenerator

#opinio — Opinio::Schema

#opinio — Opinio::OpinioModel::ClassMethods

#opinio — ActionDispatch::Routing::Mapper

#opinio_after_create_path — Opinio::Controllers::Extensions::InstanceMethods

#opinio_after_destroy_path — Opinio::Controllers::Extensions::InstanceMethods

#opinio_identifier — Opinio::Controllers::Extensions::ClassMethods

#opinio_model — ActionDispatch::Routing::Mapper

#opinio_subjectum — Opinio::OpinioSubjectum::ClassMethods

#render_comments — Opinio::Controllers::Helpers

#render_comments_form — Opinio::Controllers::Helpers

#reply — Opinio::Controllers::Replies

#resource — Opinio::Controllers::InternalHelpers

#resource_by_params — Opinio::Controllers::InternalHelpers

#resource_name — Opinio::Controllers::InternalHelpers

#set_flash — Opinio::Controllers::InternalHelpers

#view_language — Opinio::Generators::ViewsGenerator

[Validate]

Generated by RDoc 3.12.

Generated with the Darkfish Rdoc Generator 3.


text:
@class JavaxJmdnsJmDNS;
@class JavaxJmdnsServiceInfo;

@interface JavaxJmdnsServiceEvent : JavaUtilEventObject < NSCopying >

#pragma mark Public

- (instancetype)initWithId:(id)eventSource;

- (JavaxJmdnsServiceEvent *)java_clone;

- (JavaxJmdnsJmDNS *)getDNS;

- (JavaxJmdnsServiceInfo *)getInfo;

- (NSString *)getName;

- (NSString *)getType;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaxJmdnsServiceEvent)

FOUNDATION_EXPORT void JavaxJmdnsServiceEvent_initWithId_(JavaxJmdnsServiceEvent *self, id eventSource);

J2OBJC_TYPE_LITERAL_HEADER(JavaxJmdnsServiceEvent)

#endif

#pragma pop_macro("INCLUDE_ALL_JavaxJmdnsServiceEvent")


text:
A Metalsmith plugin to modify files with a given string manipulation
function. This library is essentially a convenience for building your own
plugin if all that plugin needs to do is modify files based solely on their
own contents.

This plugin is agnostic about the specific types of files it is performing
operations on. Often you will want to use this plugin in conjunction with
other plugins that filter the files you want to transform.

## Installation
``` bash
npm install --save-dev metalsmith-transformer
```

## Usage
```js
var Metalsmith = require('metalsmith');
var transformer = require('metalsmith-transformer');

Metalsmith
	.use(transformer(options))
```

## Options
All options are optional (duh!).

**transformer** - a function with type String -> String. In other words, a function that accepts a String and returns a String. This will be called on the contents of every file passed into the plugin.
*defaults to the identity function*

**decoding** - the encoding to use to decode the data from the file buffer before passing it into the transformer. If you set this value to anything but the default, and you do not set the encoding, then you will change the file's encoding.
*defaults to utf8*

**encoding** - the encoding to use to encode the transformed string into the file buffer. If you set this value to anything but the default, and you do not set the decoding, then you will change the file's encoding.
*defaults to utf8*

Please see [Node's documentation](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) for a list of supported character encodings.

## Examples
``` js
// Change every instance of the word wow to all uppercase
var options = {
	transformer: function (str) {
		return str.replace(/\swow\s/ig, 'WOW');
	}
}

// Change the encoding of the file from utf8 to ascii
var options = {
	decoding: 'utf8',
	encoding: 'ascii'
}
```

## Migrating from 1.x
Version 2.0 breaks backward compatibility (sorry!) in order to be consistent with the metalsmith plugin paradigm of accepting a single configuration object. The good news is that migrating is super simple. Simply take your transformer function, stick it in an object, and assign it to the object's `transformer` property. Here's an example:

``` js
function t (str) {
	// Return transformed string
}

// 1.x
Metalsmith
	.use(transformer(t));

// 2.0
Metalsmith
	.use(transformer({ transformer: t }));
```

And that's all there is to it!


text:
<?php

namespace Cacic\CommonBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * AquisicaoItem
 */
class AquisicaoItem
{
    /**
     * @var integer
     */
    private $idAquisicaoItem;

    /**
     * @var integer
     */
    private $qtLicenca;

    /**
     * @var \DateTime
     */
    private $dtVencimentoLicenca;

    /**
     * @var string
     */
    private $teObs;

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $idSoftwareEstacao;

    /**
     * @var \Cacic\CommonBundle\Entity\Aquisicao
     */
    private $idAquisicao;

    /**
     * @var \Cacic\CommonBundle\Entity\TipoLicenca
     */
    private $idTipoLicenca;

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $idSoftwareRelatorio;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->idSoftwareEstacao = new \Doctrine\Common\Collections\ArrayCollection();
        $this->idSoftwareRelatorio = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get idAquisicaoItem
     *
     * @return integer
     */
    public function getIdAquisicaoItem()
    {
        return $this->idAquisicaoItem;
    }

    /**
     * Set qtLicenca
     *
     * @param integer $qtLicenca
     * @return AquisicaoItem
     */
    public function setQtLicenca($qtLicenca)
    {
        $this->qtLicenca = $qtLicenca;

        return $this;
    }

    /**
     * Get qtLicenca
     *
     * @return integer
     */
    public function getQtLicenca()
    {
        return $this->qtLicenca;
    }

    /**
     * Set dtVencimentoLicenca
     *
     * @param \DateTime $dtVencimentoLicenca
     * @return AquisicaoItem
     */
    public function setDtVencimentoLicenca($dtVencimentoLicenca)
    {
        $this->dtVencimentoLicenca = $dtVencimentoLicenca;

        return $this;
    }

    /**
     * Get dtVencimentoLicenca
     *
     * @return \DateTime
     */
    public function getDtVencimentoLicenca()
    {
        return $this->dtVencimentoLicenca;
    }

    /**
     * Set teObs
     *
     * @param string $teObs
     * @return AquisicaoItem
     */
    public function setTeObs($teObs)
    {
        $this->teObs = $teObs;

        return $this;
    }

    /**
     * Get teObs
     *
     * @return string
     */
    public function getTeObs()
    {
        return $this->teObs;
    }

    /**
     * Add idSoftwareEstacao
     *
     * @param \Cacic\CommonBundle\Entity\SoftwareEstacao $idSoftwareEstacao
     * @return AquisicaoItem
     */
    public function addIdSoftwareEstacao(\Cacic\CommonBundle\Entity\SoftwareEstacao $idSoftwareEstacao)
    {
        $this->idSoftwareEstacao[] = $idSoftwareEstacao;

        return $this;
    }

    /**
     * Remove idSoftwareEstacao
     *
     * @param \Cacic\CommonBundle\Entity\SoftwareEstacao $idSoftwareEstacao
     */
    public function removeIdSoftwareEstacao(\Cacic\CommonBundle\Entity\SoftwareEstacao $idSoftwareEstacao)
    {
        $this->idSoftwareEstacao->removeElement($idSoftwareEstacao);
    }

    /**
     * Get idSoftwareEstacao
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getIdSoftwareEstacao()
    {
        return $this->idSoftwareEstacao;
    }

    /**
     * Set idAquisicao
     *
     * @param \Cacic\CommonBundle\Entity\Aquisicao $idAquisicao
     * @return AquisicaoItem
     */
    public function setIdAquisicao(\Cacic\CommonBundle\Entity\Aquisicao $idAquisicao = null)
    {
        $this->idAquisicao = $idAquisicao;

        return $this;
    }

    /**
     * Get idAquisicao
     *
     * @return \Cacic\CommonBundle\Entity\Aquisicao
     */
    public function getIdAquisicao()
    {
        return $this->idAquisicao;
    }

    /**
     * Set idTipoLicenca
     *
     * @param \Cacic\CommonBundle\Entity\TipoLicenca $idTipoLicenca
     * @return AquisicaoItem
     */
    public function setIdTipoLicenca(\Cacic\CommonBundle\Entity\TipoLicenca $idTipoLicenca = null)
    {
        $this->idTipoLicenca = $idTipoLicenca;

        return $this;
    }

    /**
     * Get idTipoLicenca
     *
     * @return \Cacic\CommonBundle\Entity\TipoLicenca
     */
    public function getIdTipoLicenca()
    {
        return $this->idTipoLicenca;
    }

    /**
     * Add idSoftwareRelatorio
     *
     * @param \Cacic\CommonBundle\Entity\SoftwareRelatorio $idSoftwareRelatorio
     * @return AquisicaoItem
     */
    public function addIdSoftwareRelatorio(\Cacic\CommonBundle\Entity\SoftwareRelatorio $idSoftwareRelatorio)
    {
        $this->idSoftwareRelatorio[] = $idSoftwareRelatorio;

        return $this;
    }

    /**
     * Remove idSoftwareRelatorio
     *
     * @param \Cacic\CommonBundle\Entity\SoftwareRelatorio $idSoftwareRelatorio
     */
    public function removeIdSoftwareRelatorio(\Cacic\CommonBundle\Entity\SoftwareRelatorio $idSoftwareRelatorio)
    {
        $this->idSoftwareRelatorio->removeElement($idSoftwareRelatorio);
    }

    /**
     * Get idSoftwareRelatorio
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getIdSoftwareRelatorio()
    {
        return $this->idSoftwareRelatorio;
    }
    /**
     * @var string
     */
    private $nmAquisicao;

    /**
     * Set nmAquisicao
     *
     * @param string $nmAquisicao
     * @return AquisicaoItem
     */
    public function setNmAquisicao($nmAquisicao)
    {
        $this->nmAquisicao = $nmAquisicao;

        return $this;
    }

    /**
     * Get nmAquisicao
     *
     * @return string
     */
    public function getNmAquisicao()
    {
        return $this->nmAquisicao;
    }
}


text:
namespace mojo {
namespace package_manager {
class PackageManagerImpl;
}
namespace runner {

class NativeApplicationLoader;

// The "global" context for the shell's main process.
class Context : public embedder::ProcessDelegate {
 public:
  explicit Context(const base::FilePath& shell_file_root);
  ~Context() override;

  static void EnsureEmbedderIsInitialized();

  // This must be called with a message loop set up for the current thread,
  // which must remain alive until after Shutdown() is called. Returns true on
  // success.
  bool Init();

  // If Init() was called and succeeded, this must be called before destruction.
  void Shutdown();

  // NOTE: call either Run() or RunCommandLineApplication(), but not both.

  // Runs the app specified by |url|.
  void Run(const GURL& url);

  // Run the application specified on the commandline. When the app finishes,
  // |callback| is run if not null, otherwise the message loop is quit.
  void RunCommandLineApplication(const base::Closure& callback);

  TaskRunners* task_runners() { return task_runners_.get(); }
  shell::ApplicationManager* application_manager() {
    return application_manager_.get();
  }

  package_manager::PackageManagerImpl* package_manager() {
    return package_manager_;
  }

 private:
  class NativeViewportApplicationLoader;

  // ProcessDelegate implementation.
  void OnShutdownComplete() override;

  void OnApplicationEnd(const GURL& url);

  ScopedUserDataDir scoped_user_data_dir;
  std::set<GURL> app_urls_;
  scoped_ptr<TaskRunners> task_runners_;
  base::FilePath shell_file_root_;
  // Owned by |application_manager_|.
  package_manager::PackageManagerImpl* package_manager_;
  scoped_ptr<shell::ApplicationManager> application_manager_;
  base::Closure app_complete_callback_;
  base::Time main_entry_time_;

  DISALLOW_COPY_AND_ASSIGN(Context);
};

}  // namespace runner
}  // namespace mojo

#endif  // MOJO_RUNNER_CONTEXT_H_