text:
package com.google.common.css.compiler.ast;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.base.Functions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Unit tests for {@code CssStringNode}
 *
 */
@RunWith(JUnit4.class)
public class CssStringNodeTest {
  @Test
  public void testCssValueNodeRoundtrip() throws Exception {
    String v = "ordinary";
    for (CssStringNode.Type t : CssStringNode.Type.values()) {
      CssStringNode n = new CssStringNode(t, v);
      n.setValue(v);
      assertThat(n.getValue()).isEqualTo(v);
    }
  }

  @Test
  public void testCssValueNodeFixedPoint() throws Exception {
    // This test doesn't care if setValue/getValue work in terms of
    // CSS or abstract values, but we just want to make sure that
    // eventually what we set is what we get.
    // Here's a value that must be escaped in CSS. It ensures that
    // we exercise whatever codec is in operation behind these
    // accessors.
    String v = "\\\\\"\"";
    CssStringNode n = new CssStringNode(
        CssStringNode.Type.DOUBLE_QUOTED_STRING, v);
    String v2 = n.getValue();
    n.setValue(v2);
    assertThat(n.getValue()).isEqualTo(v2);
  }

  @Test
  public void testConcreteRoundtrip() throws Exception {
    // This value is safe for verbatim inclusion in either kind of
    // string literal, and for each kind it includes:
    //   (a) an escape sequence that denotes a character that must
    // be escaped in literals of that kind.
    //   (b) a character (possibly as part of an escape sequence)
    // that must be escaped in literals of that kind
    // Also, it includes weird escape sequences that are unlikely
    // to occur together in sane usage, which helps demonstrate
    // normalization.
    String v = "\\'\\\"\\041zA\\0000411\\41 1";
    //          ^single quote
    //             ^double quote
    //                 ^weird A
    //                      ^z
    //                       ^A
    //                        ^weird A, second variation
    //                                ^1
    //                                 ^A with escape code delimiter
    //                                      ^1
    for (CssStringNode.Type t : CssStringNode.Type.values()) {
      CssStringNode n = new CssStringNode(t, v);
      n.setConcreteValue(v);
      assertThat(n.getConcreteValue()).isEqualTo(v);
    }
  }

  @Test
  public void testShortEscaper() throws Exception {
    for (String[] io : new String[][] {
        {"", ""},
        {"a", "a"},
        {"¤", "\\a4"},
        {"ξ", "\\3be"},
        {"ξe", "\\3be e"},
        {"ξx", "\\3bex"},
        {"唐", "\\5510"},
        {"𠍱", "\\20371"},
        {new String(
            new byte[] {(byte) 0xf0, (byte) 0xa0, (byte) 0x8d, (byte) 0xb1},
            UTF_8),
         "\\20371"}}) {
      assertThat(CssStringNode.SHORT_ESCAPER.apply(io[0])).isEqualTo(io[1]);
    }
    // Six-hexadecimal-digit codepoints aren't allowed
    // leading-zeros-padding. This is also an interesting case because
    // Java chars and Strings are defined in terms of UTF-16, which
    // represents codepoints in this range as surrogate pairs.  Let's
    // use UTF-8 to specify the input because it's simpler:
    byte[] puabUtf8 = {(byte) 0xf4, (byte) 0x80, (byte) 0x80, (byte) 0x80};
    assertThat(CssStringNode.SHORT_ESCAPER.apply(new String(puabUtf8, UTF_8)))
        .isEqualTo("\\100000");
    assertThat(CssStringNode.SHORT_ESCAPER.apply(String.format("%sa", new String(puabUtf8, UTF_8))))
        .isEqualTo("\\100000a");
  }

  @Test
  public void testInsertsIgnoredWhitespaceAfterEscape() throws Exception {
    // When parsing, we always discard zero or one whitespace after an
    // escape sequence.
    // See http://www.w3.org/TR/CSS2/syndata.html#characters
    // and http://www.w3.org/TR/css3-syntax/#consume-an-escaped-code-point
    String stringTemplate = "%s following (%s)";
    String cssTemplate = "%s  following (%s)";

    for (CssStringNode.Type type : CssStringNode.Type.values()) {
      // We produce escape sequences in three cases:
      // (1) newline
      assertThat(
              CssStringNode.escape(
                  type,
                  CssStringNode.HTML_ESCAPER,
                  String.format(stringTemplate, "\n", type.getClass().getName())))
          .isEqualTo(String.format(cssTemplate, "\\00000a", type.getClass().getName()));

      // (2) no CSS literal representation exists
      assertThat(
              CssStringNode.escape(
                  type,
                  CssStringNode.SHORT_ESCAPER,
                  String.format(stringTemplate, "¤", type.getClass().getName())))
          .isEqualTo(String.format(cssTemplate, "\\a4", type.getClass().getName()));

      // (3) HTML/SGML special character when using the HTML_ESCAPER
      assertThat(
              CssStringNode.escape(
                  type,
                  CssStringNode.HTML_ESCAPER,
                  String.format(stringTemplate, "<", type.getClass().getName())))
          .isEqualTo(String.format(cssTemplate, "\\00003c", type.getClass().getName()));
    }
  }

  @Test
  public void testHtmlEscaper() throws Exception {
    for (String[] io : new String[][] {
        {"", ""},
        {"a", "a"},
        {"¤", "\\0000a4"},
        {"ξ", "\\0003be"},
        {"ξe", "\\0003bee"},
        {"ξx", "\\0003bex"},
        {"唐", "\\005510"},
        {"𠍱", "\\020371"},
        {new String(
            new byte[] {(byte) 0xf0, (byte) 0xa0, (byte) 0x8d, (byte) 0xb1},
            UTF_8),
         "\\020371"}}) {
      assertThat(CssStringNode.HTML_ESCAPER.apply(io[0])).isEqualTo(io[1]);
    }
    assertThat(CssStringNode.HTML_ESCAPER.apply("&")).isEqualTo("\\000026");
    assertThat(CssStringNode.HTML_ESCAPER.apply("<")).isEqualTo("\\00003c");
    assertThat(CssStringNode.HTML_ESCAPER.apply(">")).isEqualTo("\\00003e");
    assertThat(CssStringNode.HTML_ESCAPER.apply("\"")).isEqualTo("\\000022");
    assertThat(CssStringNode.HTML_ESCAPER.apply("'")).isEqualTo("\\000027");
  }

  @Test
  public void testEscape() throws Exception {
    for (String[] io : new String[][] {
        {"", ""},
        {"a", "a"},
        {"\\", "\\\\"},
        {"19\\3=6", "19\\\\3=6"},
        {"say \"hello\"", "say \\\"hello\\\""},
        {"say 'goodbye'", "say 'goodbye'"}}) {
      assertThat(
              CssStringNode.escape(
                  CssStringNode.Type.DOUBLE_QUOTED_STRING, Functions.<String>identity(), io[0]))
          .isEqualTo(io[1]);
    }
    assertThat(
            CssStringNode.escape(
                CssStringNode.Type.SINGLE_QUOTED_STRING,
                Functions.<String>identity(),
                "say 'goodbye'"))
        .isEqualTo("say \\'goodbye\\'");
  }

  @Test
  public void testUnescape() throws Exception {
    for (String[] io : new String[][] {
        {"", ""},
        {"a", "a"},
        {"\\\\", "\\"},
        {"\\\"", "\""},
        {"\\41", "A"},
        {"\\41 ", "A"},
        {"\\41  ", "A "},
        // The spec requires us to discard a whitespace following an
        // escape sequence, even when the escape sequence is as long
        // as possible and hence there is no ambiguity about where it
        // ends.
        {"abc\\000041 ", "abcA"},
        {"abc\\000041  ", "abcA "},
        {"\\41x", "Ax"},
        {"\\0000a4", "¤"},
        {"\\0003be", "ξ"},
        {"\\0003bee", "ξe"},
        {"\\3be e", "ξe"},
        {"\\0003be", "ξ"},
        {"\\3be z", "ξz"},
        {"\\005510", "唐"},
        {"\\020371", "𠍱"},
        {"\\020371", new String(
            new byte[] {(byte) 0xf0, (byte) 0xa0, (byte) 0x8d, (byte) 0xb1},
            UTF_8)}}) {
      assertThat(CssStringNode.unescape(io[0])).isEqualTo(io[1]);
    }

    // Now let's look at a character that requires a max-length escape
    // code in CSS and use of surrogate pairs in the JVM
    byte[] puabUtf8 = {(byte) 0xf4, (byte) 0x80, (byte) 0x80, (byte) 0x80};
    assertThat(CssStringNode.unescape("\\100000")).isEqualTo(new String(puabUtf8, UTF_8));
    assertThat(CssStringNode.unescape("\\100000a")).isEqualTo(new String(puabUtf8, UTF_8) + "a");

    // Here's an escape sequence denoting a code point beyond the Java
    // char/String repertoire. According to CSS 2.1, we can replace the
    // escape.
    int bigCodePoint = Character.MAX_CODE_POINT + 1;
    assertThat(CssStringNode.unescape(String.format("\\%x", bigCodePoint)))
        .isEqualTo(
            // replacement character
            "\ufffd");
  }

  @Test
  public void testCopyCtor() {
    CssStringNode a = new CssStringNode(
        CssStringNode.Type.DOUBLE_QUOTED_STRING, "foo");
    a.setConcreteValue("\\0066oobar");
    CssStringNode b = new CssStringNode(a);
    assertThat(a.getConcreteValue()).isEqualTo("\\0066oobar");
    assertThat(b.getConcreteValue()).isEqualTo(a.getConcreteValue());
    assertThat(b.getValue()).isEqualTo(a.getValue());
  }

  @Test
  public void testStringCannotDirectlyContainNewline() {
    // See http://www.w3.org/TR/CSS2/syndata.html#strings
    CssStringNode a = new CssStringNode(
        CssStringNode.Type.SINGLE_QUOTED_STRING, "line1\nline2");
    assertWithMessage("We should support the Java String representation of newlines.")
        .that(a.getValue().contains("\n"))
        .isTrue();
    assertWithMessage(
            "If we set a Java newline, it should be escaped in the" + " generated concrete value.")
        .that(a.getConcreteValue().contains("\n"))
        .isFalse();
    assertWithMessage("If we ask for CSS markup, we should escape newlines per the" + " CSS spec.")
        .that(a.toString(CssStringNode.HTML_ESCAPER).contains("\n"))
        .isFalse();
    assertWithMessage("Escaping a new line shouldn't affect the left hand side")
        .that(a.toString(CssStringNode.HTML_ESCAPER).startsWith("'line1"))
        .isTrue();
    assertWithMessage("Escaping a new line shouldn't affect the right-hand side")
        .that(a.toString(CssStringNode.HTML_ESCAPER).endsWith("line2'"))
        .isTrue();
  }
}


text:
from allauth.socialaccount.providers.exist.provider import ExistProvider
from allauth.socialaccount.tests import OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase

class ExistTests(OAuth2TestsMixin, TestCase):
    provider_id = ExistProvider.id

    def get_mocked_response(self):
        return MockedResponse(200, """
            {
                "id": 1,
                "username": "josh",
                "first_name": "Josh",
                "last_name": "Sharp",
                "bio": "I made this thing you're using.",
                "url": "http://hellocode.co/",
                "avatar": "https://exist.io/static/media/avatars/josh_2.png",
                "timezone": "Australia/Melbourne",
                "local_time": "2020-07-31T22:33:49.359+10:00",
                "private": false,
                "imperial_units": false,
                "imperial_distance": false,
                "imperial_weight": false,
                "imperial_energy": false,
                "imperial_liquid": false,
                "imperial_temperature": false,
                "attributes": []
            }
        """)

redpajama_set_name: RedPajamaGithub


text:
require 'rails/generators/migration'
require 'rails/generators/active_record'

module Traka
  module Generators
    class InstallGenerator < ::Rails::Generators::Base
      include Rails::Generators::Migration

      source_root File.expand_path("../templates", __FILE__)

      desc "Installs Traka into the app."

      def create_migration
        migration_template 'migration.rb', 'db/migrate/create_traka_changes.rb'
      end

      def create_version_file
        directory "public/system"
      end

      def self.next_migration_number dirname
        ActiveRecord::Generators::Base.next_migration_number dirname
      end
    end
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Eupatorium rosmarinaceum Cabrera & Vittet

### Remarks
null


text:
using DropCore.Configuration;
using System.Reflection;

namespace DropCore.Module
{
    public class ModuleContainer
    {
        public ModuleConfiguration Configuration { get; set; }
        public Assembly Assembly { get; set; }
        public IModule Instance { get; set; }
    }
}


text:
<?php

namespace Sylius\Behat\Page\Shop\Checkout;

use Sylius\Behat\Page\SymfonyPageInterface;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
interface ShippingPageInterface extends SymfonyPageInterface
{
    /**
     * @param string $shippingMethod
     */
    public function selectShippingMethod($shippingMethod);

    /**
     * @param string $shippingMethod
     *
     * @return bool
     */
    public function hasShippingMethod($shippingMethod);

    /**
     * @return bool
     */
    public function hasNoShippingMethodsMessage();

    /**
     * @param string $shippingMethodName
     * @param string $fee
     *
     * @return bool
     */
    public function hasShippingMethodFee($shippingMethodName, $fee);

    public function nextStep();

    public function changeAddress();

    public function changeAddressByStepLabel();
}


text:
package spire
package optional

import spire.scalacompat.{Factory, FactoryCompatOps, SeqLike}

import cats.kernel.Eq
import spire.algebra.{Action, Group}
import spire.algebra.partial.PartialAction
import spire.syntax.cfor._
import spire.util._

/** Represents a permutation encoded as a map from preimages to images, including
  * only pairs that are moved by the permutation (so the identity is Map.empty).
  *
  * Note that although the preimage and image contain only moved points, the
  * domain and range of a Perm is all integers. This acts as the identity for
  * integers not in the image.
  */
class Perm private(private val mapping: Map[Int, Int]) extends (Int => Int) {

  /** Apply this permutation to an `Int`. */
  override def apply(k: Int): Int = mapping.getOrElse(k, k)

  /** A `Perm` constructed by cycling args so each n,,i,, maps to n,,i+1,,.
    *
    * This new cycle is composed with the current permutation to yield a new
    * `Perm`. Cycles provided to this constructor must be disjoint.
    * See [[Perm$.apply(n0:Int*]].
    */
  def apply(n0: Int, n1: Int, ns: Int*): Perm = {
    val cycle = n0 +: n1 +: ns
    require(!(cycle.exists(image)), "Cycle must be disjoint.")
    this.compose(Perm(n0, n1, ns: _*))
  }

  override def toString: String = {
    mapping.toSeq.sorted
      .map { case (k, v) => s"$k -> $v"}
      .mkString("Perm(", ", ", ")")
  }

  private lazy val inverseMapping = mapping.map(_.swap)

  /** The preimage of `k` (so that `apply(invert(k)) == k`). */
  def invert(k: Int): Int = inverseMapping.getOrElse(k, k)

  /** The inverse permutation, which composes with this to yield the identity.
    * Note that this uses a lazy inverse map, so the first call may be O(n)
    * rather than O(1).
    */
  def inverse: Perm = new Perm(inverseMapping)

  /** The set of points moved by this permutation (equivalent to preimage). */
  def image: Set[Int] = mapping.keySet

  /** Permute a seq as long as all the moved points are valid indices. */
  def permute[A, SA](seq: SeqLike[A, SA])(implicit cbf: Factory[A, SA]): Opt[SA] = {
    if (image.isEmpty) return Opt(cbf.fromSpecific(seq))
    if (image.max >= seq.size) return Opt.empty[SA]
    val builder = cbf.newBuilder
    cforRange(0 until seq.size) { k =>
      builder += seq(invert(k))
    }
    Opt(builder.result())
  }

  /** Compose this with another `Perm` with this permutation applied last. */
  def compose(that: Perm): Perm = new Perm(
    (this.image | that.image)
      .map(k => k -> this(that(k)))
      .filter(Function.tupled(_ != _))
      .toMap
  )

  /** Compose this with another `Perm` with this permutation applied first. */
  def andThen(that: Perm): Perm = that.compose(this)
}

object Perm {
  /** A `Perm` given a `Map[Int, Int]` from preimage to image. */
  def apply(mapping: Map[Int, Int]): Perm = {
    require(mapping.values.toSet == mapping.keySet, "Image and preimage must be the same.")
    require(mapping.keys.forall(_ >= 0), "Perm indices must be non-negative.")
    new Perm(mapping.filter(Function.tupled(_ != _)))
  }

  /** A `Perm` given a collection of preimage/image pairs. */
  def apply(pairs: (Int, Int)*): Perm = apply(Map(pairs: _*))

  /** A `Perm` constructed by cycling args so each n,,i,, maps to n,,i+1,,.
    *
    * [[Perm#apply(n0:Int*]] can be called subsequently to express any `Perm` as
    * the product of cycles rather than explicit preimage/image pairs. This is
    * provided as a convenience for constructing permutations. eg.,
    * `Perm(1,3)(2,4)` is shorthand for `Perm(1 -> 3, 2 -> 4, 3 -> 1, 4 ->
    * 2)`. At least two args are required in each parameter list.
    */
  def apply(n0: Int, n1: Int, ns: Int*): Perm = {
    val cycles = n0 +: n1 +: ns
    require(cycles.size == cycles.distinct.size, "Cycle must not repeat elements")
    apply((n0 +: n1 +: ns).zip(n1 +: ns :+ n0).toMap)
  }

  implicit val PermEq: Eq[Perm] = new Eq[Perm] {
    def eqv(p: Perm, r: Perm): Boolean = p.mapping == r.mapping
  }
  implicit val PermIntAction: Action[Int, Perm] = new PermIntAction
  implicit val PermGroup: Group[Perm] = new PermGroup
  implicit def PermSeqPartialAction[A, CC[A] <: SeqLike[A, CC[A]]](implicit cbf: Factory[A, CC[A]]): PartialAction[CC[A], Perm] = new PermSeqPartialAction[A, CC[A]]
}

final class PermIntAction extends Action[Int, Perm] {
  def actl(perm: Perm, k: Int): Int = perm(k)
  def actr(k: Int, perm: Perm): Int = perm.invert(k)
}

final class PermGroup extends Group[Perm] {
  def empty: Perm = Perm(Map.empty[Int, Int])
  def combine(x: Perm, y: Perm): Perm = x.compose(y)
  def inverse(a: Perm): Perm = a.inverse
}

final class PermSeqPartialAction[A, SA <: SeqLike[A, SA]](implicit cbf: Factory[A, SA]) extends PartialAction[SA, Perm] {
  def partialActl(perm: Perm, sa: SA): Opt[SA] = perm.permute[A, SA](sa)
  def partialActr(sa: SA, perm: Perm): Opt[SA] = partialActl(perm.inverse, sa)
}


text:
package org.hawkular.alerts.actions.api;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Mark an ActionPluginSender to be injected inside an ActionPluginListener.
 * Only one injected ActionPluginSender instance is permitted by ActionPluginListener class.
 *
 * @author Jay Shaughnessy
 * @author Lucas Ponce
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Sender {
}


text:
package org.vitrivr.cineast.core.features;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.tensorflow.Tensor;
import org.tensorflow.types.UInt8;
import org.vitrivr.cineast.core.config.QueryConfig;
import org.vitrivr.cineast.core.config.ReadableQueryConfig;
import org.vitrivr.cineast.core.data.CorrespondenceFunction;
import org.vitrivr.cineast.core.data.FloatVectorImpl;
import org.vitrivr.cineast.core.data.SemanticMap;
import org.vitrivr.cineast.core.data.frames.VideoFrame;
import org.vitrivr.cineast.core.data.score.ScoreElement;
import org.vitrivr.cineast.core.data.segments.SegmentContainer;
import org.vitrivr.cineast.core.features.abstracts.AbstractFeatureModule;
import org.vitrivr.cineast.core.features.neuralnet.tf.models.deeplab.DeepLab;
import org.vitrivr.cineast.core.features.neuralnet.tf.models.deeplab.DeepLabAde20k;
import org.vitrivr.cineast.core.features.neuralnet.tf.models.deeplab.DeepLabLabel;
import org.vitrivr.cineast.core.util.GridPartitioner;
import org.vitrivr.cineast.core.util.LogHelper;

import java.util.*;

public class ConceptMasksAde20k extends AbstractFeatureModule {

  private static final int GRID_PARTITIONS = 32;
  private static final Logger LOGGER = LogManager.getLogger();

  private DeepLab ade20k;

  public ConceptMasksAde20k() {
    super("features_conceptmasksade20k", 1, GRID_PARTITIONS * GRID_PARTITIONS * 2);
    this.correspondence = CorrespondenceFunction.hyperbolic(2000);

  }

  private static List<DeepLabLabel> linearize(DeepLabLabel[][] labels) {
    ArrayList<DeepLabLabel> list = new ArrayList<>(labels.length * labels[0].length);
    for (int i = 0; i < labels.length; ++i) {
      for (int j = 0; j < labels[0].length; ++j) {
        list.add(labels[i][j]);
      }
    }
    return list;
  }

  @Override
  public synchronized void processSegment(SegmentContainer shot) {

    if (shot == null || shot.getMostRepresentativeFrame() == null
        || shot.getMostRepresentativeFrame().getImage() == null
        || shot.getMostRepresentativeFrame().getImage() == VideoFrame.EMPTY_VIDEO_FRAME) {
      return;
    }

    if(this.ade20k == null){
      try{
        this.ade20k = new DeepLabAde20k();
      }catch (RuntimeException e){
        LOGGER.error(LogHelper.getStackTrace(e));
        return;
      }
    }

    Tensor<UInt8> inputTensor = DeepLab
        .prepareImage(shot.getMostRepresentativeFrame().getImage().getBufferedImage());

    int[][] tmp = this.ade20k.processImage(inputTensor);

    List<DeepLabLabel> ade20kLabels = linearize(
        DeepLabLabel.fromAde20kId(tmp));

    inputTensor.close();

    ArrayList<LinkedList<DeepLabLabel>> ade20kPartitions = GridPartitioner
        .partition(ade20kLabels, tmp.length, tmp[0].length, GRID_PARTITIONS, GRID_PARTITIONS);

    float[] vector = new float[2 * GRID_PARTITIONS * GRID_PARTITIONS];

    for (int i = 0; i < GRID_PARTITIONS * GRID_PARTITIONS; ++i) {
      DeepLabLabel dominantLabel = DeepLabLabel.getDominantLabel(ade20kPartitions.get(i));
      vector[2 * i] = dominantLabel.getEmbeddX();
      vector[2 * i + 1] = dominantLabel.getEmbeddY();

    }

    persist(shot.getId(), new FloatVectorImpl(vector));
  }

  @Override
  public List<ScoreElement> getSimilar(SegmentContainer sc, ReadableQueryConfig qc) {

    Optional<SemanticMap> optional = sc.getSemanticMap();
    if (!optional.isPresent()){
      return Collections.emptyList();
    }

    DeepLabLabel[][] labels = optional.get().getLabels();

    List<DeepLabLabel> list = linearize(labels);

    ArrayList<LinkedList<DeepLabLabel>> ade20kPartitions = GridPartitioner
        .partition(list, labels.length, labels[0].length, GRID_PARTITIONS, GRID_PARTITIONS);

    float[] vector = new float[2 * GRID_PARTITIONS * GRID_PARTITIONS];
    float[] weights = new float[2 * GRID_PARTITIONS * GRID_PARTITIONS];

    for (int i = 0; i < GRID_PARTITIONS * GRID_PARTITIONS; ++i) {
      DeepLabLabel dominantLabel = DeepLabLabel.getDominantLabel(ade20kPartitions.get(i));
      float weight = dominantLabel == DeepLabLabel.NOTHING ? 0f : 1f; //TODO expose this to the API
      weights[2 * i] = weight;
      weights[2 * i + 1] = weight;
      vector[2 * i] = dominantLabel.getEmbeddX();
      vector[2 * i + 1] = dominantLabel.getEmbeddY();

    }
    return this.getSimilar(vector, new QueryConfig(qc).setDistanceWeights(weights));

  }

}


text:
class AColorDialogForm : public AForm
{
	CLASS_INFO(ColorDialogForm,Form);
public:
	AColorDialogForm(AComponent* pOwner);
	virtual ~AColorDialogForm();

	virtual void InitControls();
	virtual void ConnectEvent();
	virtual void TitleBackDoMouseDown(AObject* pSender,AEvent* pEvent);
	virtual void TitleBackDoMouseMove(AObject* pSender,AEvent* pEvent);
	virtual void OnOKClick(AObject* pSender,AEvent* pEvent);
	virtual void OnCancelClick(AObject* pSender,AEvent* pEvent);

	virtual void DoCreate();
	void CreateFromXML();

	MAP_CONTROL(AButton,OK);
	MAP_CONTROL(AButton,Cancel);

	MAP_CONTROL(AContainer,ButtonsPanel);
	MAP_CONTROL(ATitleBar,TitleBar);
	MAP_CONTROL(AVertSlide,ColorSelector);
	MAP_CONTROL(AContainer,SLSelector);
	MAP_CONTROL(AContainer,BaseColorContainer);
	MAP_CONTROL(ALabel,HexColor);
	MAP_CONTROL(AHorzSlide,RSlide);
	MAP_CONTROL(AHorzSlide,GSlide);
	MAP_CONTROL(AHorzSlide,BSlide);
	MAP_CONTROL(AEdit,REdit);
	MAP_CONTROL(AEdit,GEdit);
	MAP_CONTROL(AEdit,BEdit);
	MAP_CONTROL(AHorzSlide,HSlide);
	MAP_CONTROL(AHorzSlide,SSlide);
	MAP_CONTROL(AHorzSlide,LSlide);
	MAP_CONTROL(AEdit,HEdit);
	MAP_CONTROL(AEdit,SEdit);
	MAP_CONTROL(AEdit,LEdit);

	TDialogButton *m_nButtonID;
	AColor*		m_pColor;

private:
	AColor		m_Color;
	AColorHSL	m_HSLColor;

	bool		m_bDisableChange;//½ûÖ¹´¥·¢OnChange

	void InitColorControl();

	void OnColorSelectorPaint(AObject* pSender,AEvent* pEvent);
	void OnColorSelectorMouseDown(AObject* pSender,AEvent* pEvent);
	void OnSLPaint(AObject* pSender,AEvent* pEvent);
	void OnSLMouseDown(AObject* pSender,AEvent* pEvent);
	void OnSLMouseMove(AObject* pSender,AEvent* pEvent);
	void OnColorScroll(AObject* pSender,AEvent* pEvent);
	void OnBaseColorButtonPaint(AObject* pSender,AEvent* pEvent);
	void OnColorDiffButtonPaint(AObject* pSender,AEvent* pEvent);
	void OnEditChange(AObject* pSender,AEvent* pEvent);
	void OnSlideChange(AObject* pSender,AEvent* pEvent);
	void OnBaseColorClick(AObject* pSender,AEvent* pEvent);

	void _initSlide(AHorzSlide* pSlide,int iRange);

	void _updateRGB();
	void _updateHSL();
	void _updateHSLSlide();
};

#endif//ACOLORDIALOGFORM_H


text:
/**
 * Starts listening to user input and fetches user input string.
 * Defines sessionId global variable and function to call when window closes.
 */

const mainSection = document.querySelector('.main-controls');
const formContainer = document.getElementsByName('input-form')[0];
const textInputContainer = document.getElementById("text-input");
var sessionId = "";
var queryNumber = 0;
window.onbeforeunload = deleteSessionInformation;
var isUserLoggedIn = false;
var userPhoto = "images/android.png";

var pastCommands = loadCommands();
var commandIndex = pastCommands.length;
var unsentLastCommand;

/**
 * Function triggered with each character typed in the text input container that handles
 * submitting the text input on the RETURN key, getting the command used before with the
 * UP key, and getting the command used after with the DOWN key (same basic functionality
 * as in terminal).
 *
 * @param e The key pressed.
 */
formContainer.onkeyup = function(e){
  if(e.keyCode == 13 && !isEmptyString(textInputContainer.value)) { //return key and non-empty input
    getResponseFromText();
  } else if(e.keyCode == 38) { //up arrow key
    if (commandIndex == 0) {
      return;
    }
    if (commandIndex == pastCommands.length) {
      unsentLastCommand = textInputContainer.value;
    }
    commandIndex --;
    textInputContainer.value = pastCommands[commandIndex].trim();
  } else if(e.keyCode == 40) { //down arrow key
    if (commandIndex == pastCommands.length) {
      return;
    }
    commandIndex ++;
    if (commandIndex == pastCommands.length) {
      textInputContainer.value = (unsentLastCommand == null) ? "" : unsentLastCommand;
    } else {
      textInputContainer.value = pastCommands[commandIndex].trim();
    }
  }
};

window.onresize = function() {
  canvas.width = mainSection.offsetWidth;
}

window.onresize();

// Close the liked book dropdown menu if the user presses out of the button
window.onclick = function(event) {
  if (!event.target.matches("[class^=book-button-dropbtn]") &&
      !event.target.matches("[class^=book-dropbtn-logo]")) {
    var dropdowns = document.getElementsByClassName("book-dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        updateDropdownScroll(openDropdown);
        openDropdown.classList.remove('show');
      }
    }
  }
}

/**
 * Retrives the saved language from session storage or English as default.
 *
 * @return The language to use in audio conversation.
 */
function getLanguage() {
  var language = window.sessionStorage.getItem("language");
  language = language == null ? "English" : language;
  return language;
}

/**
 * Backend call to Dialogflow that handles recognizing the user's intent and
 * accomplishing the necessary backend fulfillment to carry out the user's request.
 * Creates an audio output and handles making any displays that are necessary.
 *
 * @param blob Audio file containing the user's entire speech from start to stop recording.
 */
function getResponseFromAudio(blob) {
  const formData = new FormData();
  formData.append('audio-file', blob);
  fetch('/audio-input' + '?language=' + getLanguage() + '&session-id=' + sessionId, {
    method: 'POST',
    body: blob
  }).then(response => response.text()).then(stream => displayResponse(stream));
}

/**
 * Backend call to dialogflow that takes the user's text input from the form container and
 * accomplishes the necessary backend fulfillment to carry out the user's request.
 * Creates an audio output and handles making any displays that are necessary.
 */
function getResponseFromText(){
  var input = textInputContainer.value;
  saveCommand(input);
  unsentLastCommand = null;
  fetch('/text-input?request-input=' + input + '&language=' + getLanguage() + '&session-id=' + sessionId, {
      method: 'POST'
  }).then(response => response.text()).then(stream => displayResponse(stream));
  formContainer.reset();
}

/**
 * Backend call to UserServices to determine if user is logged in and display a personalized greeting.
 */
function authSetup() {
  fetch("/auth").then((response) => response.json()).then((displayText) => {
    var authContainer = document.getElementsByClassName("auth-link")[0];
    authContainer.innerHTML = "" + displayText.logButton + "";
    updateName(displayText.displayName);
    //Checks if user is logged in or not
    if (displayText.logButton == "Logout") {
        isUserLoggedIn = true;
        createWorkoutDashboardButton();
    } else if (displayText.logButton == "Login") {
        isUserLoggedIn = false;
        document.getElementsByClassName("workout-dashboard-link")[0].style.display = "none";
    }
    window.userPhoto = displayText.photoUrl;
    var body = document.body;
    body.insertAdjacentHTML('beforeend', '');
    getSessionID();
    // Clears any stored information in Datastore for this session upon loading
    deleteSessionInformation();
  });
}

/**
 * Saves each command made by the user into a string in session storage so that the user
 * can use the UP/DOWN arrows to access recently used commands.
 *
 * @param text The string command typed by the user.
 */
function saveCommand(text) {
  if (isEmptyString(text)) {
    return;
  }
  var commandHistory = window.sessionStorage.getItem("commandHistory");
  if (commandHistory == null) {
    commandHistory = text;
  } else {
    commandHistory += text;
  }
  pastCommands.push(text);
  commandIndex = pastCommands.length;
  window.sessionStorage.setItem("commandHistory", commandHistory);
}

/**
 * Loads all past commands from the previous session so that user initially
 * has access to their recent past commands.
 */
function loadCommands() {
  var commandHistory = window.sessionStorage.getItem("commandHistory");
  if (commandHistory == null) {
    return [];
  }
  commandHistory = commandHistory.trim();
  return commandHistory.split("\n");
}

/**
 * Checks if a given string is empty.
 *
 * @param text Input string to check
 * @return boolean indicating if the input string is empty
 */
function isEmptyString(text) {
  return text == null || text.trim() === "";
}

/**
 * Retrieves Output object created by BookAgent for the specified bookshelf
 * triggered by a Go To Bookshelf button in the display. Sends stream
 * to generic handler and does not specify a queryID (in order to generate new
 * query)
 *
 * @param intent name of book intent
 * @param bookshelfName bookshelf to retrieve information from
 */
function goToBookshelf(intent, bookshelfName){
  fetch('/book-agent?intent=' + intent + '&language=' + getLanguage() + '&session-id=' + sessionId +
    '&bookshelf=' + bookshelfName, {
      method: 'POST'
  }).then(response => response.text()).then(stream => displayResponse(stream));
}

/**
 * Retrieves Output object created by BookAgent for the specified friend's liked
 * books, triggered by pressing their name in the like list. Sends stream
 * to generic handler and does not specify a queryID (in order to generate new
 * query)
 *
 * @param intent name of book intent
 * @param friend object
 */
function seeFriendsLikedBooks(intent, friend){
  fetch('/book-agent?intent=' + intent + '&language=' + getLanguage() + '&session-id=' + sessionId +
    '&friend=' + friend.name + '&friendObject=' + JSON.stringify(friend), {
      method: 'POST'
  }).then(response => response.text()).then(stream => displayResponse(stream));
}

/**
 * Retrieves Output object created by BookAgent for specified intent
 * triggered by a button the display. Sends stream to generic handler
 * and specifies a queryID to reference stored query.
 *
 * @param intent name of book intent
 * @param queryID queryID for div that triggered button
 */
function getBooksFromButton(intent, queryID){
  fetch('/book-agent?intent=' + intent + '&language=' + getLanguage() + '&session-id=' + sessionId +
    '&query-id=' + queryID, {
      method: 'POST'
  }).then(response => response.text()).then(stream => displayResponse(stream));
}

/**
 * Handles when user hits like button for a book by storing liked book
 * or deleting stored liked book. Function is triggered by like button.
 *
 * @param type either 'like' or 'unlike'
 * @param number index of book to retrieve information for
 * @param queryID queryID for div that triggered button
 */
function handleBookLiked(type, number, queryID) {
  fetch('/book-likes?type=' + type + '&orderNum=' + number + '&query-id=' + queryID, {
      method: 'POST'
  });
}

/**
 * Retrieves list of bookshelves to add the specified volume to
 * based on valid bookshelves for the authenticated user. Function is
 * triggered by a button to add volume to bookshelf
 *
 * @param intent name of book intent
 * @param number index of book to retrieve information for
 * @param queryID queryID for div that triggered button
 */
function getBookshelfNamesFromButton(intent, number, queryID){
  fetch('/book-agent?intent=' + intent + '&language=' + getLanguage() + '&session-id=' + sessionId +
    '&number=' + number + '&query-id=' + queryID, {
      method: 'POST'
  }).then(response => response.text()).then(stream =>displayBookshelvesToAdd(stream, number, queryID));
}

/**
 * Retrieves Output object created by BookAgent for specified information intents.
 * This function is triggered by pressing a button on the display for book
 * description or book previews. The number parameter specifies the Book object number to retrieve.
 *
 * @param intent name of book intent
 * @param number index of book to retrieve information for
 * @param queryID queryID for div that triggered button for information
 */
function getBookInformation(intent, number, queryID){
  fetch('/book-agent?intent=' + intent + '&language=' + getLanguage() + '&session-id=' + sessionId +
    '&number=' + number + '&query-id=' + queryID, {
      method: 'POST'
  }).then(response => response.text()).then(stream => displayResponse(stream));
}

/**
 * Adds or deletes specified book from specified query to specified bookshelf and displays
 * book information afterwards
 *
 * @param intent name of book intent
 * @param bookshelfName name of bookshelf to edit
 * @param number index of book to retrieve information for
 * @param queryID queryID for div that triggered button for information
 */
function editBookshelf(intent, bookshelfName, number, queryID) {
  fetch('/book-agent?intent=' + intent + '&language=' + getLanguage() + '&session-id=' + sessionId +
    '&number=' + number + '&bookshelf=' + bookshelfName + '&query-id=' + queryID, {
      method: 'POST'
  }).then(response => response.text()).then(stream => displayBookAdded(stream, bookshelfName));
}

/**
 * Returns userID, if user is logged in, or guestID for the session otherwise
 */
function getSessionID(){
  fetch('/id').then(response => response.text()).then((id) => {
      window.sessionId = id;
  });
}

/**
 * Deletes all stored Entitys that match current sessionID before
 * users close the page
 */
function deleteSessionInformation(){
  fetch('/id' + '?session-id=' + sessionId, {
      method: 'POST'
  }).then(response => response.text()).then(() => {
      console.log('Deleted comments for ' + sessionId)
  });
}

/** Saves workout plan using SaveWorkoutServlet for current user
 *
 * @param workoutPlan workoutPlan string with userId and workoutPlanId
 */
function saveWorkoutPlan(workoutPlan){

  //Change button text to show user that workout plan has been saved
  var buttonToMark = document.getElementById(workoutPlan.workoutPlanId);
  var oldButtonText = buttonToMark.childNodes[0];

  if (oldButtonText.textContent == "Save Workout Plan") {
    buttonToMark.removeChild(oldButtonText);
    var newButtonText = document.createTextNode("Saved Workout Plan!");
    buttonToMark.appendChild(newButtonText);
  }

  //Create new JSON oject for workout plan to be saved
  var savedWorkoutPlan = new Object();
  savedWorkoutPlan.userId = workoutPlan.userId;
  savedWorkoutPlan.workoutPlanId  = workoutPlan.workoutPlanId;
  var workoutPlanString= JSON.stringify(savedWorkoutPlan);

  fetch('/save-workouts' + '?workout-plan=' + workoutPlanString, {
      method: 'POST'
  }).then(response => response.text()).then(() => {
      console.log('Saved workout plan');
  });
}

/**
 * Updates the scroll of the dropdown menu with each new added element.
 *
 * @param element Div for the dropdown container
 */
function updateDropdownScroll(element) {
  element.scrollTop = 0;
}

/** Saves workout video using SaveVideoServlet for current user
 *
 * @param videos workoutVideo string with userId and videoId
 * @param buttonID Unique ID of the button
 */
function saveWorkoutVideo(videos, buttonId) {

  workoutVideo = videos[parseInt(buttonId)];

  //Change button text to show user that video has been saved
  var buttonToMark = document.getElementById(buttonId);
  var oldButtonText = buttonToMark.childNodes[0];

  if (oldButtonText.textContent == "Save Video") {
    buttonToMark.removeChild(oldButtonText);
    var newButtonText = document.createTextNode("Saved!");
    buttonToMark.appendChild(newButtonText);
  }

  //Create new JSON oject for workout video to be saved
  var savedWorkoutVideo = new Object();
  savedWorkoutVideo.userId = workoutVideo.userId;
  savedWorkoutVideo.videoId  = workoutVideo.videoId;
  var workoutVideoString = JSON.stringify(savedWorkoutVideo);

  fetch('/save-video' + '?workout-video=' + workoutVideoString, {
      method: 'POST'
  }).then(response => response.text()).then(() => {
      console.log('Saved workout video');
  });
}

/**
 * Retrieves the login status of the user
 *
 * @return Boolean indicating if the user is logged in
 */
function getUserLoginStatus() {
    return isUserLoggedIn;
}


text:
package com.amazonaws.services.alexaforbusiness.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.alexaforbusiness.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * SortMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class SortMarshaller {

    private static final MarshallingInfo<String> KEY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Key").build();
    private static final MarshallingInfo<String> VALUE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Value").build();

    private static final SortMarshaller instance = new SortMarshaller();

    public static SortMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Sort sort, ProtocolMarshaller protocolMarshaller) {

        if (sort == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(sort.getKey(), KEY_BINDING);
            protocolMarshaller.marshall(sort.getValue(), VALUE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
'use strict';

angular
  .module('datetimepicker', [])

  .provider('datetimepicker', function () {
    var default_options = {};

    this.setOptions = function (options) {
      default_options = options;
    };

    this.$get = function () {
      return {
        getOptions: function () {
          return default_options;
        }
      };
    };
  })

  .directive('datetimepicker', [
    '$timeout',
    'datetimepicker',
    function ($timeout,
              datetimepicker) {

      var default_options = datetimepicker.getOptions();

      return {
        require : '?ngModel',
        restrict: 'AE',
        scope   : {
          datetimepickerOptions: '@'
        },
        link    : function ($scope, $element, $attrs, ngModelCtrl) {
          var passed_in_options = $scope.$eval($attrs.datetimepickerOptions);
          var options = jQuery.extend({}, default_options, passed_in_options);

          $element
            .on('dp.change', function (e) {
              if (ngModelCtrl) {
                $timeout(function () {
                  ngModelCtrl.$setViewValue(e.target.value);
                });
              }
            })
            .datetimepicker(options);

          function setPickerValue() {
            var date = options.defaultDate || null;

            if (ngModelCtrl && ngModelCtrl.$viewValue) {
              date = ngModelCtrl.$viewValue;
            }

            $element
              .data('DateTimePicker')
              .date(date);
          }

          if (ngModelCtrl) {
            ngModelCtrl.$render = function () {
              setPickerValue();
            };
          }

          setPickerValue();
        }
      };
    }
  ]);


text:
module Codeine
  class Container

    def services
      @services ||= {}
    end

    def filters
      @filters ||= []
    end

    def register(key, &block)
      services[key.to_sym] = block
    end

    def get(key, args = [])
      key = key.to_sym
      service = services[key].call(*args)
      filters.each do |f|
        if key.to_s =~ f[:pattern]
          f[:block].call(key, service)
        end
      end
      service
    end
    alias :[] :get

    def filter(pattern, &block)
      filters.push :pattern => pattern, :block => block
    end

    def configure
      yield self
    end
  end
end


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Dissecting Underscore,  Underscore Explained</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

    		_.max(list, [iteratee], [context])

    		var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
            _.max(stooges, function(stooge){ return stooge.age; });
            => {name: 'curly', age: 60};

			My Solution:

           var stooges = [
                {name: 'moe', age: 40, test : [{name : 'sam'}]},
                {name: 'larry', age: 50},
                {name: 'curly', age: 60}
            ];

            var numbers = [2, 4, 10, 22, 11, 19];

            //Does Shallow check
            function min(list, func, context){
                var value;
                var result;
                //loop through list
                for(var i = 0; i < list.length; i++){
                    debugger;
                    if(func !== void 0 && func.constructor === Function){
                        // if function is passed

                        //Since Context is optional can be undefined, and so checking for undefined,
                        if(context == void 0){
                            var returnedValue;

                            //If undefined then dont pass context
                            //Get value back from function call
                            returnedValue = func.call(list[i]);

                        }else{
                            //for each array value call the function passed in the argument with given context,
                            //Since we need to run this function based on context , we need to use call or apply
                            //For this example i am only using call
                            returnedValue = func.call(context);
                        }

                        //compare which one is smaller
                        if(value === void 0 || value > returnedValue){
                            value = returnedValue;
                            result = list[i];   //saving result
                        }

                    }else{
                        //compare which one is smaller
                        if(value === void 0 || value > list[i]){
                            value = list[i];
                            result = list[i]    //saving result
                        }
                    }

                }

                return result;
            }

            function functionCallback(){
                return this["age"];
            }

            //Calling Method and show output by passing Array
            $(".outputArray output").append(JSON.stringify(min(numbers)).toString());

            //Calling Method and Show Output by passing Array of Objects
            $(".outputObject output").append(JSON.stringify(min(stooges, functionCallback)).toString());

            Output for Array with Context:
            <output>
            </output>

            Output for Object with Context:
            <output>
            </output>

Comments Section

Feel free to comment on the post but keep it clean and on topic.

				Please enable JavaScript to view the comments powered by Disqus.


text:
from time import gmtime, strftime
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import Adam, SGD

import numpy
import imaginet.task as task
import imaginet.defn.audiovis_rhn as audiovis
import sys
import random
import imaginet.vendrov_provider as vdp
import imaginet.data_provider as dp
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

item_count = -1
if len(sys.argv) > 1:
    item_count = int(sys.argv[1])

def applyNeuralNetwork(train_x, train_y, test_x, test_y):
    #print "input shape", train_x.shape

    model = Sequential()

    input_size = len(train_x[0])
    model.add(Dense(1024, input_dim=input_size, init='orthogonal', activation='tanh'))
    model.add(Dense(1, init='orthogonal', activation='sigmoid'))

    # Use ADAM optimizer, setting some extra options
    optimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)

    model.compile(loss='binary_crossentropy', optimizer=optimizer)

    max_acc = 0
    # for j in range(10):
    #     model.fit(train_x, train_y, nb_epoch=(j+1)*10, batch_size=64, verbose=0)
    #     trainprd = (numpy.ndarray.flatten(model.predict(train_x, verbose=0))>=0.5).astype('float32')
    #     prd = (numpy.ndarray.flatten(model.predict(test_x, verbose=0))>=0.5).astype('float32')
    #     max_acc = max(max_acc, numpy.mean(prd==test_y))
    for j in range(10):
        model.fit(train_x, train_y, nb_epoch=10, batch_size=64, verbose=0)
        prd = (numpy.ndarray.flatten(model.predict(test_x, verbose=0))>=0.5).astype('float32')
        acc = numpy.mean(prd==test_y)
        max_acc = max(max_acc, acc)
        print j*10, acc
    return max_acc

def readStopWords():
    stop_words = set()
    inf = open("nltk-stopwords.txt", 'r')
    sw = inf.readline()
    while (sw != ""):
        stop_words.add(sw.strip().lower())
        sw = inf.readline()
    inf.close()
    stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}'])
    return stop_words

def stimuli(features):
    x = []
    for i in range(len(validate)):
        x += [numpy.concatenate((features[i],embeddings_pos[i]),axis=0), numpy.concatenate((features[i],embeddings_neg[i]),axis=0)]
    return numpy.array(x, dtype='float32')

def minall(scores):
    mmin = 1.0
    for x in scores:
        mmin = min(mmin, min(scores[x]))
    return mmin

def maxall(scores):
    mmax = 0.0
    for x in scores:
        mmax = max(mmax, max(scores[x]))
    return mmax

acc = {}
for dataset in ['flickr8k','coco']:
    print ">>>>>>>> DATASET: ", dataset
    savedir = "../data/%s/"%dataset

    print "load the model and the validation dataset..."
    if dataset == 'flickr8k':
        model = task.load("../models/flickr8k-speech.zip")
        prov = dp.getDataProvider('flickr8k', root='..', audio_kind='human.max1K.accel3.ord.mfcc')
    else:
        model = task.load("../models/coco-speech.zip")
        prov = vdp.getDataProvider(dataset='coco', root='..', audio_kind='mfcc')

    validate = list(prov.iterSentences(split='val'))
    data = [ numpy.asarray(sent['audio'], dtype='float32') for sent in validate ]
    val_embeddings = audiovis.encode_sentences(model, data)
    val_states = [ datum.mean(axis=0) for datum in audiovis.iter_layer_states(model, data) ]
    del data

    if item_count > -1:
        validate = validate[:min(item_count,len(validate))]
        val_embeddings = val_embeddings[:min(item_count,len(val_embeddings))]
        val_states = val_states[:min(item_count,len(val_states))]

    #split data into training and test
    sp = 2*len(val_embeddings)*4/5
    print "Train: 1-%d; Test: %d-%d\n"%(sp,sp+1,2*len(val_embeddings))

    ###predict the presence or absence of a word

    # For each sentence, pick a random word as the postive example.
    # Pick a positive example of another sentence as the negative example of the current sentence.
    print "generate positive and negative examples..."
    numpy.random.seed(0)
    random.seed(0)
    stopwords = readStopWords()

    positive = []
    for i in range(len(validate)):
        positem = random.choice(validate[i]['tokens'])
        while (positem.lower() in stopwords):
            positem = random.choice(validate[i]['tokens'])
        positive += [positem]

    negative = []
    pmax = len(validate)
    for i in range(pmax):
        negitem = positive[pmax-i-1]
        while (negitem in validate[i]['tokens']):
            negitem = random.choice(positive)
        negative += [negitem]

    #read synthetic representations of word forms from a file

    print "loading audio features..."

    if dataset == 'flickr8k':
        words=numpy.load(savedir+"words-flickr8k.npy")
        audiofeatures = numpy.load(savedir+"mfcc-flickr8k.npy")
    else:
        words=numpy.load(savedir+"words-coco.npy")
        audiofeatures = numpy.load(savedir+"mfcc-coco.npy")

    lexicon = dict(zip(words, audiofeatures))
    mfcc_pos = [lexicon[w] for w in positive]
    mfcc_neg = [lexicon[w] for w in negative]

    embeddings_pos = audiovis.encode_sentences(model, [ numpy.asarray(x, dtype='float32') for x in mfcc_pos ])
    embeddings_neg = audiovis.encode_sentences(model, [ numpy.asarray(x, dtype='float32') for x in mfcc_neg ])

    acc[dataset] = []

    #Predict the presence of a word in a sentence using a neural network
    y = numpy.array([1,0] * len(validate), dtype='float32')

    #Average input vectors
    x = stimuli([numpy.average(item['audio'],axis=0) for item in validate])
    acc[dataset].append(applyNeuralNetwork(x[0:sp], y[0:sp], x[sp:], y[sp:]))

    layers = val_states[0].shape[0]
    #Average activation units
    for l in range(layers):
        x = stimuli([item[l,:] for item in val_states])
        acc[dataset].append(applyNeuralNetwork(x[0:sp], y[0:sp], x[sp:], y[sp:]))

    #Sentence embeddings
    x = stimuli(val_embeddings)
    acc[dataset].append(applyNeuralNetwork(x[0:sp], y[0:sp], x[sp:], y[sp:]))

    #Average normalized activation units
    #for l in range(layers):
    #    x = stimuli([item[:,l,:].mean(axis=0) for item in val_states])
    #    acc['l2avg'+str(l)] = applyNeuralNetwork(x[0:sp], y[0:sp], x[sp:], y[sp:])
    #Activation units at the last time step
    #for l in range(layers):
    #    x = stimuli([item[-1][l] for item in val_states])
    #    acc['last'+str(l)] = applyNeuralNetwork(x[0:sp], y[0:sp], x[sp:], y[sp:])

clen = len(acc['coco'])
flen = len(acc['flickr8k'])

xaxis = [i for i in range(clen)]

plt.axis([-1,clen,minall(acc)-0.05, maxall(acc)+0.05])
plt.text(clen-1.5, acc['coco'][-1]-0.05, 'embeddings',color='blue')
plt.text(flen-1.5, acc['flickr8k'][-1]-0.05, 'embeddings', color='red')
plt.xlabel("Network layers")
plt.ylabel("Accuracy")

plt.plot(xaxis[0:2],acc['coco'][0:2],'b--')
coco, = plt.plot(xaxis[1:clen-1],acc['coco'][1:clen-1],'b-', label="COCO")
plt.plot(xaxis[clen-2:],acc['coco'][clen-2:],'b--')
plt.plot([clen-1], acc['coco'][-1], 'bo')

plt.plot(xaxis[0:2],acc['flickr8k'][0:2],'r--')
flickr, = plt.plot(xaxis[1:flen-1],acc['flickr8k'][1:flen-1],'r-', label="Flickr8k")
plt.plot(xaxis[flen-2:flen],acc['flickr8k'][flen-2:],'r--')
plt.plot([flen-1], acc['flickr8k'][-1], 'ro')

plt.legend([coco,flickr], ["COCO","Flickr8k"], loc=4)
plt.savefig('predword.pdf')


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Simple.Data.Ado.Schema;
using Simple.Data.Extensions;

namespace Simple.Data.Ado
{
    class Joiner
    {
        private readonly JoinType _joinType;
        private readonly DatabaseSchema _schema;
        private readonly ConcurrentDictionary<string, string> _done = new ConcurrentDictionary<string, string>();

        public Joiner(JoinType joinType, DatabaseSchema schema)
        {
            if (schema == null) throw new ArgumentNullException("schema");
            _joinType = joinType;
            _schema = schema;
        }

        public string GetJoinClauses(string mainTableName, SimpleExpression expression)
        {
            _done.AddOrUpdate(mainTableName, string.Empty, (s, o) => string.Empty);
            var tablePairs = GetTablePairs(expression);
            foreach (var tablePair in tablePairs)
            {
                AddJoin(tablePair.Item1, tablePair.Item2);
            }
            return string.Join(" ", tablePairs.Select(tp => _done[tp.Item2]));
        }

        private void AddJoin(string table1Name, string table2Name)
        {
            var table1 = _schema.FindTable(table1Name);
            var table2 = _schema.FindTable(table2Name);

            var foreignKey =
                table2.ForeignKeys.SingleOrDefault(fk => fk.MasterTable == table1.ActualName)
                ??
                table1.ForeignKeys.SingleOrDefault(fk => fk.MasterTable == table2.ActualName);

            if (foreignKey == null) throw new SchemaResolutionException(
                string.Format("Could not join '{0}' and '{1}'", table1.ActualName, table2.ActualName));

            _done.GetOrAdd(table2Name, s => MakeJoinText(table2, foreignKey));
        }

        private string MakeJoinText(Table rightTable, ForeignKey foreignKey)
        {
            var builder = new StringBuilder(JoinKeyword);
            builder.AppendFormat(" JOIN {0} ON (", rightTable.QuotedName);
            builder.Append(FormatJoinExpression(foreignKey, 0));

            for (int i = 1; i < foreignKey.Columns.Length; i++)
            {
                builder.Append(" AND ");
                builder.Append(FormatJoinExpression(foreignKey, i));
            }
            builder.Append(")");
            return builder.ToString();
        }

        private string FormatJoinExpression(ForeignKey foreignKey, int columnIndex)
        {
            return string.Format("{0}.{1} = {2}.{3}", _schema.QuoteObjectName(foreignKey.MasterTable), _schema.QuoteObjectName(foreignKey.UniqueColumns[columnIndex]),
                                 _schema.QuoteObjectName(foreignKey.DetailTable), _schema.QuoteObjectName(foreignKey.Columns[columnIndex]));
        }

        private string JoinKeyword
        {
            get { return _joinType == JoinType.Inner ? string.Empty : "LEFT"; }
        }

        private static IEnumerable<Tuple<string,string>> GetTablePairs(SimpleExpression expression)
        {
            return GetReferencesFromExpression(expression)
                .SelectMany(dr => dr.GetAllObjectNames().SkipLast().ToTuplePairs())
                .Distinct();
        }

        private static IEnumerable<DynamicReference> GetReferencesFromExpression(SimpleExpression expression)
        {
            if (expression.Type == SimpleExpressionType.And || expression.Type == SimpleExpressionType.Or)
            {
                return GetReferencesFromExpression((SimpleExpression) expression.LeftOperand)
                    .Concat(GetReferencesFromExpression((SimpleExpression) expression.LeftOperand));
            }

            var result = Enumerable.Empty<DynamicReference>();

            if (expression.LeftOperand is DynamicReference)
            {
                result = result.Concat(new[] {(DynamicReference) expression.LeftOperand});
            }
            if (expression.RightOperand is DynamicReference)
            {
                result = result.Concat(new[] { (DynamicReference)expression.RightOperand });
            }

            return result;
        }
    }
}


text:
import Suit from './suit';
import Card from './card';
import Cell from './cell';

class HomeCell implements Cell {
  constructor(
    private suit: Suit,
    private cards: Card[]
  ) {
  }

  getCard(): Card {
    if (this.cards.length === 0) return null;
    return this.cards[this.cards.length - 1];
  }

  getCards(): Card[] {
    return this.cards;
  }

  pop(): HomeCell {
    throw new Error();
  }

  push(newCard: Card): HomeCell {
    if (newCard === null) throw new Error();
    if (newCard.suit !== this.suit) throw new Error();
    const currentCard = this.getCard();
    if (currentCard === null && newCard.number !== 1)
      throw new Error();
    if (currentCard !== null && newCard.number !== currentCard.number + 1)
      throw new Error();
    return new HomeCell(this.suit, this.cards.concat([newCard]));
  }
}

export default HomeCell;


text:
import AuthenticatedRoute from 'ghost/routes/authenticated';

var AppsRoute = AuthenticatedRoute.extend({
    beforeModel: function () {
        if (!this.get('config.apps')) {
            this.transitionTo('settings.general');
        }
    },
    model: function () {
        return this.store.find('app');
    }
});

export default AppsRoute;


text:
'use strict';

const expect = require('chai').expect;
const request = require('request');

const HttpStatus = require('http-status-codes')

const config = require('../config');

describe('Redirect route', () => {
    it('redirection completed', (done) => {
        request.get(`http://${config.base_url}/1`, (err, res, body) => {
            expect(res.statusCode).to.equal(HttpStatus.OK);
            done();
        });
    }).timeout(5000);
});


text:
package org.apache.lucene.index;

import org.apache.lucene.util.*;
import org.apache.lucene.store.*;
import org.apache.lucene.document.*;
import org.apache.lucene.analysis.*;
import org.apache.lucene.search.*;
import org.apache.lucene.queryParser.*;

import java.util.Random;
import java.io.File;
import java.io.IOException;

public class TestAtomicUpdate extends LuceneTestCase {
  private static final Analyzer ANALYZER = new SimpleAnalyzer();
  private Random RANDOM;

  public class MockIndexWriter extends IndexWriter {

    public MockIndexWriter(Directory dir, Analyzer a, boolean create, IndexWriter.MaxFieldLength mfl) throws IOException {
      super(dir, a, create, mfl);
    }

    @Override
    boolean testPoint(String name) {
      //      if (name.equals("startCommit")) {
      if (RANDOM.nextInt(4) == 2)
        Thread.yield();
      return true;
    }
  }

  private static abstract class TimedThread extends Thread {
    boolean failed;
    int count;
    private static int RUN_TIME_SEC = 3;
    private TimedThread[] allThreads;

    abstract public void doWork() throws Throwable;

    TimedThread(TimedThread[] threads) {
      this.allThreads = threads;
    }

    @Override
    public void run() {
      final long stopTime = System.currentTimeMillis() + 1000*RUN_TIME_SEC;

      count = 0;

      try {
        while(System.currentTimeMillis() < stopTime && !anyErrors()) {
          doWork();
          count++;
        }
      } catch (Throwable e) {
        System.out.println(Thread.currentThread().getName() + ": exc");
        e.printStackTrace(System.out);
        failed = true;
      }
    }

    private boolean anyErrors() {
      for(int i=0;i<allThreads.length;i++)
        if (allThreads[i] != null && allThreads[i].failed)
          return true;
      return false;
    }
  }

  private static class IndexerThread extends TimedThread {
    IndexWriter writer;
    public int count;

    public IndexerThread(IndexWriter writer, TimedThread[] threads) {
      super(threads);
      this.writer = writer;
    }

    @Override
    public void doWork() throws Exception {
      // Update all 100 docs...
      for(int i=0; i<100; i++) {
        Document d = new Document();
        d.add(new Field("id", Integer.toString(i), Field.Store.YES, Field.Index.NOT_ANALYZED));
        d.add(new Field("contents", English.intToEnglish(i+10*count), Field.Store.NO, Field.Index.ANALYZED));
        writer.updateDocument(new Term("id", Integer.toString(i)), d);
      }
    }
  }

  private static class SearcherThread extends TimedThread {
    private Directory directory;

    public SearcherThread(Directory directory, TimedThread[] threads) {
      super(threads);
      this.directory = directory;
    }

    @Override
    public void doWork() throws Throwable {
      IndexReader r = IndexReader.open(directory, true);
      assertEquals(100, r.numDocs());
      r.close();
    }
  }

  /*
    Run one indexer and 2 searchers against single index as
    stress test.
  */
  public void runTest(Directory directory) throws Exception {

    TimedThread[] threads = new TimedThread[4];

    IndexWriter writer = new MockIndexWriter(directory, ANALYZER, true, IndexWriter.MaxFieldLength.UNLIMITED);
    writer.setMaxBufferedDocs(7);
    writer.setMergeFactor(3);

    // Establish a base index of 100 docs:
    for(int i=0;i<100;i++) {
      Document d = new Document();
      d.add(new Field("id", Integer.toString(i), Field.Store.YES, Field.Index.NOT_ANALYZED));
      d.add(new Field("contents", English.intToEnglish(i), Field.Store.NO, Field.Index.ANALYZED));
      if ((i-1)%7 == 0) {
        writer.commit();
      }
      writer.addDocument(d);
    }
    writer.commit();

    IndexReader r = IndexReader.open(directory, true);
    assertEquals(100, r.numDocs());
    r.close();

    IndexerThread indexerThread = new IndexerThread(writer, threads);
    threads[0] = indexerThread;
    indexerThread.start();

    IndexerThread indexerThread2 = new IndexerThread(writer, threads);
    threads[1] = indexerThread2;
    indexerThread2.start();

    SearcherThread searcherThread1 = new SearcherThread(directory, threads);
    threads[2] = searcherThread1;
    searcherThread1.start();

    SearcherThread searcherThread2 = new SearcherThread(directory, threads);
    threads[3] = searcherThread2;
    searcherThread2.start();

    indexerThread.join();
    indexerThread2.join();
    searcherThread1.join();
    searcherThread2.join();

    writer.close();

    assertTrue("hit unexpected exception in indexer", !indexerThread.failed);
    assertTrue("hit unexpected exception in indexer2", !indexerThread2.failed);
    assertTrue("hit unexpected exception in search1", !searcherThread1.failed);
    assertTrue("hit unexpected exception in search2", !searcherThread2.failed);
    //System.out.println("    Writer: " + indexerThread.count + " iterations");
    //System.out.println("Searcher 1: " + searcherThread1.count + " searchers created");
    //System.out.println("Searcher 2: " + searcherThread2.count + " searchers created");
  }

  /*
    Run above stress test against RAMDirectory and then
    FSDirectory.
  */
  public void testAtomicUpdates() throws Exception {
    RANDOM = newRandom();
    Directory directory;

    // First in a RAM directory:
    directory = new MockRAMDirectory();
    runTest(directory);
    directory.close();

    // Second in an FSDirectory:
    File dirPath = _TestUtil.getTempDir("lucene.test.atomic");
    directory = FSDirectory.open(dirPath);
    runTest(directory);
    directory.close();
    _TestUtil.rmDir(dirPath);
  }
}


text:
package com.mgireesh;

public class Solution {
	public boolean isSymmetric(TreeNode root) {
		if ((root == null) || ((root.left == null) && (root.right == null))) {
			return true;
		}

		return isSymmetric(root.left, root.right);
	}

	public boolean isSymmetric(TreeNode left, TreeNode right) {
		if ((left == null) && (right == null)) {
			return true;
		}

		if (((null == left) && (null != right)) || ((null != left) && (null == right))) {
			return false;
		}

		return ((left.val == right.val) && (isSymmetric(left.left, right.right))
				&& (isSymmetric(left.right, right.left)));
	}
}


text:
package org.apache.geode.distributed.internal;

import org.apache.logging.log4j.Logger;

import org.apache.geode.admin.GemFireHealth;
import org.apache.geode.admin.GemFireHealthConfig;
import org.apache.geode.admin.internal.GemFireHealthEvaluator;
import org.apache.geode.annotations.internal.MakeNotStatic;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.admin.remote.HealthListenerMessage;
import org.apache.geode.logging.internal.executors.LoggingThread;
import org.apache.geode.logging.internal.log4j.api.LogService;

/**
 * Implements a thread that monitors the health of the vm it lives in.
 *
 * @since GemFire 3.5
 */
public class HealthMonitorImpl implements HealthMonitor, Runnable {
  private static final Logger logger = LogService.getLogger();

  private final InternalDistributedMember owner;
  private final int id;
  private final ClusterDistributionManager dm;
  private final GemFireHealthEvaluator eval;

  /**
   * The current health status
   *
   * @see GemFireHealth#OKAY_HEALTH
   */
  private GemFireHealth.Health currentStatus;
  private final Thread t;
  private volatile boolean stopRequested = false;

  @MakeNotStatic
  private static int idCtr = 0;

  /* Constructors */
  /*
   * Creates a health monitor given its owner, configuration, and its dm
   */
  public HealthMonitorImpl(InternalDistributedMember owner, GemFireHealthConfig config,
      ClusterDistributionManager dm) {
    this.owner = owner;
    this.id = getNewId();
    this.dm = dm;
    this.eval = new GemFireHealthEvaluator(config, dm);
    this.currentStatus = GemFireHealth.GOOD_HEALTH;
    String threadName = String.format("Health Monitor owned by %s", owner);
    this.t = new LoggingThread(threadName, this);
  }

  /************** HealthMonitor interface implementation ******************/
  @Override
  public int getId() {
    return this.id;
  }

  @Override
  public void resetStatus() {
    this.currentStatus = GemFireHealth.GOOD_HEALTH;
    this.eval.reset();
  }

  @Override
  public String[] getDiagnosis(GemFireHealth.Health healthCode) {
    return this.eval.getDiagnosis(healthCode);
  }

  @Override
  public void stop() {
    if (this.t.isAlive()) {
      this.stopRequested = true;
      this.t.interrupt();
    }
  }

  /* HealthMonitorImpl public methods */
  /**
   * Starts the monitor so that it will periodically do health checks.
   */
  public void start() {
    if (this.stopRequested) {
      throw new RuntimeException(
          "A health monitor can not be started once it has been stopped");
    }
    if (this.t.isAlive()) {
      // it is already running
      return;
    }
    this.t.start();
  }

  /* Runnable interface implementation */

  @Override
  public void run() {
    final int sleepTime = this.eval.getEvaluationInterval() * 1000;
    if (logger.isDebugEnabled()) {
      logger.debug("Starting health monitor.  Health will be evaluated every {} seconds.",
          (sleepTime / 1000));
    }
    try {
      while (!this.stopRequested) {
        // SystemFailure.checkFailure(); dm's stopper will do this
        this.dm.getCancelCriterion().checkCancelInProgress(null);
        Thread.sleep(sleepTime);
        if (!this.stopRequested) {
          GemFireHealth.Health newStatus = this.eval.evaluate();
          if (newStatus != this.currentStatus) {
            this.currentStatus = newStatus;
            HealthListenerMessage msg = HealthListenerMessage.create(getId(), newStatus);
            msg.setRecipient(this.owner);
            this.dm.putOutgoing(msg);
          }
        }
      }

    } catch (InterruptedException ex) {
      // No need to reset interrupt bit, we're exiting.
      if (!this.stopRequested) {
        logger.warn("Unexpected stop of health monitor", ex);
      }
    } finally {
      this.eval.close();
      this.stopRequested = true;
      if (logger.isDebugEnabled()) {
        logger.debug("Stopping health monitor");
      }
    }
  }

  /********** Internal implementation **********/

  private static synchronized int getNewId() {
    idCtr += 1;
    return idCtr;
  }

}


text:
package com.amazonaws.services.ec2.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * DescribeImportImageTasksRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeImportImageTasksRequestMarshaller implements Marshaller<Request<DescribeImportImageTasksRequest>, DescribeImportImageTasksRequest> {

    public Request<DescribeImportImageTasksRequest> marshall(DescribeImportImageTasksRequest describeImportImageTasksRequest) {

        if (describeImportImageTasksRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<DescribeImportImageTasksRequest> request = new DefaultRequest<DescribeImportImageTasksRequest>(describeImportImageTasksRequest, "AmazonEC2");
        request.addParameter("Action", "DescribeImportImageTasks");
        request.addParameter("Version", "2016-11-15");
        request.setHttpMethod(HttpMethodName.POST);

        com.amazonaws.internal.SdkInternalList<String> describeImportImageTasksRequestImportTaskIdsList = (com.amazonaws.internal.SdkInternalList<String>) describeImportImageTasksRequest
                .getImportTaskIds();
        if (!describeImportImageTasksRequestImportTaskIdsList.isEmpty() || !describeImportImageTasksRequestImportTaskIdsList.isAutoConstruct()) {
            int importTaskIdsListIndex = 1;

            for (String describeImportImageTasksRequestImportTaskIdsListValue : describeImportImageTasksRequestImportTaskIdsList) {
                if (describeImportImageTasksRequestImportTaskIdsListValue != null) {
                    request.addParameter("ImportTaskId." + importTaskIdsListIndex,
                            StringUtils.fromString(describeImportImageTasksRequestImportTaskIdsListValue));
                }
                importTaskIdsListIndex++;
            }
        }

        if (describeImportImageTasksRequest.getNextToken() != null) {
            request.addParameter("NextToken", StringUtils.fromString(describeImportImageTasksRequest.getNextToken()));
        }

        if (describeImportImageTasksRequest.getMaxResults() != null) {
            request.addParameter("MaxResults", StringUtils.fromInteger(describeImportImageTasksRequest.getMaxResults()));
        }

        com.amazonaws.internal.SdkInternalList<Filter> describeImportImageTasksRequestFiltersList = (com.amazonaws.internal.SdkInternalList<Filter>) describeImportImageTasksRequest
                .getFilters();
        if (!describeImportImageTasksRequestFiltersList.isEmpty() || !describeImportImageTasksRequestFiltersList.isAutoConstruct()) {
            int filtersListIndex = 1;

            for (Filter describeImportImageTasksRequestFiltersListValue : describeImportImageTasksRequestFiltersList) {

                if (describeImportImageTasksRequestFiltersListValue.getName() != null) {
                    request.addParameter("Filters." + filtersListIndex + ".Name",
                            StringUtils.fromString(describeImportImageTasksRequestFiltersListValue.getName()));
                }

                com.amazonaws.internal.SdkInternalList<String> filterValuesList = (com.amazonaws.internal.SdkInternalList<String>) describeImportImageTasksRequestFiltersListValue
                        .getValues();
                if (!filterValuesList.isEmpty() || !filterValuesList.isAutoConstruct()) {
                    int valuesListIndex = 1;

                    for (String filterValuesListValue : filterValuesList) {
                        if (filterValuesListValue != null) {
                            request.addParameter("Filters." + filtersListIndex + ".Value." + valuesListIndex, StringUtils.fromString(filterValuesListValue));
                        }
                        valuesListIndex++;
                    }
                }
                filtersListIndex++;
            }
        }

        return request;
    }

}


text:
<?php
/*
Default Template For bbPress
*/
get_header(); ?>

	<?php /* Start loop */ ?>
	<?php while (have_posts()) : the_post(); ?>
		<article <?php post_class() ?> id="post-<?php the_ID(); ?>">

<?php the_title(); ?>

				<?php the_content(); ?>

	<?php endwhile; // End the loop ?>

<?php get_footer(); ?>


text:
import {
  getScrollingElement,
  getSlides,
} from './helpers';

describes.endtoend('AMP carousel grouping', {
}, async env => {
  const pageWidth = 800;
  const pageHeight = 600;
  const slideWidth = pageWidth / 2;
  let controller;
  let ampDriver;

  function rect(el) {
    return controller.getElementRect(el);
  }

  beforeEach(async() => {
    controller = env.controller;
    ampDriver = env.ampDriver;

    await controller.navigateTo(
        'http://localhost:8000/test/manual/amp-carousel-0-2/grouping-move-by-2.amp.html');
    await ampDriver.toggleExperiment('layers', true);
    await ampDriver.toggleExperiment('amp-carousel-v2', true);
    await controller.setWindowRect({
      width: pageWidth,
      height: pageHeight,
    });
    await controller.navigateTo(
        'http://localhost:8000/test/manual/amp-carousel-0-2/grouping-move-by-2.amp.html');
  });

  describe('snapping', () => {
    it('should snap on next group when past the midpoint', async() => {
      const el = await getScrollingElement(controller);
      const slides = await getSlides(controller);

      await controller.scrollBy(el, {left: slideWidth + 1});
      await expect(rect(slides[2])).to.include({x: 0});
    });

    // TODO(sparhami) It seems like scrolling by even 1 pixel using scrollBy
    // causes snap now. Need touch event support to actually simulate the  user
    // scrolling.
    it.skip('should snap on current group when before the midpoint',
        async() => {
          const el = await getScrollingElement(controller);
          const slides = await getSlides(controller);

          await controller.scrollBy(el, {left: slideWidth - 1});
          await expect(rect(slides[0])).to.include({x: 0});
        });
  });

  describe('advancing', () => {
    it('should move forwards by the advance-count', async() => {
      const slides = await getSlides(controller);
      const btn = await controller.findElement('[on="tap:carousel-1.next()"]');

      await controller.click(btn);
      await expect(rect(slides[2])).to.include({x: 0});
      await controller.click(btn);
      await expect(rect(slides[4])).to.include({x: 0});
      await controller.click(btn);
      await expect(rect(slides[0])).to.include({x: 0});
    });

    it('should move backwards by the advance-count', async() => {
      const slides = await getSlides(controller);
      const btn = await controller.findElement('[on="tap:carousel-1.prev()"]');

      await controller.click(btn);
      await expect(rect(slides[4])).to.include({x: 0});
      await controller.click(btn);
      await expect(rect(slides[2])).to.include({x: 0});
      await controller.click(btn);
      await expect(rect(slides[0])).to.include({x: 0});
    });
  });
});


text:
void hs_nettle_cfb_encrypt(void *ctx, nettle_crypt_func *f,
	unsigned block_size, uint8_t *iv,
	unsigned length, uint8_t *dst,
	const uint8_t *src) {
	unsigned i;

	if (0 == length) return;
	assert(0 != block_size && length % block_size == 0);

	f(ctx, block_size, dst, iv);
	memxor(dst, src, block_size);
	for (i = block_size; i < length; i += block_size) {
		f(ctx, block_size, dst + i, dst + i - block_size);
		memxor(dst +i , src + i, block_size);
	}
}

void hs_nettle_cfb_decrypt(void *ctx, nettle_crypt_func *f,
	unsigned block_size, uint8_t *iv,
	unsigned length, uint8_t *dst,
	const uint8_t *src) {
	unsigned i;

	if (0 == length) return;
	assert(0 != block_size && length % block_size == 0);

	f(ctx, block_size, dst, iv);
	memxor(dst, src, block_size);
	for (i = block_size; i < length; i += block_size) {
		f(ctx, block_size, dst + i, src + i - block_size);
		memxor(dst +i , src + i, block_size);
	}
}

void hs_nettle_aes128_init(struct hs_aes128_ctx *ctx, const char *key) {
	aes128_set_encrypt_key(&ctx->encrypt, key);
	aes128_invert_key(&ctx->decrypt, &ctx->encrypt);
}

void hs_nettle_aes192_init(struct hs_aes192_ctx *ctx, const char *key) {
	aes192_set_encrypt_key(&ctx->encrypt, key);
	aes192_invert_key(&ctx->decrypt, &ctx->encrypt);
}

void hs_nettle_aes256_init(struct hs_aes256_ctx *ctx, const char *key) {
	aes256_set_encrypt_key(&ctx->encrypt, key);
	aes256_invert_key(&ctx->decrypt, &ctx->encrypt);
}

void hs_nettle_aes_init(struct hs_aes_ctx *ctx, unsigned int key_size, const char *key) {
	assert(16 == key_size || 24 == key_size || 32 == key_size);

	switch (key_size) {
	case 16:
		ctx->selector = AES128;
		aes128_set_encrypt_key(&ctx->encrypt.inner128, key);
		aes128_invert_key(&ctx->decrypt.inner128, &ctx->encrypt.inner128);
		break;
	case 24:
		ctx->selector = AES192;
		aes192_set_encrypt_key(&ctx->encrypt.inner192, key);
		aes192_invert_key(&ctx->decrypt.inner192, &ctx->encrypt.inner192);
		break;
	case 32:
		ctx->selector = AES256;
		aes256_set_encrypt_key(&ctx->encrypt.inner256, key);
		aes256_invert_key(&ctx->decrypt.inner256, &ctx->encrypt.inner256);
		break;
	}
}

void hs_nettle_aes_encrypt(const struct hs_aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) {
	switch (ctx->selector) {
	case AES128:
		aes128_encrypt(&ctx->encrypt.inner128, length, dst, src);
		break;
	case AES192:
		aes192_encrypt(&ctx->encrypt.inner192, length, dst, src);
		break;
	case AES256:
		aes256_encrypt(&ctx->encrypt.inner256, length, dst, src);
		break;
	}
}

void hs_nettle_aes_decrypt(const struct hs_aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) {
	switch (ctx->selector) {
	case AES128:
		aes128_decrypt(&ctx->decrypt.inner128, length, dst, src);
		break;
	case AES192:
		aes192_decrypt(&ctx->decrypt.inner192, length, dst, src);
		break;
	case AES256:
		aes256_decrypt(&ctx->decrypt.inner256, length, dst, src);
		break;
	}
}

void hs_nettle_camellia128_init(struct hs_camellia128_ctx *ctx, const char *key) {
	camellia128_set_encrypt_key(&ctx->encrypt, key);
	camellia128_invert_key(&ctx->decrypt, &ctx->encrypt);
}

void hs_nettle_camellia192_init(struct hs_camellia192_ctx *ctx, const char *key) {
	camellia192_set_encrypt_key(&ctx->encrypt, key);
	camellia192_invert_key(&ctx->decrypt, &ctx->encrypt);
}

void hs_nettle_camellia256_init(struct hs_camellia256_ctx *ctx, const char *key) {
	camellia256_set_encrypt_key(&ctx->encrypt, key);
	camellia256_invert_key(&ctx->decrypt, &ctx->encrypt);
}

void hs_nettle_camellia_init(struct hs_camellia_ctx *ctx, unsigned int key_size, const char *key) {
	assert(16 == key_size || 24 == key_size || 32 == key_size);

	switch (key_size) {
	case 16:
		ctx->selector = CAMELLIA128;
		camellia128_set_encrypt_key(&ctx->encrypt.inner128, key);
		camellia128_invert_key(&ctx->decrypt.inner128, &ctx->encrypt.inner128);
		break;
	case 24:
		ctx->selector = CAMELLIA192;
		camellia192_set_encrypt_key(&ctx->encrypt.inner192, key);
		camellia192_invert_key(&ctx->decrypt.inner192, &ctx->encrypt.inner192);
		break;
	case 32:
		ctx->selector = CAMELLIA256;
		camellia256_set_encrypt_key(&ctx->encrypt.inner256, key);
		camellia256_invert_key(&ctx->decrypt.inner256, &ctx->encrypt.inner256);
		break;
	}
}

void hs_nettle_camellia_encrypt(const struct hs_camellia_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) {
	switch (ctx->selector) {
	case CAMELLIA128:
		camellia128_crypt(&ctx->encrypt.inner128, length, dst, src);
		break;
	case CAMELLIA192:
		camellia192_crypt(&ctx->encrypt.inner192, length, dst, src);
		break;
	case CAMELLIA256:
		camellia256_crypt(&ctx->encrypt.inner256, length, dst, src);
		break;
	}
}

void hs_nettle_camellia_decrypt(const struct hs_camellia_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) {
	switch (ctx->selector) {
	case CAMELLIA128:
		camellia128_crypt(&ctx->decrypt.inner128, length, dst, src);
		break;
	case CAMELLIA192:
		camellia192_crypt(&ctx->decrypt.inner192, length, dst, src);
		break;
	case CAMELLIA256:
		camellia256_crypt(&ctx->decrypt.inner256, length, dst, src);
		break;
	}
}


text:
package org.gluu.model;

public class TrustContact implements java.io.Serializable {

    private static final long serialVersionUID = -3268590744030750954L;
    private String name;
    private String phone;
    private String mail;
    private String title;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public boolean equals(Object o) {
        boolean result = (o instanceof TrustContact);
        if (result) {
            TrustContact contact = (TrustContact) o;
            result &= contact.getName() == name || contact.getName().equals(name);
            result &= contact.getTitle() == title || contact.getTitle().equals(title);
            result &= contact.getMail() == mail || contact.getMail().equals(mail);
            result &= contact.getPhone() == phone || contact.getPhone().equals(phone);
        }
        return result;
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

}


text:
package _19June2016;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class P02CubicsRube {
    public static void main(String[] args) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        int side = Integer.parseInt(reader.readLine());
        int changedCells = 0;
        long sumChanges = 0;
        List<String> hitCells = new ArrayList<>();
        while (true) {
            String[] particle = reader.readLine().split("\\s+");
            if ("Analyze".equalsIgnoreCase(particle[0])) {
                break;
            }

            int x = Integer.parseInt(particle[0]);
            int y = Integer.parseInt(particle[1]);
            int z = Integer.parseInt(particle[2]);

            if (x >= 0 && x < side && y >= 0 && y < side && z >= 0 && z < side) {

                String coordinates = particle[0] + " " + particle[1] + " " + particle[2];
                if (hitCells.contains(coordinates)) {
                    continue;
                }

                hitCells.add(coordinates);

                int change = Integer.parseInt(particle[3]);
                if (change != 0) {
                    changedCells++;
                }
                sumChanges += change;
            }
        }

        int numberOfUnchangedCells = (side * side * side) - changedCells;
        System.out.println(sumChanges);
        System.out.println(numberOfUnchangedCells);
    }
}


text:
import draco2
from draco2.locale.exception import LocaleError
from draco2.locale.translator import Translator, DummyTranslator
from draco2.locale.data import LocaleData
from draco2.locale import util, format as locfmt

def tr(message, context=None, name=None):
    """Translate a string `message' using the current locale, if available."""
    try:
        return draco2.api.locale.translate(message, context, name)
    except AttributeError:
        return message

def tr_attr(object, attribute):
    """Translate `attribute' of `object' using a named message."""
    message = object[attribute]
    if not message:
        return ''
    objectid = object._object_id()
    if objectid is not None:
        name = '%s.%s' % (objectid, attribute)
    else:
        name = None
    return tr(message, name=name)

def tr_mark(s):
    """Mark a string for translation and return it unchanged."""
    return s

class Locale(object):
    """The Locale object.

    The Locale object implements Draco's L10N/I18n
    (localisation/internationalisation) subsystem.
    """

    default = 'en-us'

    def __init__(self, data, locale=None, translator=None):
        """Constructor."""
        self.m_locale = None
        self._set_locale_data(data)
        if translator is None:
            translator = DummyTranslator()
        self._set_translator(translator)
        self.set_locale(locale)

    def _set_locale_data(self, data):
        """Set the locale data base to `data'."""
        if not isinstance(data, LocaleData):
            raise TypeError, 'Expecting LocaleData instance.'
        self.m_locale_data = data

    def _set_translator(self, translator):
        """Set the translator."""
        if not isinstance(translator, Translator):
            raise TypeError, 'Expecting Translator instance.'
        self.m_translator = translator

    def set_locale(self, locale=None):
        """Set the locale to `locale'."""
        if not locale:
            locale = self.default
        if locale == self.m_locale:
            return
        if locale not in self.m_locale_data.sections():
            raise LocaleError, 'Unknown locale: %s' % locale
        self.m_locale = locale
        language, territory = util.parse_locale(self.m_locale)
        self.m_language = language
        self.m_territory = territory
        self.m_languages = (self.m_locale, self.m_language)
        self.m_conventions = {}
        self.m_conventions.update(self.m_locale_data.namespace(self.m_territory))
        self.m_conventions.update(self.m_locale_data.namespace(self.m_locale))

    def locale(self):
        """Return the current locale."""
        return self.m_locale

    def language(self):
        """Return the current language, as parsed from the locale."""
        return self.m_language

    def territory(self):
        """Return the current country, as parsed from the locale."""
        return self.m_country

    def languages(self):
        """Return the language search path."""
        return self.m_languages

    def localeconv(self):
        """Return a dictionary with locale conventions."""
        return self.m_conventions

    langinfo = localeconv

    def translate(self, message, context=None, name=None):
        """Translate a string `message'."""
        message = self.m_translator.translate(message, self.languages(),
                                              context, name)
        return message

    def format_date(self, date, format='%x', **kwargs):
        if kwargs:
            conv = self.localeconv().copy()
            conv.update(kwargs)
        else:
            conv = self.localeconv()
        result = locfmt.format_date(date, format, conv)
        return result

    def format_time(self, time, format='%X', **kwargs):
        if kwargs:
            conv = self.localeconv().copy()
            conv.update(kwargs)
        else:
            conv = self.localeconv()
        result = locfmt.format_time(time, format, conv)
        return result

    def format_datetime(self, datetime, format='%c', **kwargs):
        """Format datetime 'dt' according to `format'."""
        if kwargs:
            conv = self.localeconv().copy()
            conv.update(kwargs)
        else:
            conv = self.localeconv()
        result = locfmt.format_datetime(datetime, format, conv)
        return result

    def format_numeric(self, value, format='%s', **kwargs):
        """Format a numeric value."""
        if kwargs:
            conv = self.localeconv().copy()
            conv.update(kwargs)
        else:
            conv = self.localeconv()
        result = locfmt.format_numeric(value, format, conv)
        return result

    def format_monetary(self, value, format='%s', **kwargs):
        """Format a monetary value."""
        if kwargs:
            conv = self.localeconv().copy()
            conv.update(kwargs)
        else:
            conv = self.localeconv()
        result = locfmt.format_monetary(value, format, conv)
        return result


text:
/**
 * Created with blackjack.
 * User: alexzad
 * Date: 2014-09-11
 * Time: 02:35 PM
 * To change this template use Tools | Templates.
 */
exports.init = function(app, mongoose) {
    var Story = require("./../model/Story.js").make(mongoose.Schema, mongoose);
    app.get("(/api)?/stories", function(req, res) {
        console.log("querying all stories");
        var queryText = req.query.query || "{}";
        console.log("query is " + queryText);
        var query = Story.where(JSON.parse(queryText));
        query.find(function(err, stories) {
            if(err) {
                handleError(req, res, err);
            } else if(stories == null) {
                console.log("internal server error when querying stories for query " + queryText);
                res.status(500).send({
                    errorCode: 500,
                    errorMessage: "internal server error when querying stories for query " + queryText
                });
            } else {
                console.log("found: " + JSON.stringify(stories));
                res.set("Content-type", "application/json");
                res.status(200).send(stories);
            }
        });
    });
    app.post("(/api)?/stories", function(req, res) {
        console.log("create story: " + JSON.stringify(req.body));
        var story = new Story(req.body);
        story.save(function(err) {
            if(err) {
                handleError(req, res, err);
            } else {
                console.log("story created with id: " + story._id);
                res.set("Link", "</api/stories/" + story._id + ">; rel=\"created-resource\"");
                res.status(201).send({
                    storyId: story._id
                });
            }
        });
    });
    app.delete("(/api)?/stories/:0", function(req, res) {
        var id = req.params[0];
        console.log("delete story: " + id);
        Story.remove({
            _id: id
        }, function(err) {
            if(err) {
                handleError(req, res, err);
            } else {
                console.log("story " + id + " deleted");
                res.status(204).send({
                    errorCode: 204,
                    errorMessage: "story " + id + " deleted"
                });
            }
        });
    });
    app.put("(/api)?/stories/:0", function(req, res) {
        console.log("create story: " + JSON.stringify(req.body));
        var id = req.params[0];
        var query = Story.where({
            _id: id
        });
        var newVal = req.body;
        query.findOne(function(err, story) {
            if(err) {
                handleError(req, res, err);
            } else if(story == null) {
                console.log("story " + id + " not found");
                res.status(404).send({
                    errorCode: 404,
                    errorMessage: "story " + id + " not found"
                });
            } else {
                console.log('found: ' + JSON.stringify(story));
                console.log('newVal.active: ' + newVal.active);
                console.log('story.active != newVal.active: ' + (story.active != newVal.active));
                if(newVal.active && story.active != newVal.active) {
                    console.log("requested to activate story: " + id + ", resetting other stories in desk: " + story.deskId);
                    Story.update({
                        deskId: story.deskId
                    }, {
                        active: false
                    }, {
                        multi: true
                    }, function(err, numberAffected) {
                        if(err) {
                            console.log("failed to reset stories, error: " + JSON.stringify(err));
                            res.status(500).send({
                                errorCode: 500,
                                errorMessage: "failed to reset stories",
                                innerError: err
                            });
                            return;
                        } else {
                            console.log(numberAffected + " stories in desk: " + story.deskId + " deactivated");
                            updateStory(req, res, id, newVal);
                        }
                    });
                } else {
                    updateStory(req, res, id, newVal);
                }
            }
        });
    });

    function updateStory(req, res, id, newVal) {
        delete newVal["_id"];
        delete newVal["deskId"];
        Story.update({
            _id: id
        }, newVal, function(err) {
            if(err) {
                handleError(req, res, err);
            } else {
                console.log("story id: " + id + " updated with new values: " + JSON.stringify(newVal));
                res.set("Content-type", "application/json");
                res.status(200).send({
                    storyId: id
                });
            }
        });
    }

    function handleError(req, res, err) {
        console.log("error: " + JSON.stringify(err));
        res.status(500).send({
            errorCode: 500,
            errorMessage: "internal server error",
            innerError: err
        });
    }
    console.log("story controller initialized");
};


text:
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main( int argc, char **argv )
#endif
{
    ap::server::Server *serverPtr = new ap::server::Server(50740);
    serverPtr->start();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Cats.Web.Adminstration.Models.ViewModels
{
    public class HubUserViewModel
    {
        public int UserProfileID { get; set; }
        public string User { get; set; }
        public string Hub { get; set; }
        public int HubID { get; set; }
        public string Name { get; set; }
        public string LongName { get; set; }
        public int UserHubID { get; set; }
        public string IsDefault { get; set; }

    }
}