text:
namespace mojo {
namespace internal {

inline base::StringPiece16 TruncateString16(const std::u16string& string) {
  // We restrict the maximum length for all the strings inside the Manifest
  // when it is sent over Mojo. The renderer process truncates the strings
  // before sending the Manifest and the browser process validates that.
  return base::StringPiece16(string).substr(0, 4 * 1024);
}

inline absl::optional<base::StringPiece16> TruncateOptionalString16(
    const absl::optional<std::u16string>& string) {
  if (!string)
    return absl::nullopt;

  return TruncateString16(*string);
}

}  // namespace internal

template <>
struct BLINK_COMMON_EXPORT
    StructTraits<blink::mojom::ManifestImageResourceDataView,
                 ::blink::Manifest::ImageResource> {
  static const GURL& src(const ::blink::Manifest::ImageResource& icon) {
    return icon.src;
  }

  static base::StringPiece16 type(
      const ::blink::Manifest::ImageResource& icon) {
    return internal::TruncateString16(icon.type);
  }
  static const std::vector<gfx::Size>& sizes(
      const ::blink::Manifest::ImageResource& icon) {
    return icon.sizes;
  }

  static const std::vector<::blink::mojom::ManifestImageResource_Purpose>&
  purpose(const ::blink::Manifest::ImageResource& icon) {
    return icon.purpose;
  }

  static bool Read(blink::mojom::ManifestImageResourceDataView data,
                   ::blink::Manifest::ImageResource* out);
};

template <>
struct BLINK_COMMON_EXPORT
    StructTraits<blink::mojom::ManifestShortcutItemDataView,
                 ::blink::Manifest::ShortcutItem> {
  static base::StringPiece16 name(
      const ::blink::Manifest::ShortcutItem& shortcut) {
    return internal::TruncateString16(shortcut.name);
  }

  static absl::optional<base::StringPiece16> short_name(
      const ::blink::Manifest::ShortcutItem& shortcut) {
    return internal::TruncateOptionalString16(shortcut.short_name);
  }

  static absl::optional<base::StringPiece16> description(
      const ::blink::Manifest::ShortcutItem& shortcut) {
    return internal::TruncateOptionalString16(shortcut.description);
  }

  static const GURL& url(const ::blink::Manifest::ShortcutItem& shortcut) {
    return shortcut.url;
  }

  static const std::vector<::blink::Manifest::ImageResource>& icons(
      const ::blink::Manifest::ShortcutItem& shortcut) {
    return shortcut.icons;
  }

  static bool Read(blink::mojom::ManifestShortcutItemDataView data,
                   ::blink::Manifest::ShortcutItem* out);
};

template <>
struct BLINK_COMMON_EXPORT
    StructTraits<blink::mojom::ManifestRelatedApplicationDataView,
                 ::blink::Manifest::RelatedApplication> {
  static absl::optional<base::StringPiece16> platform(
      const ::blink::Manifest::RelatedApplication& related_application) {
    return internal::TruncateOptionalString16(related_application.platform);
  }

  static const GURL& url(
      const ::blink::Manifest::RelatedApplication& related_application) {
    return related_application.url;
  }

  static absl::optional<base::StringPiece16> id(
      const ::blink::Manifest::RelatedApplication& related_application) {
    return internal::TruncateOptionalString16(related_application.id);
  }

  static bool Read(blink::mojom::ManifestRelatedApplicationDataView data,
                   ::blink::Manifest::RelatedApplication* out);
};

template <>
struct BLINK_COMMON_EXPORT
    StructTraits<blink::mojom::ManifestFileFilterDataView,
                 ::blink::Manifest::FileFilter> {
  static base::StringPiece16 name(
      const ::blink::Manifest::FileFilter& share_target_file) {
    return internal::TruncateString16(share_target_file.name);
  }

  static const std::vector<base::StringPiece16> accept(
      const ::blink::Manifest::FileFilter& share_target_file) {
    std::vector<base::StringPiece16> accept_types;

    for (const std::u16string& accept_type : share_target_file.accept)
      accept_types.push_back(internal::TruncateString16(accept_type));

    return accept_types;
  }

  static bool Read(blink::mojom::ManifestFileFilterDataView data,
                   ::blink::Manifest::FileFilter* out);
};

template <>
struct BLINK_COMMON_EXPORT
    StructTraits<blink::mojom::ManifestShareTargetParamsDataView,
                 ::blink::Manifest::ShareTargetParams> {
  static const absl::optional<base::StringPiece16> text(
      const ::blink::Manifest::ShareTargetParams& share_target_params) {
    return internal::TruncateOptionalString16(share_target_params.text);
  }
  static const absl::optional<base::StringPiece16> title(
      const ::blink::Manifest::ShareTargetParams& share_target_params) {
    return internal::TruncateOptionalString16(share_target_params.title);
  }
  static const absl::optional<base::StringPiece16> url(
      const ::blink::Manifest::ShareTargetParams& share_target_params) {
    return internal::TruncateOptionalString16(share_target_params.url);
  }
  static const std::vector<blink::Manifest::FileFilter>& files(
      const ::blink::Manifest::ShareTargetParams& share_target_params) {
    return share_target_params.files;
  }

  static bool Read(blink::mojom::ManifestShareTargetParamsDataView data,
                   ::blink::Manifest::ShareTargetParams* out);
};

template <>
struct BLINK_COMMON_EXPORT
    StructTraits<blink::mojom::ManifestShareTargetDataView,
                 ::blink::Manifest::ShareTarget> {
  static const GURL& action(
      const ::blink::Manifest::ShareTarget& share_target) {
    return share_target.action;
  }
  static ::blink::mojom::ManifestShareTarget_Method method(
      const ::blink::Manifest::ShareTarget& share_target) {
    return share_target.method;
  }
  static ::blink::mojom::ManifestShareTarget_Enctype enctype(
      const ::blink::Manifest::ShareTarget& share_target) {
    return share_target.enctype;
  }
  static const ::blink::Manifest::ShareTargetParams& params(
      const ::blink::Manifest::ShareTarget& share_target) {
    return share_target.params;
  }
  static bool Read(blink::mojom::ManifestShareTargetDataView data,
                   ::blink::Manifest::ShareTarget* out);
};

template <>
struct BLINK_COMMON_EXPORT
    StructTraits<blink::mojom::ManifestLaunchHandlerDataView,
                 ::blink::Manifest::LaunchHandler> {
  static blink::mojom::ManifestLaunchHandler::RouteTo route_to(
      const ::blink::Manifest::LaunchHandler& launch_handler) {
    return launch_handler.route_to;
  }

  static blink::mojom::ManifestLaunchHandler::NavigateExistingClient
  navigate_existing_client(
      const ::blink::Manifest::LaunchHandler& launch_handler) {
    return launch_handler.navigate_existing_client;
  }

  static bool Read(blink::mojom::ManifestLaunchHandlerDataView data,
                   ::blink::Manifest::LaunchHandler* out);
};

template <>
struct BLINK_COMMON_EXPORT
    StructTraits<blink::mojom::ManifestTranslationItemDataView,
                 ::blink::Manifest::TranslationItem> {
  static absl::optional<base::StringPiece16> name(
      const ::blink::Manifest::TranslationItem& translation) {
    return internal::TruncateOptionalString16(translation.name);
  }

  static absl::optional<base::StringPiece16> short_name(
      const ::blink::Manifest::TranslationItem& translation) {
    return internal::TruncateOptionalString16(translation.short_name);
  }

  static absl::optional<base::StringPiece16> description(
      const ::blink::Manifest::TranslationItem& translation) {
    return internal::TruncateOptionalString16(translation.description);
  }

  static bool Read(blink::mojom::ManifestTranslationItemDataView data,
                   ::blink::Manifest::TranslationItem* out);
};

}  // namespace mojo

#endif  // THIRD_PARTY_BLINK_PUBLIC_COMMON_MANIFEST_MANIFEST_MOJOM_TRAITS_H_


text:
#ifndef ALERTLOGIN_H
#define ALERTLOGIN_H

#include <QObject>
#include <QUrlQuery>
#include "qtnicolivelib.h"
#include "httpgetter.h"
#include "strabstractor.h"

namespace nicolive {

//! ニコ生アラートのログインをして AlertAdmin に必要なチケットを取得します

class QTNICOLIVELIBSHARED_EXPORT AlertLogin : public HttpGetter
{
  Q_OBJECT
public:
  //! コンストラクタ
  explicit AlertLogin(QObject *parent = 0);

  //! リクエストを発行します。
  /*!
   * 取得後、Signalの got() または error() をemitします。
   */
  void get(const QString& mailAddress, const QString& password);
private:
  void gotReply(QNetworkReply* reply) override;
signals:
  //! エラーになった場合にエミットされるシグナルです。
  /*! 参考: get() */
  void error(QString code, QString description);

  //! 取得成功した場合にエミットされるシグナルです。
  /*! 参考: get() */
  void got(QString ticket);
};

}

#endif // ALERTLOGIN_H

redpajama_set_name: RedPajamaGithub


text:
package airportmanagement;

import airportmanagement.DTO.CreatingAirportDto;
import airportmanagement.DTO.CreatingFlightDto;
import airportmanagement.DTO.FlightDto;
import airportmanagement.comparators.FlightComparator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest
public class AirportGatherInfoTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    @Before
    // Will be performed before each test.
    public void testSetup()
    {
        System.out.println("Setup for test complete.");
    }

    @After
    // Will be performed after each test.
    public void testComplete()
    {
        System.out.println("Test complete.");
    }
    @Test
    public void test_air_cont(){
        FlightDto d1= new FlightDto();
        d1.day="Luni";
        FlightDto d2= new FlightDto();
        d2.day="Viner";
        FlightComparator flightComparator=new FlightComparator("day");
        flightComparator.compare(d1,d2);
        CreatingAirportDto dto =new CreatingAirportDto();
        dto.location=dto.name="padure";
        try {ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
            byte[] bytes = objectMapper.writeValueAsBytes(dto);
            this.mockMvc.perform(post("/airports").contentType(APPLICATION_JSON_UTF8).content(bytes));

            this.mockMvc.perform(get("/airports"))
                    .andExpect(status().isOk()).andDo(print());
            this.mockMvc.perform(get("/airports/padure"))
                    .andExpect(status().isOk());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void test_fli_cont(){
        CreatingFlightDto dto =new CreatingFlightDto();
        dto.arrivalCity=dto.departureCity=dto.departureHour=dto.arrivalHour=dto.company=dto.day=dto.flightNumber="nop";
        try {ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
            byte[] bytes = objectMapper.writeValueAsBytes(dto);
            this.mockMvc.perform(post("/airports/{location}/flights","padure").contentType(APPLICATION_JSON_UTF8).content(bytes))
                   ;
            this.mockMvc.perform(get("/airports/{location}/flights?day=nop&page=1&pageSize=2","padure"))
                    .andExpect(status().isOk()).andDo(print());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void test_nr_JsonObjects(){
        /* testing insert*/
        InputStream is = null;
        InputStream is1= null;
        try {

            JSONObject obj = new JSONObject();
            obj.put("name", "student");
            obj.put("day","Luni");
            obj.put("flightNumber", "Luni");
            obj.put("company", "Blue");
            obj.put("arrivalCity", "Bacau");
            obj.put("departureCity", "Bacau");
            obj.put("departureHour", "10:44");
            obj.put("arrivalHour", "10:44");
            obj.put("status", "done");

            is = new URL("http://localhost:8081/airports/bacau/flights").openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONArray arr=new JSONArray(jsonText);
            int contor = arr.length();

            AirportGatherInfo gth = new AirportGatherInfo();
           gth.gatherObject("Luni","1111", "Blue", "Bacau","Bacau", "10:44", "10:44","bacau") ;
            is1 = new URL("http://localhost:8081/airports/bacau/flights").openStream();
            BufferedReader rd1 = new BufferedReader(new InputStreamReader(is1, Charset.forName("UTF-8")));

            String jsonText1 = readAll(rd1);
            JSONArray arr1=new JSONArray(jsonText1);
            int contor1 = arr1.length();
            assertEquals("Testing the insert",contor + 1,contor1);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void test_uniqueness() {
        InputStream is = null;
        InputStream is1 =null;
        try {
            is = new URL("http://localhost:8081/airports/bacau/flights").openStream();

        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONArray arr=new JSONArray(jsonText);
        int contor = arr.length();
            AirportGatherInfo.main(null);
            is1 = new URL("http://localhost:8081/airports/bacau/flights").openStream();
            BufferedReader rd1 = new BufferedReader(new InputStreamReader(is1, Charset.forName("UTF-8")));

            String jsonText1 = readAll(rd1);
            JSONArray arr1=new JSONArray(jsonText1);
            int contor1 = arr1.length();
            assertNotEquals("Testing the unique values",contor,contor1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}


text:
package org.locationtech.geomesa.convert2.validators

import org.junit.runner.RunWith
import org.locationtech.geomesa.convert2.metrics.ConverterMetrics
import org.locationtech.geomesa.features.ScalaSimpleFeature
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

@RunWith(classOf[JUnitRunner])
class CqlValidatorTest extends Specification {

  val sft = SimpleFeatureTypes.createType("foo", "dtg:Date,*geom:Point:srid=4326")

  "CqlValidator" should {
    "require ecql expression" in {
      SimpleFeatureValidator(sft, Seq("cql"), ConverterMetrics.empty) must throwAn[IllegalArgumentException]
    }
    "validate ecql expressions" in {
      val validator = SimpleFeatureValidator(sft, Seq("cql(bbox(geom,45,-90,55,90))"), ConverterMetrics.empty)
      validator must not(beNull)
      val sf = ScalaSimpleFeature.create(sft, "0", "2018-01-01T00:00:00.000Z", "POINT (50 45)")
      validator.validate(sf) must beNull
      sf.setAttribute("geom", "POINT (-50 45)")
      validator.validate(sf) must not(beNull)
    }
  }
}


text:
importScripts('lib/tank.js');

var turnDirection, turnTimer, direction, backTimer, boostTimer;

tank.init(function(settings, info) {
  settings.SKIN = 'forest';
  // the direction where tank will turning.
  // 1 is clockwise, -1 is couter clockwise
  turnDirection = Math.random() < 0.5 ? 1 : -1;
  turnTimer = Math.round(Math.randomRange(0, 30));
  direction = 1;
  backTimer = 0;
});

tank.loop(function(state, control) {

  if(state.collisions.enemy || state.collisions.ally) {
    backTimer = 12;
    boostTimer = 40;
  }
  if(backTimer > 0) {
    backTimer--;
    direction = -1;
  } else {
    direction = 1;
  }

  if(boostTimer > 0) {
    boostTimer--;
    control.BOOST = 1;
  } else {
    control.BOOST = 0;
  }
  control.THROTTLE = direction;

  if(!state.radar.enemy) {
    control.RADAR_TURN = 1;
    if(state.collisions.wall) {
      turnTimer = Math.round(Math.randomRange(20, 50));
    }
    if(turnTimer > 0) {
      turnTimer--;
      control.THROTTLE = 0;
      control.TURN = turnDirection;
    } else {
      control.THROTTLE = direction;
      control.TURN = 0;
    }

  } else {
    // find target angle to aim the enemy
    var targetAngle = Math.deg.atan2(
      state.radar.enemy.y - state.y,
      state.radar.enemy.x - state.x
    );

    // make sure that the angle is between (-180 and 180)
    var radarAngleDelta = Math.deg.normalize(targetAngle - (state.radar.angle + state.angle));

    // adjust radar direction to follow the target
    control.RADAR_TURN = radarAngleDelta*0.2;

    // make sure that the angle is between (-180 and 180)
    var tankAngleDelta = Math.deg.normalize(targetAngle - state.angle);

    // adjust radar direction to follow the target
    control.TURN = tankAngleDelta * 0.2;
  }

  control.DEBUG = {
    boost: state.boost
  };
  control.SHOOT = state.radar.enemy ? 0.3 : 0;
});


text:
"""
The cysolve module comes with the following submodules:

1) cysolve.ode:
    This provides mechanisms to efficiently solve (in parallel) a given ode for many parametersets.

"""


text:
from django.conf import settings

# Admin Site Title
ADMIN_HEADLINE = getattr(settings, "GRAPPELLI_ADMIN_HEADLINE", '都全后台管理系统')
ADMIN_TITLE = getattr(settings, "GRAPPELLI_ADMIN_TITLE", '都全后台管理系统')

# Link to your Main Admin Site (no slashes at start and end)
ADMIN_URL = getattr(settings, "GRAPPELLI_ADMIN_URL", '/')


text:
// The source is licensed to the .NET Foundation under the MIT license:
// https://github.com/dotnet/corefx/blob/master/src/System.Runtime.Extensions/tests/System/Convert.ToByte.cs
// https://github.com/dotnet/corefx/blob/master/LICENSE

using Bridge.Test.NUnit;
using System;

namespace Bridge.ClientTest.ConvertTests
{
    [Category(Constants.MODULE_CONVERT)]
    [TestFixture(TestNameFormat = "Convert.ToByte - {0}")]
    public class ConvertToByteTests : ConvertTestBase<byte>
    {
        [Test]
        public void FromBoolean()
        {
            bool[] testValues = { true, false };
            byte[] expectedValues = { 1, 0 };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);
        }

        [Test]
        public void FromChar()
        {
            char[] testValues = { 'A', char.MinValue };
            byte[] expectedValues = { (byte)'A', (byte)char.MinValue };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            char[] overflowValues = { char.MaxValue };
            VerifyThrowsViaObj<OverflowException, char>(Convert.ToByte, overflowValues);
        }

        [Test]
        public void FromDecimal()
        {
            decimal[] testValues = { byte.MaxValue, byte.MinValue, 254.01m, 254.9m };
            byte[] expectedValues = { byte.MaxValue, byte.MinValue, 254, 255 };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            decimal[] overflowValues = { decimal.MinValue, decimal.MaxValue };
            VerifyThrowsViaObj<OverflowException, decimal>(Convert.ToByte, overflowValues);
        }

        [Test]
        public void FromDouble()
        {
            double[] testValues = { byte.MinValue, byte.MaxValue, 100.0, 254.9, 255.2 };
            byte[] expectedValues = { byte.MinValue, byte.MaxValue, 100, 255, 255 };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            double[] overflowValues = { -double.MaxValue, double.MaxValue };
            VerifyThrowsViaObj<OverflowException, double>(Convert.ToByte, overflowValues);
        }

        [Test]
        public void FromInt16()
        {
            short[] testValues = { byte.MinValue, byte.MaxValue, 10, 2 };
            byte[] expectedValues = { byte.MinValue, byte.MaxValue, 10, 2 };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            short[] overflowValues = { short.MinValue, short.MaxValue };
            VerifyThrowsViaObj<OverflowException, short>(Convert.ToByte, overflowValues);
        }

        [Test]
        public void FromInt32()
        {
            int[] testValues = { byte.MinValue, byte.MaxValue, 10 };
            byte[] expectedValues = { byte.MinValue, byte.MaxValue, 10 };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            int[] overflowValues = { int.MinValue, int.MaxValue };
            VerifyThrowsViaObj<OverflowException, int>(Convert.ToByte, overflowValues);
        }

        [Test]
        public void FromInt64()
        {
            long[] testValues = { byte.MinValue, byte.MaxValue, 10 };
            byte[] expectedValues = { byte.MinValue, byte.MaxValue, 10 };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            long[] overflowValues = { long.MinValue, long.MaxValue };
            VerifyThrowsViaObj<OverflowException, long>(Convert.ToByte, overflowValues);
        }

        [Test]
        public void FromObject()
        {
            object[] testValues = { null };
            byte[] expectedValues = { 0 };
            VerifyFromObject(Convert.ToByte, Convert.ToByte, testValues, expectedValues);

            object[] invalidValues = { new object(), DateTime.Now };
            VerifyFromObjectThrows<InvalidCastException>(Convert.ToByte, Convert.ToByte, invalidValues);
        }

        [Test]
        public void FromSByte()
        {
            sbyte[] testValues = { 0, 10, sbyte.MaxValue };
            byte[] expectedValues = { 0, 10, (byte)sbyte.MaxValue };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            sbyte[] overflowValues = { sbyte.MinValue };
            VerifyThrowsViaObj<OverflowException, sbyte>(Convert.ToByte, overflowValues);
        }

        [Test]
        public void FromSingle()
        {
            float[] testValues = { byte.MaxValue, byte.MinValue, 254.01f, 254.9f };
            byte[] expectedValues = { byte.MaxValue, byte.MinValue, 254, 255 };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            float[] overflowValues = { float.MinValue, float.MaxValue };
            VerifyThrowsViaObj<OverflowException, float>(Convert.ToByte, overflowValues);
        }

        [Test]
        public void FromString()
        {
            var byteMinValue = byte.MinValue;
            var byteMaxValue = byte.MaxValue;
            var intMinValue = int.MinValue;
            var intMaxValue = int.MaxValue;

            string[] testValues = { byteMaxValue.ToString(), byteMinValue.ToString(), "0", "100", null };
            byte[] expectedValues = { byteMaxValue, byteMinValue, 0, 100, 0 };
            VerifyFromString(Convert.ToByte, Convert.ToByte, testValues, expectedValues);

            string[] overflowValues = { intMinValue.ToString(), intMaxValue.ToString() };
            VerifyFromStringThrows<OverflowException>(Convert.ToByte, Convert.ToByte, overflowValues);

            string[] formatExceptionValues = { "abba" };
            VerifyFromStringThrows<FormatException>(Convert.ToByte, Convert.ToByte, formatExceptionValues);
        }

        [Test]
        public void FromStringWithBase()
        {
            string[] testValues = { null, null, null, null, "10", "100", "1011", "ff", "0xff", "77", "11", "11111111" };
            int[] testBases = { 10, 2, 8, 16, 10, 10, 2, 16, 16, 8, 2, 2 };
            byte[] expectedValues = { 0, 0, 0, 0, 10, 100, 11, 255, 255, 63, 3, 255 };
            VerifyFromStringWithBase(Convert.ToByte, testValues, testBases, expectedValues);

            string[] overflowValues = { "256", "111111111", "ffffe", "7777777", "-1" };
            int[] overflowBases = { 10, 2, 16, 8, 10 };
            VerifyFromStringWithBaseThrows<OverflowException>(Convert.ToByte, overflowValues, overflowBases);

            string[] formatExceptionValues = { "fffg", "0xxfff", "8", "112", "!56" };
            int[] formatExceptionBases = { 16, 16, 8, 2, 10 };
            VerifyFromStringWithBaseThrows<FormatException>(Convert.ToByte, formatExceptionValues, formatExceptionBases);

            string[] argumentExceptionValues = { null };
            int[] argumentExceptionBases = { 11 };
            VerifyFromStringWithBaseThrows<ArgumentException>(Convert.ToByte, argumentExceptionValues, argumentExceptionBases);
        }

        [Test]
        public void FromUInt16()
        {
            ushort[] testValues = { byte.MinValue, byte.MaxValue, 10, 100 };
            byte[] expectedValues = { byte.MinValue, byte.MaxValue, 10, 100 };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            ushort[] overflowValues = { ushort.MaxValue };
            VerifyThrowsViaObj<OverflowException, ushort>(Convert.ToByte, overflowValues);
        }

        [Test]
        public void FromUInt32()
        {
            uint[] testValues = { byte.MinValue, byte.MaxValue, 10, 100 };
            byte[] expectedValues = { byte.MinValue, byte.MaxValue, 10, 100 };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            uint[] overflowValues = { uint.MaxValue };
            VerifyThrowsViaObj<OverflowException, uint>(Convert.ToByte, overflowValues);
        }

        [Test]
        public void FromUInt64()
        {
            ulong[] testValues = { byte.MinValue, byte.MaxValue, 10, 100 };
            byte[] expectedValues = { byte.MinValue, byte.MaxValue, 10, 100 };
            VerifyViaObj(Convert.ToByte, testValues, expectedValues);

            ulong[] overflowValues = { ulong.MaxValue };
            VerifyThrowsViaObj<OverflowException, ulong>(Convert.ToByte, overflowValues);
        }
    }
}


text:
package org.pitest.mutationtest.build.intercept.javafeatures;

import org.pitest.mutationtest.build.InterceptorParameters;
import org.pitest.mutationtest.build.MutationInterceptor;
import org.pitest.mutationtest.build.MutationInterceptorFactory;
import org.pitest.plugin.Feature;

public class EnumConstructorFilterFactory implements MutationInterceptorFactory {

    @Override
    public String description() {
        return "Enum constructor filter";
    }

    @Override
    public MutationInterceptor createInterceptor(InterceptorParameters params) {
        return new EnumConstructorFilter();
    }

    @Override
    public Feature provides() {
        return Feature.named("FENUM")
                .withOnByDefault(true)
                .withDescription("Filters mutations in enum constructors");
    }

}


text:
package edu.gemini.qpt.ui.view.variant.edit;

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import edu.gemini.qpt.core.Variant;
import edu.gemini.ui.gface.GSelection;
import edu.gemini.ui.gface.GViewer;
import edu.gemini.ui.workspace.IShell;

@SuppressWarnings("serial")
public class DeleteAction extends AbstractAction implements PropertyChangeListener {

	private final IShell shell;
	private final GViewer<?, Variant> viewer;

	public DeleteAction(final IShell shell, final GViewer<?, Variant> viewer) {
		this.shell = shell;
		this.viewer = viewer;
		setEnabled(false);
		viewer.addPropertyChangeListener(GViewer.PROP_SELECTION, this);
	}

	public void actionPerformed(ActionEvent e) {
		GSelection<Variant> sel = viewer.getSelection();
		for (Variant v: sel) {

			// Delete the selected variant. Selection will change.
			if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(shell.getPeer(),
						"Do you really want to delete this variant?",
						"Confirm Delete", JOptionPane.YES_NO_OPTION))
					continue;

			v.getSchedule().removeVariant(v);
		}
	}

	public void propertyChange(PropertyChangeEvent evt) {
		GSelection<?> sel = (GSelection<?>) evt.getNewValue();
		setEnabled(sel.isSelectionOf(Variant.class));
	}

}


text:
<ivy-module version="1.0">
	<info organisation="org8"
	       module="mod8.5"
	/>
	<configurations>
		<conf name="compile"/>
		<conf name="runtime" extends="compile"/>
		<conf name="test" extends="runtime" visibility="private" />
	</configurations>
	<dependencies>
		<dependency name="mod8.6" rev="2.+" conf="test->runtime"/>
	</dependencies>
</ivy-module>


text:
set -euo pipefail

if test $# -gt 0; then
    echo "$0 does not accept arguments" >&2
    exit 32
fi

set -x

trap exit INT

echo "Running services with supervisord"

supervisord -c /etc/supervisord.conf


text:
LICENSE
=======

Copyright 2013 Google Inc. All Rights Reserved.

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

    http://www.apache.org/licenses/LICENSE-2.0

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

Get Ready to Build Chrome Apps!
===============================
Chrome apps are written in HTML5, JavaScript, and CSS, just like web apps.
But they look and behave more like native apps, and they have super-powerful capabilities,
like the ability to interact with network and hardware devices, media tools, and much more.

> This repository contains only the code for the Codelab. Please, make sense of this code by following the step-by-step tutorial in the [Chrome Apps docs site](http://developer.chrome.com/trunk/apps/app_codelab.html)


text:
namespace Google.Cloud.ContactCenterInsights.V1.Snippets
{
    // [START contactcenterinsights_v1_generated_ContactCenterInsights_ListAnalyses_sync_flattened_resourceNames]
    using Google.Api.Gax;
    using Google.Cloud.ContactCenterInsights.V1;
    using System;

    public sealed partial class GeneratedContactCenterInsightsClientSnippets
    {
        /// <summary>Snippet for ListAnalyses</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListAnalysesResourceNames()
        {
            // Create client
            ContactCenterInsightsClient contactCenterInsightsClient = ContactCenterInsightsClient.Create();
            // Initialize request argument(s)
            ConversationName parent = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]");
            // Make the request
            PagedEnumerable<ListAnalysesResponse, Analysis> response = contactCenterInsightsClient.ListAnalyses(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Analysis item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListAnalysesResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Analysis item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Analysis> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Analysis item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END contactcenterinsights_v1_generated_ContactCenterInsights_ListAnalyses_sync_flattened_resourceNames]
}


text:
using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TravelAgent.Web.member
{
    public partial class CarOrder : System.Web.UI.Page
    {
        public int clubid;
        private static readonly TravelAgent.BLL.Order OrderBll = new TravelAgent.BLL.Order();
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = "租车订单-" + Master.webinfo.WebName;
            string strUid = TravelAgent.Tool.CookieHelper.GetCookieValue("uid");
            if (string.IsNullOrEmpty(strUid))
            {
                Response.Redirect("/member/Login.aspx");
            }
            else
            {
                clubid = Convert.ToInt32(strUid);
            }
        }
        ///
        /// 显示线路订单
        ///
        public string ShowOrder()
        {
            StringBuilder sbLineOrder = new StringBuilder();
            DataSet dsLineOrder = OrderBll.GetCarList(0, "orderType=" + Convert.ToInt32(TravelAgent.Tool.EnumSummary.OrderType.租车) + " and clubid=" + clubid, "orderDate desc");
            foreach (DataRow r in dsLineOrder.Tables[0].Rows)
            {
                sbLineOrder.Append("
");
                sbLineOrder.Append("" + r["ordercode"] + "	");
                sbLineOrder.Append("" + r["CarName"] + "	");
                sbLineOrder.Append("" + r["usedate"] + "	");
                sbLineOrder.Append("¥" + (Convert.ToInt32(r["orderPrice"]) + Convert.ToInt32(r["attachPrice"]) + Convert.ToInt32(r["subPrice"])) + "	");
                sbLineOrder.Append("" + TravelAgent.Tool.EnumHelper.GetMemberName<TravelAgent.Tool.EnumSummary.OrderState>(r["orderState"]) + "	");
                sbLineOrder.Append("" + r["orderDate"] + "	");
                sbLineOrder.Append("");
                if (Convert.ToInt32(r["orderState"]) == Convert.ToInt32(TravelAgent.Tool.EnumSummary.OrderState.待付款))
                {
                    sbLineOrder.Append("付款");
                }
                else
                {
                    sbLineOrder.Append("");
                }

                sbLineOrder.Append("	");
                sbLineOrder.Append("
");
            }
            return sbLineOrder.ToString();
        }
    }
}


text:
namespace util {

template<typename T>
class ScopedPtr {
 public:
  explicit ScopedPtr(T* ptr) : ptr_(ptr) {}
  ~ScopedPtr() { delete ptr_; }
  void reset(T* ptr) { ScopedPtr(ptr).swap(*this); }
  T& operator*() const { return *ptr_; }
  T* operator->() const { return ptr_; }
  T* get() const { return ptr_; }
  void swap(ScopedPtr& b) {
    T* tmp = ptr_;
    ptr_ = b.ptr_;
    b.ptr_ = tmp;
  }
 private:
  T* ptr_;
  DISALLOW_COPY_AND_ASSIGN(ScopedPtr);
};

template<typename T>
inline void swap(ScopedPtr<T>& a, ScopedPtr<T>& b) {
  a.swap(b);
}

template<typename T>
class ScopedArray {
 public:
  explicit ScopedArray(T* array) : array_(array) {}
  ~ScopedArray() { delete[] array_; }
  void reset(T* array) { ScopedArray(array).swap(*this); }
  T& operator[](ptrdiff_t i) const { return array_[i]; }
  T* get() const { return array_; }
  void swap(ScopedArray& b) {
    T* tmp = array_;
    array_ = b.array_;
    b.array_ = tmp;
  }
 private:
  T* array_;
  DISALLOW_COPY_AND_ASSIGN(ScopedArray);
};

template<typename T>
inline void swap(ScopedArray<T>& a, ScopedArray<T>& b) {
  a.swap(b);
}
}  // namespace util
#endif  // UTIL_SCOPED_H_


text:
from django.db import models

class Flat(models.Model):
    name = models.CharField(max_length=256)
    numberOfMembers = models.PositiveSmallIntegerField()
    oauth_token = models.CharField(max_length=40, blank=True, null=True)
    oauth_token_secret = models.CharField(max_length=40, blank=True, null=True)

    def __unicode__(self):              # __unicode__ on Python 2
        return self.name

class User(models.Model):
    name = models.CharField(max_length=256)
    email = models.EmailField(max_length=254)
    password = models.CharField(max_length=50)
    flat = models.ForeignKey(Flat, blank=True, null=True)

    def __unicode__(self):              # __unicode__ on Python 2
        return self.name

class Bill(models.Model):
    start = models.DateField(blank=True, null=True)
    end = models.DateField(blank=True, null=True)
    cost = models.DecimalField(max_digits=6, decimal_places=2)
    cost_per_user = models.DecimalField(max_digits=6, decimal_places=2, blank=True)
    flat = models.ForeignKey(Flat, blank=True, null=True)

    def __unicode__(self):              # __unicode__ on Python 2
        return str(self.start)

class UserBill(models.Model):
    user = models.ForeignKey(User)
    bill = models.ForeignKey(Bill)
    date_paid = models.DateField()


text:
layout: markdown
hero-image: url(/assets/images/workshops/justin-demo-cropped.jpg)
hero-message: Fall Workshops Registration Form
---
<div class="cognito">
  <script src="https://services.cognitoforms.com/s/2JccztZj5ECcSf6u5HN1zg"></script>
  <script>Cognito.load("forms", { id: "3" });</script>
</div>


text:
import { helper } from '@ember/component/helper';

export function number(params, hash = { style: 'decimal' }) {
	let options = Object.assign({}, hash);
	options.style = 'decimal';
	return Number(params[0]).toLocaleString([], options);
}

export default helper(number);


text:
package org.ethontos.phylontal.project;

import static org.junit.Assert.*;

import java.io.File;
import java.net.URI;
import java.net.URL;
import java.util.HashSet;
import java.util.List;

import org.apache.log4j.BasicConfigurator;
import org.ethontos.phylontal.project.impl.DataFactory;
import org.ethontos.phylontal.project.impl.ExtendableStringMetric;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestProject {

    private Project p;
    final URL OntologyURL1 = ClassLoader.getSystemResource("testFiles/spider_anatomy.owl");
    final URL OntologyURL2 = ClassLoader.getSystemResource("testFiles/tick_anatomy.owl");
    File OntologyFile1 = new File(OntologyURL1.getPath());
    File OntologyFile2 = new File(OntologyURL2.getPath());

    @Before
    public void setUp() throws Exception {
        BasicConfigurator.configure();
        p = ProjectFactory.createProject();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testAddOntology() {
        p.addOntology(OntologyFile1);
        assertNotNull(p.listOntologies());
    }

    @Test
    public void testAddTerm() {
        fail("Not yet implemented"); // TODO
    }

    @Test
    public void testContinueGuidedMatch() {
        fail("Not yet implemented"); // TODO
    }

    @Test
    public void testListOntologies() {
        p.addOntology(OntologyFile1);
        p.addOntology(OntologyFile2);
        List<URI> result = p.listOntologies();
        assertNotNull(result);
        assert((result.size() == 2));
    }

    @Test
    public void testLoadAlignment() {
        fail("Not yet implemented"); // TODO
    }

    @Test
    public void testLoadTree() {
        fail("Not yet implemented"); // TODO
    }

    @Test
    public void testSaveAlignment() {
        fail("Not yet implemented"); // TODO
    }

    @Test
    public void testSaveMergedOntologies() {
        fail("Not yet implemented"); // TODO
    }

    @Test
    public void testShowOntology() {
        fail("Not yet implemented"); // TODO
    }

    @Test
    public void testShowTree() {
        fail("Not yet implemented"); // TODO
    }

    @Test
    public void testStartGuidedMatch() {
        fail("Not yet implemented"); // TODO
    }

    @Test
    public void testUnguidedMatch() {
        DataFactory factory = p.getDataFactory();
        p.addOntology(OntologyFile1);
        p.addOntology(OntologyFile2);
        List <URI> onts = p.listOntologies();  //need to get this pair from somewhere
        if (onts.size()>1){
            Alignment newAlignment = factory.getAlignment();
            ExtendableStringMetric m = factory.getExtendableStringMetric(ExtendableStringMetric.Metric.MongeElkan);
            OntologyWrapper w1 = p.showOntology(onts.get(0));
            OntologyWrapper w2 = p.showOntology(onts.get(1));
            List <OntTerm> names1 = w1.getPreOrderedTermList(new HashSet<OntTerm>());
            List <OntTerm> names2 = w2.getPreOrderedTermList(new HashSet<OntTerm>());
            p.unguidedMatch(newAlignment, w1, names1, w2, names2, m);
        }
        else
            fail("One or more ontologies failed to load; ont count = " + onts.size());
    }

    @Test
    public void testValidate() {
        fail("Not yet implemented"); // TODO
    }

    @Test
    public void testDoCommand() {
        fail("Not yet implemented"); // TODO
    }

}


text:
package top.ningg.java;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by guoning on 15/9/5.
 */
public class Demo6CallableFuture implements Callable<String> {

    @Override
    public String call() throws Exception {
        return Thread.currentThread().getName();
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = new ThreadPoolExecutor(0, 2, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50),
                new ThreadPoolExecutor.CallerRunsPolicy());
        List<Future<String>> futures = Lists.newLinkedList();
        for (int index = 0 ; index <100; index++){
            Callable<String> callable = new Demo6CallableFuture();
            futures.add(executor.submit(callable));
        }
        // Thread.sleep(5 * 1000);

        for (Future future : futures){
            try {
                System.out.println(future.get());
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

    }
}


text:
require File.dirname(__FILE__) + '/spec_helper'

class CallbackRecorder
  include CouchTomato::Persistence

  property :required_property

  validates_presence_of :required_property

  [:before_validation, :before_validation_on_create,
    :before_validation_on_save, :before_validation_on_update,
    :before_save, :before_create, :before_create,
    :after_save, :after_create, :after_create,
    :before_update, :after_update,
    :before_destroy, :after_destroy
  ].each do |callback|
    define_method callback do
      callbacks << callback
    end
    self.send callback, callback
  end

  view :all, :key  => :required_property

  attr_accessor :lambda_works
  before_create lambda {|model| model.lambda_works = true }

  def callbacks
    @callbacks ||= []
  end

  private

  def method_callback_with_argument(db)
    db.view CallbackRecorder.all
  end

end

describe "multiple callbacks at once" do

  class Monkey
    include CouchTomato::Persistence
    attr_accessor :eaten_banana, :eaten_apple

    before_create :eat_apple, :eat_banana

    private

    def eat_banana
      self.eaten_banana = true
    end

    def eat_apple
      self.eaten_apple = true
    end
  end
  it "should run all callback methods given to the callback method call" do
    monkey = Monkey.new
    CouchTomato.database.save_document! monkey
    monkey.eaten_banana.should be_true
    monkey.eaten_apple.should be_true
  end
end

describe 'create callbacks' do

  before(:each) do
    @recorder = CallbackRecorder.new
    couchrest_database = stub 'couchrest_database', :save_doc => {'id' => '1', 'rev' => '2'}, :view => {'rows' => []}, :info => nil
    @db = CouchTomato::Database.new(couchrest_database)
  end

  describe "successful create" do
    before(:each) do
       @recorder.required_property = 1
    end

    it "should call before_validation" do
      @recorder.valid?
      @recorder.callbacks.should include(:before_validation)
    end

    it "should call before_validation_on_create" do
      @db.save_document! @recorder
      @recorder.callbacks.should include(:before_validation_on_create)
    end

    it "should call before_validation_on_save" do
      @db.save_document! @recorder
      @recorder.callbacks.should include(:before_validation_on_save)
    end

    it "should call before_save" do
      @db.save_document! @recorder
      @recorder.callbacks.should include(:before_save)
    end

    it "should call after_save" do
      @db.save_document! @recorder
      @recorder.callbacks.should include(:after_save)
    end

    it "should call before_create" do
      @db.save_document! @recorder
      @recorder.callbacks.should include(:before_create)
    end

    it "should call after_create" do
      @db.save_document! @recorder
      @recorder.callbacks.should include(:after_create)
    end

  end

  describe "failed create" do

    it "should call before_validation" do
      @recorder.valid?
      @recorder.callbacks.should include(:before_validation)
    end

    it "should call before_validation_on_create" do
      @db.save_document @recorder
      @recorder.callbacks.should include(:before_validation_on_create)
    end

    it "should call before_validation_on_save" do
      @db.save_document @recorder
      @recorder.callbacks.should include(:before_validation_on_save)
    end

    it "should not call before_save" do
      @db.save_document @recorder
      @recorder.callbacks.should_not include(:before_save)
    end

    it "should not call after_save" do
      @db.save_document @recorder
      @recorder.callbacks.should_not include(:after_save)
    end

    it "should not call before_create" do
      @db.save_document @recorder
      @recorder.callbacks.should_not include(:before_create)
    end

    it "should not call after_create" do
      @db.save_document @recorder
      @recorder.callbacks.should_not include(:after_create)
    end
  end
end

describe "update callbacks" do

  before(:each) do
    @recorder = CallbackRecorder.new :required_property => 1

    couchrest_database = stub 'couchrest_database', :save_doc => {'id' => '1', 'rev' => '2'}, :view => {'rows' => []}, :info => nil
    @db = CouchTomato::Database.new(couchrest_database)
    @db.save_document! @recorder

    @recorder.required_property = 2
    @recorder.callbacks.clear
  end

  describe "successful update" do

    before(:each) do
      @db.save_document! @recorder
    end

    it "should call before_validation" do
      @recorder.callbacks.should include(:before_validation)
    end

    it "should call before_validation_on_update" do
      @recorder.callbacks.should include(:before_validation_on_update)
    end

    it "should call before_validation_on_save" do
      @recorder.callbacks.should include(:before_validation_on_save)
    end

    it "should call before_save" do
      @recorder.callbacks.should include(:before_save)
    end

    it "should call after_save" do
      @recorder.callbacks.should include(:after_save)
    end

    it "should call before_update" do
      @recorder.callbacks.should include(:before_update)
    end

    it "should call after_update" do
      @recorder.callbacks.should include(:after_update)
    end

  end

  describe "failed update" do

    before(:each) do
       @recorder.required_property = nil
       @db.save_document @recorder
    end

    it "should call before_validation" do
      @recorder.callbacks.should include(:before_validation)
    end

    it "should call before_validation_on_update" do
      @recorder.callbacks.should include(:before_validation_on_update)
    end

    it "should call before_validation_on_save" do
      @recorder.callbacks.should include(:before_validation_on_save)
    end

    it "should not call before_save" do
      @recorder.callbacks.should_not include(:before_save)
    end

    it "should not call after_save" do
      @recorder.callbacks.should_not include(:after_save)
    end

    it "should not call before_update" do
      @recorder.callbacks.should_not include(:before_update)
    end

    it "should not call after_update" do
      @recorder.callbacks.should_not include(:after_update)
    end

  end

end

describe "destroy callbacks" do

  before(:each) do
    @recorder = CallbackRecorder.new :required_property => 1
    couchrest_database = stub 'couchrest_database', :save_doc => {'id' => '1', 'rev' => '2'}, :delete_doc => nil, :view => {'rows' => []}, :info => nil
    @db = CouchTomato::Database.new(couchrest_database)
    @db.save_document! @recorder

    @recorder.callbacks.clear
  end

  it "should call before_destroy" do
    @db.destroy_document @recorder
    @recorder.callbacks.should include(:before_destroy)
  end

  it "should call after_destroy" do
    @db.destroy_document @recorder
    @recorder.callbacks.should include(:after_destroy)
  end
end

describe "lambda callbacks" do
  it "should run the lambda" do
    recorder = CallbackRecorder.new
    recorder.run_callbacks :before_create
    recorder.lambda_works.should be_true
  end
end


text:
import React from 'react'
import styled from '@emotion/styled'
import mediaqueries from '@styles/media'

const StyledTable = styled.table`
  position: relative;
  line-height: 1.65;
  color: ${(p) => p.theme.colors.grey};
  font-family: ${(p) => p.theme.fonts.sansSerif};
  transition: ${(p) => p.theme.colorModeTransition};
  background: ${(p) => p.theme.colors.card};
  margin: 45px auto 85px;
  width: 100%;
  max-width: 1004px;
  border: 1px solid ${(p) => p.theme.colors.horizontalRule};
  border-radius: 5px;
  overflow: hidden;
  border-collapse: separate;

  ${mediaqueries.desktop`
    margin: 25px auto 65px;
  `}

  ${mediaqueries.tablet`
    max-width: 486px;
  `};

  ${mediaqueries.phablet`
    margin: 15px auto 55px;
  `};
`

const Table: React.FC<{}> = ({ children }) => {
  return (
    <div style={{ overflowX: 'auto', padding: '0 20px' }}>
      <StyledTable>{children}</StyledTable>
    </div>
  )
}

export default Table


text:
module.exports = function (_) {
    // @module({ "client": true })

    /**
     * Recursively go into an object and make sure no fields matching remove list
     * exist
     * @param data Data to be changed
     * @param fieldsToRemove An array of field names
     */
    function removeAllFieldsFromObj(data, fieldsToRemove) {

        // if data is an array, loop through it and call this function recursively
        if (_.isArray(data)) {
            _.each(data, function (item) {
                removeAllFieldsFromObj(item, fieldsToRemove);
            });
        }
        else if (!_.isFunction(data) && _.isObject(data)) {
            _.each(data, function (item, key) {
                if (fieldsToRemove.indexOf(key) >= 0) {
                    delete data[key];
                }
                else {
                    removeAllFieldsFromObj(item, fieldsToRemove);
                }
            });
        }
    }

    /**
     * Translate data from one format to another. The map contains keys
     * with the values from the data and then the values of the map correspond to the
     * desired output. For example: "col1": "some.thing.blah" would move the value
     * for 'col1' into a value 'blah' that is within an object 'thing' within another
     * object 'some'
     *
     * @param map An object with the mapping
     * @param data The data to be changed
     */
    function mapData(map, data) {
        if (!map || !_.isObject(map) || !data || !_.isObject(data)) {
            return data;
        }

        var obj = {};
        _.each(map, function (targets, sourceName) {

            // if not an array, turn it into one for the sake of our logic
            if (!_.isArray(targets)) {
                targets = [targets];
            }

            // loop through targets
            _.each(targets, function (target) {
                var pathParts = target.split('.');
                var lastItemIndex = pathParts.length - 1;
                var pointer = obj;
                var sourceValue = data[sourceName];

                // if the source value actual exists, attempt to map it to the target data
                if (sourceValue) {
                    _.each(pathParts, function (part, index) {
                        if (index < lastItemIndex) {
                            if (!pointer.hasOwnProperty(part)) {
                                pointer[part] = {};
                            }
                            pointer = pointer[part];
                        }
                        else {
                            pointer[part] = sourceValue;
                        }
                    });
                }
            });
        });

        return obj;
    }

    /**
     * Get a value within given data by traversing the data according to a
     * dot deliminated field. For example, if the data is { foo: { choo: 'some' } }
     * and then the field is foo.choo, the return value would be 'some'.
     *
     * @param data
     * @param field
     * @param defaultValue
     */
    function getNestedValue(data, field, defaultValue) {
        if (!data || !field) { return defaultValue; }

        var pntr = data;
        var fieldParts = field.split('.');

        var i, fieldPart;
        for (i = 0; i < fieldParts.length; i++) {
            fieldPart = fieldParts[i];
            pntr = pntr[fieldPart];
            //if (!pntr) { return pntr; }
            if (!pntr) { return defaultValue; }
        }

        return pntr || defaultValue;
    }

    /**
     * Set a nested value based on a field param which can have a nested field
     * separated by dots (ex: blah.foo.me)
     * @param data
     * @param field
     * @param value
     */
    function setNestedValue(data, field, value) {
        var fieldParts = _.isArray(field) ? field : field.split('.');

        // if no nesting, just set the value
        if (fieldParts.length === 1) {
            data[field] = _.isString(value) ? value.trim() : value;
            return;
        }

        // make sure the parent value exists
        data[fieldParts[0]] = data[fieldParts[0]] || {};

        // recursively call to go down a level
        setNestedValue(data[fieldParts[0]], fieldParts.slice(1, fieldParts.length), value);
    }

    /**
     * True if the given data matches the criteria. If criteria empty,
     * then always true
     *
     * Examples
     *
     * Obj: { a: 'monday', b: 'tuesday' }  Criteria: { a: 'monday' } // true
     * Obj: { a: 'monday', b: 'tuesday' }  Criteria: { a: 'tuesday' } // false
     * Obj: { a: 'monday', b: 'tuesday' }  Criteria: { c: 'monday' } // false
     * Obj: { a: 'monday', b: 'tuesday' }  Criteria: { a: { '$ne' : tuesday' } } // true
     *
     * @param data
     * @param criteria
     * @returns {Boolean}
     */
    function matchesCriteria(data, criteria) {
        data = data || {};
        criteria = criteria || {};

        var match = true;
        _.each(criteria, function (val, key) {
            var hasNotOperand = false;

            if (_.isObject(val) && val['$ne'] ) {
                hasNotOperand = true;
                val = val['$ne'];
            }
            var dataValue = getNestedValue(data, key);
            if (_.isString(val) && _.isArray(dataValue)) { // allows you to check if an array contains a value
                match = (dataValue.indexOf(val) > -1);
            }
            else {
                var vals = _.isArray(val) ? val : [val];
                if (vals.indexOf(dataValue) < 0) {
                    match = false;
                }
                if ( hasNotOperand ) {
                    match = !match;
                }
            }
        });

        return match;
    }

    // expose functions
    return {
        removeAllFieldsFromObj: removeAllFieldsFromObj,
        mapData: mapData,
        getNestedValue: getNestedValue,
        setNestedValue: setNestedValue,
        matchesCriteria: matchesCriteria
    };
};


text:
require 'ordoro/record/base'

module Ordoro
  module Record
    # Supplier record included as part of a Product result
    class ProductSupplier < Base

      attribute :supplier_sku, String
      attribute :min_order_qty, Integer
      attribute :is_default, Boolean
      attribute :supplier_price, BigDecimal

      def save_embedded(parent)
        parent.client.adapter_for(self.class.demodulized_name)
              .save_embedded(self, parent)
      end

    end
  end
end


text:
"""
@package mi.dataset.parser.adcpt_acfgm_dcl_pd8
@file marine-integrations/mi/dataset/parser/adcpt_acfgm_dcl_pd8.py
@author Sung Ahn
@brief Parser for the adcpt_acfgm_dcl_pd8 dataset driver

This file contains code for the adcpt_acfgm_dcl_pd8 parsers and code to produce data particles.
instrument and instrument recovered.

All records start with a timestamp.
DCL log records: timestamp [text] more text newline.
Sensor Data records: timestamp sensor_data newline.
Only sensor data records produce particles if properly formed.
Mal-formed sensor data records and all dcl log records produce no particles.

The sensor data record has the following format:

<DCL Timestamp> <Instrument Timestamp> <Ensemble Number>
<DCL Timestamp> Hdg: <Heading> Pitch: <Pitch> Roll: <Roll>
<DCL Timestamp> Temp: <Temperature> SoS: <Speed of Sound> BIT: <BIT>
<DCL Timestamp> Bin    Dir    Mag     E/W     N/S    Vert     Err   Echo1  Echo2  Echo3  Echo4..
<DCL Timestamp>   1   <DIR 1>   <MAG 1>      <EW 1>      <NS 1>      <VERT 1>       <ERR 1>    <ECHO1 1>    <ECHO2 1>    <ECHO3 1>    <ECHO4 1>
<DCL Timestamp>   ...
<DCL Timestamp>   <N>   <DIR N>   <MAG N>      <EW N>      <NS N>      <VERT N>       <ERR N>    <ECHO1 N>    <ECHO2 N>    <ECHO3 N>    <ECHO4 N>

Release notes:

Initial Release
"""

__author__ = 'Sung Ahn'
__license__ = 'Apache 2.0'

import re
import numpy
from mi.core.log import get_logger
log = get_logger()
from mi.core.common import BaseEnum

from mi.dataset.parser.dcl_file_common import DclInstrumentDataParticle, \
    TIMESTAMP, START_METADATA, END_METADATA, START_GROUP, END_GROUP, SENSOR_GROUP_TIMESTAMP

from mi.core.exceptions import RecoverableSampleException
from mi.dataset.dataset_parser import SimpleParser

from mi.dataset.parser.common_regexes import FLOAT_REGEX, UNSIGNED_INT_REGEX, INT_REGEX, \
    SPACE_REGEX, ANY_CHARS_REGEX, ASCII_HEX_CHAR_REGEX

# Basic patterns
UINT = '(' + UNSIGNED_INT_REGEX + ')'   # unsigned integer as a group
SINT = '(' + INT_REGEX + ')'            # signed integer as a group
FLOAT = '(' + FLOAT_REGEX + ')'         # floating point as a captured group
FLOAT_OR_DASH = '(' + FLOAT_REGEX + '|\-\-' + ')'         # floating point as a captured group
MULTI_SPACE = SPACE_REGEX + '+'
ANY_NON_BRACKET_CHAR = r'[^\[\]]+'

# DCL Timestamp at the start of each record: YYYY/MM/DD HH:MM:SS.mmm
SENSOR_DATE = r'\d{4}/\d{2}/\d{2}'          # Sensor Date: YYYY/MM/DD
SENSOR_TIME = r'\d{2}:\d{2}:\d{2}.\d{2}'    # Sensor Time: HH:MM:SS.mm
TWO_HEX = '(' + ASCII_HEX_CHAR_REGEX + ASCII_HEX_CHAR_REGEX + ')'

# DCL Log record:
#   Timestamp [Text]MoreText newline
DCL_LOG_PATTERN = TIMESTAMP + SPACE_REGEX   # DCL controller timestamp
DCL_LOG_PATTERN += START_METADATA           # Metadata record starts with '['
DCL_LOG_PATTERN += ANY_NON_BRACKET_CHAR     # followed by text
DCL_LOG_PATTERN += END_METADATA             # followed by ']'
DCL_LOG_PATTERN += ANY_CHARS_REGEX          # followed by more text
DCL_LOG_MATCHER = re.compile(DCL_LOG_PATTERN)

# Header 1
# 2013/12/01 01:04:18.213 2013/12/01 01:00:27.53 00001\n
SENSOR_TIME_PATTERN = TIMESTAMP + MULTI_SPACE  # DCL controller timestamp
SENSOR_TIME_PATTERN += START_GROUP + SENSOR_DATE + MULTI_SPACE  # sensor date
SENSOR_TIME_PATTERN += SENSOR_TIME + END_GROUP + MULTI_SPACE    # sensor time
SENSOR_TIME_PATTERN += UINT                                     # Ensemble Number
SENSOR_TIME_MATCHER = re.compile(SENSOR_TIME_PATTERN)

# Header 2
# 2013/12/01 01:04:18.246 Hdg: 34.7 Pitch: 0.0 Roll: -1.1\n
SENSOR_HEAD_PATTERN = TIMESTAMP + MULTI_SPACE  # DCL controller timestamp
SENSOR_HEAD_PATTERN += 'Hdg:' + MULTI_SPACE + FLOAT + MULTI_SPACE           # Hdg
SENSOR_HEAD_PATTERN += 'Pitch:' + MULTI_SPACE + FLOAT + MULTI_SPACE         # Pitch
SENSOR_HEAD_PATTERN += 'Roll:' + MULTI_SPACE + FLOAT                        # Roll
SENSOR_HEAD_MATCHER = re.compile(SENSOR_HEAD_PATTERN)

# Header 3
# 2013/12/01 01:04:18.279 Temp: 13.8 SoS: 1505 BIT: 00\n
SENSOR_TEMP_PATTERN = TIMESTAMP + MULTI_SPACE  # DCL controller timestamp
SENSOR_TEMP_PATTERN += 'Temp:' + MULTI_SPACE + FLOAT + MULTI_SPACE          # temp
SENSOR_TEMP_PATTERN += 'SoS:' + MULTI_SPACE + SINT + MULTI_SPACE            # SoS
SENSOR_TEMP_PATTERN += 'BIT:' + MULTI_SPACE + TWO_HEX                       # sensor BIT
SENSOR_TEMP_MATCHER = re.compile(SENSOR_TEMP_PATTERN)

# Header 4
# 2013/12/01 01:04:18.363 Bin    Dir    Mag     E/W     N/S    Vert     Err   Echo1  Echo2  Echo3  Echo4\n
IGNORE_HEADING_PATTERN = TIMESTAMP + MULTI_SPACE  # DCL controller timestamp
IGNORE_HEADING_PATTERN += 'Bin' + MULTI_SPACE + ANY_CHARS_REGEX
IGNORE_HEADING_MATCHER = re.compile(IGNORE_HEADING_PATTERN)

# Sensor Data Record:
# 2013/12/01 01:04:18.446   1   14.6   47.5      12      46      -3       5    162    168    164    168\n
SENSOR_DATA_PATTERN = TIMESTAMP + MULTI_SPACE   # DCL controller timestamp
SENSOR_DATA_PATTERN += UINT + MULTI_SPACE       # bin
SENSOR_DATA_PATTERN += FLOAT_OR_DASH + MULTI_SPACE      # Dir
SENSOR_DATA_PATTERN += FLOAT_OR_DASH + MULTI_SPACE      # Mag
SENSOR_DATA_PATTERN += SINT + MULTI_SPACE       # E/W
SENSOR_DATA_PATTERN += SINT + MULTI_SPACE       # N/S
SENSOR_DATA_PATTERN += SINT + MULTI_SPACE       # Vert
SENSOR_DATA_PATTERN += SINT + MULTI_SPACE       # Err
SENSOR_DATA_PATTERN += UINT + MULTI_SPACE       # Echo1
SENSOR_DATA_PATTERN += UINT + MULTI_SPACE       # Echo2
SENSOR_DATA_PATTERN += UINT + MULTI_SPACE       # Echo3
SENSOR_DATA_PATTERN += UINT                     # Echo4
SENSOR_DATA_MATCHER = re.compile(SENSOR_DATA_PATTERN)

# Empty Timestamp
# 2013/12/01 01:04:20.834\n
IGNORE_EMPTY_PATTERN = TIMESTAMP + '\s*$'       # DCL controller timestamp
IGNORE_EMPTY_MATCHER = re.compile(IGNORE_EMPTY_PATTERN)

# The following are indices into groups()
# incremented after common timestamp values.
# i.e, match.groups()[INDEX]

# SENSOR_TIME_MATCHER produces the following groups.
SENSOR_TIME_SENSOR_DATE_TIME = 8
SENSOR_TIME_ENSEMBLE = 9

# SENSOR_HEAD_MATCHER produces the following groups.
HEAD_HEADING = 8
HEAD_PITCH = 9
HEAD_ROLL = 10

# SENSOR_TEMP_MATCHER produces the following groups.
TEMP_TEMP = 8
TEMP_SOS = 9
TEMP_HEX = 10

# SENSOR_DATA_MATCHER produces the following groups.
SENSOR_DATA_BIN = 8

#  encoding function for water_velocity and water_direction
#  the adcp puts "--" in the output when these can't be computed
#  return fill value when found
def float_or_dash(val):
    if val == '--':
        return None
    else:
        return float(val)

# The following is used for DclInstrumentDataParticle._build_parsed_values() and defined as below:
# (parameter name, index into parsed_data[], encoding function)
PD8_DATA_MAP = [
    ('dcl_controller_timestamp',            0,  str),       # Last timestamp from the DCL controller
    ('instrument_timestamp',                8,  str),
    ('ensemble_number',                     9, int),
    ('heading',                             10, float),
    ('pitch',                               11, float),
    ('roll',                                12, float),
    ('temperature',                         13, float),
    ('speed_of_sound',                      14, int),
    ('bit_result_demod_1',                  15, int),
    ('bit_result_demod_0',                  16, int),
    ('bit_result_timing',                   17, int),
    ('water_direction',                     18, lambda x: [float_or_dash(y) for y in x]),
    ('water_velocity',                      19, lambda x: [float_or_dash(y) for y in x]),
    ('water_velocity_east',                 20, lambda x: [int(y) for y in x]),
    ('water_velocity_north',                21, lambda x: [int(y) for y in x]),
    ('water_velocity_up',                   22, lambda x: [int(y) for y in x]),
    ('error_velocity',                      23, lambda x: [int(y) for y in x]),
    ('echo_intensity_beam1',                24, lambda x: [int(y) for y in x]),
    ('echo_intensity_beam2',                25, lambda x: [int(y) for y in x]),
    ('echo_intensity_beam3',                26, lambda x: [int(y) for y in x]),
    ('echo_intensity_beam4',                27, lambda x: [int(y) for y in x]),
    ('num_cells',                           28, int)
]

class DataParticleType(BaseEnum):
    ADCPT_ACFGM_PD8_DCL_INSTRUMENT = 'adcpt_acfgm_pd8_dcl_instrument'
    ADCPT_ACFGM_PD8_DCL_INSTRUMENT_RECOVERED = 'adcpt_acfgm_pd8_dcl_instrument_recovered'

class AdcptAcfgmPd8InstrumentDataParticle(DclInstrumentDataParticle):
    """
    Class for generating the adcpt_acfgm_dcl_pd8 instrument particle.
    """

    def __init__(self, raw_data, *args, **kwargs):
        super(AdcptAcfgmPd8InstrumentDataParticle, self).__init__(
            raw_data, PD8_DATA_MAP, *args, **kwargs)

class AdcptAcfgmPd8DclInstrumentParticle(AdcptAcfgmPd8InstrumentDataParticle):
    """
    Class for generating Data Particles from Telemetered data.
    """
    _data_particle_type = DataParticleType.ADCPT_ACFGM_PD8_DCL_INSTRUMENT

class AdcptAcfgmPd8DclInstrumentRecoveredParticle(AdcptAcfgmPd8InstrumentDataParticle):
    """
    Class for generating Data Particles from Recovered data.
    """
    _data_particle_type = DataParticleType.ADCPT_ACFGM_PD8_DCL_INSTRUMENT_RECOVERED

class AdcptAcfgmPd8Parser(SimpleParser):
    """
    ADCPT ACFGM PD8 Parser.
    """

    def recov_exception_callback(self, message):
        log.warn(message)
        self._exception_callback(RecoverableSampleException(message))

    def parse_file(self):
        """
        Open and read the file and parser the data within, and at the end of
        this method self._record_buffer will be filled with all the particles in the file.
        """

        while True:  # loop through file looking for beginning of an adcp data burst

            line = self._stream_handle.readline()  # READ NEXT LINE

            if line == "":
                break

            # Check if this is a DCL Log message
            dcl_log_match = DCL_LOG_MATCHER.match(line)
            if dcl_log_match:
                # verified to be a regular DCL Log. Discard & move to next line.
                continue  # skip to next line in outer loop

            line_match = SENSOR_TIME_MATCHER.match(line)
            if line_match is None:
                self.recov_exception_callback("Expected starting DCL Timestamp, received: %r" % line)
                continue  # skip to next line in outer loop

            matches = line_match.groups()
            sensor_data_list = []

            # Save timestamp from the DCL controller log and it's parts
            parsed_data = list(matches[SENSOR_GROUP_TIMESTAMP:SENSOR_TIME_SENSOR_DATE_TIME])

            # Get instrument_timestamp & ensemble_number
            parsed_data.append(matches[SENSOR_TIME_SENSOR_DATE_TIME])
            parsed_data.append(matches[SENSOR_TIME_ENSEMBLE])

            line = self._stream_handle.readline()  # READ NEXT LINE

            line_match = SENSOR_HEAD_MATCHER.match(line)
            if line_match is None:
                self.recov_exception_callback("Expecting Heading, Pitch, & Roll data, received: %r" % line)
                continue  # skip to next line in outer loop

            matches = line_match.groups()
            # Get head, pitch, & roll
            parsed_data.append(matches[HEAD_HEADING])
            parsed_data.append(matches[HEAD_PITCH])
            parsed_data.append(matches[HEAD_ROLL])

            line = self._stream_handle.readline()  # READ NEXT LINE

            line_match = SENSOR_TEMP_MATCHER.match(line)
            if line_match is None:
                self.recov_exception_callback("Expecting Temperature, Speed of Sound, & BIT data,"
                                              " received: %r" % line)
                continue  # skip to next line in outer loop

            matches = line_match.groups()
            # Get temperature,  speed of sound, & BIT values
            parsed_data.append(matches[TEMP_TEMP])
            parsed_data.append(matches[TEMP_SOS])

            binary_string = '{0:08b}'.format(int(matches[TEMP_HEX], 16))
            parsed_data.append(binary_string[3])
            parsed_data.append(binary_string[4])
            parsed_data.append(binary_string[6])

            line = self._stream_handle.readline()  # READ NEXT LINE

            line_match = IGNORE_HEADING_MATCHER.match(line)
            if line_match is None:
                self.recov_exception_callback("Expecting Header, received: %s" % line)
                continue  # skip to next line in outer loop

            # Start looking for sensor data
            while True:  # loop through all the velocity and echo data records

                line = self._stream_handle.readline()  # READ NEXT LINE

                line_match = SENSOR_DATA_MATCHER.match(line)
                if line_match is not None:
                    # Collect velocity data sextets and echo power quartets
                    sensor_data_list.append(line_match.groups()[SENSOR_DATA_BIN:])
                else:
                    try:
                        # Transpose velocity data sextets and echo power quartets
                        np_array = numpy.array(sensor_data_list)
                        parsed_data.extend(np_array.transpose().tolist()[1:])

                        # Get number of cells
                        parsed_data.append(sensor_data_list[-1][0])
                        particle = self._extract_sample(self._particle_class,
                                                        None,
                                                        parsed_data,
                                                        None)
                        if particle is not None:
                            self._record_buffer.append(particle)

                    except Exception:
                        self.recov_exception_callback("Error parsing sensor data row,"
                                                      " received: %s" % line)

                    break  # exit inner loop once a particle has been produced


text:
<?php

namespace Google\Service\Docs;

class NamedRanges extends \Google\Collection
{
  protected $collection_key = 'namedRanges';
  /**
   * @var string
   */
  public $name;
  protected $namedRangesType = NamedRange::class;
  protected $namedRangesDataType = 'array';

  /**
   * @param string
   */
  public function setName($name)
  {
    $this->name = $name;
  }
  /**
   * @return string
   */
  public function getName()
  {
    return $this->name;
  }
  /**
   * @param NamedRange[]
   */
  public function setNamedRanges($namedRanges)
  {
    $this->namedRanges = $namedRanges;
  }
  /**
   * @return NamedRange[]
   */
  public function getNamedRanges()
  {
    return $this->namedRanges;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(NamedRanges::class, 'Google_Service_Docs_NamedRanges');


text:
<?php

namespace UBC\Exam\MainBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormError;
use UBC\Exam\MainBundle\Entity\Exam;
use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\TextFilterType;
use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\ChoiceFilterType;
use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\NumberFilterType;
use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateRangeFilterType;
use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\BooleanFilterType;

class ExamFilterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            //->add('id', NumberRangeFilterType::class)
            ->add('campus', 'filter_choice', array('choices' => Exam::$CAMPUSES, 'choices_as_values' => true))
            ->add('faculty', 'filter_text')
            ->add('dept', 'filter_text')
            ->add('subject_code', 'filter_text')
            ->add('year', 'filter_number')
            ->add('term', 'filter_choice', array('choices' => array_flip(Exam::$TERMS), 'choices_as_values' => true))
            ->add('type', 'filter_choice', array('choices' => array_flip(Exam::$TYPES), 'choices_as_values' => true))
            //->add('comments', 'filter_text')
            ->add('cross_listed', 'filter_text')
            ->add('legal_content_owner', 'filter_text')
            ->add('legal_uploader', 'filter_text')
            //->add('legal_date', DateRangeFilterType::class)
            ->add('legal_agreed', 'filter_boolean')
            ->add('access_level', 'filter_choice', array('choices' => array_flip(Exam::$ACCESS_LEVELS), 'choices_as_values' => true))
            //->add('created', DateRangeFilterType::class)
            //->add('modified', DateRangeFilterType::class)
            //->add('downloads', NumberRangeFilterType::class)
        ;

        $listener = function(FormEvent $event)
        {
            // Is data empty?
            foreach ($event->getData() as $data) {
                if(is_array($data)) {
                    foreach ($data as $subData) {
                        if(!empty($subData)) return;
                    }
                }
                else {
                    if(!empty($data)) return;
                }
            }

            $event->getForm()->addError(new FormError('Filter empty'));
        };
        $builder->addEventListener(FormEvents::POST_SUBMIT, $listener);
    }

    public function getBlockPrefix()
    {
        return 'ubc_exam_mainbundle_examfiltertype';
    }
}


text:
   var path = require('path');

var webpack = require("webpack");
var ExtractTextPlugin = require("extract-text-webpack-plugin");

var PROD = JSON.parse(process.env.PROD_DEV || "0");

module.exports = {
    entry: [
      	"babel-polyfill",
    	"./less/main.less",
    	"./resources/js/game.js"
   	],
    output: {
        path: __dirname + "/build/",
        filename: PROD ? "bundle.min.js" : "bundle.js"
    },
    module: {
        loaders: [
         	{
         		test: /\.js$/,
         		loader: "babel-loader",
                query: {
                  presets: 'es2015',
                },

         	},
            {
                test: /\.less$/,
                loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")
            }
        ]
    },
  	plugins: PROD ? [
  		new ExtractTextPlugin("main.css"),
    	new webpack.optimize.UglifyJsPlugin({minimize: true}),
      new webpack.DefinePlugin({
          'process.env': {
            'NODE_ENV': JSON.stringify('production')
          }
        })
  	] : [
		  new ExtractTextPlugin("main.css"),
  	],
	stats: {
		colors: true
	},
    // Create Sourcemaps for the bundle
    //devtool: 'cheap-module-source-map',
    devtool: 'source-map',
};


text:
package db

import "gopkg.in/mgo.v2"

var (
	Db        *mgo.Database
	UsersC    *mgo.Collection
	PagesC    *mgo.Collection
	CommentsC *mgo.Collection
)

func Init(servers string)  {
	session, err := mgo.Dial(servers)
	if err != nil {
		panic(err)
	}
	Db = session.DB("comments")
	UsersC = Db.C("users")
	PagesC = Db.C("pages")
	CommentsC = Db.C("comments")
}


text:
package com.android.commands.monkey;

import android.view.InputDevice;
import android.view.MotionEvent;

/**
 * monkey touch event
 */
public class MonkeyHoverEvent extends MonkeyMotionEvent {
    public MonkeyHoverEvent(int action) {
        super(MonkeyEvent.EVENT_TYPE_HOVER, InputDevice.SOURCE_STYLUS, action);
        setToolType(MotionEvent.TOOL_TYPE_STYLUS);
    }

    @Override
    protected String getTypeLabel() {
        return "Hover";
    }
}


text:
package com.thinkbiganalytics.es;

import com.google.common.base.MoreObjects;

import java.util.ArrayList;
import java.util.List;

/**
 * Return the Elastic Search Index Mapping data
 */
public class IndexMappingDTO {

    private String index;
    private List<TypeMappingDTO> types;

    public String getIndex() {
        return index;
    }

    public void setIndex(String index) {
        this.index = index;
    }

    public List<TypeMappingDTO> getTypes() {
        if (types == null) {
            types = new ArrayList();
        }
        return types;
    }

    public void setTypes(List<TypeMappingDTO> types) {
        this.types = types;
    }

    public void addType(TypeMappingDTO type) {
        getTypes().add(type);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
            .add("index", index)
            .add("types", types)
            .toString();
    }
}


text:
package io.opentelemetry.sdk.extension.trace.jaeger.sampler;

import io.opentelemetry.exporter.internal.marshal.CodedInputStream;
import java.io.IOException;
import javax.annotation.Nullable;

class SamplingStrategyResponseUnMarshaler extends UnMarshaler {

  @Nullable private SamplingStrategyResponse samplingStrategyResponse;

  @Nullable
  public SamplingStrategyResponse get() {
    return samplingStrategyResponse;
  }

  @Override
  public void read(byte[] payload) throws IOException {
    SamplingStrategyResponse.Builder responseBuilder = new SamplingStrategyResponse.Builder();
    try {
      CodedInputStream codedInputStream = CodedInputStream.newInstance(payload);
      parseResponse(responseBuilder, codedInputStream);
      samplingStrategyResponse = responseBuilder.build();
    } catch (IOException ex) {
      // use null message
    }
  }

  private static void parseResponse(
      SamplingStrategyResponse.Builder responseBuilder, CodedInputStream input) throws IOException {
    boolean done = false;
    while (!done) {
      int tag = input.readTag();
      switch (tag) {
        case 0:
          done = true;
          break;
        case 8:
          parseSamplingStrategyType(responseBuilder, input);
          break;
        case 18:
          int length = input.readRawVarint32();
          responseBuilder.setProbabilisticSamplingStrategy(parseProbabilistic(input, length));
          break;
        case 26:
          input.readRawVarint32(); // skip length
          responseBuilder.setRateLimitingSamplingStrategy(parseRateLimiting(input));
          break;
        case 34:
          input.readRawVarint32(); // skip length
          responseBuilder.setPerOperationSamplingStrategies(parsePerOperationStrategy(input));
          break;
        default:
          input.skipField(tag);
      }
    }
  }

  private static void parseSamplingStrategyType(
      SamplingStrategyResponse.Builder responseBuilder, CodedInputStream input) throws IOException {
    int tagValue = input.readRawVarint32();
    switch (tagValue) {
      case 0:
        responseBuilder.setSamplingStrategyType(
            SamplingStrategyResponse.SamplingStrategyType.PROBABILISTIC);
        break;
      case 1:
        responseBuilder.setSamplingStrategyType(
            SamplingStrategyResponse.SamplingStrategyType.RATE_LIMITING);
        break;
      default:
        responseBuilder.setSamplingStrategyType(
            SamplingStrategyResponse.SamplingStrategyType.UNRECOGNIZED);
        break;
    }
  }

  private static SamplingStrategyResponse.ProbabilisticSamplingStrategy parseProbabilistic(
      CodedInputStream input, int length) throws IOException {
    SamplingStrategyResponse.ProbabilisticSamplingStrategy.Builder builder =
        new SamplingStrategyResponse.ProbabilisticSamplingStrategy.Builder();
    if (length == 0) {
      // Default probabilistic strategy.
      return builder.setSamplingRate(0.0).build();
    }
    boolean done = false;
    while (!done) {
      int tag = input.readTag();
      switch (tag) {
        case 0:
          done = true;
          break;
        case 9:
          double samplingRate = input.readDouble();
          return builder.setSamplingRate(samplingRate).build();
        default:
          input.skipField(tag);
          break;
      }
    }
    return builder.build();
  }

  private static SamplingStrategyResponse.RateLimitingSamplingStrategy parseRateLimiting(
      CodedInputStream input) throws IOException {
    SamplingStrategyResponse.RateLimitingSamplingStrategy.Builder builder =
        new SamplingStrategyResponse.RateLimitingSamplingStrategy.Builder();
    boolean done = false;
    while (!done) {
      int tag = input.readTag();
      switch (tag) {
        case 0:
          done = true;
          break;
        case 8:
          int rate = input.readRawVarint32();
          return builder.setMaxTracesPerSecond(rate).build();
        default:
          input.skipField(tag);
          break;
      }
    }
    return builder.build();
  }

  private static SamplingStrategyResponse.PerOperationSamplingStrategies parsePerOperationStrategy(
      CodedInputStream input) throws IOException {
    SamplingStrategyResponse.PerOperationSamplingStrategies.Builder builder =
        new SamplingStrategyResponse.PerOperationSamplingStrategies.Builder();
    boolean done = false;
    while (!done) {
      int tag = input.readTag();
      switch (tag) {
        case 0:
          done = true;
          break;
        case 9:
          double defaultProbability = input.readDouble();
          builder.setDefaultSamplingProbability(defaultProbability);
          break;
        case 17:
          double lowerBoundPerSecond = input.readDouble();
          builder.setDefaultLowerBoundTracesPerSecond(lowerBoundPerSecond);
          break;
        case 26:
          input.readRawVarint32(); // skip length
          SamplingStrategyResponse.OperationSamplingStrategy strategy =
              parseOperationStrategy(input);
          if (strategy != null) {
            builder.addOperationStrategy(strategy);
          }
          break;
        case 33:
          double upperBoundPerSecond = input.readDouble();
          builder.setDefaultUpperBoundTracesPerSecond(upperBoundPerSecond);
          break;
        default:
          input.skipField(tag);
          break;
      }
    }
    return builder.build();
  }

  private static SamplingStrategyResponse.OperationSamplingStrategy parseOperationStrategy(
      CodedInputStream input) throws IOException {

    SamplingStrategyResponse.OperationSamplingStrategy.Builder builder =
        new SamplingStrategyResponse.OperationSamplingStrategy.Builder();

    boolean done = false;
    boolean operationParsed = false;
    boolean probabilisticSamplingParsed = false;
    while (!done) {
      int tag = input.readTag();
      switch (tag) {
        case 0:
          done = true;
          break;
        case 10:
          operationParsed = true;
          String operation = input.readStringRequireUtf8();
          builder.setOperation(operation);
          break;
        case 18:
          probabilisticSamplingParsed = true;
          int length = input.readRawVarint32();
          builder.setProbabilisticSamplingStrategy(parseProbabilistic(input, length));
          break;
        default:
          input.skipField(tag);
          break;
      }

      if (operationParsed && probabilisticSamplingParsed) {
        break;
      }
    }
    return builder.build();
  }
}


text:
var mongoose = require('mongoose');
var random = require('mongoose-random');

var questionSchema = mongoose.Schema({
  text: {
    type: String,
    unique: true,
    required: true
  },
  type: {
    type: String,
    enum: ['multichoice', 'numerical', 'truefalse'],
    required: true
  },
  language: {
    type: String,
    enum: ['en', 'es'],
    required: true
  },
  answers: [{
    text: String,
    score: {
      type: Number,
      min: 0,
      max: 100,
      default: 0
    }
  }],
  meta: {
    favs: {
      type: Number,
      default: 0
    },
    votes: {
      type: Number,
      default: 0
    },
    tags: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'tag'
    }]
  }
});

questionSchema.plugin(random);

module.exports = mongoose.model('question', questionSchema);


text: sudo apt-get install sendmail


text:
#include "../colorlog.h"

/* compile this example with :
 * g++ example.cpp -o example_cpp -D_LOG_ALL
 *   to print all log line
 * or
 * g++ example.cpp -o example_cpp -D_LOG_WARNING -D_LOG_INFO
 *   to print only warning and info levels
 * or
 * g++ example.cpp -o example_cpp -D_LOG_ALL -D_LOG_NO_VERBOSE
 *   to print all log line except verbose level
 */

int main(int argc, char* argv[]) {

	VERBOSE("main","start log");
	WARNING("main","start warning %d",1);
	ALERT("main","start alert %f",1.2);
	INFO("main","start info %d %f",1,2.3);
	SUCCESS("main","start success %d %d %d",1,2,3);

	return 0;
}


text:
import lombok.extern.log4j.Log4j;
@lombok.extern.log4j.Log4j class LoggerLog4j {
  private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LoggerLog4j.class);
  <clinit>() {
  }
  LoggerLog4j() {
    super();
  }
}
@Log4j class LoggerLog4jWithImport {
  private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LoggerLog4jWithImport.class);
  <clinit>() {
  }
  LoggerLog4jWithImport() {
    super();
  }
}


text:
/*
Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined
as a binary tree in which the depth of the two subtrees of
every node never differ by more than 1.
*/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <common.hpp>
class Solution
{
public:
    bool isBalanced(TreeNode *root)
    {
        //1.recursion terminator
        if (root == NULL)
        {
            return true;
        }

        //2.current level processing
        int depth1 = depth(root->left);
        int depth2 = depth(root->right);
        if (abs(depth1 - depth2) > 1)
        {
            return false;
        }

        //3.drill down
        return isBalanced(root->left) && isBalanced(root->right);
    }
    int depth(TreeNode *root)
    {
        if (root == NULL)
        {
            return 0;
        }
        return std::max(depth(root->left), depth(root->right)) + 1;
    }
};

//dp time:O(N^2) top to down method

//solution2 DFS
class solution
{
public:
    int dfsHeight(TreeNode *root)
    {
        if (root == NULL)
            return 0;

        int leftHeight = dfsHeight(root->left);
        if (leftHeight == -1)
            return -1;
        int rightHeight = dfsHeight(root->right);
        if (rightHeight == -1)
            return -1;

        if (abs(leftHeight - rightHeight) > 1)
            return -1;
        return std::max(leftHeight, rightHeight) + 1;
    }
    bool isBalanced(TreeNode *root)
    {
        return dfsHeight(root) != -1;
    }
};

//time:O(N)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ztop.Todo.Common;
namespace Ztop.Todo.Web.Areas.Jurisdiction
{
    [UserAuthorize]
    public class JurisdictionControllerBase : Ztop.Todo.Web.Controllers.ControllerBase
    {

    }
}