text:
class CaterpillarGenerator < Rails::Generator::Base

  attr_accessor :project_name

  def msg(txt)
    _txt = " *\n"
    txt.split("\n").each do |line|
      _txt << " * %s\n" % line
    end
    _txt << " *\n"
    STDOUT.puts _txt
    STDOUT.flush
  end

  def after_generate
    # generate random shared secret
    msg(
      "Generating new random shared secret to config/portlets.rb"
    )
    File.open(File.join('config','portlets.rb'), "r+") do |f|
      newconf = f.read().sub('somereallylongrandomkey', Caterpillar::Security::random_secret)
      f.seek 0
      f.write newconf
    end

    msg(
      "If you want to use the portlet test bench,\n" + \
      "put the following line in your config/routes.rb before other routes.\n" + \
      "  map.caterpillar"
    )
  end

  def manifest
    require 'find'
    file = File.symlink?(__FILE__) ? File.readlink(__FILE__) : __FILE__
    this_dir = File.dirname(File.expand_path(file))
    tmpl = File.join(this_dir,'templates')

    @project_name = RAILS_ROOT.split('/')[-1]
    msg 'Installing configuration file with images, stylesheets and javascripts.'

    record do |m|

      ### config ###
      file = File.join('config','portlets.rb')
      m.template(file,file)

      ### Navigation ###
      target = File.join('public','images')
      m.directory(target)
      file = 'caterpillar.gif'
      m.file(File.join('images','caterpillar',file), File.join(target,file))

      ### Test bench ###
      testb = 'portlet_test_bench'

      #
      # images
      #
      target = File.join('public','images',testb)
      m.directory(target)
      Find.find(File.join(tmpl,'images',testb)) do |file|
        if FileTest.directory?(file)
          next
        else
          img = File.basename(file)
          next unless img[/(.jpg|.png|.gif)$/]
          m.file(File.join('images',testb,img), File.join(target,img))
        end
      end

      #
      # stylesheets
      #
      target = File.join('public','stylesheets',testb)
      m.directory(target)
      file = 'main.css'
      m.file(File.join('stylesheets',testb,file), File.join(target,file))

      #
      # javascripts
      #
      target = File.join('public','javascripts',testb)
      m.directory(target)
      file = 'main.js'
      m.file(File.join('javascripts',testb,file), File.join(target,file))

    end
  end
end


text:
using BackendlessAPI;
using BackendlessAPI.Async;
using BackendlessAPI.Data;
using BackendlessAPI.Exception;
using BackendlessAPI.Geo;
using BackendlessAPI.Service;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using BackendlessAPI.Property;

namespace BackendlessAPI.Test
{

    [TestClass()]
    public class AsyncGeoServiceTest
    {

        private double METERS = 0.00001d;
        private TestContext testContextInstance;
        GeoService target = new GeoService();
        Random random = new Random((int)DateTime.Now.Ticks);
        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes

        #endregion
        [TestInitialize()]
        public void MyTestInitialize()
        {
            string applicationId = "validApp-Ids0-0000-0000-000000000000"; // TODO: Initialize to an appropriate value
            string secretKey = "validSec-retK-eys0-0000-000000000000"; // TODO: Initialize to an appropriate value
            string version = "v1"; // TODO: Initialize to an appropriate value
            Backendless.InitApp(applicationId, secretKey, version);
        }

        ///
        ///A test for AddCategory
        ///
        [TestMethod()]
        public void AddNullCategoryTest()
        {
            try
            {
                AsyncCallback<GeoCategory> callback = new AsyncCallback<GeoCategory>(
                u =>
                {

                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                target.AddCategory(null, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.AreEqual("N/A", ex.Code);
            }
        }
        [TestMethod()]
        public void AddEmptyCategoryTest()
        {
            try
            {
                AsyncCallback<GeoCategory> callback = new AsyncCallback<GeoCategory>(
                u =>
                {

                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                target.AddCategory(string.Empty, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.AreEqual("N/A", ex.Code);
            }
        }
        [TestMethod()]
        public void DeleteNullCategoryTest()
        {
            try
            {
                AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>(
                u =>
                {
                    Assert.IsTrue(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                string categoryName = null;
                target.DeleteCategory(categoryName, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.AreEqual("N/A", ex.Code);
            }
        }
        [TestMethod()]
        public void DeleteEmptyCategoryTest()
        {
            try
            {
                AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>(
                u =>
                {
                    Assert.IsTrue(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                string categoryName = string.Empty;
                target.DeleteCategory(categoryName, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.AreEqual("N/A", ex.Code);
            }
        }
        [TestMethod()]
        public void AddDefaultCategoryTest()
        {
            try
            {
                AsyncCallback<GeoCategory> callback = new AsyncCallback<GeoCategory>(
                u =>
                {
                    Assert.AreEqual("Default", u.Name);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                string categoryName = "Default";
                target.AddCategory(categoryName, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.AreEqual("N/A", ex.Code);
            }
        }
        [TestMethod()]
        public void DeleteDefaultCategoryTest()
        {
            try
            {
                AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>(
                u =>
                {
                    Assert.IsTrue(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                string categoryName ="Default";
                target.DeleteCategory(categoryName, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.AreEqual("N/A", ex.Code);
            }
        }
        [TestMethod()]
        public void AddCategoryTest()
        {
            try
            {
                string categoryName = "category_test";
                AsyncCallback<GeoCategory> callback = new AsyncCallback<GeoCategory>(
                u =>
                {
                    Assert.AreEqual(categoryName, u.Name);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });

                target.AddCategory(categoryName, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        [TestMethod()]
        public void AddCategoryTwiceTest()
        {
            try
            {
                string categoryName = "cate"+random.Next();
                AsyncCallback<GeoCategory> callback2 = new AsyncCallback<GeoCategory>(
                u =>
                {
                    AsyncCallback<GeoCategory> callback1 = new AsyncCallback<GeoCategory>(
                    r =>
                    {
                        Assert.AreEqual(r.ObjectId, u.ObjectId);
                    },
                    f =>
                    {
                        Assert.Fail(f.Message);
                    });
                    target.AddCategory(categoryName, callback1);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });

                target.AddCategory(categoryName, callback2);

            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        [TestMethod()]
        public void RemoveCategoryTest()
        {
            try
            {
                string categoryName = "cate" + random.Next();
                AsyncCallback<bool> deleteCallback = new AsyncCallback<bool>(
                u =>
                {
                    Assert.IsTrue(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                AsyncCallback<GeoCategory> saveCallback = new AsyncCallback<GeoCategory>(
                u =>
                {
                    target.DeleteCategory(u.Name,deleteCallback);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                target.AddCategory(categoryName, saveCallback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        [TestMethod()]
        public void RemoveNonExistingCategoryTest()
        {
            try
            {
                string categoryName = "cate" + random.Next();
                AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>(
                u =>
                {
                    Assert.IsTrue(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                target.DeleteCategory(categoryName, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        [TestMethod()]
        public void RetrieveListOfCategoryTest()
        {
            try
            {
                AsyncCallback<List<GeoCategory>> callback = new AsyncCallback<List<GeoCategory>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                target.GetCategories(callback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
          }
        [TestMethod()]
        public void AddPointIntoEmptyCategoryTest()
        {
            try
            {
                AsyncCallback<GeoPoint> callback = new AsyncCallback<GeoPoint>(
                u =>
                {
                    Assert.IsTrue(u.Categories[0].Contains("Default"));
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                double latitude = 1.23;
                double longitude = 2.36;
                List<string> categoryName = null;
                Dictionary<string, string> metadata = new Dictionary<string, string>();
                metadata.Add("aa", "aa");
                target.AddPoint(latitude, longitude, categoryName, metadata, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        [TestMethod()]
        public void AddPointWithTrueValueTest()
        {
            try
            {
                AsyncCallback<GeoPoint> callback = new AsyncCallback<GeoPoint>(
                u =>
                {
                    Assert.AreEqual(1.23, u.Latitude);
                    Assert.AreEqual(2.36, u.Longitude);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                double latitude = 1.23;
                double longitude = 2.36;
                Dictionary<string, string> metadata = new Dictionary<string, string>();
                metadata.Add("aa", "aa");
                target.AddPoint(latitude, longitude, metadata, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        //[TestMethod()]
        //public void AddPointWithoutParametersTest()
        //{
        //}
        [TestMethod()]
        public void AddPointWithTrueMetadataTest()
        {
            try
            {
                AsyncCallback<GeoPoint> callback = new AsyncCallback<GeoPoint>(
                u =>
                {
                    Assert.AreEqual(1.23, u.Latitude);
                    Assert.AreEqual(2.36, u.Longitude);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                Dictionary<string, string> metadata = new Dictionary<string, string>();
                metadata.Add("aa", "aa");
                double latitude = 1.23;
                double longitude = 2.36;
                List<string> categories = new List<string> {"cateName1","cateName2" };
                target.AddPoint(latitude, longitude,categories, metadata, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        [TestMethod()]
        public void AddPointAgainWithTrueMetadataTest()
        {
            try
            {
                double latitude = 1.23;
                double longitude = 2.36;
                List<string> cateName = new List<string> { "cate" + random.Next() };
                Dictionary<string, string> metadata1 = new Dictionary<string, string>();
                metadata1.Add("A", "aaa");
                metadata1.Add("B", "bbb");
                Dictionary<string, string> metadata2 = new Dictionary<string, string>();
                metadata2.Add("A", "aaa2");
                metadata2.Add("B", "bbb2");

                AsyncCallback<GeoPoint> callback = new AsyncCallback<GeoPoint>(
                u =>
                {
                    AsyncCallback<GeoPoint> callback2 = new AsyncCallback<GeoPoint>(
                    u2 =>
                    {
                         Assert.AreEqual(u.ObjectId, u2.ObjectId);
                    },
                    f =>
                    {
                        Assert.Fail(f.Message);
                    });
                    target.AddPoint(latitude, longitude, cateName, metadata2,callback2);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                target.AddPoint(latitude, longitude, cateName, metadata1,callback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        [TestMethod()]
        public void AddPointToMultipleCategoriesTest()
        {
            try
            {
                double latitude = 11.23;
                double longitude = 22.36;
                List<string> categoryName = new List<string>();
                categoryName.Add("test" + random.Next());
                categoryName.Add("test" + random.Next());
                Dictionary<string, string> metadata = new Dictionary<string, string>();
                metadata.Add("aa", "aa");
                AsyncCallback<GeoPoint> callback = new AsyncCallback<GeoPoint>(
                u =>
                {
                    Assert.AreEqual(2, u.Categories.Count);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                target.AddPoint(latitude, longitude, categoryName, metadata, callback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
        }

        [TestMethod()]
        public void GetPointsForRectCategoriesTest()
        {
            try
            {
                List<string> categories = new List<string> { "cate" + random.Next() };
                for (int i = 1; i <= 10; i++)
                {
                    double nwlat = 80.01 - 0.00001 * i;
                    double nwlon = 60.01 + 0.00001 * i;
                    Dictionary<string, string> metadata = new Dictionary<string, string>();
                    metadata.Add("TEST", "test" + i);
                    AsyncCallback<GeoPoint> saveCallback = new AsyncCallback<GeoPoint>(
                    u =>
                    {
                        Assert.IsNotNull(u);
                    },
                    f =>
                    {
                        Assert.Fail(f.Message);
                    });
                    target.AddPoint(nwlat, nwlon,categories, metadata,saveCallback);
                }

                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery(80.01, 60.01, 60.01, 80.01);
                geoQuery.Categories = categories;
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException ex)
            {
                Assert.AreEqual("N/A", ex.Code);
            }

        }
        [TestMethod()]
        public void SearchPointsInDefaultCategoryFor10MilesTest()
        {

            try
            {
                double lon = 10 * 1609.344 * METERS;
                Dictionary<string, string> metadata = new Dictionary<string, string>();
                metadata.Add("A", "aaa");
                metadata.Add("B", "bbb");
                for (int i = 0; i < 10; i++)
                {
                    AsyncCallback<GeoPoint> saveCallback = new AsyncCallback<GeoPoint>(
                    u =>
                    {

                    },
                    f =>
                    {
                        Assert.Fail(f.Message);
                    });
                    double lat = i * 1609.344 * METERS;
                    target.AddPoint(lat, lon, metadata, saveCallback);
                }
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery(5 * 1609.344 * METERS, 5 * 1609.344 * METERS, 10, Units.MILES);
                target.GetPoints(geoQuery,callback);

            }
            catch (BackendlessException e)
            {
                Assert.Fail(e.Message);
            }
        }
        [TestMethod()]
        public void SearchPointsInDefaultCategoryFor100YardsTest()
        {
            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery(1.23, 2.36, 100, Units.YARDS);
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException e)
            {
                Assert.Fail(e.Message);
            }
        }
        [TestMethod()]
        public void SearchPointsInDefaultCategoryFor1KilometerTest()
        {
            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery(1.23, 2.36, 1, Units.KILOMETERS);
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException e)
            {
                Assert.Fail(e.Message);
            }
        }
        [TestMethod()]
        public void SearchPointsInMetadataTest()
        {

            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                double latitude = 1.23;
                double longitude = 2.36;
                Dictionary<string, string> metadata = new Dictionary<string, string>();
                metadata.Add("A", "aaa");
                target.AddPoint(latitude, longitude, metadata);
                BackendlessGeoQuery query = new BackendlessGeoQuery(metadata);
                target.GetPoints(query,callback);
            }
            catch (BackendlessException e)
            {
                Assert.AreEqual("N/A", e.Code);
            }

        }
        [TestMethod()]
        public void SearchPointsInDefaultCategoryWithNegativeOffsetTest()
        {
            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.AreEqual("4003",f.FaultCode);
                });
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery(60.01, 60.01, 2, -1);
                geoQuery.Radius = 20;
                geoQuery.Units = Units.METERS;
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException ex)
            {
                Assert.AreEqual("N/A", ex.Code);
            }
        }
        [TestMethod()]
        public void searchPointsInDefaultCategoryWithOffsetGreaterThanMaxPointTest()
        {
            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.AreEqual("4003", f.FaultCode);
                });
                double lon = 10 * METERS;
                Dictionary<string, string> metadata = new Dictionary<string, string>();
                metadata.Add("A", "aaa");
                metadata.Add("B", "bbb");
                for (int i = 0; i < 14; i++)
                {
                    double lat = i * METERS;
                    target.AddPoint(lat, lon, metadata);
                }
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery(5 * METERS, 5 * METERS, 10, Units.MILES);
                geoQuery.PageSize = 1;
                geoQuery.Offset = 15;
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        [TestMethod()]
        public void SearchPointsIncludemetadataWithNegativeOffsetTest()
        {

            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();
                geoQuery.IncludeMeta = false;
                geoQuery.Latitude = 60.01;
                geoQuery.Longitude = 60.01;
                geoQuery.Radius = 20;
                geoQuery.PageSize = 2;
                geoQuery.Offset = 0;
                geoQuery.Units = Units.METERS;
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException e)
            {
                Assert.Fail(e.Message);
            }

        }
        [TestMethod()]
        public void SearchPointsInMultipleCategoriesTest()
        {
            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add("Test", "Test");
                List<string> cateName = new List<string> { "cateName1", "cateName2" };
                BackendlessGeoQuery query = new BackendlessGeoQuery();
                query.Categories = cateName;
                query.Radius = 20;
                query.Units = Units.METERS;
                query.PageSize = 5;
                query.Offset = 0;
                target.GetPoints(query,callback);
            }
            catch (BackendlessException ex)
            {
                Assert.Fail(ex.Message);
            }

        }
        [TestMethod()]
        public void GetPointsForRectangleAndRadiusTest()
        {
            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.AreEqual("4008", f.FaultCode);
                });
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery(80.01, 60.01, 60.01, 80.01);
                geoQuery.Radius = 20;
                geoQuery.Units = Units.METERS;
                geoQuery.PageSize = 2;
                geoQuery.Offset = 1;
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException ex)
            {
                Assert.AreEqual("N/A", ex.Code);
            }
        }
        [TestMethod()]
        public void SearchPointsWithWrongLatitudeTest()
        {

            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();
                geoQuery.Latitude = 91;
                geoQuery.Longitude = 180;
                geoQuery.Radius = 20;
                geoQuery.Units = Units.METERS;
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException e)
            {
                Assert.AreEqual("N/A", e.Code);
            }
        }
        [TestMethod()]
        public void SearchPointsWithWrongLongitudeTest()
        {

            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();
                geoQuery.Latitude = 90;
                geoQuery.Longitude = 181;
                geoQuery.Radius = 20;
                geoQuery.Units = Units.METERS;
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException e)
            {
                Assert.AreEqual("N/A", e.Code);
            }
        }
        [TestMethod()]
        public void SearchPointsWithNegativePagesizeTest()
        {
            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();
                geoQuery.Latitude = 30;
                geoQuery.Longitude = 60;
                geoQuery.Radius = 20;
                geoQuery.Units = Units.METERS;
                geoQuery.PageSize = -2;
                geoQuery.Offset = 1;
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException e)
            {
                Assert.AreEqual("N/A", e.Code);
            }
        }
        [TestMethod()]
        public void SearchPointsInCategoriesTest()
        {
            try
            {
                AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<BackendlessCollection<GeoPoint>>(
                u =>
                {
                    Assert.IsNotNull(u);
                },
                f =>
                {
                    Assert.Fail(f.Message);
                });
                List<string> cateName = new List<string> { "cateName1", "cateName2" };
                BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();
                geoQuery.Categories = cateName;
                geoQuery.Radius = 20;
                geoQuery.Units = Units.METERS;
                geoQuery.PageSize = 2;
                geoQuery.Offset = 0;
                target.GetPoints(geoQuery,callback);
            }
            catch (BackendlessException e)
            {
                Assert.Fail(e.Message);
            }
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.action.search;

import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.PipelineAggregationBuilder;
import org.elasticsearch.search.builder.PointInTimeBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.elasticsearch.search.fetch.subphase.FieldAndFormat;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.rescore.RescorerBuilder;
import org.elasticsearch.search.slice.SliceBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * A search action request builder.
 */
public class SearchRequestBuilder extends ActionRequestBuilder<SearchRequest, SearchResponse> {

    public SearchRequestBuilder(ElasticsearchClient client, SearchAction action) {
        super(client, action, new SearchRequest());
    }

    /**
     * Sets the indices the search will be executed on.
     */
    public SearchRequestBuilder setIndices(String... indices) {
        request.indices(indices);
        return this;
    }

    /**
     * The search type to execute, defaults to {@link org.elasticsearch.action.search.SearchType#DEFAULT}.
     */
    public SearchRequestBuilder setSearchType(SearchType searchType) {
        request.searchType(searchType);
        return this;
    }

    /**
     * The a string representation search type to execute, defaults to {@link SearchType#DEFAULT}. Can be
     * one of "dfs_query_then_fetch" or "query_then_fetch".
     */
    public SearchRequestBuilder setSearchType(String searchType) {
        request.searchType(searchType);
        return this;
    }

    /**
     * If set, will enable scrolling of the search request.
     */
    public SearchRequestBuilder setScroll(Scroll scroll) {
        request.scroll(scroll);
        return this;
    }

    /**
     * If set, will enable scrolling of the search request for the specified timeout.
     */
    public SearchRequestBuilder setScroll(TimeValue keepAlive) {
        request.scroll(keepAlive);
        return this;
    }

    /**
     * If set, will enable scrolling of the search request for the specified timeout.
     */
    public SearchRequestBuilder setScroll(String keepAlive) {
        request.scroll(keepAlive);
        return this;
    }

    /**
     * An optional timeout to control how long search is allowed to take.
     */
    public SearchRequestBuilder setTimeout(TimeValue timeout) {
        sourceBuilder().timeout(timeout);
        return this;
    }

    /**
     * An optional document count, upon collecting which the search
     * query will early terminate
     */
    public SearchRequestBuilder setTerminateAfter(int terminateAfter) {
        sourceBuilder().terminateAfter(terminateAfter);
        return this;
    }

    /**
     * A comma separated list of routing values to control the shards the search will be executed on.
     */
    public SearchRequestBuilder setRouting(String routing) {
        request.routing(routing);
        return this;
    }

    /**
     * The routing values to control the shards that the search will be executed on.
     */
    public SearchRequestBuilder setRouting(String... routing) {
        request.routing(routing);
        return this;
    }

    /**
     * Sets the preference to execute the search. Defaults to randomize across shards. Can be set to
     * {@code _local} to prefer local shards or a custom value, which guarantees that the same order
     * will be used across different requests.
     */
    public SearchRequestBuilder setPreference(String preference) {
        request.preference(preference);
        return this;
    }

    /**
     * Specifies what type of requested indices to ignore and wildcard indices expressions.
     *

     * For example indices that don't exist.
     */
    public SearchRequestBuilder setIndicesOptions(IndicesOptions indicesOptions) {
        request().indicesOptions(indicesOptions);
        return this;
    }

    /**
     * Constructs a new search source builder with a search query.
     *
     * @see org.elasticsearch.index.query.QueryBuilders
     */
    public SearchRequestBuilder setQuery(QueryBuilder queryBuilder) {
        sourceBuilder().query(queryBuilder);
        return this;
    }

    /**
     * Sets a filter that will be executed after the query has been executed and only has affect on the search hits
     * (not aggregations). This filter is always executed as last filtering mechanism.
     */
    public SearchRequestBuilder setPostFilter(QueryBuilder postFilter) {
        sourceBuilder().postFilter(postFilter);
        return this;
    }

    /**
     * Sets the minimum score below which docs will be filtered out.
     */
    public SearchRequestBuilder setMinScore(float minScore) {
        sourceBuilder().minScore(minScore);
        return this;
    }

    /**
     * From index to start the search from. Defaults to {@code 0}.
     */
    public SearchRequestBuilder setFrom(int from) {
        sourceBuilder().from(from);
        return this;
    }

    /**
     * The number of search hits to return. Defaults to {@code 10}.
     */
    public SearchRequestBuilder setSize(int size) {
        sourceBuilder().size(size);
        return this;
    }

    /**
     * Should each {@link org.elasticsearch.search.SearchHit} be returned with an
     * explanation of the hit (ranking).
     */
    public SearchRequestBuilder setExplain(boolean explain) {
        sourceBuilder().explain(explain);
        return this;
    }

    /**
     * Should each {@link org.elasticsearch.search.SearchHit} be returned with its
     * version.
     */
    public SearchRequestBuilder setVersion(boolean version) {
        sourceBuilder().version(version);
        return this;
    }

    /**
     * Should each {@link org.elasticsearch.search.SearchHit} be returned with the
     * sequence number and primary term of the last modification of the document.
     */
    public SearchRequestBuilder seqNoAndPrimaryTerm(boolean seqNoAndPrimaryTerm) {
        sourceBuilder().seqNoAndPrimaryTerm(seqNoAndPrimaryTerm);
        return this;
    }

    /**
     * Sets the boost a specific index will receive when the query is executed against it.
     *
     * @param index      The index to apply the boost against
     * @param indexBoost The boost to apply to the index
     */
    public SearchRequestBuilder addIndexBoost(String index, float indexBoost) {
        sourceBuilder().indexBoost(index, indexBoost);
        return this;
    }

    /**
     * The stats groups this request will be aggregated under.
     */
    public SearchRequestBuilder setStats(String... statsGroups) {
        sourceBuilder().stats(Arrays.asList(statsGroups));
        return this;
    }

    /**
     * The stats groups this request will be aggregated under.
     */
    public SearchRequestBuilder setStats(List<String> statsGroups) {
        sourceBuilder().stats(statsGroups);
        return this;
    }

    /**
     * Indicates whether the response should contain the stored _source for every hit
     */
    public SearchRequestBuilder setFetchSource(boolean fetch) {
        sourceBuilder().fetchSource(fetch);
        return this;
    }

    /**
     * Indicate that _source should be returned with every hit, with an "include" and/or "exclude" set which can include simple wildcard
     * elements.
     *
     * @param include An optional include (optionally wildcarded) pattern to filter the returned _source
     * @param exclude An optional exclude (optionally wildcarded) pattern to filter the returned _source
     */
    public SearchRequestBuilder setFetchSource(@Nullable String include, @Nullable String exclude) {
        sourceBuilder().fetchSource(include, exclude);
        return this;
    }

    /**
     * Indicate that _source should be returned with every hit, with an "include" and/or "exclude" set which can include simple wildcard
     * elements.
     *
     * @param includes An optional list of include (optionally wildcarded) pattern to filter the returned _source
     * @param excludes An optional list of exclude (optionally wildcarded) pattern to filter the returned _source
     */
    public SearchRequestBuilder setFetchSource(@Nullable String[] includes, @Nullable String[] excludes) {
        sourceBuilder().fetchSource(includes, excludes);
        return this;
    }

    /**
     * Adds a docvalue based field to load and return. The field does not have to be stored,
     * but its recommended to use non analyzed or numeric fields.
     *
     * @param name The field to get from the docvalue
     */
    public SearchRequestBuilder addDocValueField(String name, String format) {
        sourceBuilder().docValueField(name, format);
        return this;
    }

    /**
     * Adds a docvalue based field to load and return. The field does not have to be stored,
     * but its recommended to use non analyzed or numeric fields.
     *
     * @param name The field to get from the docvalue
     */
    public SearchRequestBuilder addDocValueField(String name) {
        return addDocValueField(name, null);
    }

    /**
     * Adds a field to load and return. The field must be present in the document _source.
     *
     * @param name The field to load
     */
    public SearchRequestBuilder addFetchField(String name) {
        sourceBuilder().fetchField(new FieldAndFormat(name, null, null));
        return this;
    }

    /**
     * Adds a field to load and return. The field must be present in the document _source.
     *
     * @param fetchField a {@link FieldAndFormat} specifying the field pattern, optional format (for example a date format) and
     * whether this field pattern sould also include unmapped fields
     */
    public SearchRequestBuilder addFetchField(FieldAndFormat fetchField) {
        sourceBuilder().fetchField(fetchField);
        return this;
    }

    /**
     * Adds a stored field to load and return (note, it must be stored) as part of the search request.
     */
    public SearchRequestBuilder addStoredField(String field) {
        sourceBuilder().storedField(field);
        return this;
    }

    /**
     * Adds a script based field to load and return. The field does not have to be stored,
     * but its recommended to use non analyzed or numeric fields.
     *
     * @param name   The name that will represent this value in the return hit
     * @param script The script to use
     */
    public SearchRequestBuilder addScriptField(String name, Script script) {
        sourceBuilder().scriptField(name, script);
        return this;
    }

    /**
     * Adds a sort against the given field name and the sort ordering.
     *
     * @param field The name of the field
     * @param order The sort ordering
     */
    public SearchRequestBuilder addSort(String field, SortOrder order) {
        sourceBuilder().sort(field, order);
        return this;
    }

    /**
     * Adds a generic sort builder.
     *
     * @see org.elasticsearch.search.sort.SortBuilders
     */
    public SearchRequestBuilder addSort(SortBuilder<?> sort) {
        sourceBuilder().sort(sort);
        return this;
    }

    /**
     * Set the sort values that indicates which docs this request should "search after".
     *
     */
    public SearchRequestBuilder searchAfter(Object[] values) {
        sourceBuilder().searchAfter(values);
        return this;
    }

    public SearchRequestBuilder slice(SliceBuilder builder) {
        sourceBuilder().slice(builder);
        return this;
    }

    /**
     * Applies when sorting, and controls if scores will be tracked as well. Defaults to {@code false}.
     */
    public SearchRequestBuilder setTrackScores(boolean trackScores) {
        sourceBuilder().trackScores(trackScores);
        return this;
    }

    /**
     * Indicates if the total hit count for the query should be tracked. Requests will count total hit count accurately
     * up to 10,000 by default, see {@link #setTrackTotalHitsUpTo(int)} to change this value or set to true/false to always/never
     * count accurately.
     */
    public SearchRequestBuilder setTrackTotalHits(boolean trackTotalHits) {
        sourceBuilder().trackTotalHits(trackTotalHits);
        return this;
    }

    /**
     * Indicates the total hit count that should be tracked accurately or null if the value is unset. Defaults to 10,000.
     */
    public SearchRequestBuilder setTrackTotalHitsUpTo(int trackTotalHitsUpTo) {
        sourceBuilder().trackTotalHitsUpTo(trackTotalHitsUpTo);
        return this;
    }

    /**
     * Adds stored fields to load and return (note, it must be stored) as part of the search request.
     * To disable the stored fields entirely (source and metadata fields) use {@code storedField("_none_")}.
     */
    public SearchRequestBuilder storedFields(String... fields) {
        sourceBuilder().storedFields(Arrays.asList(fields));
        return this;
    }

    /**
     * Adds an aggregation to the search operation.
     */
    public SearchRequestBuilder addAggregation(AggregationBuilder aggregation) {
        sourceBuilder().aggregation(aggregation);
        return this;
    }

    /**
     * Adds an aggregation to the search operation.
     */
    public SearchRequestBuilder addAggregation(PipelineAggregationBuilder aggregation) {
        sourceBuilder().aggregation(aggregation);
        return this;
    }

    public SearchRequestBuilder highlighter(HighlightBuilder highlightBuilder) {
        sourceBuilder().highlighter(highlightBuilder);
        return this;
    }

    /**
     * Delegates to {@link SearchSourceBuilder#suggest(SuggestBuilder)}
     */
    public SearchRequestBuilder suggest(SuggestBuilder suggestBuilder) {
        sourceBuilder().suggest(suggestBuilder);
        return this;
    }

    /**
     * Clears all rescorers on the builder and sets the first one.  To use multiple rescore windows use
     * {@link #addRescorer(org.elasticsearch.search.rescore.RescorerBuilder, int)}.
     *
     * @param rescorer rescorer configuration
     * @return this for chaining
     */
    public SearchRequestBuilder setRescorer(RescorerBuilder<?> rescorer) {
        sourceBuilder().clearRescorers();
        return addRescorer(rescorer);
    }

    /**
     * Clears all rescorers on the builder and sets the first one.  To use multiple rescore windows use
     * {@link #addRescorer(org.elasticsearch.search.rescore.RescorerBuilder, int)}.
     *
     * @param rescorer rescorer configuration
     * @param window   rescore window
     * @return this for chaining
     */
    public SearchRequestBuilder setRescorer(RescorerBuilder rescorer, int window) {
        sourceBuilder().clearRescorers();
        return addRescorer(rescorer.windowSize(window));
    }

    /**
     * Adds a new rescorer.
     *
     * @param rescorer rescorer configuration
     * @return this for chaining
     */
    public SearchRequestBuilder addRescorer(RescorerBuilder<?> rescorer) {
        sourceBuilder().addRescorer(rescorer);
        return this;
    }

    /**
     * Adds a new rescorer.
     *
     * @param rescorer rescorer configuration
     * @param window   rescore window
     * @return this for chaining
     */
    public SearchRequestBuilder addRescorer(RescorerBuilder<?> rescorer, int window) {
        sourceBuilder().addRescorer(rescorer.windowSize(window));
        return this;
    }

    /**
     * Clears all rescorers from the builder.
     *
     * @return this for chaining
     */
    public SearchRequestBuilder clearRescorers() {
        sourceBuilder().clearRescorers();
        return this;
    }

    /**
     * Sets the source of the request as a SearchSourceBuilder.
     */
    public SearchRequestBuilder setSource(SearchSourceBuilder source) {
        request.source(source);
        return this;
    }

    /**
     * Sets if this request should use the request cache or not, assuming that it can (for
     * example, if "now" is used, it will never be cached). By default (not set, or null,
     * will default to the index level setting if request cache is enabled or not).
     */
    public SearchRequestBuilder setRequestCache(Boolean requestCache) {
        request.requestCache(requestCache);
        return this;
    }

    /**
     * Sets if this request should allow partial results.  (If method is not called,
     * will default to the cluster level setting).
     */
    public SearchRequestBuilder setAllowPartialSearchResults(boolean allowPartialSearchResults) {
        request.allowPartialSearchResults(allowPartialSearchResults);
        return this;
    }

    /**
     * Should the query be profiled. Defaults to false
     */
    public SearchRequestBuilder setProfile(boolean profile) {
        sourceBuilder().profile(profile);
        return this;
    }

    public SearchRequestBuilder setCollapse(CollapseBuilder collapse) {
        sourceBuilder().collapse(collapse);
        return this;
    }

    /**
     * If specified, Elasticsearch will execute this search request using reader contexts from that point in time.
     */
    public SearchRequestBuilder setPointInTime(PointInTimeBuilder pointInTimeBuilder) {
        sourceBuilder().pointInTimeBuilder(pointInTimeBuilder);
        return this;
    }

    @Override
    public String toString() {
        if (request.source() != null) {
            return request.source().toString();
        }
        return new SearchSourceBuilder().toString();
    }

    private SearchSourceBuilder sourceBuilder() {
        if (request.source() == null) {
            request.source(new SearchSourceBuilder());
        }
        return request.source();
    }

    /**
     * Sets the number of shard results that should be reduced at once on the coordinating node. This value should be used as a protection
     * mechanism to reduce the memory overhead per search request if the potential number of shards in the request can be large.
     */
    public SearchRequestBuilder setBatchedReduceSize(int batchedReduceSize) {
        this.request.setBatchedReduceSize(batchedReduceSize);
        return this;
    }

    /**
     * Sets the number of shard requests that should be executed concurrently on a single node. This value should be used as a
     * protection mechanism to reduce the number of shard requests fired per high level search request. Searches that hit the entire
     * cluster can be throttled with this number to reduce the cluster load. The default is {@code 5}.
     */
    public SearchRequestBuilder setMaxConcurrentShardRequests(int maxConcurrentShardRequests) {
        this.request.setMaxConcurrentShardRequests(maxConcurrentShardRequests);
        return this;
    }

    /**
     * Sets a threshold that enforces a pre-filter roundtrip to pre-filter search shards based on query rewriting if the number of shards
     * the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for
     * instance a shard can not match any documents based on its rewrite method ie. if date filters are mandatory to match but the shard
     * bounds and the query are disjoint.
     *
     * When unspecified, the pre-filter phase is executed if any of these conditions is met:
     *

     *
The request targets more than 128 shards

     *
The request targets one or more read-only index

     *
The primary sort of the query targets an indexed field

     *

     */
    public SearchRequestBuilder setPreFilterShardSize(int preFilterShardSize) {
        this.request.setPreFilterShardSize(preFilterShardSize);
        return this;
    }

    /**
     * Set runtime mappings to create runtime fields that exist only as part of this particular search.
     */
    public SearchRequestBuilder setRuntimeMappings(Map<String, Object> runtimeMappings) {
        sourceBuilder().runtimeMappings(runtimeMappings);
        return this;
    }
}


text:
"""PKONE serial communicator."""
import asyncio
import re
from distutils.version import StrictVersion

from mpf.platforms.base_serial_communicator import BaseSerialCommunicator
from mpf.platforms.pkone.pkone_extension import PKONEExtensionBoard
from mpf.platforms.pkone.pkone_lightshow import PKONELightshowBoard

MYPY = False
if MYPY:    # pragma: no cover
    from mpf.platforms.pkone.pkone import PKONEHardwarePlatform   # pylint: disable-msg=cyclic-import,unused-import

NANO_MIN_FW = '1.0'
EXTENSION_MIN_FW = '1.0'
LIGHTSHOW_MIN_FW = '1.0'

class PKONESerialCommunicator(BaseSerialCommunicator):

    """Handles the serial communication to the PKONE platform."""

    ignored_messages = ['PWD',  # Watchdog
                        ]

    __slots__ = ["part_msg", "send_queue", "remote_firmware", "remote_hardware_rev", "received_msg",
                 "max_messages_in_flight", "messages_in_flight", "send_ready"]

    # pylint: disable=too-many-arguments
    def __init__(self, platform: "PKONEHardwarePlatform", port, baud) -> None:
        """Initialize Serial Connection to PKONE Hardware.

        Args:
        ----
            platform(mpf.platforms.pkone.pkone.HardwarePlatform): the pkone hardware platform
            port: serial port
            baud: baud rate
        """
        self.send_queue = asyncio.Queue()
        self.remote_firmware = None
        self.remote_hardware_rev = None
        self.received_msg = b''
        self.max_messages_in_flight = 10
        self.messages_in_flight = 0

        self.send_ready = asyncio.Event()
        self.send_ready.set()

        super().__init__(platform, port, baud)

    async def _read_with_timeout(self, timeout):
        try:
            msg_raw = await asyncio.wait_for(self.readuntil(b'E'), timeout=timeout)
        except asyncio.TimeoutError:
            return ""
        return msg_raw.decode()

    async def _identify_connection(self):
        """Identify which controller this serial connection is talking to."""
        count = 0
        while True:
            if (count % 10) == 0:
                self.platform.debug_log("Sending 'PCN' command to port '%s'", self.port)

            count += 1
            self.writer.write('PCNE'.encode('ascii', 'replace'))
            msg = await self._read_with_timeout(.5)
            if msg.startswith('PCN'):
                break

            await asyncio.sleep(.5)

            if count == 100:
                raise AssertionError('No response from PKONE hardware on port {}'.format(self.port))

        # PCN (Determine connected controller board) reply is in the following format:
        # PCNF[Firmware rev]H[Hardware rev]E
        match = re.match('PCNF([0-9]+)H([0-9]+)E', msg)
        if not match:
            raise AssertionError(
                'Received an unexpected response. {} is not a recognized response to the PCN command.'.format(msg))

        self.remote_firmware = match[1][:-1] + '.' + match[1][-1]
        self.remote_hardware_rev = match[2]

        self.platform.log.info("Connected! "
                               "Board Type: PKONE Nano Controller, Firmware: %s, Hardware Rev: %s",
                               self.remote_firmware, self.remote_hardware_rev)

        self.machine.variables.set_machine_var("pkone_firmware", self.remote_firmware)
        '''machine_var: pkone_firmware

        desc: Holds the version number of the firmware for the Penny K Pinball PKONE controller that's connected.'''

        self.machine.variables.set_machine_var("pkone_hardware",
                                               "PKONE Nano Controller (rev {})".format(self.remote_hardware_rev))
        '''machine_var: pkone_hardware

        desc: Holds the model name and hardware revision number of the Penny K Pinball PKONE controller
        board that's connected.'''

        if StrictVersion(NANO_MIN_FW) > StrictVersion(self.remote_firmware):
            raise AssertionError('Firmware version mismatch. MPF requires '
                                 'the PKONE Nano Controller to be firmware {}, but yours is {}. '
                                 'Please update your firmware.'.
                                 format(NANO_MIN_FW, self.remote_firmware))

        # Reset the Nano controller and connected boards
        await self.reset_controller()

        # Determine what additional boards are connected to the Nano controller
        await self.query_pkone_boards()

        # Read the initial state of all switches
        await self.read_all_switches()

        self.platform.controller_connection = self

    async def reset_controller(self):
        """Reset the controller."""
        self.platform.debug_log('Resetting controller.')

        # this command returns several responses (one from each board, starting with the Nano controller)
        self.writer.write('PRSE'.encode())
        msg = ''
        while msg != 'PRSE' and not msg.startswith('PXX'):
            msg = (await self.readuntil(b'E')).decode()
            self.platform.debug_log("Got: {}".format(msg))

        if msg.startswith('PXX'):
            raise AssertionError('Received an error while resetting the controller: {}'.format(msg))

    async def query_pkone_boards(self):
        """Query the NANO processor to discover which additional boards are connected."""
        self.platform.debug_log('Querying PKONE boards...')

        # Determine connected add-on boards (PCB command)
        # Responses:
        # Extension board - PCB01XF11H1 = PCB[board number 0-7]XP[Y:48V, N: no 48V]F[firmware rev]H[hardware rev]
        # Lightshow board - PCB01LF10H1RGBW = PCB[board number 0-3]LF[firmware rev]H[hardware rev][firmware_type]
        # No board at the address: PCB[board number 0-7]N
        for address_id in range(8):
            self.writer.write('PCB{}E'.format(address_id).encode('ascii', 'replace'))
            msg = await self._read_with_timeout(.5)
            if msg == 'PCB{}NE'.format(address_id):
                self.platform.log.debug("No board at address ID {}".format(address_id))
                continue

            match = re.fullmatch('PCB([0-7])([XLN])F([0-9]+)H([0-9]+)(P[YN])?(RGB|RGBW)?E', msg)
            if not match:
                self.platform.log.warning("Received unexpected message from PKONE: {}".format(msg))

            if match.group(2) == "X":
                # Extension board
                firmware = match.group(3)[:-1] + '.' + match.group(3)[-1]
                hardware_rev = match.group(4)

                if StrictVersion(EXTENSION_MIN_FW) > StrictVersion(firmware):
                    raise AssertionError('Firmware version mismatch. MPF requires '
                                         'PKONE Extension boards to be at least firmware {}, but yours is {}. '
                                         'Please update your firmware.'.
                                         format(EXTENSION_MIN_FW, firmware))

                self.platform.debug_log('PKONE Extension Board {0}: '
                                        'Firmware: {1}, Hardware Rev: {2}'.format(address_id,
                                                                                firmware, hardware_rev))

                self.platform.register_extension_board(PKONEExtensionBoard(address_id, firmware, hardware_rev))

            elif match.group(2) == "L":
                # Lightshow board
                firmware = match.group(3)[:-1] + '.' + match.group(3)[-1]
                hardware_rev = match.group(4)
                rgbw_firmware = match.group(6) == 'RGBW'

                if StrictVersion(LIGHTSHOW_MIN_FW) > StrictVersion(firmware):
                    raise AssertionError('Firmware version mismatch. MPF requires '
                                         'PKONE Lightshow boards to be at least firmware {}, but yours is {}. '
                                         'Please update your firmware.'.
                                         format(LIGHTSHOW_MIN_FW, firmware))

                self.platform.debug_log('PKONE Lightshow Board {0}: Firmware: {1} ({2}), '
                                        'Hardware Rev: {3}'.format(address_id,
                                                                   firmware,
                                                                   'RGBW' if rgbw_firmware else 'RGB',
                                                                   hardware_rev))

                self.platform.register_lightshow_board(PKONELightshowBoard(address_id,
                                                                           firmware,
                                                                           hardware_rev,
                                                                           rgbw_firmware))

            else:
                raise AttributeError("Unrecognized PKONE board type in message: {}".format(msg))

    async def read_all_switches(self):
        """Read the current state of all switches from the hardware."""
        self.platform.debug_log('Reading all switches.')
        for address_id in self.platform.pkone_extensions:
            self.writer.write('PSA{}E'.format(address_id).encode())
            msg = ''
            while not msg.startswith('PSA'):
                msg = (await self.readuntil(b'E')).decode()
                if not msg.startswith('PSA'):
                    self.platform.log.warning("Received unexpected message from PKONE: {}".format(msg))

            self.platform.process_received_message(msg)

    def _parse_msg(self, msg):
        self.received_msg += msg

        while True:
            pos = self.received_msg.find(b'E')

            # no more complete messages
            if pos == -1:
                break

            msg = self.received_msg[:pos]
            self.received_msg = self.received_msg[pos + 1:]

            self.messages_in_flight -= 1
            if self.messages_in_flight <= self.max_messages_in_flight or not self.read_task:
                self.send_ready.set()
            if self.messages_in_flight < 0:
                self.log.warning("Received more messages than were sent! Resetting!")
                self.messages_in_flight = 0

            if not msg:
                continue

            if msg.decode() not in self.ignored_messages:
                self.platform.process_received_message(msg.decode())

    def send(self, msg):
        """Send a message to the remote processor over the serial connection.

        Args:
        ----
            msg: Bytes of the message you want to send.
        """
        if self.debug:
            self.log.debug("%s sending: %s", self, msg)

        self.writer.write(msg.encode() + b'E')


text:
package org.colorcoding.ibas.importexport.transformer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.function.Consumer;

import org.colorcoding.ibas.bobas.bo.IBusinessObject;
import org.colorcoding.ibas.bobas.common.Criteria;
import org.colorcoding.ibas.bobas.common.ICondition;
import org.colorcoding.ibas.bobas.common.ICriteria;
import org.colorcoding.ibas.bobas.common.IOperationResult;
import org.colorcoding.ibas.bobas.data.DateTime;
import org.colorcoding.ibas.bobas.i18n.I18N;
import org.colorcoding.ibas.bobas.mapping.BusinessObjectUnit;
import org.colorcoding.ibas.bobas.organization.OrganizationFactory;
import org.colorcoding.ibas.bobas.repository.InvalidTokenException;
import org.colorcoding.ibas.importexport.MyConfiguration;
import org.colorcoding.ibas.importexport.transformer.template.Property;
import org.colorcoding.ibas.importexport.transformer.template.ResolvingException;
import org.colorcoding.ibas.importexport.transformer.template.Template;
import org.colorcoding.ibas.importexport.transformer.template.WriteFileException;
import org.colorcoding.ibas.initialfantasy.bo.boinformation.BOInformation;
import org.colorcoding.ibas.initialfantasy.bo.boinformation.IBOInformation;
import org.colorcoding.ibas.initialfantasy.bo.boinformation.IBOPropertyInformation;
import org.colorcoding.ibas.initialfantasy.repository.BORepositoryInitialFantasyShell;

/**
 * 业务对象转换xlsx文件
 *
 * @author Niuren.Zhu
 *
 */
@TransformerInfo(name = "TO_FILE_XLSX")
public class TransformerExcel extends TransformerFile {

	public final static String TYPE_NAME = "xlsx";
	public final static String PROPERTY_DATATYPE_ALPHANUMERIC = "Alphanumeric";

	@Override
	public void transform() throws TransformException {
		if (this.getInputData() == null || this.getInputData().length == 0) {
			return;
		}
		try {
			Template template = new Template();
			// 解析输入数据
			for (IBusinessObject bo : this.getInputData()) {
				template.resolving(bo);
			}
			// 更新模板描述
			this.describing(template);
			// 输出文件
			File file = new File(this.getWorkFolder() + File.separator + template.getName() + "_"
					+ DateTime.getNow().getTime() + "." + TYPE_NAME);
			if (!file.getParentFile().exists()) {
				file.mkdirs();
			}
			template.write(file);
			this.setOutputData(new ArrayList<>());
			this.getOutputData().add(file);
		} catch (ResolvingException | InvalidTokenException | WriteFileException | IOException e) {
			throw new TransformException(e);
		}
	}

	/**
	 * 描述模板
	 *
	 * @param template
	 * @throws InvalidTokenException
	 * @throws Exception
	 */
	protected void describing(Template template) throws InvalidTokenException {
		if (template == null) {
			return;
		}
		String language = I18N.getInstance().getLanguageCode();
		if (language != null && !language.startsWith("zh")) {
			// 非中文语言,使用英文
			return;
		}
		ICriteria criteria = null;
		IOperationResult<IBOInformation> opRslt = null;
		BORepositoryInitialFantasyShell boRepository = new BORepositoryInitialFantasyShell();
		boRepository.setUserToken(OrganizationFactory.SYSTEM_USER.getToken());
		// 描述表头
		criteria = new Criteria();
		ICondition condition = criteria.getConditions().create();
		condition.setAlias(BOInformation.PROPERTY_CODE.getName());
		if (template.getHead().getCode() != null && !template.getHead().getCode().isEmpty()) {
			// 查编码
			condition.setValue(template.getHead().getCode());
		} else {
			// 查名称
			condition.setValue(template.getHead().getName());
		}
		opRslt = boRepository.fetchBOInformation(criteria);
		IBOInformation masterInfo = opRslt.getResultObjects().firstOrDefault();
		if (masterInfo == null) {
			// 未找到对象描述
			return;
		}
		template.setDescription(masterInfo.getDescription());
		template.getHead().setDescription(masterInfo.getDescription());
		// 描述对象方法
		Consumer<IBOInformation> describingObject = new Consumer<IBOInformation>() {

			@Override
			public void accept(IBOInformation t) {
				if (t == null) {
					return;
				}
				for (org.colorcoding.ibas.importexport.transformer.template.Object object : template.getObjects()) {
					if (object.getName().equals(t.getName())) {
						object.setDescription(t.getDescription());
						for (Property property : object.getProperties()) {
							IBOPropertyInformation itemInfo = t.getBOPropertyInformations()
									.firstOrDefault(c -> c.getPropertyName().equals(property.getName()));
							if (itemInfo == null) {
								itemInfo = t.getBOPropertyInformations()
										.firstOrDefault(c -> c.getMapped().equals(property.getName()));
							}
							if (itemInfo != null) {
								property.setDescription(itemInfo.getDescription());
								if (PROPERTY_DATATYPE_ALPHANUMERIC.equalsIgnoreCase(itemInfo.getDataType())) {
									property.setDescription(String.format("%s (%d)", property.getDescription(),
											itemInfo.getEditSize()));
								}
							}
						}
					} else if (object.getName().startsWith(t.getName())) {
						String name = object.getName().substring(t.getName().length() + 1)
								.replace(Template.PROPERTY_PATH_LIST_SIGN, "");
						IBOPropertyInformation itemInfo = t.getBOPropertyInformations()
								.firstOrDefault(c -> c.getPropertyName().equals(name));
						if (itemInfo != null) {
							// 对象定义的属性
							ICriteria criteria = new Criteria();
							ICondition condition = criteria.getConditions().create();
							condition.setAlias(BOInformation.PROPERTY_CODE.getName());
							condition.setValue(itemInfo.getMapped());
							IBOInformation childInfo = boRepository.fetchBOInformation(criteria).getResultObjects()
									.firstOrDefault();
							if (childInfo != null) {
								childInfo.setName(object.getName());
								this.accept(childInfo);
							}
						} else {
							// 对象没有定义的,按类名称查询
							ICriteria criteria = new Criteria();
							ICondition condition = criteria.getConditions().create();
							try {
								String code = object.getBindingClass().getAnnotation(BusinessObjectUnit.class).code();
								condition.setAlias(BOInformation.PROPERTY_CODE.getName());
								condition.setValue(MyConfiguration.applyVariables(code));
							} catch (Exception e) {
								condition.setAlias(BOInformation.PROPERTY_NAME.getName());
								condition.setValue(object.getBindingClass().getSimpleName());
							}
							IBOInformation childInfo = boRepository.fetchBOInformation(criteria).getResultObjects()
									.firstOrDefault();
							if (childInfo != null) {
								childInfo.setName(object.getName());
								this.accept(childInfo);
							}
						}
					}
				}

			}
		};
		describingObject.accept(masterInfo);
	}

}


text:
{% extends "base.html" %}
{% load static %}

{% block title %}
Batch submission
{% endblock %}

{% block header %}

        Batch submission

{% endblock %}

{% block content %}

Data input

    <form action="" method="post" novalidate>
      {% csrf_token %}

        {% for error in form.non_field_errors %}

          {{ error }}

        {% endfor %}
        {{ form.data }}
        <input type="submit" class="btn btn-primary btn-block" value="Submit" />

    </form>

How to use

{% endblock %}


text:
<vos:transfer xmlns:vos="http://www.ivoa.net/xml/VOSpace/v2.0">
	<vos:target>vos://edu.jhu!vospace/test_cont1/pulleddata1.txt</vos:target>
	<vos:direction>pullFromVoSpace</vos:direction>
	<vos:view>ivo://net.ivoa/vospace/core#anyview</vos:view>
	<vos:protocol uri="ivo://ivoa.net/vospace/core#udtget"></vos:protocol>
</vos:transfer>


text:
package wvw.utils;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonUtils {

	public static void notFound(JsonReadable caller, String name)
			throws JSONException {

		notFound(caller.getClass(), name);
	}

	@SuppressWarnings("rawtypes")
	public static void notFound(Class clazz, String name) throws JSONException {
		throw new JSONException(clazz.getName() + ": expected '" + name
				+ "' field");
	}

	public static void checkField(JsonReadable caller, JSONObject obj,
			String name) throws JSONException {

		checkField(caller.getClass(), obj, name);
	}

	@SuppressWarnings("rawtypes")
	public static void checkField(Class clazz, JSONObject obj, String name)
			throws JSONException {

		if (!obj.has(name))
			notFound(clazz, name);
	}

	public static boolean isEnum(JSONObject obj) {
		return obj.has("id");
	}

	public static int getEnumId(JSONObject obj) throws JSONException {
		return obj.getInt("id");
	}

	public static int getEnumId(JSONObject obj, String name)
			throws JSONException {

		return obj.getJSONObject(name).getInt("id");
	}

	public static JSONObject genEnum(int id) throws JSONException {
		JSONObject obj = new JSONObject();
		obj.put("id", id);

		return obj;
	}

	public static int getInt(JsonReadable caller, JSONObject obj,
			String[] altNames) throws JSONException {

		return getInt(caller, obj, altNames, true);
	}

	public static int getInt(JsonReadable caller, JSONObject obj,
			String[] altNames, boolean throwExc) throws JSONException {

		int value = -1;
		for (String altName : altNames) {

			if (obj.has(altName)) {
				value = (Integer) obj.getInt(altName);

				break;
			}
		}

		if (value == -1 && throwExc)
			throw new JSONException(caller.getClass() + ": expected "
					+ LogUtils.toString(altNames, " / ", "'") + " field");

		return value;
	}

	public static List<JSONObject> getObjects(JSONObject obj, String name)
			throws JSONException {

		return getObjects(obj, name, name + "s");
	}

	public static List<JSONObject> getObjects(JSONObject obj, String name,
			String plural) throws JSONException {

		List<JSONObject> objs = new ArrayList<JSONObject>();
		if (obj.has(plural)) {

			JSONArray array = obj.getJSONArray(plural);
			for (int i = 0; i < array.length(); i++)
				objs.add(array.getJSONObject(i));

		} else if (obj.has(name))
			objs.add(obj.getJSONObject(name));

		else
			throw new JSONException("Severity: no " + name + " info found");

		return objs;
	}
}


text:
var db = require('./models')

var phrases = [{
    word: "HTTP",
    definition: "Hypertext transfer protocol: the standard protocol for transferring hypertext documents on the World Wide Web."
}, {
    word: "Array",
    definition: "Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed.."
}, {
    word: "DOM",
    definition: "one of the most-used APIs on the Web because it allows code running in a browser to access and interact with every node in the document."
}, {
    word: "Query",
    definition: "Used to specify the query for a template. The attributes and content of the query are dependent on the type of datasource being used."
}, {
    word: "Boolean",
    definition: "A boolean is a logical data type that can have only the values true or false."
}];

db.Phrase.remove({}, function(err, result){

  db.Phrase.create(phrases, function(err, phrases){
    if (err) { return console.log(err) };
    console.log("created", phrases.length, "phrases")
    process.exit();
  });

});


text:
import { ReactElement } from 'react'

import { Box } from '@mui/material'
import { OpenNebulaLogo } from 'client/components/Icons'

/**
 * Component with OpenNebula logo as spinner in full width and height.
 *
 * @returns {ReactElement} Container with logo inside
 */
const LoadingScreen = () => (
  <Box className="loading_screen">
    <OpenNebulaLogo width={360} height={360} spinner withText />
  </Box>
)

export default LoadingScreen


text:
"use strict"

//global object containing reference to the html canvas object and associated context
var Can  = { can: document.getElementById("canvas") };
Can.con = Can.can.getContext("2d");

var timerSetting = {
	onId: 'setTimerOn',
	offId: 'setTimerOff',
	isOn: true,
	init: function(){
		document.getElementById(this.isOn ? this.onId : this.offId).checked = true;
	},
	apply: function(){
		this.isOn = document.getElementById(this.onId).checked;
		if(!this.isOn) timer.reset();
		cube.drawCube(true);
	}
}
var colorSetting = {
	faces: ['front', 'back', 'up', 'down', 'left', 'right'],
	ids: [ 'setFColor', 'setBColor', 'setUColor', 'setDColor', 'setLColor', 'setRColor'],
	init: function(){
		for(var i = 0; i < this.faces.length; i++){
			document.getElementById(this.ids[i]).value = cube.colors[this.faces[i]];
		}
	},
	apply: function(){
		for(var i = 0; i < this.faces.length; i++){
			cube.colors[this.faces[i]] = document.getElementById(this.ids[i]).value;
		}
		cube.drawCube();
	},
	loadScheme: function(scheme){
		for(var i = 0; i < this.faces.length; i++){
			document.getElementById(this.ids[i]).value = scheme[this.faces[i]];
		}
	}
}

var sizeSetting = {
	sizeId: 'setSize',
	init: function(){
		document.getElementById(this.sizeId).value = cube.size;
	},
	apply: function(){
		var s = parseInt(document.getElementById(this.sizeId).value);
		if(!isNaN(s) && s != cube.size && s > 0 && (cube.isSolved() || confirm('change size?'))){
			cube.setSize(s);
		}
	}
}

var canSizeSetting = {
	widthId: 'setCanWidth',
	heightId: 'setCanHeight',
	init: function(){
		document.getElementById(this.widthId).value = Can.can.width;
		document.getElementById(this.heightId).value = Can.can.height;
	},
	apply: function(){
		var w = parseInt(document.getElementById(this.widthId).value);
		var h = parseInt(document.getElementById(this.heightId).value);
		if(!isNaN(w) && !isNaN(h)){
			Can.can.width = w;
			Can.can.height = h;
			depthView.draw();
			cube.drawCube();
		}
	}
}

var btnCtrlsSetting = {
	onId: 'setBtnCtrlsOn',
	offId: 'setBtnCtrlsOff',
	init: function(){
		document.getElementById(btnControls.visible ? this.onId : this.offId).checked = true;
	},
	apply: function(){
		if(document.getElementById(this.onId).checked)
			btnControls.show();
		else
			btnControls.hide();
	}
}

var keyboardSetting = {
	init: function(){
		document.getElementById(keyProfile.settingId).checked = true;
	},
	apply: function(){
		if(document.getElementById(qCubeKeys.settingId).checked)
			setKeyProfile(qCubeKeys);
		else if(document.getElementById(sideNameKeys.settingId).checked)
			setKeyProfile(sideNameKeys);
		else
			setKeyProfile(ad8Keys);
	}
}

var settings = {
	showDivId: 'showSettings',
	divId: 'settings',
	stateId: 'setState',
	show: function(){
		timer.stop();
		ignoreKeys = true;
		colorSetting.init();
		sizeSetting.init();
		timerSetting.init();
		canSizeSetting.init();
		btnCtrlsSetting.init();
		keyboardSetting.init();
		document.getElementById(this.stateId).value = state.saveString();
		document.getElementById(this.showDivId).style.display = 'none';
		document.getElementById(this.divId).style.display = '';
	},
	hide: function(){
		ignoreKeys = false;
		document.getElementById(this.divId).style.display = 'none';
		document.getElementById(this.showDivId).style.display = '';
	},
	apply: function(){
		colorSetting.apply();
		sizeSetting.apply();
		timerSetting.apply();
		canSizeSetting.apply();
		btnCtrlsSetting.apply();
		keyboardSetting.apply();
		this.hide();
	},
	importState: function(){
		state.loadString(document.getElementById(this.stateId).value);
		this.hide();
	}
}


text:
package clicommand

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

	"github.com/andrew-d/go-termutil"
	"github.com/buildkite/agent/agent"
	"github.com/buildkite/agent/api"
	"github.com/buildkite/agent/cliconfig"
	"github.com/buildkite/agent/logger"
	"github.com/buildkite/agent/retry"
	"github.com/codegangsta/cli"
)

var PipelineUploadHelpDescription = `Usage:

   buildkite-agent pipeline upload <file> [arguments...]

Description:

   Allows you to change the pipeline of a running build by uploading a
   JSON configuration file. By default, we try to upload
   .buildkite/steps.json, but you can customize which file to use.

Example:

   $ buildkite-agent pipeline upload
   $ buildkite-agent pipeline upload my-custom-steps.json
   $ ./script/dynamic_step_generator | buildkite-agent pipeline upload`

type PipelineUploadConfig struct {
	FilePath         string `cli:"arg:0" label:"upload paths"`
	Replace          bool   `cli:"replace"`
	Job              string `cli:"job" validate:"required"`
	AgentAccessToken string `cli:"agent-access-token" validate:"required"`
	Endpoint         string `cli:"endpoint" validate:"required"`
	NoColor          bool   `cli:"no-color"`
	Debug            bool   `cli:"debug"`
	DebugHTTP        bool   `cli:"debug-http"`
}

var PipelineUploadCommand = cli.Command{
	Name:        "upload",
	Usage:       "Uploads a description of a build pipleine adds it to the currently running build after the current job.",
	Description: PipelineUploadHelpDescription,
	Flags: []cli.Flag{
		cli.BoolFlag{
			Name:   "replace",
			Usage:  "Replace the rest of the existing pipeline with the steps uploaded. Jobs that are already running are not removed.",
			EnvVar: "BUILDKITE_PIPELINE_REPLACE",
		},
		cli.StringFlag{
			Name:   "job",
			Value:  "",
			Usage:  "The job that is making the changes to it's build",
			EnvVar: "BUILDKITE_JOB_ID",
		},
		AgentAccessTokenFlag,
		EndpointFlag,
		NoColorFlag,
		DebugFlag,
		DebugHTTPFlag,
	},
	Action: func(c *cli.Context) {
		// The configuration will be loaded into this struct
		cfg := PipelineUploadConfig{}

		// Load the configuration
		loader := cliconfig.Loader{CLI: c, Config: &cfg}
		if err := loader.Load(); err != nil {
			logger.Fatal("%s", err)
		}

		// Setup the any global configuration options
		HandleGlobalFlags(cfg)

		// Find the pipeline file either from STDIN or the first
		// argument
		var input []byte
		var err error
		var filename string

		if cfg.FilePath != "" {
			filename = filepath.Base(cfg.FilePath)
			input, err = ioutil.ReadFile(cfg.FilePath)
			if err != nil {
				logger.Fatal("Failed to read file: %s", err)
			}
		} else if !termutil.Isatty(os.Stdin.Fd()) {
			input, err = ioutil.ReadAll(os.Stdin)
			if err != nil {
				logger.Fatal("Failed to read from STDIN: %s", err)
			}
		} else {
			// Default to opening .buildkite/steps.json
			filename = "steps.json"
			path, _ := filepath.Abs(".buildkite/" + filename)
			input, err = ioutil.ReadFile(path)
			if err != nil {
				logger.Fatal("Failed to read file: %s", err)
			}
		}

		// Create the API client
		client := agent.APIClient{
			Endpoint: cfg.Endpoint,
			Token:    cfg.AgentAccessToken,
		}.Create()

		// Generate a UUID that will identifiy this pipeline change. We
		// do this outside of the retry loop because we want this UUID
		// to be the same for each attempt at updating the pipeline.
		uuid := api.NewUUID()

		// Retry the pipeline upload a few times before giving up
		err = retry.Do(func(s *retry.Stats) error {
			_, err = client.Pipelines.Upload(cfg.Job, &api.Pipeline{UUID: uuid, Data: input, FileName: filename, Replace: cfg.Replace})
			if err != nil {
				logger.Warn("%s (%s)", err, s)
			}

			return err
		}, &retry.Config{Maximum: 5, Interval: 1 * time.Second})
		if err != nil {
			logger.Fatal("Failed to upload and process pipeline: %s", err)
		}

		logger.Info("Successfully uploaded and parsed pipeline config")
	},
}


text:
module Forms::Fields
  class Checkboxes < Field
    include OptionedField

    property :label, String, :required => true
    property :required, Boolean, :default => false

    self.renderer = Forms::CheckboxesRenderer
  end
end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>{{ title }}</title>
	<meta name="generator" content="frappe">
	<link type="text/css" rel="stylesheet"
        href="/assets/frappe/css/bootstrap.css">
	<link type="text/css" rel="stylesheet"
        href="/assets/frappe/css/font-awesome.css">

		{{ body }}

{%- if comment -%}

{%- endif -%}


text:
using UnityEngine;
using System.Collections;

namespace Implementation.Features
{
    public abstract class BaseFeature : BaseMonoBehaviour
    {
    }
}


text:
package org.semanticweb.elk.owl.visitors;

import org.semanticweb.elk.owl.interfaces.ElkDataAllValuesFrom;

/**
 * Visitor pattern interface for instances of {@link ElkDataAllValuesFrom}.
 *
 * @author "Yevgeny Kazakov"
 *
 * @param <O>
 *            the type of the output of this visitor
 */
public interface ElkDataAllValuesFromVisitor<O> {

	public O visit(ElkDataAllValuesFrom expression);

}


text:
<?php

class Ffuenf_Contact_Model_System_Config_Backend_Links extends Mage_Adminhtml_Model_System_Config_Backend_Cache
{
  /**
  * Cache tags to clean
  *
  * @var array
  */
  protected $_cacheTags = array(Mage_Core_Model_Store::CACHE_TAG, Mage_Cms_Model_Block::CACHE_TAG);
}


text:
/* $OpenBSD: bn_kron.c,v 1.6 2015/02/09 15:49:22 jsing Exp $ */
/* ====================================================================
 * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    openssl-core@openssl.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

#include "bn_lcl.h"

/* least significant word */
#define BN_lsw(n) (((n)->top == 0) ? (BN_ULONG) 0 : (n)->d[0])

/* Returns -2 for errors because both -1 and 0 are valid results. */
int
BN_kronecker(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx)
{
	int i;
	int ret = -2; /* avoid 'uninitialized' warning */
	int err = 0;
	BIGNUM *A, *B, *tmp;

	/* In 'tab', only odd-indexed entries are relevant:
	 * For any odd BIGNUM n,
	 *     tab[BN_lsw(n) & 7]
	 * is $(-1)^{(n^2-1)/8}$ (using TeX notation).
	 * Note that the sign of n does not matter.
	 */
	static const int tab[8] = {0, 1, 0, -1, 0, -1, 0, 1};

	bn_check_top(a);
	bn_check_top(b);

	BN_CTX_start(ctx);
	if ((A = BN_CTX_get(ctx)) == NULL)
		goto end;
	if ((B = BN_CTX_get(ctx)) == NULL)
		goto end;

	err = !BN_copy(A, a);
	if (err)
		goto end;
	err = !BN_copy(B, b);
	if (err)
		goto end;

	/*
	 * Kronecker symbol, imlemented according to Henri Cohen,
	 * "A Course in Computational Algebraic Number Theory"
	 * (algorithm 1.4.10).
	 */

	/* Cohen's step 1: */

	if (BN_is_zero(B)) {
		ret = BN_abs_is_word(A, 1);
		goto end;
	}

	/* Cohen's step 2: */

	if (!BN_is_odd(A) && !BN_is_odd(B)) {
		ret = 0;
		goto end;
	}

	/* now  B  is non-zero */
	i = 0;
	while (!BN_is_bit_set(B, i))
		i++;
	err = !BN_rshift(B, B, i);
	if (err)
		goto end;
	if (i & 1) {
		/* i is odd */
		/* (thus  B  was even, thus  A  must be odd!)  */

		/* set 'ret' to $(-1)^{(A^2-1)/8}$ */
		ret = tab[BN_lsw(A) & 7];
	} else {
		/* i is even */
		ret = 1;
	}

	if (B->neg) {
		B->neg = 0;
		if (A->neg)
			ret = -ret;
	}

	/* now  B  is positive and odd, so what remains to be done is
	 * to compute the Jacobi symbol  (A/B)  and multiply it by 'ret' */

	while (1) {
		/* Cohen's step 3: */

		/*  B  is positive and odd */

		if (BN_is_zero(A)) {
			ret = BN_is_one(B) ? ret : 0;
			goto end;
		}

		/* now  A  is non-zero */
		i = 0;
		while (!BN_is_bit_set(A, i))
			i++;
		err = !BN_rshift(A, A, i);
		if (err)
			goto end;
		if (i & 1) {
			/* i is odd */
			/* multiply 'ret' by  $(-1)^{(B^2-1)/8}$ */
			ret = ret * tab[BN_lsw(B) & 7];
		}

		/* Cohen's step 4: */
		/* multiply 'ret' by  $(-1)^{(A-1)(B-1)/4}$ */
		if ((A->neg ? ~BN_lsw(A) : BN_lsw(A)) & BN_lsw(B) & 2)
			ret = -ret;

		/* (A, B) := (B mod |A|, |A|) */
		err = !BN_nnmod(B, B, A, ctx);
		if (err)
			goto end;
		tmp = A;
		A = B;
		B = tmp;
		tmp->neg = 0;
	}

end:
	BN_CTX_end(ctx);
	if (err)
		return -2;
	else
		return ret;
}


text:
[![Build Status](https://secure.travis-ci.org/blambeau/alf-shell.png)](http://travis-ci.org/blambeau/alf-shell)
[![Dependency Status](https://gemnasium.com/blambeau/alf-shell.png)](https://gemnasium.com/blambeau/alf-shell)

Bring Alf's relational algebra to the shell

## Links

http://github.com/blambeau/alf-shell
http://github.com/blambeau/alf


text:
package mcore

type Email string

// Validate implements Validator
func (e Email) Validate() (b bool) {
	b = String(e).IsEmail()
	return
}


text:
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Soumyajit De
 */

#include <shogun/lib/config.h>
#include <shogun/lib/SGVector.h>
#include <shogun/lib/SGSparseMatrix.h>
#include <shogun/lib/SGSparseVector.h>
#include <shogun/base/Parameter.h>
#include <shogun/mathematics/linalg/linop/SparseMatrixOperator.h>
#include <shogun/mathematics/eigen3.h>

namespace shogun
{

template<class T>
CSparseMatrixOperator<T>::CSparseMatrixOperator()
	: CMatrixOperator<T>()
	{
		init();
	}

template<class T>
CSparseMatrixOperator<T>::CSparseMatrixOperator(SGSparseMatrix<T> op)
	: CMatrixOperator<T>(op.num_features),
	  m_operator(op)
	{
		init();
	}

template<class T>
CSparseMatrixOperator<T>::CSparseMatrixOperator
	(const CSparseMatrixOperator<T>& orig)
	: CMatrixOperator<T>(orig.get_dimension())
	{
		init();

		typedef SGSparseVector<T> vector;
		typedef SGSparseVectorEntry<T> entry;

		m_operator=SGSparseMatrix<T>(orig.m_operator.num_vectors, orig.m_operator.num_features);

		vector* rows=SG_MALLOC(vector, m_operator.num_features);
		for (index_t i=0; i<m_operator.num_vectors; ++i)
		{
			entry* features=SG_MALLOC(entry, orig.m_operator[i].num_feat_entries);
			for (index_t j=0; j<orig.m_operator[i].num_feat_entries; ++j)
			{
				features[j].feat_index=orig.m_operator[i].features[j].feat_index;
				features[j].entry=orig.m_operator[i].features[j].entry;
			}
			rows[i].features=features;
			rows[i].num_feat_entries=m_operator[i].num_feat_entries;
		}
		m_operator.sparse_matrix=rows;

		SG_SGCDEBUG("%s deep copy created (%p)\n", this->get_name(), this);
	}

template<class T>
void CSparseMatrixOperator<T>::init()
	{
		CSGObject::set_generic<T>();

		this->m_parameters->add_vector(&m_operator.sparse_matrix,
				&m_operator.num_vectors, "sparse_matrix",
				"The sparse matrix of the linear operator.");
		this->m_parameters->add(&m_operator.num_features,
				"m_operator.num_features", "Number of features.");
	}

template<class T>
CSparseMatrixOperator<T>::~CSparseMatrixOperator()
	{
	}

template<class T>
SGSparseMatrix<T> CSparseMatrixOperator<T>::get_matrix_operator() const
	{
		return m_operator;
	}

#ifdef HAVE_EIGEN3
template<class T>
SparsityStructure* CSparseMatrixOperator<T>::get_sparsity_structure(
	int64_t power) const
	{
		REQUIRE(power>0, "matrix-power is non-positive!\n");

		// create casted operator in bool for capturing the sparsity
		CSparseMatrixOperator<bool>* sp_str
			=static_cast<CSparseMatrixOperator<bool>*>(*this);

		// eigen3 map for this sparse matrix in which we compute current power
		Eigen::SparseMatrix<bool> current_power
			=EigenSparseUtil<bool>::toEigenSparse(sp_str->get_matrix_operator());

		// final power of the matrix goes into this one
		Eigen::SparseMatrix<bool> matrix_power;

		// compute matrix power with O(log(n)) matrix-multiplication!
		// traverse the bits of the power and compute the powers of 2 which
		// makes up this number. in the process multiply these to get the result
		bool lsb=true;
		while (power)
		{
			// if the current bit is on, it should contribute to the final result
			if (1 & power)
			{
				if (lsb)
				{
					// if seeing a 1 for the first time, then this should be the first
					// power we should consider
					matrix_power=current_power;
					lsb=false;
				}
				else
					matrix_power=matrix_power*current_power;
			}
			power=power>>1;

			// save unnecessary matrix-multiplication
			if (power)
				current_power=current_power*current_power;
		}

		// create the sparsity structure using the final power
		int32_t* outerIndexPtr=const_cast<int32_t*>(matrix_power.outerIndexPtr());
		int32_t* innerIndexPtr=const_cast<int32_t*>(matrix_power.innerIndexPtr());

		SG_UNREF(sp_str);

		return new SparsityStructure(outerIndexPtr, innerIndexPtr,
			matrix_power.rows());
	}
#else
template<class T>
SparsityStructure* CSparseMatrixOperator<T>::get_sparsity_structure(
	int64_t power) const
	{
		SG_SWARNING("Eigen3 required\n");
		return new SparsityStructure();
	}
#endif // HAVE_EIGEN3

template<> \
SparsityStructure* CSparseMatrixOperator<complex128_t>
	::get_sparsity_structure(int64_t power) const
  {
    SG_SERROR("Not supported for complex128_t\n");
    return new SparsityStructure();
  }

template<class T>
SGVector<T> CSparseMatrixOperator<T>::get_diagonal() const
	{
		REQUIRE(m_operator.sparse_matrix, "Operator not initialized!\n");

		const int32_t diag_size=m_operator.num_vectors>m_operator.num_features ?
			m_operator.num_features : m_operator.num_vectors;

		SGVector<T> diag(diag_size);
		diag.set_const(static_cast<T>(0));
		for (index_t i=0; i<diag_size; ++i)
		{
			SGSparseVectorEntry<T>* current_row=m_operator[i].features;
			for (index_t j=0; j<m_operator[i].num_feat_entries; ++j)
			{
				if (i==current_row[j].feat_index)
				{
					diag[i]=current_row[j].entry;
					break;
				}
			}
		}

		return diag;
	}

template<class T>
void CSparseMatrixOperator<T>::set_diagonal(SGVector<T> diag)
	{
		REQUIRE(m_operator.sparse_matrix, "Operator not initialized!\n");
		REQUIRE(diag.vector, "Diagonal not initialized!\n");

		const int32_t diag_size=m_operator.num_vectors>m_operator.num_features ?
			m_operator.num_features : m_operator.num_vectors;

		REQUIRE(diag_size==diag.vlen, "Dimension mismatch!\n");

		bool need_sorting=false;
		for (index_t i=0; i<diag_size; ++i)
		{
			SGSparseVectorEntry<T>* current_row=m_operator[i].features;
			bool inserted=false;
			// we just change the entry if the diagonal element for this row exists
			for (index_t j=0; j<m_operator[i].num_feat_entries; ++j)
			{
				if (i==current_row[j].feat_index)
				{
					current_row[j].entry=diag[i];
					inserted=true;
					break;
				}
			}

			// we create a new entry if the diagonal element for this row doesn't exist
			if (!inserted)
			{
				index_t j=m_operator[i].num_feat_entries;
				m_operator[i].num_feat_entries=j+1;
				m_operator[i].features=SG_REALLOC(SGSparseVectorEntry<T>,
					m_operator[i].features, j, j+1);
				m_operator[i].features[j].feat_index=i;
				m_operator[i].features[j].entry=diag[i];
				need_sorting=true;
			}
		}

		if (need_sorting)
			m_operator.sort_features();
	}

template<class T>
SGVector<T> CSparseMatrixOperator<T>::apply(SGVector<T> b) const
	{
		REQUIRE(m_operator.sparse_matrix, "Operator not initialized!\n");
		REQUIRE(this->get_dimension()==b.vlen,
			"Number of rows of vector must be equal to the "
			"number of cols of the operator!\n");

		SGVector<T> result(m_operator.num_vectors);
		result=m_operator*b;

		return result;
	}

#define UNDEFINED(type) \
template<> \
SGVector<type> CSparseMatrixOperator<type>::apply(SGVector<type> b) const \
	{	\
		SG_SERROR("Not supported for %s\n", #type);\
		return b; \
	}

UNDEFINED(bool)
UNDEFINED(char)
UNDEFINED(int8_t)
UNDEFINED(uint8_t)
UNDEFINED(int16_t)
UNDEFINED(uint16_t)
UNDEFINED(int32_t)
UNDEFINED(uint32_t)
UNDEFINED(int64_t)
UNDEFINED(uint64_t)
UNDEFINED(float32_t)
UNDEFINED(floatmax_t)
#undef UNDEFINED

template class CSparseMatrixOperator<bool>;
template class CSparseMatrixOperator<char>;
template class CSparseMatrixOperator<int8_t>;
template class CSparseMatrixOperator<uint8_t>;
template class CSparseMatrixOperator<int16_t>;
template class CSparseMatrixOperator<uint16_t>;
template class CSparseMatrixOperator<int32_t>;
template class CSparseMatrixOperator<uint32_t>;
template class CSparseMatrixOperator<int64_t>;
template class CSparseMatrixOperator<uint64_t>;
template class CSparseMatrixOperator<float32_t>;
template class CSparseMatrixOperator<float64_t>;
template class CSparseMatrixOperator<floatmax_t>;
template class CSparseMatrixOperator<complex128_t>;
}


text:
package thymeleafexamples.gtvg.business.entities;

import java.util.Calendar;

public class Customer {

    private Integer id = null;
    private String name = null;
    private Calendar customerSince = null;

    public Customer() {
        super();
    }

    public Integer getId() {
        return this.id;
    }
    public void setId(final Integer id) {
        this.id = id;
    }

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

    public Calendar getCustomerSince() {
        return this.customerSince;
    }
    public void setCustomerSince(final Calendar customerSince) {
        this.customerSince = customerSince;
    }

}


text:
cask :v1 => 'xampp' do
  version '1.8.3.3'
  sha256 'b54cced0697caa418851a4bdb11ee1697b3f7f71130e1e6bce19582d60e41530'

  # sourceforge.net is the official download host per the vendor homepage
  url "https://downloads.sourceforge.net/project/xampp/XAMPP%20Mac%20OS%20X/#{version.sub(%r{\.\d$},'')}/xampp-osx-#{version}-installer.dmg"
  homepage 'http://www.apachefriends.org/index.html'
  license :oss

  installer :manual => "xampp-osx-#{version}-installer.app"
  uninstall :delete => '/Applications/XAMPP'
end


text:
"""Mongo osid profile elements for commenting service packages"""
# -*- coding: utf-8 -*-
# pylint: disable=unused-import
#    importing common values to be used by commenting.ProfileManger implementation

from ..profile import ID
from ..profile import LANGUAGETYPE
from ..profile import SCRIPTTYPE
from ..profile import FORMATTYPE
from ..profile import VERSIONSCHEME
from ..profile import LOCALES
from ..profile import LICENSE
from ..profile import PROVIDERID
from ..profile import OSIDVERSION

DISPLAYNAME = 'Mongo commenting'

DESCRIPTION = 'MongoDB based commenting implementation'

VERSIONCOMPONENTS = [0, 1, 45]

RELEASEDATE = "2018-03-08"

SUPPORTS = [  # 'Remove the # when implementations exist:'
    # 'supports_journal_rollback',
    # 'supports_journal_branching',
    # 'supports_visible_federation',
    'supports_comment_lookup',
    # 'supports_rating_lookup',
    'supports_comment_query',
    # 'supports_comment_search',
    'supports_comment_admin',
    # 'supports_comment_notification',
    'supports_comment_book',
    'supports_comment_book_assignment',
    # 'supports_comment_smart_book',
    'supports_book_lookup',
    # 'supports_book_query',
    # 'supports_book_search',
    'supports_book_admin',
    # 'supports_book_notification',
    'supports_book_hierarchy',
    'supports_book_hierarchy_design',
    # 'supports_commenting_batch',
]


text:
class Main {
  void foo() throws ReflectiveOperationException {
    bar().getField("<caret>");
  }

  Class<Test> bar() throws ClassNotFoundException { return (Class<Test>) Class.forName("Test"); }
}

class Test {
  public int num;
  public void method(){}
}