text:
package org.apache.hadoop.yarn.webapp.hamlet2;

import org.apache.hadoop.thirdparty.com.google.common.base.Joiner;
import static org.apache.hadoop.thirdparty.com.google.common.base.Preconditions.*;
import org.apache.hadoop.thirdparty.com.google.common.base.Splitter;
import org.apache.hadoop.thirdparty.com.google.common.collect.Iterables;

import java.io.PrintWriter;
import java.util.EnumSet;
import static java.util.EnumSet.*;
import java.util.Iterator;

import static org.apache.commons.text.StringEscapeUtils.*;
import static org.apache.hadoop.yarn.webapp.hamlet2.HamletImpl.EOpt.*;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.yarn.webapp.SubView;
import org.apache.hadoop.yarn.webapp.WebAppException;

/**
 * A simple unbuffered generic hamlet implementation.
 *
 * Zero copy but allocation on every element, which could be
 * optimized to use a thread-local element pool.
 *
 * Prints HTML as it builds. So the order is important.
 */
@InterfaceAudience.Private
public class HamletImpl extends HamletSpec {
  private static final String INDENT_CHARS = "  ";
  private static final Splitter SS = Splitter.on('.').
      omitEmptyStrings().trimResults();
  private static final Joiner SJ = Joiner.on(' ');
  private static final Joiner CJ = Joiner.on(", ");
  static final int S_ID = 0;
  static final int S_CLASS = 1;

  int nestLevel;
  int indents; // number of indent() called. mostly for testing.
  private final PrintWriter out;
  private final StringBuilder sb = new StringBuilder(); // not shared
  private boolean wasInline = false;

  /**
   * Element options. (whether it needs end tag, is inline etc.)
   */
  public enum EOpt {
    /** needs end(close) tag */
    ENDTAG,
    /** The content is inline */
    INLINE,
    /** The content is preformatted */
    PRE
  };

  /**
   * The base class for elements
   * @param <T> type of the parent (containing) element for the element
   */
  public class EImp<T extends __> implements _Child {
    private final String name;
    private final T parent; // short cut for parent element
    private final EnumSet<EOpt> opts; // element options

    private boolean started = false;
    private boolean attrsClosed = false;

    EImp(String name, T parent, EnumSet<EOpt> opts) {
      this.name = name;
      this.parent = parent;
      this.opts = opts;
    }

    @Override
    public T __() {
      closeAttrs();
      --nestLevel;
      printEndTag(name, opts);
      return parent;
    }

    protected void _p(boolean quote, Object... args) {
      closeAttrs();
      for (Object s : args) {
        if (!opts.contains(PRE)) {
          indent(opts);
        }
        out.print(quote ? escapeHtml4(String.valueOf(s))
                        : String.valueOf(s));
        if (!opts.contains(INLINE) && !opts.contains(PRE)) {
          out.println();
        }
      }
    }

    protected void _v(Class<? extends SubView> cls) {
      closeAttrs();
      subView(cls);
    }

    protected void closeAttrs() {
      if (!attrsClosed) {
        startIfNeeded();
        ++nestLevel;
        out.print('>');
        if (!opts.contains(INLINE) && !opts.contains(PRE)) {
          out.println();
        }
        attrsClosed = true;
      }
    }

    protected void addAttr(String name, String value) {
      checkState(!attrsClosed, "attribute added after content");
      startIfNeeded();
      printAttr(name, value);
    }

    protected void addAttr(String name, Object value) {
      addAttr(name, String.valueOf(value));
    }

    protected void addMediaAttr(String name, EnumSet<Media> media) {
      // 6.13 comma-separated list
      addAttr(name, CJ.join(media));
    }

    protected void addRelAttr(String name, EnumSet<LinkType> types) {
      // 6.12 space-separated list
      addAttr(name, SJ.join(types));
    }

    private void startIfNeeded() {
      if (!started) {
        printStartTag(name, opts);
        started = true;
      }
    }

    protected void _inline(boolean choice) {
      if (choice) {
        opts.add(INLINE);
      } else {
        opts.remove(INLINE);
      }
    }

    protected void _endTag(boolean choice) {
      if (choice) {
        opts.add(ENDTAG);
      } else {
        opts.remove(ENDTAG);
      }
    }

    protected void _pre(boolean choice) {
      if (choice) {
        opts.add(PRE);
      } else {
        opts.remove(PRE);
      }
    }
  }

  public class Generic<T extends __> extends EImp<T> implements PCData {
    Generic(String name, T parent, EnumSet<EOpt> opts) {
      super(name, parent, opts);
    }

    public Generic<T> _inline() {
      super._inline(true);
      return this;
    }

    public Generic<T> _noEndTag() {
      super._endTag(false);
      return this;
    }

    public Generic<T> _pre() {
      super._pre(true);
      return this;
    }

    public Generic<T> _attr(String name, String value) {
      addAttr(name, value);
      return this;
    }

    public Generic<Generic<T>> _elem(String name, EnumSet<EOpt> opts) {
      closeAttrs();
      return new Generic<Generic<T>>(name, this, opts);
    }

    public Generic<Generic<T>> elem(String name) {
      return _elem(name, of(ENDTAG));
    }

    @Override
    public Generic<T> __(Object... lines) {
      _p(true, lines);
      return this;
    }

    @Override
    public Generic<T> _r(Object... lines) {
      _p(false, lines);
      return this;
    }
  }

  public HamletImpl(PrintWriter out, int nestLevel, boolean wasInline) {
    this.out = out;
    this.nestLevel = nestLevel;
    this.wasInline = wasInline;
  }

  public int nestLevel() {
    return nestLevel;
  }

  public boolean wasInline() {
    return wasInline;
  }

  public void setWasInline(boolean state) {
    wasInline = state;
  }

  public PrintWriter getWriter() {
    return out;
  }

  /**
   * Create a root-level generic element.
   * Mostly for testing purpose.
   * @param <T> type of the parent element
   * @param name of the element
   * @param opts {@link EOpt element options}
   * @return the element
   */
  public <T extends __>
  Generic<T> root(String name, EnumSet<EOpt> opts) {
    return new Generic<T>(name, null, opts);
  }

  public <T extends __> Generic<T> root(String name) {
    return root(name, of(ENDTAG));
  }

  protected void printStartTag(String name, EnumSet<EOpt> opts) {
    indent(opts);
    sb.setLength(0);
    out.print(sb.append('<').append(name).toString()); // for easier mock test
  }

  protected void indent(EnumSet<EOpt> opts) {
    if (opts.contains(INLINE) && wasInline) {
      return;
    }
    if (wasInline) {
      out.println();
    }
    wasInline = opts.contains(INLINE) || opts.contains(PRE);
    for (int i = 0; i < nestLevel; ++i) {
      out.print(INDENT_CHARS);
    }
    ++indents;
  }

  protected void printEndTag(String name, EnumSet<EOpt> opts) {
    if (!opts.contains(ENDTAG)) {
      return;
    }
    if (!opts.contains(PRE)) {
      indent(opts);
    } else {
      wasInline = opts.contains(INLINE);
    }
    sb.setLength(0);
    out.print(sb.append("</").append(name).append('>').toString()); // ditto
    if (!opts.contains(INLINE)) {
      out.println();
    }
  }

  protected void printAttr(String name, String value) {
    sb.setLength(0);
    sb.append(' ').append(name);
    if (value != null) {
      sb.append("=\"").append(escapeHtml4(value)).append("\"");
    }
    out.print(sb.toString());
  }

  /**
   * Sub-classes should override this to do something interesting.
   * @param cls the sub-view class
   */
  protected void subView(Class<? extends SubView> cls) {
    indent(of(ENDTAG)); // not an inline view
    sb.setLength(0);
    out.print(sb.append('[').append(cls.getName()).append(']').toString());
    out.println();
  }

  /**
   * Parse selector into id and classes
   * @param selector in the form of (#id)?(.class)*
   * @return an two element array [id, "space-separated classes"].
   *         Either element could be null.
   * @throws WebAppException when both are null or syntax error.
   */
  public static String[] parseSelector(String selector) {
    String[] result = new String[]{null, null};
    Iterable<String> rs = SS.split(selector);
    Iterator<String> it = rs.iterator();
    if (it.hasNext()) {
      String maybeId = it.next();
      if (maybeId.charAt(0) == '#') {
        result[S_ID] = maybeId.substring(1);
        if (it.hasNext()) {
          result[S_CLASS] = SJ.join(Iterables.skip(rs, 1));
        }
      } else {
        result[S_CLASS] = SJ.join(rs);
      }
      return result;
    }
    throw new WebAppException("Error parsing selector: "+ selector);
  }

  /**
   * Set id and/or class attributes for an element.
   * @param <E> type of the element
   * @param e the element
   * @param selector Haml form of "(#id)?(.class)*"
   * @return the element
   */
  public static <E extends CoreAttrs> E setSelector(E e, String selector) {
    String[] res = parseSelector(selector);
    if (res[S_ID] != null) {
      e.$id(res[S_ID]);
    }
    if (res[S_CLASS] != null) {
      e.$class(res[S_CLASS]);
    }
    return e;
  }

  public static <E extends LINK> E setLinkHref(E e, String href) {
    if (href.endsWith(".css")) {
      e.$rel("stylesheet"); // required in html5
    }
    e.$href(href);
    return e;
  }

  public static <E extends SCRIPT> E setScriptSrc(E e, String src) {
    if (src.endsWith(".js")) {
      e.$type("text/javascript"); // required in html4
    }
    e.$src(src);
    return e;
  }
}


text:
package com.github.ksoichiro.android.observablescrollview.samples;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;

/**
 * This doesn't include ObservableScrollViews,
 * just shows how to show/hide Toolbar on the parent Activity of Fragment
 * to help you implement a screen that uses Fragments.
 */
public class FragmentTransitionActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragmenttransition);

        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));

        initFragment();
    }

    /**
     * Fragment should be added programmatically.
     * Using fragment tag in XML causes IllegalStateException on rotation of screen
     * or restoring states of activity.
     */
    private void initFragment() {
        FragmentManager fm = getSupportFragmentManager();
        if (fm.findFragmentByTag(FragmentTransitionDefaultFragment.FRAGMENT_TAG) == null) {
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(R.id.fragment, new FragmentTransitionDefaultFragment(), FragmentTransitionDefaultFragment.FRAGMENT_TAG);
            ft.commit();
            fm.executePendingTransactions();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/footer"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_alignParentBottom="true" >

        <View
            android:layout_width="match_parent"
            android:layout_height="1dip"
            android:layout_alignParentTop="true"
            android:background="?android:attr/dividerVertical" />

        <View
            android:id="@+id/horizontalDivider"
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="4dp"
            android:layout_marginTop="4dp"
            android:background="?android:attr/dividerVertical" />

        <Button
            android:id="@+id/btnCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@id/horizontalDivider"
            android:background="?android:attr/selectableItemBackground"
            android:text="@string/cancel_label" />

        <Button
            android:id="@+id/btnConfirm"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@id/horizontalDivider"
            android:background="?android:attr/selectableItemBackground"
            android:text="@string/confirm_label" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/directoryInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true" >

        <ImageButton
            android:id="@+id/btnNavUp"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/borderless_button"
            android:contentDescription="@string/up_label"
            android:src="@drawable/navigation_up" />

        <TextView
            android:id="@+id/txtvSelectedFolderLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="8dp"
            android:layout_toRightOf="@id/btnNavUp"
            android:text="@string/selected_folder_label"
            android:textStyle="bold" >
        </TextView>

        <TextView
            android:id="@+id/txtvSelectedFolder"
            android:layout_below="@id/txtvSelectedFolderLabel"
            android:layout_toRightOf="@id/btnNavUp"
            android:layout_toLeftOf="@+id/btnCreateFolder"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="start"
            android:scrollHorizontally="true"
            android:singleLine="true"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            />

        <ImageButton
                android:id="@+id/btnCreateFolder"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:contentDescription="@string/create_folder_label"
                android:background="@drawable/borderless_button"
                android:src="@drawable/ic_action_create"
                />

        <View
            android:id="@+id/divider"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_below="@id/btnNavUp"
            android:background="@color/bright_blue" />
    </RelativeLayout>

    <ListView
        android:id="@+id/directoryList"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_above="@id/footer"
        android:layout_below="@id/directoryInfo" />

</RelativeLayout>


text:
package uk.ac.ebi.embl.flatfile.writer.embl;

import junit.framework.TestCase;
import uk.ac.ebi.embl.api.entry.Entry;
import uk.ac.ebi.embl.api.entry.EntryFactory;
import uk.ac.ebi.embl.flatfile.writer.WrapType;

public abstract class EmblWriterTest extends TestCase {

	protected Entry entry;
	protected WrapType wrapType;

    protected void setUp() throws Exception {
		super.setUp();
		entry = (new EntryFactory()).createEntry();
		wrapType = WrapType.EMBL_WRAP;
	}
}


text:
package integration

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/docker/docker/pkg/namesgenerator"
	"github.com/go-check/check"
	d "github.com/libkermit/docker"
	"github.com/libkermit/docker-check"
	"github.com/traefik/traefik/v2/integration/try"
	checker "github.com/vdemeester/shakers"
)

// Images to have or pull before the build in order to make it work.
// FIXME handle this offline but loading them before build.
var RequiredImages = map[string]string{
	"swarm":          "1.0.0",
	"traefik/whoami": "latest",
}

// Docker tests suite.
type DockerSuite struct {
	BaseSuite
	project *docker.Project
}

func (s *DockerSuite) startContainer(c *check.C, image string, args ...string) string {
	return s.startContainerWithConfig(c, image, d.ContainerConfig{
		Cmd: args,
	})
}

func (s *DockerSuite) startContainerWithLabels(c *check.C, image string, labels map[string]string, args ...string) string {
	return s.startContainerWithConfig(c, image, d.ContainerConfig{
		Cmd:    args,
		Labels: labels,
	})
}

func (s *DockerSuite) startContainerWithNameAndLabels(c *check.C, name, image string, labels map[string]string, args ...string) string {
	return s.startContainerWithConfig(c, image, d.ContainerConfig{
		Name:   name,
		Cmd:    args,
		Labels: labels,
	})
}

func (s *DockerSuite) startContainerWithConfig(c *check.C, image string, config d.ContainerConfig) string {
	if config.Name == "" {
		config.Name = namesgenerator.GetRandomName(10)
	}

	container := s.project.StartWithConfig(c, image, config)

	// FIXME(vdemeester) this is ugly (it's because of the / in front of the name in docker..)
	return strings.SplitAfter(container.Name, "/")[1]
}

func (s *DockerSuite) stopAndRemoveContainerByName(c *check.C, name string) {
	s.project.Stop(c, name)
	s.project.Remove(c, name)
}

func (s *DockerSuite) SetUpSuite(c *check.C) {
	project := docker.NewProjectFromEnv(c)
	s.project = project

	// Pull required images
	for repository, tag := range RequiredImages {
		image := fmt.Sprintf("%s:%s", repository, tag)
		s.project.Pull(c, image)
	}
}

func (s *DockerSuite) TearDownTest(c *check.C) {
	s.project.Clean(c, os.Getenv("CIRCLECI") != "") // FIXME
}

func (s *DockerSuite) TestSimpleConfiguration(c *check.C) {
	tempObjects := struct {
		DockerHost  string
		DefaultRule string
	}{
		DockerHost:  s.getDockerHost(),
		DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)",
	}

	file := s.adaptFile(c, "fixtures/docker/simple.toml", tempObjects)
	defer os.Remove(file)

	cmd, display := s.traefikCmd(withConfigFile(file))
	defer display(c)
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer s.killCmd(cmd)

	// TODO validate : run on 80
	// Expected a 404 as we did not configure anything
	err = try.GetRequest("http://127.0.0.1:8000/", 500*time.Millisecond, try.StatusCodeIs(http.StatusNotFound))
	c.Assert(err, checker.IsNil)
}

func (s *DockerSuite) TestDefaultDockerContainers(c *check.C) {
	tempObjects := struct {
		DockerHost  string
		DefaultRule string
	}{
		DockerHost:  s.getDockerHost(),
		DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)",
	}

	file := s.adaptFile(c, "fixtures/docker/simple.toml", tempObjects)
	defer os.Remove(file)

	name := s.startContainer(c, "swarm:1.0.0", "manage", "token://blablabla")

	// Start traefik
	cmd, display := s.traefikCmd(withConfigFile(file))
	defer display(c)
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer s.killCmd(cmd)

	req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil)
	c.Assert(err, checker.IsNil)
	req.Host = fmt.Sprintf("%s.docker.localhost", strings.ReplaceAll(name, "_", "-"))

	// FIXME Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?)
	resp, err := try.ResponseUntilStatusCode(req, 1500*time.Millisecond, http.StatusOK)
	c.Assert(err, checker.IsNil)

	body, err := ioutil.ReadAll(resp.Body)
	c.Assert(err, checker.IsNil)

	var version map[string]interface{}

	c.Assert(json.Unmarshal(body, &version), checker.IsNil)
	c.Assert(version["Version"], checker.Equals, "swarm/1.0.0")
}

func (s *DockerSuite) TestDockerContainersWithTCPLabels(c *check.C) {
	tempObjects := struct {
		DockerHost  string
		DefaultRule string
	}{
		DockerHost:  s.getDockerHost(),
		DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)",
	}

	file := s.adaptFile(c, "fixtures/docker/simple.toml", tempObjects)
	defer os.Remove(file)

	// Start a container with some labels
	labels := map[string]string{
		"traefik.tcp.Routers.Super.Rule":                      "HostSNI(`my.super.host`)",
		"traefik.tcp.Routers.Super.tls":                       "true",
		"traefik.tcp.Services.Super.Loadbalancer.server.port": "8080",
	}

	s.startContainerWithLabels(c, "traefik/whoamitcp", labels, "-name", "my.super.host")

	// Start traefik
	cmd, display := s.traefikCmd(withConfigFile(file))
	defer display(c)
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer s.killCmd(cmd)

	err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`my.super.host`)"))
	c.Assert(err, checker.IsNil)

	who, err := guessWho("127.0.0.1:8000", "my.super.host", true)
	c.Assert(err, checker.IsNil)

	c.Assert(who, checker.Contains, "my.super.host")
}

func (s *DockerSuite) TestDockerContainersWithLabels(c *check.C) {
	tempObjects := struct {
		DockerHost  string
		DefaultRule string
	}{
		DockerHost:  s.getDockerHost(),
		DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)",
	}

	file := s.adaptFile(c, "fixtures/docker/simple.toml", tempObjects)
	defer os.Remove(file)

	// Start a container with some labels
	labels := map[string]string{
		"traefik.http.Routers.Super.Rule": "Host(`my.super.host`)",
	}
	s.startContainerWithLabels(c, "swarm:1.0.0", labels, "manage", "token://blabla")

	// Start another container by replacing a '.' by a '-'
	labels = map[string]string{
		"traefik.http.Routers.SuperHost.Rule": "Host(`my-super.host`)",
	}
	s.startContainerWithLabels(c, "swarm:1.0.0", labels, "manage", "token://blablabla")

	// Start traefik
	cmd, display := s.traefikCmd(withConfigFile(file))
	defer display(c)
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer s.killCmd(cmd)

	req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil)
	c.Assert(err, checker.IsNil)
	req.Host = "my-super.host"

	// FIXME Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?)
	_, err = try.ResponseUntilStatusCode(req, 1500*time.Millisecond, http.StatusOK)
	c.Assert(err, checker.IsNil)

	req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil)
	c.Assert(err, checker.IsNil)
	req.Host = "my.super.host"

	// FIXME Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?)
	resp, err := try.ResponseUntilStatusCode(req, 1500*time.Millisecond, http.StatusOK)
	c.Assert(err, checker.IsNil)

	body, err := ioutil.ReadAll(resp.Body)
	c.Assert(err, checker.IsNil)

	var version map[string]interface{}

	c.Assert(json.Unmarshal(body, &version), checker.IsNil)
	c.Assert(version["Version"], checker.Equals, "swarm/1.0.0")
}

func (s *DockerSuite) TestDockerContainersWithOneMissingLabels(c *check.C) {
	tempObjects := struct {
		DockerHost  string
		DefaultRule string
	}{
		DockerHost:  s.getDockerHost(),
		DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)",
	}

	file := s.adaptFile(c, "fixtures/docker/simple.toml", tempObjects)
	defer os.Remove(file)

	// Start a container with some labels
	labels := map[string]string{
		"traefik.random.value": "my.super.host",
	}
	s.startContainerWithLabels(c, "swarm:1.0.0", labels, "manage", "token://blabla")

	// Start traefik
	cmd, display := s.traefikCmd(withConfigFile(file))
	defer display(c)
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer s.killCmd(cmd)

	req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil)
	c.Assert(err, checker.IsNil)
	req.Host = "my.super.host"

	// FIXME Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?)
	// TODO validate : run on 80
	// Expected a 404 as we did not configure anything
	err = try.Request(req, 1500*time.Millisecond, try.StatusCodeIs(http.StatusNotFound))
	c.Assert(err, checker.IsNil)
}

func (s *DockerSuite) TestRestartDockerContainers(c *check.C) {
	tempObjects := struct {
		DockerHost  string
		DefaultRule string
	}{
		DockerHost:  s.getDockerHost(),
		DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)",
	}

	file := s.adaptFile(c, "fixtures/docker/simple.toml", tempObjects)
	defer os.Remove(file)

	// Start a container with some labels
	labels := map[string]string{
		"traefik.http.Routers.Super.Rule":                       "Host(`my.super.host`)",
		"traefik.http.Services.powpow.LoadBalancer.server.Port": "2375",
	}
	s.startContainerWithNameAndLabels(c, "powpow", "swarm:1.0.0", labels, "manage", "token://blabla")

	// Start traefik
	cmd, display := s.traefikCmd(withConfigFile(file))
	defer display(c)
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer s.killCmd(cmd)

	req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil)
	c.Assert(err, checker.IsNil)
	req.Host = "my.super.host"

	// FIXME Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?)
	resp, err := try.ResponseUntilStatusCode(req, 1500*time.Millisecond, http.StatusOK)
	c.Assert(err, checker.IsNil)

	body, err := ioutil.ReadAll(resp.Body)
	c.Assert(err, checker.IsNil)

	var version map[string]interface{}

	c.Assert(json.Unmarshal(body, &version), checker.IsNil)
	c.Assert(version["Version"], checker.Equals, "swarm/1.0.0")

	err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("powpow"))
	c.Assert(err, checker.IsNil)

	s.stopAndRemoveContainerByName(c, "powpow")
	defer s.project.Remove(c, "powpow")

	time.Sleep(5 * time.Second)

	err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("powpow"))
	c.Assert(err, checker.NotNil)

	s.startContainerWithNameAndLabels(c, "powpow", "swarm:1.0.0", labels, "manage", "token://blabla")

	err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("powpow"))
	c.Assert(err, checker.IsNil)
}


text:
function Add-ToLocalGroup {
    <#
    .SYNOPSIS
    Adds a user or a group to local administrators of a remote computer

    .PARAMETER ComputerName
    Destination computer name where to add user or group (Identity parameter).

    .PARAMETER Group
    Destination local group the Identity should be added to.

    .PARAMETER DomainName
    Domain name - required for user/group string creation. Can be a workgroup or local computer name instead of domain name.

    .PARAMETER Type
    Type of identity to add - user or group.

    .PARAMETER Identity
    Identity of a user/group to add. Provide samaccountname

    .EXAMPLE
    This will add 'someuser' to 'somecomputer' as local administrator for default domain Objectivity
    Add-ToLocalGroup -ComputerName 'somecomputer' -Group Administrators -Type User -Identity 'someuser'
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidDefaultValueForMandatoryParameter', '')]
    [CmdletBinding()]
    [OutputType([void])]
    param(
        [Parameter(Mandatory=$true,HelpMessage='Destination Computer name')]
        [string[]]
        $ComputerName='localhost',

        [Parameter(Mandatory=$true,HelpMessage='Local Group to add Identity to')]
        [string]
        $Group,

        [Parameter(Mandatory=$false,HelpMessage='Domain or workgroup name')]
        [string]
        $DomainName,

        [Parameter(Mandatory=$true,HelpMessage='Type of Identity to add')]
        [ValidateSet('User', 'Group')]
        [string]
        $Type,

        [Parameter(Mandatory=$true,HelpMessage='Identity to add')]
        [string]
        $Identity
   )

    $LocalGroup = [ADSI]"WinNT://$ComputerName/$Group,group"
    if ($Type -eq 'Group') {
        $addgroup = [ADSI]"WinNT://$DomainName/$Identity,group"
        $LocalGroup.Add($addgroup.Path)
    }
    elseif ($Type -eq 'User') {
        $addUser = [ADSI]"WinNT://$DomainName/$Identity,user"
        $LocalGroup.Add($addUser.Path)
    }
    Write-Log -Info "Added {$Identity} Type {$Type} to local group {$Group} on {$Computername}"
}


text:
static NSString *identifier = @"Focuse";

@interface LLPFocuseViewController ()

@property (nonatomic, strong) NSMutableArray * dataList;

@end

@implementation LLPFocuseViewController

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

    [self initUI];

    [self loadData];

}

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

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    LLPLiveCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    cell.live = self.dataList[indexPath.row];

    return cell;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    LLPLive *live = self.dataList[indexPath.row];

    LLPPlayerViewController * playerVc = [[LLPPlayerViewController alloc] init];
    playerVc.live = live;

    [self.navigationController pushViewController:playerVc animated:YES];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 70 + SCREEN_WIDTH + 5;
}

- (NSMutableArray *)dataList {

    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

-(void) initUI{

    [self.tableView registerNib:[UINib nibWithNibName:@"LLPLiveCell" bundle:nil] forCellReuseIdentifier:identifier];
}

-(void) loadData{

    LLPLive * live = [[LLPLive alloc] init];
    LLPCreator * creator = [[LLPCreator alloc] init];
    live.creator = creator;

    live.streamAddr = Live_He_bi;
    live.city = @"上海";
    live.onlineUsers = 62518;
    live.creator.nick = @"hebi";
    [self.dataList addObject:live];

}

@end


text:
Oto Boyama Giriş

                <form action="<?=  base_url()?>Admin/admin_login" method="post" class="form-horizontal m-t-20">

                            <input class="form-control" name="username" placeholder="Kullanıcı Adı" required type="text">

                            <input class="form-control" name="password" placeholder="Şifre" required type="password">

                                <input id="checkbox-signup" type="checkbox">
                                Beni Hatırla

                            <button class="btn btn-default btn-block text-uppercase waves-effect waves-light" type="submit">Giriş</button>

                             Şifremi unuttum

                </form>


text:
package javax.swing.plaf.synth;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.border.*;
import java.io.Serializable;

/**
 * Synth's CheckBoxMenuItemUI.
 *
 * @author Leif Samuelsson
 * @author Georges Saab
 * @author David Karlton
 * @author Arnaud Weber
 */
class SynthCheckBoxMenuItemUI extends SynthMenuItemUI {

    public static ComponentUI createUI(JComponent c) {
        return new SynthCheckBoxMenuItemUI();
    }

    protected String getPropertyPrefix() {
        return "CheckBoxMenuItem";
    }

    public void processMouseEvent(JMenuItem item, MouseEvent e,
                                  MenuElement path[], MenuSelectionManager manager) {
        Point p = e.getPoint();
        if (p.x >= 0 && p.x < item.getWidth() && p.y >= 0 && p.y < item.getHeight()) {
            if (e.getID() == MouseEvent.MOUSE_RELEASED) {
                manager.clearSelectedPath();
                item.doClick(0);
            } else {
                manager.setSelectedPath(path);
            }
        } else if (item.getModel().isArmed()) {
            int c = path.length - 1;
            MenuElement newPath[] = new MenuElement[c];
            for (int i = 0; i < c; i++) {
                newPath[i] = path[i];
            }
            manager.setSelectedPath(newPath);
        }
    }

    void paintBackground(SynthContext context, Graphics g, JComponent c) {
        context.getPainter().paintCheckBoxMenuItemBackground(context, g, 0, 0,
                                                  c.getWidth(), c.getHeight());
    }

    public void paintBorder(SynthContext context, Graphics g, int x,
                            int y, int w, int h) {
        context.getPainter().paintCheckBoxMenuItemBorder(context, g, x, y, w, h);
    }
}


text:
from nipype.testing import assert_equal
from nipype.interfaces.slicer.legacy.segmentation import OtsuThresholdSegmentation

def test_OtsuThresholdSegmentation_inputs():
    input_map = dict(args=dict(argstr='%s',
    ),
    brightObjects=dict(argstr='--brightObjects ',
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    faceConnected=dict(argstr='--faceConnected ',
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    inputVolume=dict(argstr='%s',
    position=-2,
    ),
    minimumObjectSize=dict(argstr='--minimumObjectSize %d',
    ),
    numberOfBins=dict(argstr='--numberOfBins %d',
    ),
    outputVolume=dict(argstr='%s',
    hash_files=False,
    position=-1,
    ),
    terminal_output=dict(nohash=True,
    ),
    )
    inputs = OtsuThresholdSegmentation.input_spec()

    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(inputs.traits()[key], metakey), value

def test_OtsuThresholdSegmentation_outputs():
    output_map = dict(outputVolume=dict(position=-1,
    ),
    )
    outputs = OtsuThresholdSegmentation.output_spec()

    for key, metadata in output_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(outputs.traits()[key], metakey), value


text:
package actors_test

import (
	"code.cloudfoundry.org/cli/cf/errors"

	"code.cloudfoundry.org/cli/cf/actors"
	"code.cloudfoundry.org/cli/cf/actors/planbuilder/planbuilderfakes"
	"code.cloudfoundry.org/cli/cf/actors/servicebuilder/servicebuilderfakes"
	"code.cloudfoundry.org/cli/cf/api/apifakes"
	"code.cloudfoundry.org/cli/cf/api/organizations/organizationsfakes"
	"code.cloudfoundry.org/cli/cf/models"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Service Plans", func() {
	var (
		actor actors.ServicePlanActor

		servicePlanRepo           *apifakes.OldFakeServicePlanRepo
		servicePlanVisibilityRepo *apifakes.FakeServicePlanVisibilityRepository
		orgRepo                   *organizationsfakes.FakeOrganizationRepository

		planBuilder    *planbuilderfakes.FakePlanBuilder
		serviceBuilder *servicebuilderfakes.FakeServiceBuilder

		privateServicePlanVisibilityFields models.ServicePlanVisibilityFields
		publicServicePlanVisibilityFields  models.ServicePlanVisibilityFields
		limitedServicePlanVisibilityFields models.ServicePlanVisibilityFields

		publicServicePlan  models.ServicePlanFields
		privateServicePlan models.ServicePlanFields
		limitedServicePlan models.ServicePlanFields

		publicService           models.ServiceOffering
		mixedService            models.ServiceOffering
		privateService          models.ServiceOffering
		publicAndLimitedService models.ServiceOffering

		org1 models.Organization
		org2 models.Organization

		visibility1 models.ServicePlanVisibilityFields
	)

	BeforeEach(func() {
		servicePlanRepo = new(apifakes.OldFakeServicePlanRepo)
		servicePlanVisibilityRepo = new(apifakes.FakeServicePlanVisibilityRepository)
		orgRepo = new(organizationsfakes.FakeOrganizationRepository)
		planBuilder = new(planbuilderfakes.FakePlanBuilder)
		serviceBuilder = new(servicebuilderfakes.FakeServiceBuilder)

		actor = actors.NewServicePlanHandler(servicePlanRepo, servicePlanVisibilityRepo, orgRepo, planBuilder, serviceBuilder)

		org1 = models.Organization{}
		org1.Name = "org-1"
		org1.GUID = "org-1-guid"

		org2 = models.Organization{}
		org2.Name = "org-2"
		org2.GUID = "org-2-guid"

		orgRepo.FindByNameReturns(org1, nil)

		publicServicePlanVisibilityFields = models.ServicePlanVisibilityFields{
			GUID:            "public-service-plan-visibility-guid",
			ServicePlanGUID: "public-service-plan-guid",
		}

		privateServicePlanVisibilityFields = models.ServicePlanVisibilityFields{
			GUID:            "private-service-plan-visibility-guid",
			ServicePlanGUID: "private-service-plan-guid",
		}

		limitedServicePlanVisibilityFields = models.ServicePlanVisibilityFields{
			GUID:             "limited-service-plan-visibility-guid",
			ServicePlanGUID:  "limited-service-plan-guid",
			OrganizationGUID: "org-1-guid",
		}

		publicServicePlan = models.ServicePlanFields{
			Name:   "public-service-plan",
			GUID:   "public-service-plan-guid",
			Public: true,
		}

		privateServicePlan = models.ServicePlanFields{
			Name:   "private-service-plan",
			GUID:   "private-service-plan-guid",
			Public: false,
		}

		limitedServicePlan = models.ServicePlanFields{
			Name:   "limited-service-plan",
			GUID:   "limited-service-plan-guid",
			Public: false,
		}

		publicService = models.ServiceOffering{
			ServiceOfferingFields: models.ServiceOfferingFields{
				Label: "my-public-service",
				GUID:  "my-public-service-guid",
			},
			Plans: []models.ServicePlanFields{
				publicServicePlan,
				publicServicePlan,
			},
		}

		mixedService = models.ServiceOffering{
			ServiceOfferingFields: models.ServiceOfferingFields{
				Label: "my-mixed-service",
				GUID:  "my-mixed-service-guid",
			},
			Plans: []models.ServicePlanFields{
				publicServicePlan,
				privateServicePlan,
				limitedServicePlan,
			},
		}

		privateService = models.ServiceOffering{
			ServiceOfferingFields: models.ServiceOfferingFields{
				Label: "my-private-service",
				GUID:  "my-private-service-guid",
			},
			Plans: []models.ServicePlanFields{
				privateServicePlan,
				privateServicePlan,
			},
		}
		publicAndLimitedService = models.ServiceOffering{
			ServiceOfferingFields: models.ServiceOfferingFields{
				Label: "my-public-and-limited-service",
				GUID:  "my-public-and-limited-service-guid",
			},
			Plans: []models.ServicePlanFields{
				publicServicePlan,
				publicServicePlan,
				limitedServicePlan,
			},
		}

		visibility1 = models.ServicePlanVisibilityFields{
			GUID:             "visibility-guid-1",
			OrganizationGUID: "org-1-guid",
			ServicePlanGUID:  "limited-service-plan-guid",
		}
	})

	Describe(".UpdateAllPlansForService", func() {
		BeforeEach(func() {
			servicePlanVisibilityRepo.SearchReturns(
				[]models.ServicePlanVisibilityFields{privateServicePlanVisibilityFields}, nil,
			)

			servicePlanRepo.SearchReturns = map[string][]models.ServicePlanFields{
				"my-mixed-service-guid": {
					publicServicePlan,
					privateServicePlan,
				},
			}
		})

		It("Returns an error if the service cannot be found", func() {
			serviceBuilder.GetServiceByNameWithPlansReturns(models.ServiceOffering{}, errors.New("service was not found"))
			err := actor.UpdateAllPlansForService("not-a-service", true)
			Expect(err.Error()).To(Equal("service was not found"))
		})

		It("Removes the service plan visibilities for any non-public service plans", func() {
			serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
			err := actor.UpdateAllPlansForService("my-mixed-service", true)
			Expect(err).ToNot(HaveOccurred())

			servicePlanVisibilityGUID := servicePlanVisibilityRepo.DeleteArgsForCall(0)
			Expect(servicePlanVisibilityGUID).To(Equal("private-service-plan-visibility-guid"))
		})

		Context("when setting all plans to public", func() {
			It("Sets all non-public service plans to public", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
				err := actor.UpdateAllPlansForService("my-mixed-service", true)
				Expect(err).ToNot(HaveOccurred())

				servicePlan, serviceGUID, public := servicePlanRepo.UpdateArgsForCall(0)
				Expect(servicePlan.Public).To(BeFalse())
				Expect(serviceGUID).To(Equal("my-mixed-service-guid"))
				Expect(public).To(BeTrue())
			})

			It("Does not try to update service plans if they are all already public", func() {
				servicePlanRepo.SearchReturns = map[string][]models.ServicePlanFields{
					"my-public-service-guid": {
						publicServicePlan,
						publicServicePlan,
					},
				}

				err := actor.UpdateAllPlansForService("my-public-service", true)
				Expect(err).ToNot(HaveOccurred())

				Expect(servicePlanRepo.UpdateCallCount()).To(Equal(0))
			})
		})

		Context("when setting all plans to private", func() {
			It("Sets all public service plans to private", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)

				err := actor.UpdateAllPlansForService("my-mixed-service", false)
				Expect(err).ToNot(HaveOccurred())

				servicePlan, serviceGUID, public := servicePlanRepo.UpdateArgsForCall(0)
				Expect(servicePlan.Public).To(BeTrue())
				Expect(serviceGUID).To(Equal("my-mixed-service-guid"))
				Expect(public).To(BeFalse())
			})

			It("Does not try to update service plans if they are all already private", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(privateService, nil)

				err := actor.UpdateAllPlansForService("my-private-service", false)
				Expect(err).ToNot(HaveOccurred())

				Expect(servicePlanRepo.UpdateCallCount()).To(Equal(0))
			})
		})
	})

	Describe(".UpdateOrgForService", func() {
		BeforeEach(func() {
			serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)

			orgRepo.FindByNameReturns(org1, nil)
		})

		It("Returns an error if the service cannot be found", func() {
			serviceBuilder.GetServiceByNameWithPlansReturns(models.ServiceOffering{}, errors.New("service was not found"))

			err := actor.UpdateOrgForService("not-a-service", "org-1", true)
			Expect(err.Error()).To(Equal("service was not found"))
		})

		Context("when giving access to all plans for a single org", func() {
			It("creates a service plan visibility for all plans", func() {
				err := actor.UpdateOrgForService("my-mixed-service", "org-1", true)
				Expect(err).ToNot(HaveOccurred())

				Expect(servicePlanVisibilityRepo.CreateCallCount()).To(Equal(2))

				planGUID, orgGUID := servicePlanVisibilityRepo.CreateArgsForCall(0)
				Expect(planGUID).To(Equal("private-service-plan-guid"))
				Expect(orgGUID).To(Equal("org-1-guid"))

				planGUID, orgGUID = servicePlanVisibilityRepo.CreateArgsForCall(1)
				Expect(planGUID).To(Equal("limited-service-plan-guid"))
				Expect(orgGUID).To(Equal("org-1-guid"))
			})

			It("Does not try to update service plans if they are all already public or the org already has access", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(publicAndLimitedService, nil)

				err := actor.UpdateOrgForService("my-public-and-limited-service", "org-1", true)
				Expect(err).ToNot(HaveOccurred())
				Expect(servicePlanVisibilityRepo.CreateCallCount()).To(Equal(1))
			})
		})

		Context("when disabling access to all plans for a single org", func() {
			It("deletes the associated visibilities for all limited plans", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(publicAndLimitedService, nil)
				servicePlanVisibilityRepo.SearchReturns([]models.ServicePlanVisibilityFields{visibility1}, nil)
				err := actor.UpdateOrgForService("my-public-and-limited-service", "org-1", false)
				Expect(err).ToNot(HaveOccurred())
				Expect(servicePlanVisibilityRepo.DeleteCallCount()).To(Equal(1))

				services := servicePlanVisibilityRepo.SearchArgsForCall(0)
				Expect(services["organization_guid"]).To(Equal("org-1-guid"))

				visibilityGUID := servicePlanVisibilityRepo.DeleteArgsForCall(0)
				Expect(visibilityGUID).To(Equal("visibility-guid-1"))
			})

			It("Does not try to update service plans if they are all public", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(publicService, nil)

				err := actor.UpdateOrgForService("my-public-and-limited-service", "org-1", false)
				Expect(err).ToNot(HaveOccurred())
				Expect(servicePlanVisibilityRepo.DeleteCallCount()).To(Equal(0))
			})

			It("Does not try to update service plans if the org already did not have visibility", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(privateService, nil)

				err := actor.UpdateOrgForService("my-private-service", "org-1", false)
				Expect(err).ToNot(HaveOccurred())
				Expect(servicePlanVisibilityRepo.DeleteCallCount()).To(Equal(0))
			})
		})
	})

	Describe(".UpdateSinglePlanForService", func() {
		It("Returns an error if the service cannot be found", func() {
			serviceBuilder.GetServiceByNameWithPlansReturns(models.ServiceOffering{}, errors.New("service was not found"))
			err := actor.UpdateSinglePlanForService("not-a-service", "public-service-plan", true)
			Expect(err.Error()).To(Equal("service was not found"))
		})

		It("Returns an error if the plan cannot be found", func() {
			serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
			err := actor.UpdateSinglePlanForService("my-mixed-service", "not-a-service-plan", true)
			Expect(err.Error()).To(Equal("The plan not-a-service-plan could not be found for service my-mixed-service"))
		})

		Context("when setting a public service plan to public", func() {
			It("Does not try to update the service plan", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
				err := actor.UpdateSinglePlanForService("my-mixed-service", "public-service-plan", true)
				Expect(err).ToNot(HaveOccurred())
				Expect(servicePlanRepo.UpdateCallCount()).To(Equal(0))
			})
		})

		Context("when setting private service plan to public", func() {
			BeforeEach(func() {
				servicePlanVisibilityRepo.SearchReturns(
					[]models.ServicePlanVisibilityFields{privateServicePlanVisibilityFields}, nil)
			})

			It("removes the service plan visibilities for the service plan", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
				err := actor.UpdateSinglePlanForService("my-mixed-service", "private-service-plan", true)
				Expect(err).ToNot(HaveOccurred())

				servicePlanVisibilityGUID := servicePlanVisibilityRepo.DeleteArgsForCall(0)
				Expect(servicePlanVisibilityGUID).To(Equal("private-service-plan-visibility-guid"))
			})

			It("sets a service plan to public", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
				err := actor.UpdateSinglePlanForService("my-mixed-service", "private-service-plan", true)
				Expect(err).ToNot(HaveOccurred())

				servicePlan, serviceGUID, public := servicePlanRepo.UpdateArgsForCall(0)
				Expect(servicePlan.Public).To(BeFalse())
				Expect(serviceGUID).To(Equal("my-mixed-service-guid"))
				Expect(public).To(BeTrue())
			})
		})

		Context("when setting a private service plan to private", func() {
			It("Does not try to update the service plan", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
				err := actor.UpdateSinglePlanForService("my-mixed-service", "private-service-plan", false)
				Expect(err).ToNot(HaveOccurred())
				Expect(servicePlanRepo.UpdateCallCount()).To(Equal(0))
			})
		})

		Context("When setting public service plan to private", func() {
			BeforeEach(func() {
				servicePlanVisibilityRepo.SearchReturns(
					[]models.ServicePlanVisibilityFields{publicServicePlanVisibilityFields}, nil)
			})

			It("removes the service plan visibilities for the service plan", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
				err := actor.UpdateSinglePlanForService("my-mixed-service", "public-service-plan", false)
				Expect(err).ToNot(HaveOccurred())

				servicePlanVisibilityGUID := servicePlanVisibilityRepo.DeleteArgsForCall(0)
				Expect(servicePlanVisibilityGUID).To(Equal("public-service-plan-visibility-guid"))
			})

			It("sets the plan to private", func() {
				serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
				err := actor.UpdateSinglePlanForService("my-mixed-service", "public-service-plan", false)
				Expect(err).ToNot(HaveOccurred())

				servicePlan, serviceGUID, public := servicePlanRepo.UpdateArgsForCall(0)
				Expect(servicePlan.Public).To(BeTrue())
				Expect(serviceGUID).To(Equal("my-mixed-service-guid"))
				Expect(public).To(BeFalse())
			})
		})
	})

	Describe(".UpdatePlanAndOrgForService", func() {
		BeforeEach(func() {
			orgRepo.FindByNameReturns(org1, nil)
		})

		It("returns an error if the service cannot be found", func() {
			serviceBuilder.GetServiceByNameWithPlansReturns(models.ServiceOffering{}, errors.New("service was not found"))

			err := actor.UpdatePlanAndOrgForService("not-a-service", "public-service-plan", "public-org", true)
			Expect(err.Error()).To(Equal("service was not found"))
		})

		It("returns an error if the org cannot be found", func() {
			orgRepo.FindByNameReturns(models.Organization{}, errors.NewModelNotFoundError("organization", "not-an-org"))
			err := actor.UpdatePlanAndOrgForService("a-real-service", "public-service-plan", "not-an-org", true)
			Expect(err).To(HaveOccurred())
		})

		It("returns an error if the plan cannot be found", func() {
			serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)

			err := actor.UpdatePlanAndOrgForService("a-real-service", "not-a-plan", "org-1", true)
			Expect(err).To(HaveOccurred())
		})

		Context("when disabling access to a single plan for a single org", func() {
			Context("for a public plan", func() {
				It("does not try and delete the visibility", func() {
					serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
					err := actor.UpdatePlanAndOrgForService("my-mixed-service", "public-service-plan", "org-1", false)
					Expect(err).NotTo(HaveOccurred())

					Expect(servicePlanVisibilityRepo.DeleteCallCount()).To(Equal(0))
				})
			})

			Context("for a private plan", func() {
				Context("with no service plan visibilities", func() {
					It("does not try and delete the visibility", func() {
						serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
						err := actor.UpdatePlanAndOrgForService("my-mixed-service", "private-service-plan", "org-1", false)

						Expect(servicePlanVisibilityRepo.DeleteCallCount()).To(Equal(0))
						Expect(err).NotTo(HaveOccurred())
					})
				})

				Context("with service plan visibilities", func() {
					BeforeEach(func() {
						servicePlanVisibilityRepo.SearchReturns(
							[]models.ServicePlanVisibilityFields{limitedServicePlanVisibilityFields}, nil)

					})
					It("deletes a service plan visibility", func() {
						serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
						err := actor.UpdatePlanAndOrgForService("my-mixed-service", "limited-service-plan", "org-1", false)

						servicePlanVisGUID := servicePlanVisibilityRepo.DeleteArgsForCall(0)
						Expect(err).NotTo(HaveOccurred())
						Expect(servicePlanVisGUID).To(Equal("limited-service-plan-visibility-guid"))
					})

					It("does not call delete on the non-existant service plan visibility", func() {
						serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
						orgRepo.FindByNameReturns(org2, nil)
						servicePlanVisibilityRepo.SearchReturns(nil, nil)
						err := actor.UpdatePlanAndOrgForService("my-mixed-service", "limited-service-plan", "org-2", false)
						Expect(err).NotTo(HaveOccurred())

						Expect(servicePlanVisibilityRepo.DeleteCallCount()).To(Equal(0))
					})
				})
			})
		})

		Context("when enabling access", func() {
			Context("for a public plan", func() {
				It("does not try and create the visibility", func() {
					serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
					err := actor.UpdatePlanAndOrgForService("my-mixed-service", "public-service-plan", "org-1", true)

					Expect(servicePlanVisibilityRepo.CreateCallCount()).To(Equal(0))
					Expect(err).NotTo(HaveOccurred())
				})
			})

			Context("for a private plan", func() {
				It("returns None", func() {
					serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
					err := actor.UpdatePlanAndOrgForService("my-mixed-service", "private-service-plan", "org-1", true)

					Expect(err).NotTo(HaveOccurred())
				})

				It("creates a service plan visibility", func() {
					serviceBuilder.GetServiceByNameWithPlansReturns(mixedService, nil)
					err := actor.UpdatePlanAndOrgForService("my-mixed-service", "private-service-plan", "org-1", true)

					servicePlanGUID, orgGUID := servicePlanVisibilityRepo.CreateArgsForCall(0)
					Expect(err).NotTo(HaveOccurred())
					Expect(servicePlanGUID).To(Equal("private-service-plan-guid"))
					Expect(orgGUID).To(Equal("org-1-guid"))
				})
			})
		})
	})
})


text:
import os
import tarfile

from contextlib import closing
from gppylib.commands.base import ExecutionError
from gppylib.commands.unix import Scp
from gppylib.operations.package import GpScp
from gppylib.operations.test.regress.test_package import GppkgTestCase, unittest, skipIfNoStandby, get_host_list, ARCHIVE_PATH, run_command
from gppylib.operations.unix import RemoveRemoteFile

@skipIfNoStandby()
class MuckWithInternalsOnStandby(GppkgTestCase):
    @unittest.expectedFailure
    def test00_delete_package_from_archive_on_standby_and_install(self):
        gppkg_file = self.build(self.alpha_spec, self.A_spec)
        archive_file = os.path.join(ARCHIVE_PATH, gppkg_file)
        self.install(gppkg_file)

        #Remove package from standby
        standby = get_host_list()[0]
        RemoveRemoteFile(os.path.join(ARCHIVE_PATH, gppkg_file), standby).run()

        try:
            self.install(gppkg_file)
        except ExecutionError as e:
            Scp(name = "copy gppkg to standby",
                srcFile = gppkg_file,
                dstFile = archive_file,
                srcHost = None,
                dstHost = standby).run(validateAfter = True)
            self.fail("ExecutionError %s" % e)

    @unittest.expectedFailure
    def test01_delete_package_from_archive_on_standby_and_uninstall(self):
        """
            Known issue: MPP-15737
        """
        gppkg_file = self.alpha_spec.get_filename()
        archive_file = os.path.join(ARCHIVE_PATH, gppkg_file)
        self.install(gppkg_file)

        #Remove package from standby
        standby = get_host_list()[0]
        RemoveRemoteFile(os.path.join(ARCHIVE_PATH, gppkg_file), standby).run()

        try:
            self.remove(gppkg_file)
        except ExecutionError as e:
            GpScp(source_path = gppkg_file,
                  target_path = archive_file,
                  host_list = get_host_list()[1]).run()
            Scp(name = "copy gppkg to standby",
                srcFile = gppkg_file,
                dstFile = archive_file,
                srcHost = None,
                dstHost = standby).run(validateAfter = True)
            self.fail("ExecutionError %s" % e)

    @unittest.expectedFailure
    def test02_uninstall_rpm_on_standby_and_install(self):
        #Use gppkg from previous test
        gppkg_file = self.alpha_spec.get_filename()
        self.install(gppkg_file)

        standby = get_host_list()[0]

        self.uninstall_rpm_remotely(self.A_spec.get_filename(), standby)
        try:
            self.install(gppkg_file)
        except ExecutionError as e:
            #Install the rpm
            with closing(tarfile.open(self.alpha_spec.get_filename())) as tf:
                tf.extract(self.A_spec.get_filename())
            Scp(name = "copy rpm to standby",
                srcFile = self.A_spec.get_filename(),
                dstFile = self.A_spec.get_filename(),
                srcHost = None,
                dstHost = standby).run(validateAfter = True)
            self.install_rpm_remotely(self.A_spec.get_filename(), standby)
            os.remove(self.A_spec.get_filename())
            RemoveRemoteFile(self.A_spec.get_filename(), standby).run()
            self.fail("ExecutionError %s" % e)

    def test03_uninstall_rpm_on_standby_and_uninstall(self):
        #Use gppkg from previous test
        gppkg_file = self.alpha_spec.get_filename()
        self.install(gppkg_file)

        standby = get_host_list()[0]

        self.uninstall_rpm_remotely(self.A_spec.get_filename(), standby)
        self.remove(gppkg_file)

    def test04_install_rpm_on_standby_and_install(self):
        gppkg_file = self.alpha_spec.get_filename()

        standby = get_host_list()[0]

        #Install the rpm
        with closing(tarfile.open(self.alpha_spec.get_filename())) as tf:
            tf.extract(self.A_spec.get_filename())
        Scp(name = "copy the rpm to standby",
            srcFile = self.A_spec.get_filename(),
            dstFile = self.A_spec.get_filename(),
            srcHost = None,
            dstHost = standby).run(validateAfter = True)

        self.install_rpm_remotely(self.A_spec.get_filename(), standby)
        self.install(gppkg_file)

    @unittest.expectedFailure
    def test05_install_rpm_on_standby_and_uninstall(self):
        gppkg_file = self.alpha_spec.get_filename()

        standby = get_host_list()[0]

        #Install the rpm
        with closing(tarfile.open(self.alpha_spec.get_filename())) as tf:
            tf.extract(self.A_spec.get_filename())
        Scp(name = "copy rpm to standby",
            srcFile = self.A_spec.get_filename(),
            dstFile = self.A_spec.get_filename(),
            srcHost = None,
            dstHost = standby).run(validateAfter = True)

        self.install_rpm_remotely(self.A_spec.get_filename(), standby)

        try:
            self.remove(gppkg_file)
        except ExecutionError as e:
            self.uninstall_rpm_remotely(self.A_spec.get_filename(), standby)
            os.remove(self.A_spec.get_filename())
            RemoveRemoteFile(self.A_spec.get_filename(), standby).run()
            self.fail("ExecutionError %s" % e)

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


text:
module Admin
  class CustomersController < ApplicationController
    before_action(:authenticate_user!) if defined?(Devise)
    before_action { EffectiveResources.authorize!(self, :admin, :effective_orders) }

    include Effective::CrudController

    if (config = EffectiveOrders.layout)
      layout(config.kind_of?(Hash) ? config[:admin] : config)
    end

  end
end


text:
<?php
	require_once('init.php');
	require_once('reviewsfunctions.php');
	use JasonKaz\FormBuild\Form as Form;
	use JasonKaz\FormBuild\Text as Text;
	use JasonKaz\FormBuild\Help as Help;
	use JasonKaz\FormBuild\Checkbox as Checkbox;
	use JasonKaz\FormBuild\Submit as Submit;
	use JasonKaz\FormBuild\Password as Password;
	use JasonKaz\FormBuild\Select as Select;
	use JasonKaz\FormBuild\Radio as Radio;
	use JasonKaz\FormBuild\Button as Button;
	use JasonKaz\FormBuild\Reset as Reset;
	use JasonKaz\FormBuild\Custom as Custom;
	use JasonKaz\FormBuild\Textarea as Textarea;
	use JasonKaz\FormBuild\Hidden as Hidden;
	use JasonKaz\FormBuild\Email as Email;
	use JasonKaz\FormBuild\Star as Star;
?>
<!DOCTYPE HTML>

         <title><?php Woodle(); ?></title>
         <link href="bootstrap/css/bootstrap.css" rel="stylesheet">
         <link href="bootstrap/css/bootstrap-responsive.css" rel="stylesheet">
         <link href="bootstrap/css/bootstrap-rowlink.css" rel="stylesheet">
         <link href="bootstrap/css/footer.css" rel="stylesheet">
		 <link href="datatables/media/css/bootstrap-dt.css" rel="stylesheet">

			<?php DisplayNavbar(basename(__FILE__)); ?>

					<?php DisplaySidebar(); ?>

		                 <?php ReviewNav(true) ?>

Find reviews by
						 <select class="input-medium" id="searchType" style="width: 120px">
							 <option value="Course">Course</option>
						 	 <option value="Professor">Professor</option>
						 </select>

		                     <?php
		                  		$dbc = new dbw(DBSERVER,DBUSER,DBPASS,DBCATALOG);
		                  		echo "
";
		                  			$ReviewSearchCourseForm=new Form;
									echo $ReviewSearchCourseForm->init('','get',array('class'=>'form-inline', 'name'=>'reviewSearchCourseForm', 'id'=>'reviewSearchCourseForm'))
										->group('',
											new Select($dbc->queryPairs('SELECT Abbreviation,Description FROM Department WHERE RowOrder = 1 ORDER BY RowOrder,Abbreviation'), 1, array('class'=>'input-xlarge','name'=>'courseDept', 'id'=>'courseDept')),
											new Text(array('class'=>'input-small','name'=>'courseNumber', 'id'=>'courseNumber', 'placeholder'=>'Course #')),
											new Submit('Search',array('class'=>'btn btn-primary'))
										)
										->render();
								echo "
";

								echo '
';
									$ReviewSearchProfForm=new Form;
									echo $ReviewSearchProfForm->init('','get',array('class'=>'form-inline', 'name'=>'reviewSearchProfForm', 'id'=>'reviewSearchProfForm'))
										->group('',
											new Select($dbc->queryPairs('SELECT Name,Name FROM Professor WHERE RowOrder = 1 ORDER BY RowOrder,Name'),1, array('class'=>'input-xlarge','name'=>'searchProf', 'id'=>'searchProf')),
											new Submit('Search',array('class'=>'btn btn-primary'))
										)
										->render();
								echo "
";
							?>

				              <?php

									if (isset($_GET['searchProf'])) {
										$prof = $_GET['searchProf'];
										$qry = "SELECT CourseDept, CourseNumber, Professor, Workload, LectureQuality, TestRelevance, RelevanceToProgram, Enjoyable, BookNecessity, Comments, Overall, PostID FROM Review WHERE Professor = '$prof' AND RecordStatus <> 3 ORDER BY PostID DESC;";
										ShowReviews($qry, false, true);
									}
									else if (isset($_GET['courseDept']) && isset($_GET['courseNumber'])) {
										$courseDept = $_GET['courseDept'];
										$courseNum = $_GET['courseNumber'];
										$qry = "SELECT CourseDept, CourseNumber, Professor, Workload, LectureQuality, TestRelevance, RelevanceToProgram, Enjoyable, BookNecessity, Comments, Overall, PostID FROM Review WHERE CourseDept = '$courseDept' AND CourseNumber = '$courseNum' AND RecordStatus <> 3 ORDER BY PostID DESC;";
										ShowReviews($qry, true, false);
									}
									else {
										$qry = "SELECT CourseDept, CourseNumber, Professor, Workload, LectureQuality, TestRelevance, RelevanceToProgram, Enjoyable, BookNecessity, Comments, Overall, PostID FROM Review WHERE RecordStatus <> 3 ORDER BY PostID DESC LIMIT 10 ;";
										ShowReviews($qry, true, false);
									}
								?>

        <?php DisplayFooter(); ?>


text:
/*
 * Do not modify this file. This file is generated from the apigateway-2015-07-09.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.APIGateway.Model
{
    ///
    /// Container for the parameters to the UpdateDeployment operation.
    /// Changes information about a Deployment resource.
    ///
    public partial class UpdateDeploymentRequest : AmazonAPIGatewayRequest
    {
        private string _deploymentId;
        private List<PatchOperation> _patchOperations = new List<PatchOperation>();
        private string _restApiId;

        ///
        /// Gets and sets the property DeploymentId.
        /// <para>
        /// The replacment identifier for the Deployment resource to change information
        /// about.
        /// </para>
        ///
        public string DeploymentId
        {
            get { return this._deploymentId; }
            set { this._deploymentId = value; }
        }

        // Check to see if DeploymentId property is set
        internal bool IsSetDeploymentId()
        {
            return this._deploymentId != null;
        }

        ///
        /// Gets and sets the property PatchOperations.
        /// <para>
        /// A list of operations describing the updates to apply to the specified resource. The
        /// patches are applied in the order specified in the list.
        /// </para>
        ///
        public List<PatchOperation> PatchOperations
        {
            get { return this._patchOperations; }
            set { this._patchOperations = value; }
        }

        // Check to see if PatchOperations property is set
        internal bool IsSetPatchOperations()
        {
            return this._patchOperations != null && this._patchOperations.Count > 0;
        }

        ///
        /// Gets and sets the property RestApiId.
        /// <para>
        /// The replacement identifier of the RestApi resource for the Deployment
        /// resource to change information about.
        /// </para>
        ///
        public string RestApiId
        {
            get { return this._restApiId; }
            set { this._restApiId = value; }
        }

        // Check to see if RestApiId property is set
        internal bool IsSetRestApiId()
        {
            return this._restApiId != null;
        }

    }
}


text:
package org.wfe.validation.extra;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wfe.engine.model.IExecutionRequest;
import org.wfe.validation.IConditionValidator;
import org.wfe.validation.IValidationResult;
import org.wfe.validation.IValidationResult.ResultCode;
import org.wfe.validation.exception.ValidationException;
import org.wfe.validation.impl.ValidationResultImpl;
import org.wfe.validation.validator.condition.BaseConditionValidator;

public class StateChangeDate extends BaseConditionValidator<IExecutionRequest<?>>
		implements IConditionValidator<IExecutionRequest<?>> {

	private static final String DATE_FORMAT = "dd-MM-yyyy";

	private final static Logger log = LoggerFactory.getLogger(StateChangeDate.class);

	private String date;

	private String condition = "BEFORE";

	private Date objDate = null;

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getCondition() {
		return condition;
	}

	public void setCondition(String condition) {
		this.condition = condition;
	}

	public enum Condition {
		BEFORE,AFTER
	}

	@Override
	public List<IValidationResult> validate(IExecutionRequest<?> request) throws ValidationException {
		List<IValidationResult> result = new ArrayList<IValidationResult>();
		IValidationResult vresult = new ValidationResultImpl();

		if (validate(getDate(), getCondition())) {
			vresult.setCode(ResultCode.OK);
		} else {
			vresult.setCode(ResultCode.ERROR);
			vresult.setDescription("Validation " + condition + " " + date + " failed ");
			vresult.setField("Not allowed");
		}
		result.add(vresult);
		return result;
	}

	private boolean validate(String sdate, String condition) {
		if (date == null) {
			return true;
		}
		try {
			Date date = getDate(sdate);
			Date currentDate = new Date();

			return (Condition.BEFORE.equals(Condition.valueOf(condition))) ? currentDate.before(date): currentDate.after(date);
		} catch (ParseException pe) {
			return false;
		}
	}

	private Date getDate(String sdate) throws ParseException {

		if (this.objDate == null) {
			SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
			try {
				objDate = sdf.parse(sdate);
			} catch (ParseException pe) {
				log.error("Incorrect date format configuration - should be : " + DATE_FORMAT, pe);
				throw pe;
			}
		}

		return this.objDate;
	}

}


text:
/*global describe: false, it: false */
var BaseCollection = require('../../src/js/collections/base'),
    chai = require('chai'),
    expect = chai.expect;

describe("BaseCollection", function () {
    "use strict";
    var localApiBase = "http://localhost:8080/";
    describe("apiBase", function () {
        it("is the local API base because tests run locally", function () {
            var collection = new BaseCollection();
            expect(collection.apiBase).to.equal(localApiBase);
        });
    });
});


text:
BugSweeper
======

This is a familiar game with a new twist. Ten bugs are hidden in a 9-by-9 grid of tiles.
To win, you must find and flag all ten bugs.

**If you open the solution in Xamarin Studio, it will not be able to load the Windows Phone project;
and if you open the solution in Xamarin Studio under Windows, it will not be able to load the iOS project either.**

Begin playing by double tapping any tile. That first double tap is always safe.
Thereafter, numbers indicate the number of surrounding tiles with bugs.
If you know that a tile has a bug, flag it (or unflag it) with a single tap.
Avoid double-tapping a tile with a bug!

Author
------

Charles Petzold


text:
TEST(StorageTest, RemoveRestoreEntityHavingComponents) {

    struct Foo {
        Foo() { }
    };

    using StorageT = Giraffe::Storage<Foo>;
    using EntityT = Giraffe::Entity<StorageT>;

    StorageT storage;

    EntityT e = storage.addEntity();
    e.addComponent<Foo>();

    storage.removeEntity(e);
    EntityT e1 = storage.addEntity();

    std::size_t result = 0;
    auto iterBegin = storage.begin<Foo>();
    auto iterEnd = storage.end<Foo>();
    for (; iterBegin != iterEnd; ++iterBegin) {
        ++result;
    }

    EXPECT_EQ(result, 0);
}

TEST(StorageTest, RemoveAndAndNewEntityWithComponents) {

    struct Foo {
        Foo(int i) : m_i(i) { }

        int getI() const {
            return m_i;
        }

        int m_i;
    };

    using StorageT = Giraffe::Storage<Foo>;
    using EntityT = Giraffe::Entity<StorageT>;

    StorageT storage;

    EntityT e1 = storage.addEntity();
    e1.addComponent<Foo>(42);
    storage.removeEntity(e1);

    EntityT e2 = storage.addEntity();
    e2.addComponent<Foo>(43);

    std::size_t count = 0;
    for (const auto &e : storage.range<Foo>()) {
        ASSERT_TRUE(e.hasComponent<Foo>());
        ASSERT_TRUE(e.getComponent<Foo>() != nullptr);
        ASSERT_EQ(e.getComponent<Foo>()->getI(), 43);
        ++count;
    }

    EXPECT_EQ(count, 1);
}

int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
package org.jetbrains.plugins.scala.codeInsight.intention.types

import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.ScalaBundle
import org.jetbrains.plugins.scala.codeInspection.methodSignature.quickfix
import org.jetbrains.plugins.scala.extensions.{IteratorExt, PsiElementExt}
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScFunctionDefinition
import org.jetbrains.plugins.scala.project.ProjectContext
import org.jetbrains.plugins.scala.util.IntentionAvailabilityChecker

class AddUnitTypeAnnotationIntention extends PsiElementBaseIntentionAction {

  import AddUnitTypeAnnotationIntention._

  override def invoke(project: Project, editor: Editor, element: PsiElement): Unit = {
    if (!isAvailable(project, editor, element)) return

    findDefinition(element).foreach { definition =>
      import quickfix._
      implicit val context: ProjectContext = project

      removeAssignment(definition)
      removeTypeElement(definition)
      addUnitTypeElement(definition)
    }
  }

  override def isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean = element match {
    case null => false
    case _ if IntentionAvailabilityChecker.checkIntention(this, element)
      && findDefinition(element).isDefined =>
      setText(ScalaBundle.message("intention.type.annotation.function.add.text"))
      true
    case _ => false
  }

  override def getFamilyName: String = FamilyName
}

object AddUnitTypeAnnotationIntention {

  private[types] val FamilyName = ScalaBundle.message("intention.add.explicit.unit.type.annotation")

  private def findDefinition(element: PsiElement) = for {
    definition <- element.parentsInFile.findByType[ScFunctionDefinition]
    if !definition.hasAssign
    body <- definition.body
    if !body.isAncestorOf(element)
  } yield definition
}


text:
/* Isaac Wismer
 *
 */
package nutrientcalculator;

import java.util.ArrayList;

/**
 *
 * @author isaac
 */
public class Ingredient {

    //food ID number, the cmb number for the fraction, the cmb num for the unit, quantity
    private int id, fractionNum, unitNum, quantity;
    //Short name, what unit is used, Formatted name (with correct quantity in front), the name of the fraction/other unit
    private String name, unit, formattedName, FractionName;
    private ArrayList<Measures> measures = new ArrayList<>();

    /**
     *
     * @param i The ID of the ingredient
     * @param s The name of the ingredient
     */
    public Ingredient(int i, String s) {
        id = i;
        name = s;
    }

    /**
     * Constructor method
     */
    public Ingredient() {
    }

    /**
     *
     * @return the ID of the ingredient
     */
    public int getID() {
        return id;
    }

    /**
     *
     * @return the name of the ingredient
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @return the quantity of the the ingredient
     */
    public int getQuantity() {
        return quantity;
    }

    /**
     *
     * @return the unit used for the ingredient
     */
    public String getUnit() {
        return unit;
    }

    /**
     *
     * @param i the ID of the ingredient
     */
    public void setID(int i) {
        id = i;
    }

    /**
     *
     * @param s the name of the ingredient
     */
    public void setName(String s) {
        name = s;
    }

    /**
     *
     * @param q the quantity of the ingredient
     */
    public void setQuantity(int q) {
        quantity = q;
    }

    /**
     *
     * @param u the Unit of the ingredient
     */
    public void setUnit(String u) {
        unit = u;
    }

    /**
     *
     * @return the index in the combobox of the fraction
     */
    public int getFractionNum() {
        return fractionNum;
    }

    /**
     *
     * @param fractionNum the index in the combobox of the fraction
     */
    public void setFractionNum(int fractionNum) {
        this.fractionNum = fractionNum;
    }

    /**
     *
     * @return The formatted name for output to the user
     */
    public String getFormattedName() {
        return formattedName;
    }

    /**
     *
     * @param formattedName The formatted name for output to the user
     */
    public void setFormattedName(String formattedName) {
        this.formattedName = formattedName;
    }

    /**
     *
     * @return the name of the fraction
     */
    public String getFractionName() {
        return FractionName;
    }

    /**
     *
     * @param FractionName the name of the fraction
     */
    public void setFractionName(String FractionName) {
        this.FractionName = FractionName;
    }

    /**
     *
     * @return the combobox index of the unit
     */
    public int getUnitNum() {
        return unitNum;
    }

    /**
     *
     * @param unitNum the combobox index of the unit
     */
    public void setUnitNum(int unitNum) {
        this.unitNum = unitNum;
    }

    /**
     *
     * @return a full list of measures
     */
    public ArrayList<Measures> getMeasures() {
        return measures;
    }

    /**
     *
     * @param measures set a full list of measures
     */
    public void setMeasures(ArrayList<Measures> measures) {
        this.measures = measures;
    }

    /**
     *
     * @param ID the ID of the measure
     * @return the matching measure object
     */
    public Measures getSingleMeasureID(int ID) {
        for (int i = 0; i < measures.size(); i++) {
            if (measures.get(i).getID() == ID) {
                return measures.get(i);
            }
        }
        return null;
    }

    /**
     *
     * @param ID the ID of the measure
     * @param name the name of the measure
     */
    public void setMeasures(int ID, String name) {
        for (int i = 0; i < measures.size(); i++) {
            if (measures.get(i).getID() == ID) {
                measures.get(i).setName(name);
            }
        }
    }

    /**
     *
     * @param ID the ID of the measure
     * @param conversion the conversion rate of the measure
     */
    public void addMeasure(int ID, double conversion) {
        measures.add(new Measures(ID, conversion));
    }

    /**
     *
     * @param measure the measure to add, as an object
     */
    public void addMeasureFull(Measures measure) {
        measures.add(measure);
    }

    /**
     *
     * @param index the index of the measure to remove
     */
    public void removeSingleMeasure(int index) {
        measures.remove(index);
    }

    /**
     *
     * @param index the position of the mesure
     * @return the specified measure object
     */
    public Measures getSingleMeasureIndex(int index) {
        return measures.get(index);
    }

    /**
     * Checks if 2 ingredients are equal
     * @param in Another ingedient object
     * @return a boolean with true of they are equal, false if not
     */
    public boolean equals(Ingredient in) {
        if (in == null) {
            return false;
        }
        if (getClass() != in.getClass()) {
            return false;
        }
        if (this.id != in.id) {
            return false;
        }
        if (this.quantity != in.quantity) {
            return false;
        }
        return true;
    }

}


text:
class Api::V1::UsersController < Api::V1::ApiController
  def create
    user = User.create(create_params)
    user.confirm
    render json: {}, each_serializer: UserSerializer, status: :created
  end

  def index
    users = User.all
    render json: users, each_serializer: UserSerializer, status: :ok
  end

  def show
    user = User.find params[:id]
    render json: user, each_serializer: UserSerializer
  end

  def update
    user = User.find params[:id]
    user.update_attributes(update_params)
    render json: user, each_serializer: UserSerializer, status: :accepted
  end

  def destroy
    user = User.find params[:id]
    user.destroy
    render json: {}, status: :accepted
  end

  private

  def update_params
    params.permit(:first_name, :last_name, :email, :zip_code, :time_zone, :location_id, :roles, :statuses, :archived, :test, :admin_notes, :password, :password_confirmation)
  end

  def create_params
    params.permit(:first_name, :last_name, :email, :zip_code, :time_zone, :location_id, :roles, :statuses, :archived, :test, :admin_notes, :password, :password_confirmation)
  end
end


text:
const context = {};
global.w = Object.create(context);
w.proto = context;

const Module = require('module');

//const orig_require = Module.prototype.require;
//Module.prototype.require = function(id){ return orig_require(id); }
//Module.prototype.require = function(id){ return orig_require.call(this, id); }

//create context prototype
////const context = {};
//context.proto = context;

//create global work context
////const w = Module.prototype.work = Object.create(context);
////w.proto = context;

require("./doc.js");

require("./dependencies.js");

w.mw = {};
w.cache = {};

//work_require for autoreload in development mode defaults to require
Module.prototype.work_require = Module.prototype.require;

w.proto.rootdir = process.cwd();
w.proto.coredir = __dirname.replace("/core", "");

w.conf = {};
require("../CONF");
require(w.rootdir+"/CONF");

require("./work.js");
require("./logger.js");

w.log("WorkJS starting >>> " + w.conf.name);

if (w.conf.servermode.toUpperCase() == "DEVELOPMENT") {
  Module.prototype.work_require = function requireUncached(module){
    delete require.cache[require.resolve(module)];
    return require.call(w, module);
  };
};

w.verbs = [];
w.flags = {};
for (var i = 0; i<w.conf.verbs.length; ++i) {
  var verb = w.conf.verbs[i];
  w.verbs.push(verb);
  w.flags[verb] = w.conf.flags[verb] || w.conf.flags["default"]
};

//load templating subsystem
///w.templating = module.require('./templating.js')({
///  searchpaths: [w.rootdir, w.rootdir+'/LAYOUT']
///});

//load database subsystem

//w.dbm = require('./pg_native.js')({dburl:w.conf.db_url, poolsize:w.conf.db_poolsize});
//w.db = w.dbm.db;
//install required DB contents

w.dep.syncho(function setup() {

  require('./pg.js');
  require('./db.js');

  require('./cookies.js');

//load global db fkts
///// deleted !! var dbfkt = require("./db.js");
  require('./util.js');

  //load session subsystem
  require('./session.js');

  //load user+auth subsystem
  require('./auth.js');

  require('./groups.js');

  //load email subsystem
  require('./smtp.js');

  //load content repository subsystem
  require('./repo.js');

  require('./work-socket.js');

try { w.dependencies.fs.mkdirSync(w.conf.uploaddir); } catch (e) { };

/////YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
//w.Work = require("./Work.js");
//w.Work.prototype.work = w;

require("./body_parser.js");

//parse packages into route map
w.map = {};
w.packages = {};

require("./package_parser.js");

//start requests processor
require("./request_processor.js");

w.api_doc.init();

});


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Popup - Sidebar</title>
    <link rel="stylesheet" href="http://js.arcgis.com/3.14/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">
    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Open Sans">

Click to select feature(s)


text:
react app using css grid as framework for a single page map-like interface

Very experimental. Far from production ready, but fun to play around with.


text:
<!--

    Copyright 2004-2014 The Kuali Foundation

    Licensed under the Educational Community License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.opensource.org/licenses/ecl2.php

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

    <changeSet id="1" author="tkagata" context="kpme-client-bootstrap">
        <addColumn tableName="TK_DEPT_LUNCH_RL_T">
            <column name="GRP_KEY_CD" type="VARCHAR(30)"/>
        </addColumn>
        <update tableName="TK_DEPT_LUNCH_RL_T">
            <column name="GRP_KEY_CD" value="DEFAULT" />
        </update>
        <addNotNullConstraint columnName="GRP_KEY_CD" tableName="TK_DEPT_LUNCH_RL_T" columnDataType="VARCHAR(30)"/>
    </changeSet>

</databaseChangeLog>


text:
//-----------------------------------------------------------------------
// <copyright file="EnumeratorExtensions.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System.Collections.Generic;

namespace Akka.Util.Internal.Collections
{
    public static class EnumeratorExtensions
    {
        public static Iterator<T> Iterator<T>(this IEnumerable<T> enumerable)
        {
            return new Iterator<T>(enumerable);
        }
    }
}


text:
'''Test case for configuration reader
'''
import unittest

class CommandsTestCase(unittest.TestCase):
    '''Test case for partial template execution
    '''

    def testLoadCommandsFromApp(self):
        '''Test loading commands for one application'''
        from lighty.commands import load_commands_from_app
        from tests.commands import test
        cmds = load_commands_from_app('tests')
        assert cmds == [('test', test)], ('Error loading commands for '
                                          'application tests:\n%s' % cmds)
        cmds = load_commands_from_app('lighty.wsgi')
        from lighty.wsgi import commands
        assert cmds == [('make_application', commands.make_application),
                        ('run_server', commands.run_server),
                        ('run_tornado', commands.run_tornado)], (
                                'Error loading commands for '
                                'application lighty.wsgi:\n%s' % cmds)
        cmds = load_commands_from_app('lighty.templates')
        assert cmds == [], ('Error loading commands for application '
                            'lighty.templates:\n%s' % cmds)

    def testLoadCommands(self):
        '''Test loading commands for few applications'''
        from lighty.commands import load_commands
        cmds = load_commands(['lighty.wsgi', 'tests'])
        assert sorted(cmds.keys()) == ['make_application', 'run_server',
                                       'run_tornado', 'test'], ('Error loading'
                                ' commands for ["lighty.wsgi","tests"]:\n%s' %
                                sorted(cmds.keys()))

def test():
    suite = unittest.TestSuite()
    suite.addTest(CommandsTestCase('testLoadCommandsFromApp'))
    suite.addTest(CommandsTestCase('testLoadCommands'))
    return suite


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Echium acutifolium J.G.C.Lehmann

### Remarks
null


text:
namespace MassTransit.Transports.InMemory.GraphValidation
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// Maintains a list of nodes for a given set of instances of T
    /// </summary>
    /// <typeparam name="T">The type encapsulated in the node</typeparam>
    /// <typeparam name="TNode">The type of node contained in the list</typeparam>
    class NodeList<T, TNode>
        where TNode : Node<T>
    {
        readonly Func<int, T, TNode> _nodeFactory;
        readonly NodeTable<T> _nodeTable;
        readonly IList<TNode> _nodes;

        public NodeList(Func<int, T, TNode> nodeFactory, int capacity)
        {
            _nodeFactory = nodeFactory;
            _nodes = new List<TNode>(capacity);
            _nodeTable = new NodeTable<T>(capacity);
        }

        /// <summary>
        /// Retrieves the node for the given key
        /// </summary>
        /// <param name="key">The key</param>
        /// <returns>The unique node that relates to the specified key</returns>
        public TNode this[T key]
        {
            get { return _nodes[Index(key) - 1]; }
        }

        /// <summary>
        /// Retrieve the index for a given key
        /// </summary>
        /// <param name="key">The key</param>
        /// <returns>The index</returns>
        public int Index(T key)
        {
            int index = _nodeTable[key];

            if (index <= _nodes.Count)
                return index;

            TNode node = _nodeFactory(index, key);
            _nodes.Add(node);

            return index;
        }
    }
}


text:
"""
Based on cairo-demo/X11/cairo-demo.c
"""
from gi.repository import Gdk, Gtk, GObject
from graphline import GraphTable
import simconstants
from simulator import Simulator
import sys
import argparse

class SimulatorWindow(Gtk.Window):
    def __init__(self, controller):
        super( SimulatorWindow, self ).__init__()
        self.controller = controller
        self.elapsed = 0.0
        self.epoch = 0
        self.throttleval = 0.0
        self.loadval = 0.0
        self.committedThrottleVal = 0.0
        self.dt = 1.0 / simconstants.SIMFREQ
        self.va = 0.0
        self.vb = 0.0
        self.vc = 0.0

        self.connect('destroy', lambda w: Gtk.main_quit())
        self.set_default_size(1024, 800)

        vbox = Gtk.VBox()
        self.add(vbox)

        self.table = GraphTable()
        vbox.pack_start( self.table, True, True, 0 )

        self.table.add_row( "omega", 0.05 )
        self.table.add_row( "theta", 5 )
        self.table.add_row( "va", 3 )
        self.table.add_row( "ia", 3 )
        self.table.add_row( "bemf", 4 )
        self.table.add_row( "torque", 50 )
        self.table.add_row( "errors", 5 )

        hbox = Gtk.HBox()
        self.pwm = self.add_label( "throttle (%): ", hbox )
        adj1 = Gtk.Adjustment(0.0, 0.0, 101.0, 0.1, 1.0, 1.0)
        self.throttlescale = Gtk.HScale()
        self.throttlescale.set_adjustment( adj1 )
        self.throttlescale.set_digits(1)
        self.throttlescale.set_draw_value(True)
        hbox.pack_start( self.throttlescale, True, True, 0 )
        self.throttlescale.connect( "change-value", self.change_throttle )

        self.load = self.add_label( "load (Nm): ", hbox )
        adj2 = Gtk.Adjustment(0.0, 0.0, 5.0, 0.01, 1.0, 1.0)
        self.loadscale = Gtk.HScale()
        self.loadscale.set_adjustment( adj2 )
        self.loadscale.set_digits(2)
        self.loadscale.set_draw_value(True)
        hbox.pack_start( self.loadscale, True, True, 0 )
        self.loadscale.connect( "change-value", self.change_load )

        vbox.pack_start(hbox, False, False, 0)
        self.sim = Simulator()

        GObject.timeout_add( 1, self.callback )

        self.show_all()

    def run( self ):
        Gtk.main()

    def add_label( self, labelname, hbox ):
        ln = Gtk.Label( labelname )
        vlabel = Gtk.Label( "0.00" )
        hbox.pack_start( ln, True, True, 0 )
        hbox.pack_start( vlabel, True, True, 0 )
        return vlabel

    def change_throttle( self, scale, scroll, value ):
        if value > 100.0:
            value = 100.0
        if value < 0.0:
            value = 0.0
        self.throttleval = value
        return

    def change_load( self, scale, scroll, value ):
        if value > 5.0:
            value = 5.0
        if value < 0.0:
            value = 0.0
        self.loadval = value
        self.load.set_text( "%3.2f"%( self.loadval ))
        return

    def callback( self ):
        self.elapsed = self.elapsed + (1.0 / self.dt)
        self.epoch = self.epoch + 1

        if self.epoch % simconstants.THROTTLE_INTERVAL == 0:
            self.committedThrottleVal = self.throttleval
            self.pwm.set_text( "%3.2f"%( self.committedThrottleVal ))

        process_variables = self.sim.get_variables()

        if self.epoch % simconstants.CONTROLLER_INTERVAL == 0:
            self.va, self.vb, self.vc = self.controller.step_sim( self.dt, self.elapsed, self.epoch, self.committedThrottleVal, process_variables )

        # t = t in s after last step
        s = self.sim.step_sim( self.dt, self.elapsed, self.epoch, self.loadval, self.va, self.vb, self.vc )
        c = self.controller.get_variables()
        e = self.controller.get_errors()

        s.append( e[0] )
        c.append( e[1] )

        self.table.update_data( s,c )

        return True

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("controller", help="Specify name of controller module (.py file minus directory)")
    args = parser.parse_args()

    mod = get_module( args.controller )
    controller = mod.make_controller()

    win = SimulatorWindow( controller )
    win.run()

def get_module(name):
    try:
        mod = __import__("controllers.%s"%( name ), fromlist=[''])
        return mod
    except ImportError as e:
        pass

    mod = __import__(name, fromlist=[''])
    return mod

if __name__ == '__main__':
    main()


text:
Ext.define('Budget.view.conto.Total' ,{
	extend: 'Ext.panel.Panel',
	alias: 'widget.contototal',

	frame: false,
	bodyPadding: 5,

	baseTitle: 'Totals',

    initComponent: function() {

		this.title = this.baseTitle;
		this.tpl = this.getTplDefinition();

		this.callParent(arguments);

	},

	getTplDefinition: function() {
		return new Ext.XTemplate(
			'<tpl for=".">',
			'
',
			'
',
			'		Total income: 	 {[this.renderValue(values.income)]} 	',
			'
',
			'
',
			'		Total outcome: 	 {[this.renderValue(values.outcome)]} 	',
			'
',
			'
',
			'		TOTAL BALANCE: 	 {[this.renderValue(values.balance)]} 	',
			'
',
			'
',
			'</tpl>',
			{
				disableFormats: true,
				renderValue: function(value) {
					return (value) ? Ext.util.Format.currency(value) : '-';
				}
			}
		);
	}
});


text:
This is **VERY** experimental, please wait until the release 0.1.0 before using it in production!

## Installation

Add this line to your application's Gemfile:

    gem 'has_audit_trail'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install has_audit_trail

Create the migration:

    $ rails generate has_audit_trail:install

## Usage

```ruby
class User < ActiveRecord::Base
  has_audit_trail
end
```

```ruby
class User < ActiveRecord::Base
  has_audit_trail :only => [ :name, :email ]
end
```

```ruby
class User < ActiveRecord::Base
  has_audit_trail :only => [ :name, :email, :projects => { :audit => Proc.new { |p| p.name } } ]
end
```

```ruby
class Project < ActiveRecord::Base
  has_many :tasks

  accepts_nested_attributes_for :tasks

  has_audit_trail(
    :audit_nested => {
      :tasks => {
        :label => Proc.new { |task| task.name },
        :value_print => Proc.new { |value| value }
      }
    }
  )
end
```

## TODO

* Test suite using Test::Unit or rspec

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package com.asksunny.tool;

import java.util.List;

public class BulkRegistrationConfiguration {

	private Resource resource;

	private List<SchemaMapping> schemaMappings;

	public BulkRegistrationConfiguration() {

	}

	public static BulkRegistrationConfiguration newInstance()
	{
		return new BulkRegistrationConfiguration();
	}

	public Resource getResource() {
		return resource;
	}

	public BulkRegistrationConfiguration setResource(Resource resource) {
		this.resource = resource;
		return this;
	}

	public List<SchemaMapping> getSchemaMappings() {
		return schemaMappings;
	}

	public BulkRegistrationConfiguration setSchemaMappings(List<SchemaMapping> schemaMappings) {
		this.schemaMappings = schemaMappings;
		return this;
	}

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>使用JSX定义React组件-组件使用动态值-变量</title>

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>使用JSX定义React组件-组件使用动态值</title>