text:
package schema

import (
	"testing"

	. "github.com/onsi/gomega"

	"istio.io/istio/galley/pkg/config/meta/schema/ast"
	"istio.io/istio/galley/pkg/config/meta/schema/collection"
)

func TestSchema_ParseAndBuild(t *testing.T) {
	var cases = []struct {
		Input    string
		Expected *Metadata
	}{
		{
			Input: ``,
			Expected: &Metadata{
				collections: collection.NewSpecsBuilder().Build(),
				snapshots:   map[string]*Snapshot{},
			},
		},
		{
			Input: `
collections:
  - name:         "k8s/networking.istio.io/v1alpha3/virtualservices"
    proto:        "istio.networking.v1alpha3.VirtualService"
    protoPackage: "istio.io/api/networking/v1alpha3"

  - name:         "istio/networking.istio.io/v1alpha3/virtualservices"
    proto:        "istio.networking.v1alpha3.VirtualService"
    protoPackage: "istio.io/api/networking/v1alpha3"

snapshots:
  - name: "default"
    strategy: debounce
    collections:
      - "istio/networking.istio.io/v1alpha3/virtualservices"

sources:
  - type: kubernetes
    resources:
    - collection:   "k8s/networking.istio.io/v1alpha3/virtualservices"
      kind:         "VirtualService"
      group:        "networking.istio.io"
      version:      "v1alpha3"

transforms:
  - type: direct
    mapping:
      "k8s/networking.istio.io/v1alpha3/virtualservices": "istio/networking.istio.io/v1alpha3/virtualservices"
`,
			Expected: &Metadata{
				collections: func() collection.Specs {
					b := collection.NewSpecsBuilder()
					b.MustAdd(
						collection.MustNewSpec(
							"k8s/networking.istio.io/v1alpha3/virtualservices",
							"istio.io/api/networking/v1alpha3",
							"istio.networking.v1alpha3.VirtualService"),
					)
					b.MustAdd(
						collection.MustNewSpec(
							"istio/networking.istio.io/v1alpha3/virtualservices",
							"istio.io/api/networking/v1alpha3",
							"istio.networking.v1alpha3.VirtualService"),
					)
					return b.Build()
				}(),
				snapshots: map[string]*Snapshot{
					"default": {
						Name:     "default",
						Strategy: "debounce",
						Collections: []collection.Name{
							collection.NewName("istio/networking.istio.io/v1alpha3/virtualservices"),
						},
					},
				},
				sources: []Source{
					&KubeSource{
						resources: []*KubeResource{
							{
								Collection: collection.MustNewSpec(
									"k8s/networking.istio.io/v1alpha3/virtualservices",
									"istio.io/api/networking/v1alpha3",
									"istio.networking.v1alpha3.VirtualService"),
								Version: "v1alpha3",
								Kind:    "VirtualService",
								Group:   "networking.istio.io",
							},
						},
					},
				},
				transformSettings: []TransformSettings{
					&DirectTransformSettings{
						mapping: map[collection.Name]collection.Name{
							collection.NewName("k8s/networking.istio.io/v1alpha3/virtualservices"): collection.NewName("istio/networking.istio.io/v1alpha3/virtualservices"),
						},
					},
				},
			},
		},
	}

	for _, c := range cases {
		t.Run("", func(t *testing.T) {
			g := NewGomegaWithT(t)

			actual, err := ParseAndBuild(c.Input)
			g.Expect(err).To(BeNil())
			g.Expect(actual).To(Equal(c.Expected))
		})
	}
}

func TestSchema_ParseAndBuild_Error(t *testing.T) {
	var cases = []string{
		`
	$$$
`,

		`
collections:
  - name:         "$$$"
    proto:        "istio.networking.v1alpha3.VirtualService"
    protoPackage: "istio.io/api/networking/v1alpha3"
`,
		`
collections:
  - name:         "k8s/networking.istio.io/v1alpha3/virtualservices"
    proto:        "istio.networking.v1alpha3.VirtualService"
    protoPackage: "istio.io/api/networking/v1alpha3"
  - name:         "k8s/networking.istio.io/v1alpha3/virtualservices"
    proto:        "istio.networking.v1alpha3.VirtualService"
    protoPackage: "istio.io/api/networking/v1alpha3"
`,

		`
collections:
  - name:         "k8s/networking.istio.io/v1alpha3/virtualservices"
    proto:        "istio.networking.v1alpha3.VirtualService"
    protoPackage: "istio.io/api/networking/v1alpha3"
snapshots:
- name: "default"
  strategy: debounce
  collections:
  - "istio/networking.istio.io/v1alpha3/virtualservices"
`,
		`
collections:
sources:
  - type: kubernetes
    resources:
    - collection:   "k8s/networking.istio.io/v1alpha3/virtualservices"
      kind:         "VirtualService"
      group:        "networking.istio.io"
      version:      "v1alpha3"
`,
		`
collections:
  - name:         "k8s/networking.istio.io/v1alpha3/virtualservices"
    proto:        "istio.networking.v1alpha3.VirtualService"
    protoPackage: "istio.io/api/networking/v1alpha3"
transforms:
  - type: direct
    mapping:
      "k8s/networking.istio.io/v1alpha3/virtualservices": "istio/networking.istio.io/v1alpha3/virtualservices"
`,
		`
collections:
  - name:         "istio/networking.istio.io/v1alpha3/virtualservices"
    proto:        "istio.networking.v1alpha3.VirtualService"
    protoPackage: "istio.io/api/networking/v1alpha3"
transforms:
  - type: direct
    mapping:
      "k8s/networking.istio.io/v1alpha3/virtualservices": "istio/networking.istio.io/v1alpha3/virtualservices"
`,
	}

	for _, c := range cases {
		t.Run("", func(t *testing.T) {
			g := NewGomegaWithT(t)

			_, err := ParseAndBuild(c)
			g.Expect(err).NotTo(BeNil())
		})
	}
}

var input = `
collections:
  - name:         "k8s/networking.istio.io/v1alpha3/virtualservices"
    proto:        "istio.networking.v1alpha3.VirtualService"
    protoPackage: "istio.io/api/networking/v1alpha3"

  - name:         "istio/networking.istio.io/v1alpha3/virtualservices"
    proto:        "istio.networking.v1alpha3.VirtualService"
    protoPackage: "istio.io/api/networking/v1alpha3"

snapshots:
  - name: "default"
    strategy: debounce
    collections:
      - "istio/networking.istio.io/v1alpha3/virtualservices"

sources:
  - type: kubernetes
    resources:
    - collection:   "k8s/networking.istio.io/v1alpha3/virtualservices"
      kind:         "VirtualService"
      group:        "networking.istio.io"
      version:      "v1alpha3"

transforms:
  - type: direct
    mapping:
      "k8s/networking.istio.io/v1alpha3/virtualservices": "istio/networking.istio.io/v1alpha3/virtualservices"
`

func TestSchemaBasic(t *testing.T) {
	g := NewGomegaWithT(t)

	s, err := ParseAndBuild(input)
	g.Expect(err).To(BeNil())

	b := collection.NewSpecsBuilder()
	b.MustAdd(collection.MustNewSpec("k8s/networking.istio.io/v1alpha3/virtualservices",
		"istio.io/api/networking/v1alpha3",
		"istio.networking.v1alpha3.VirtualService"))
	b.MustAdd(collection.MustNewSpec("istio/networking.istio.io/v1alpha3/virtualservices",
		"istio.io/api/networking/v1alpha3",
		"istio.networking.v1alpha3.VirtualService"))
	g.Expect(s.AllCollections()).To(Equal(b.Build()))
	g.Expect(s.AllCollectionsInSnapshots([]string{"default"})).To(ConsistOf("istio/networking.istio.io/v1alpha3/virtualservices"))
	g.Expect(func() { s.AllCollectionsInSnapshots([]string{"bogus"}) }).To(Panic())

	g.Expect(s.TransformSettings()).To(HaveLen(1))
	g.Expect(s.TransformSettings()[0]).To(Equal(
		&DirectTransformSettings{
			mapping: map[collection.Name]collection.Name{
				collection.NewName("k8s/networking.istio.io/v1alpha3/virtualservices"): collection.NewName("istio/networking.istio.io/v1alpha3/virtualservices"),
			},
		}))
	g.Expect(s.DirectTransformSettings()).To(Equal(
		&DirectTransformSettings{
			mapping: map[collection.Name]collection.Name{
				collection.NewName("k8s/networking.istio.io/v1alpha3/virtualservices"): collection.NewName("istio/networking.istio.io/v1alpha3/virtualservices"),
			},
		}))

	g.Expect(s.DirectTransformSettings().Mapping()).To(Equal(
		map[collection.Name]collection.Name{
			collection.NewName("k8s/networking.istio.io/v1alpha3/virtualservices"): collection.NewName("istio/networking.istio.io/v1alpha3/virtualservices"),
		}))

	g.Expect(s.AllSources()).To(HaveLen(1))
	g.Expect(s.AllSources()[0]).To(Equal(
		&KubeSource{
			resources: []*KubeResource{
				{
					Collection: collection.MustNewSpec("k8s/networking.istio.io/v1alpha3/virtualservices",
						"istio.io/api/networking/v1alpha3",
						"istio.networking.v1alpha3.VirtualService"),
					Group:   "networking.istio.io",
					Version: "v1alpha3",
					Kind:    "VirtualService",
				},
			},
		}))

	g.Expect(s.AllSnapshots()).To(HaveLen(1))
	g.Expect(s.AllSnapshots()[0]).To(Equal(
		&Snapshot{
			Name:        "default",
			Strategy:    "debounce",
			Collections: []collection.Name{collection.NewName("istio/networking.istio.io/v1alpha3/virtualservices")},
		}))

	g.Expect(s.KubeSource()).To(Equal(&KubeSource{
		resources: []*KubeResource{
			{
				Collection: collection.MustNewSpec("k8s/networking.istio.io/v1alpha3/virtualservices",
					"istio.io/api/networking/v1alpha3",
					"istio.networking.v1alpha3.VirtualService"),
				Group:   "networking.istio.io",
				Version: "v1alpha3",
				Kind:    "VirtualService",
			},
		},
	}))

	g.Expect(s.KubeSource().Resources()).To(Equal(KubeResources{
		{
			Collection: collection.MustNewSpec("k8s/networking.istio.io/v1alpha3/virtualservices",
				"istio.io/api/networking/v1alpha3",
				"istio.networking.v1alpha3.VirtualService"),
			Group:   "networking.istio.io",
			Version: "v1alpha3",
			Kind:    "VirtualService",
		},
	}))

	g.Expect(s.KubeSource().Resources().Collections()).To(Equal([]collection.Name{
		collection.NewName("k8s/networking.istio.io/v1alpha3/virtualservices"),
	}))

	g.Expect(s.KubeSource().Resources()[0].CanonicalResourceName()).To(Equal("networking.istio.io/v1alpha3/VirtualService"))
}

func TestSchema_Find(t *testing.T) {
	g := NewGomegaWithT(t)

	s, err := ParseAndBuild(input)
	g.Expect(err).To(BeNil())

	k, b := s.KubeSource().Resources().Find("networking.istio.io", "VirtualService")
	g.Expect(b).To(BeTrue())
	g.Expect(k).To(Equal(KubeResource{
		Collection: collection.MustNewSpec("k8s/networking.istio.io/v1alpha3/virtualservices",
			"istio.io/api/networking/v1alpha3",
			"istio.networking.v1alpha3.VirtualService"),
		Group:   "networking.istio.io",
		Version: "v1alpha3",
		Kind:    "VirtualService",
	}))

	_, b = s.KubeSource().Resources().Find("foo", "bar")
	g.Expect(b).To(BeFalse())
}

func TestSchema_MustFind(t *testing.T) {
	g := NewGomegaWithT(t)

	defer func() {
		r := recover()
		g.Expect(r).To(BeNil())
	}()

	s, err := ParseAndBuild(input)
	g.Expect(err).To(BeNil())

	k := s.KubeSource().Resources().MustFind("networking.istio.io", "VirtualService")
	g.Expect(k).To(Equal(KubeResource{
		Collection: collection.MustNewSpec("k8s/networking.istio.io/v1alpha3/virtualservices",
			"istio.io/api/networking/v1alpha3",
			"istio.networking.v1alpha3.VirtualService"),
		Group:   "networking.istio.io",
		Version: "v1alpha3",
		Kind:    "VirtualService",
	}))
}

func TestSchema_MustFind_Panic(t *testing.T) {
	g := NewGomegaWithT(t)

	defer func() {
		r := recover()
		g.Expect(r).NotTo(BeNil())
	}()

	s, err := ParseAndBuild(input)
	g.Expect(err).To(BeNil())

	_ = s.KubeSource().Resources().MustFind("foo.istio.io", "bar")
}

func TestSchema_KubeResource_Panic(t *testing.T) {
	g := NewGomegaWithT(t)

	defer func() {
		r := recover()
		g.Expect(r).NotTo(BeNil())
	}()

	s, err := ParseAndBuild(``)
	g.Expect(err).To(BeNil())

	_ = s.KubeSource()
}

func TestSchema_DirectTransform_Panic(t *testing.T) {
	g := NewGomegaWithT(t)

	defer func() {
		r := recover()
		g.Expect(r).NotTo(BeNil())
	}()

	s, err := ParseAndBuild(``)
	g.Expect(err).To(BeNil())

	_ = s.DirectTransformSettings()
}

func TestBuild_UnknownSource(t *testing.T) {
	g := NewGomegaWithT(t)

	a := &ast.Metadata{
		Sources: []ast.Source{
			&struct{}{},
		},
	}

	_, err := Build(a)
	g.Expect(err).NotTo(BeNil())
}

func TestBuild_UnknownTransform(t *testing.T) {
	g := NewGomegaWithT(t)

	a := &ast.Metadata{
		TransformSettings: []ast.TransformSettings{
			&unknownXformSettings{},
		},
	}

	_, err := Build(a)
	g.Expect(err).NotTo(BeNil())
}

type unknownXformSettings struct {
}

var _ ast.TransformSettings = &unknownXformSettings{}

func (u *unknownXformSettings) Type() string { return "unknown" }


text:
package com.cyberlightning.realvirtualinteraction.backend.sockets;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

import com.cyberlightning.realvirtualinteraction.backend.StaticResources;
import com.cyberlightning.realvirtualinteraction.backend.interfaces.IMessageEvent;
import com.cyberlightning.realvirtualinteraction.backend.services.Gzip;
import com.cyberlightning.realvirtualinteraction.backend.services.MessageService;

public class UdpSocket implements Runnable  {

  public DatagramSocket serverSocket;
  private int port;
  public static final String uuid = UUID.randomUUID().toString();
  public  final int type = StaticResources.UDP_RECEIVER;
  public SendWorker sendWorker;
  /**
   *
   */
  public UdpSocket () {
    this(StaticResources.SERVER_PORT_COAP);
  }

  /**
   *
   * @param _port
   */
  public UdpSocket (int _port) {
    this.port = _port;
    Thread t = new Thread(this);
    t.start();
  }

  @Override
  public void run() {

    try {

      serverSocket = new DatagramSocket(this.port);
      this.serverSocket.setReceiveBufferSize(StaticResources.UDP_PACKET_SIZE);
      this.sendWorker = new SendWorker(uuid);

    } catch (SocketException e) {
      // TODO Auto-generated catch block
      if (this.sendWorker != null){
          this.sendWorker.destroy();
      }
    }

    while(true) {

      if (!MessageService.isStarted()) continue;

      byte[] receivedData = new byte[StaticResources.UDP_PACKET_SIZE];
      DatagramPacket receivedPacket = new DatagramPacket(receivedData, receivedData.length);

      try {
        serverSocket.receive(receivedPacket);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      String receivedData_decrypted = null;

      try {
          receivedData_decrypted = Gzip.decompress(receivedPacket.getData());
           } catch (IOException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
           }
      System.out.println("PACKET AT LEAST RECEIVED: " +receivedData_decrypted);

      this.handleIncomingMessage(receivedPacket);

    }
  }

  public void handleIncomingMessage(DatagramPacket _packet) {
    MessageService.getInstance().addToMessageBuffer(new MessageObject(uuid,StaticResources.UDP_RECEIVER, _packet));
    MessageService.getInstance().wakeThread();
  }

  public class SendWorker implements Runnable,IMessageEvent {

    public CopyOnWriteArrayList<MessageObject> sendBuffer = new CopyOnWriteArrayList<MessageObject>();
    public String uuid;
    private boolean suspendFlag = true;
    private boolean destroyFlag = false;
    private Thread thread;
    /**
     *
     * @param _uuid
     */
    public SendWorker (String _uuid) {
      this.uuid = _uuid;
      this.thread = new Thread(this);
      this.thread.start();
    }

    @Override
    public void run() {

      MessageService.getInstance().registerReceiver(this,this.uuid);

      while (true) {

        synchronized(this) {

          while(suspendFlag && !destroyFlag) {
            try {
              wait();
            } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              return;
            }
          }
        }
        if (!sendBuffer.isEmpty()) {

         try {

           Iterator<MessageObject> i = this.sendBuffer.iterator();
           while(i.hasNext()) {

            MessageObject msg = i.next();

            if (msg.payload instanceof DatagramPacket) {
              serverSocket.send((DatagramPacket)msg.payload);
            } else if (msg.payload instanceof String) {

              byte[] b = ((String) msg.payload).getBytes();

              for (InetSocketAddress target : msg.targetAddresses) {
                DatagramPacket packet = new DatagramPacket(b,b.length,InetAddress.getByAddress(target.getAddress().getAddress()),target.getPort());
                serverSocket.send(packet);
              }

            }
            MessageObject response;
            if (msg.targetAddresses.size() == 0) {
              response = new MessageObject(msg.originUUID,StaticResources.UDP_RESPONSE,StaticResources.ERROR_CODE_NOT_FOUND);

            } else {
              response = new MessageObject(msg.originUUID,StaticResources.UDP_RESPONSE,StaticResources.HTTP_CODE_OK);
            }
            MessageService.getInstance().addToMessageBuffer(response);
            MessageService.getInstance().wakeThread();
            sendBuffer.remove(msg);
          }
          this.suspendThread();

        } catch (IOException e) {
          System.out.println(e.getMessage());
          if (serverSocket.isClosed()) break;
        }
      }
    }
      return; //Exit thread
    }

    public void suspendThread() {
      suspendFlag = true;
    }

    private synchronized void wakeThread() {
      suspendFlag = false;
      notify();
    }

    private synchronized void destroy() {
      this.destroyFlag = true;
      notify();
    }

    @Override
    public void onMessageReceived(MessageObject _msg) {
      this.sendBuffer.add(_msg);
      this.wakeThread();
    }

  }

}

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.OData.Client;
using OfficeTicTacToe.Common;
using OfficeTicTacToe.Graph;
using OfficeTicTacToe.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using System.Threading.Tasks;
using Windows.UI.Xaml.Media.Animation;
using System.Diagnostics;
using System.Threading;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Text;

using OfficeTicTacToe.ViewModels;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace OfficeTicTacToe.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class BoardView : IRefreshPage
    {
        private CancellationTokenSource tokenSource;
        public GameViewModel Game { get; set; }
        public CancellationTokenSource TokenSource
        {
            get
            {
                return this.tokenSource;
            }
            set
            {
                this.tokenSource = value;
            }
        }

        public bool IsRefreshButtonEnabled
        {
            get
            {
                return AppShell.Current.RefreshButton.IsEnabled;
            }
            set
            {
                AppShell.Current.RefreshButton.IsEnabled = value;
            }
        }

        public string Title
        {
            get
            {
                return "office tic tac toe";
            }
        }

        TaskScheduler uiScheduler;
        public BoardView()
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Required;
            uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

            ((App)(App.Current)).Channel.PushNotificationReceived += Channel_PushNotificationReceived;
        }

        private async void Channel_PushNotificationReceived(Windows.Networking.PushNotifications.PushNotificationChannel sender, Windows.Networking.PushNotifications.PushNotificationReceivedEventArgs args)
        {
            Debug.WriteLine("Notification received");
            await Task.Factory.StartNew(Refresh, CancellationToken.None, TaskCreationOptions.None, uiScheduler);
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            Game = e?.Parameter as GameViewModel ?? new GameViewModel();
            DataContext = Game;
            using (this.TokenSource = new CancellationTokenSource())
            {
                try
                {
                    this.IsRefreshButtonEnabled = false;
                    await Refresh(this.TokenSource.Token, false);

                }
                catch (OperationCanceledException ex)
                {
                    Debug.WriteLine("Operation canceled " + ex.Message);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                finally
                {
                    this.IsRefreshButtonEnabled = true;
                }

            }

        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
        }

        public async Task Refresh()
        {
            using (this.TokenSource = new CancellationTokenSource())
            {
                try
                {
                    this.IsRefreshButtonEnabled = false;
                    await Refresh(this.TokenSource.Token, true);
                }
                catch (OperationCanceledException ex)
                {
                    Debug.WriteLine("Operation canceled " + ex.Message);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                finally
                {
                    this.IsRefreshButtonEnabled = true;
                }

            }
        }
        public async Task Refresh(CancellationToken token, bool forceRefresh = false)
        {

            if (Game != null)
                await Game.Refresh();

            StackPanelLoader.Visibility = Visibility.Visible;
            StackPanelLoader.Opacity = 1.0d;

            //ProgressRingLoader.Visibility = Visibility.Visible;
            //ProgressRingLoader.IsActive = true;

            //DoubleAnimation animationOpacity = new DoubleAnimation();
            //animationOpacity.To = 0.0d;
            //animationOpacity.From = 1.0d;
            //Storyboard.SetTarget(animationOpacity, StackPanelLoader);
            //Storyboard.SetTargetProperty(animationOpacity, "Opacity");

            //DoubleAnimation animationOpacity2 = new DoubleAnimation();
            //animationOpacity2.To = 1.0d;
            //animationOpacity2.From = 0.0d;
            //Storyboard.SetTarget(animationOpacity2, EventViewList);
            //Storyboard.SetTargetProperty(animationOpacity2, "Opacity");

            //Storyboard sb = new Storyboard();
            //sb.Children.Add(animationOpacity);
            //sb.Children.Add(animationOpacity2);

            //sb.Duration = animationOpacity.Duration = animationOpacity2.Duration = TimeSpan.FromMilliseconds(150);

            //sb.Completed += (s, o) =>
            //{

            //    ProgressRingLoader.IsActive = false;
            //    ProgressRingLoader.Visibility = Visibility.Collapsed;
            //    StackPanelLoader.Visibility = Visibility.Collapsed;
            //    AppShell.Current.SetTitle("next meetings");

            //};

            // sb.Begin();
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button == null)
                return;
            var cell = Convert.ToInt16(button.Tag);
            if ((cell < 0) || (cell > Game.Board.Length))
                return;
            var board = Game.InitialBoard.ToArray();
            if (board[cell] == ' ')
            {
                board[cell] = Game.CurrentPawn;
                Game.Board = new string(board);
            }

            await Game.Update();
        }
    }
}


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: android/platform/libcore/ojluni/src/main/java/java/lang/annotation/Repeatable.java
//

#include "../../../J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_JavaLangAnnotationRepeatable")
#ifdef RESTRICT_JavaLangAnnotationRepeatable
#define INCLUDE_ALL_JavaLangAnnotationRepeatable 0
#else
#define INCLUDE_ALL_JavaLangAnnotationRepeatable 1
#endif
#undef RESTRICT_JavaLangAnnotationRepeatable

#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

#if !defined (JavaLangAnnotationRepeatable_) && (INCLUDE_ALL_JavaLangAnnotationRepeatable || defined(INCLUDE_JavaLangAnnotationRepeatable))
#define JavaLangAnnotationRepeatable_

#define RESTRICT_JavaLangAnnotationAnnotation 1
#define INCLUDE_JavaLangAnnotationAnnotation 1
#include "../../../java/lang/annotation/Annotation.h"

@class IOSClass;
@class IOSObjectArray;

/*!
 @brief The annotation type java.lang.annotation.Repeatable is
 used to indicate that the annotation type whose declaration it
 (meta-)annotates is repeatable.
 The value of
 @@Repeatable indicates the containing annotation
 type for the repeatable annotation type.
 @since 1.8
  9.6 Annotation Types
  9.7 Annotations
 */
@protocol JavaLangAnnotationRepeatable < JavaLangAnnotationAnnotation >

@property (readonly) IOSClass *value;

@end

@interface JavaLangAnnotationRepeatable : NSObject < JavaLangAnnotationRepeatable > {
 @public
  IOSClass *value_;
}

@end

J2OBJC_EMPTY_STATIC_INIT(JavaLangAnnotationRepeatable)

FOUNDATION_EXPORT id<JavaLangAnnotationRepeatable> create_JavaLangAnnotationRepeatable(IOSClass *value);

J2OBJC_TYPE_LITERAL_HEADER(JavaLangAnnotationRepeatable)

#endif

#pragma clang diagnostic pop
#pragma pop_macro("INCLUDE_ALL_JavaLangAnnotationRepeatable")


text:
In general the contributing guidelines of OpenUI5 also apply to this project. They can be found here:
https://github.com/SAP/openui5/blob/master/CONTRIBUTING.md

Some parts might not be relevant for this project (e.g. the browser-specific requirements like jQuery, CSS and
accessibility in the "Contribution Content Guidelines") and the contribution process is easier (pull requests will be
merged directly on GitHub).


text:
@interface Tools : NSObject
+ (UIViewController *)getCurrentVC;
+ (UIViewController *)getPresentedViewController;
@end


text:
//
// SFConnectorGroupZone.h
//
// Autogenerated by a tool
//  Copyright (c) 2016 Citrix ShareFile. All rights reserved.
//

#import "SFODataObject.h"

@class SFZone;

@interface SFConnectorGroupZone : SFODataObject
{
}

/**
   Zone that contains this connector class
 */
@property (nonatomic, strong) SFZone *Zone;
/**
   List of Storage Centers in this Zone that contain this Connector
 */
@property (nonatomic, strong) NSArray *StorageCenters;
/**
   Minimum API version supported by this connector group
 */
@property (nonatomic, strong) NSString *ApiVersionMin;
/**
   Maximum API version supported by this connector group
 */
@property (nonatomic, strong) NSString *ApiVersionMax;
/**
   URL for the Connector Group Icon.
 */
@property (nonatomic, strong) NSString *IconUrl;
/**
   URL for the Form that creates or updates connectors
 */
@property (nonatomic, strong) NSString *FormUrl;

@end


text:
<?php
/*
Plugin Name: Video Background
Plugin URI: http://blakewilson.me/projects/video-background/
Description: jQuery WordPress plugin to easily assign a video background to any element. Awesome.
Author: Blake Wilson
Version: 2.5.8
Author URI: http://blakewilson.me
Donate Link: http://paypal.me/blakewilsonme
Text Domain: video-background
Domain Path: /languages
*/

/**
 * Include the metabox framework
 */
if ( file_exists( dirname( __FILE__ ) . '/framework/init.php' ) ) {
	require_once dirname( __FILE__ ) . '/framework/init.php';
}
if ( file_exists( dirname( __FILE__ ) . '/framework/cmb2_field_slider.php' ) ) {
	require_once dirname( __FILE__ ) . '/framework/cmb2_field_slider.php';
}

/**
 * Install the plugin
 * deactivate vidbgpro if installed
 *
 * @since 2.5.2
 *
 * @uses is_plugin_active()
 * @uses deactivate_plugins()
 * @uses delete_option()
 */
function vidbg_install_plugin() {
	if( is_plugin_active( 'video-background-pro/vidbgpro.php') ) {
		deactivate_plugins( 'video-background-pro/vidbgpro.php' );
	}
	delete_option( 'vidbgpro-notice-dismissed' );
	delete_option( 'vidbg_disable_pro_fields' );
}
register_activation_hook( __FILE__, 'vidbg_install_plugin' );

/**
 * Load plugin textdomain.
 *
 * @since 2.5.0
 *
 * @uses load_plugin_textdomain()
 * @uses plugin_basename()
 */
function vidbg_load_textdomain() {
	load_plugin_textdomain( 'video-background', false, plugin_basename( dirname( __FILE__ ) ) . '/languages' );
}
add_action( 'plugins_loaded', 'vidbg_load_textdomain' );

/**
 * Enqueue backend style and script
 *
 * @since 2.1.4
 *
 * @uses wp_enqueue_style()
 * @uses plugins_url()
 * @uses wp_enqueue_script()
 * @uses plugin_dir_url()
 */
function vidbg_metabox_scripts() {
	wp_enqueue_style('vidbg-metabox-style', plugins_url('/css/vidbg-style.css', __FILE__));
	wp_enqueue_script( 'vidbg-admin-backend', plugin_dir_url( __FILE__ ) . '/js/vidbg-backend.js' );

	wp_localize_script( 'vidbg-admin-backend', 'vidbg_localized_text', array(
		'show_advanced' => __( 'Show Advanced Options', 'video-background' ),
		'hide_advanced' => __( 'Hide Advanced Options', 'video-background' ),
	) );
}
add_action('admin_enqueue_scripts', 'vidbg_metabox_scripts');

/**
 * Enqueue vidbg jquery script
 *
 * @since 2.0.0
 *
 * @uses wp_enqueue_script()
 * @uses plugins_url()
 */
function vidbg_jquery() {
	wp_register_script( 'vidbg-video-background', plugins_url('/js/dist/vidbg.min.js', __FILE__), array('jquery'), '1.1', true);
}
add_action( 'wp_enqueue_scripts', 'vidbg_jquery' );

/**
 * Add custom color palette
 *
 * @since 2.5.0
 */
function vidbg_default_color_palette( $l10n ) {
	$l10n['defaults']['color_picker'] = array(
		'palettes' => array( '#000000', '#3498db', '#e74c3c', '#374e64', '#2ecc71', '#f1c40f' ),
	);
	return $l10n;
}
add_filter( 'cmb2_localized_data', 'vidbg_default_color_palette' );

/**
 * Helper function to output disabled Video Background Pro fields
 *
 * @since 2.5.4
 *
 * @uses get_option()
 */
function vidbg_disabled_pro_field( $field_name = 'Blank Pro', $field_id = 'pro_blank', $field_type = 'input', $field_description = '' ) {

	$output = '';
	$options = get_option( 'vidbg_disable_pro_fields' );

	if ( ! $options ) {
		if ( $field_type === 'input' ) {
			$field_class = 'cmb-row cmb-type-text cmb2-id-pro-disabled-field-' . $field_id . ' table-layout';
		} elseif ( $field_type === 'radio' ) {
			$field_class = 'cmb-row cmb-type-radio-inline cmb2-id-pro-disabled-field-' . $field_id . ' cmb-inline';
		}

		$output .= '
';
		$output .= '
' . $field_name . '
';
		$output .= '
';

		if ( $field_type === 'input' ) {
			$output .= '<input type="text" class="regular-text" name="pro_disabled_' . $field_id . '" id="' . $field_id . '" disabled>';
		}

		if ( $field_type === 'radio' ) {
			$output .= '
';
			$output .= '
<input type="radio" value="off" class="cmb2-option" name="pro_disabled_' . $field_id . '" id="pro_disabled_' . $field_id . '1" checked="checked" disabled> Off
';
			$output .= '
<input type="radio" class="cmb2-option" name="pro_disabled_' . $field_id . '" id="pro_disabled_' . $field_id . '2" value="on" disabled> On
';
			$output .= '
';
		}

		if ( $field_id === 'overlay_texture' ) {
			$output .= '<input class="cmb2-upload-button button" type="button" value="Upload Overlay Texture" disabled="">';
		}

		$output .= '
' . $field_description . '
';
		$output .= '
';
		$output .= '
';
	}

	return $output;
}

/**
 * Register metabox and scripts
 *
 * @since 2.5.0
 *
 * @uses new_cmb2_box()
 * @uses __()
 * @uses add_field()
 * @uses vidbg_disabled_pro_field()
 */
function vidbg_register_metabox() {
	$prefix = 'vidbg_metabox_field_';
	$post_types = array( 'post', 'page' );

	/**
	 * Allow the post types to be filtered out
	 */
	$post_types = apply_filters( 'vidbg_post_types', $post_types );

	$vidbg_metabox = new_cmb2_box( array(
		'id'           => 'vidbg-metabox',
		'title'        => __( 'Video Background', 'video-background' ),
		'object_types' => $post_types,
		'context'      => 'normal',
		'priority'     => 'high',
	) );

	$vidbg_metabox->add_field( array(
		'name' => __( 'Container', 'video-background' ),
		'desc' => __( 'Please specify the container you would like your video background to be in.
ex: .header or body', 'video-background' ),
		'id'   => $prefix . 'container',
		'type' => 'text',
		'after_row' => vidbg_disabled_pro_field(
										__( 'YouTube Link', 'video-background' ),
										'youtube_link',
										'input',
										__( 'To create YouTube video backgrounds, please download the pro version!', 'video-background' )
									 ),
	) );

	$vidbg_metabox->add_field( array(
		'name'    => __( 'Link to .mp4', 'video-background' ),
		'desc'    => __( 'Please specify the link to the .mp4 file. You can either enter a URL or upload a file.
For browser compatability, please enter an .mp4 and .webm file for video backgrounds.', 'video-background' ),
		'id'      => $prefix . 'mp4',
		'type'    => 'file',
		'options' => array(
			'add_upload_file_text' => __( 'Upload .mp4 file', 'video-background' ),
		),
	) );

	$vidbg_metabox->add_field( array(
		'name'    => __( 'Link to .webm', 'video-background' ),
		'desc'    => __( 'Please specify the link to the .webm file. You can either enter a URL or upload a file.
For browser compatability, please enter an .mp4 and .webm file for video backgrounds.', 'video-background' ),
		'id'      => $prefix . 'webm',
		'type'    => 'file',
		'options' => array(
			'add_upload_file_text' => __( 'Upload .webm file', 'video-background' ),
		),
	) );

	$vidbg_metabox->add_field( array(
		'name'    => __( 'Link to fallback image', 'video-background' ),
		'desc'    => __( 'Please specify a link to the fallback image in case the browser does not support video backgrounds. You can either enter a URL or upload a file.', 'video-background' ),
		'id'      => $prefix . 'poster',
		'type'    => 'file',
		'options' => array(
			'add_upload_file_text' => __( 'Upload fallback image', 'video-background' ),
		),
	) );

	$vidbg_metabox->add_field( array(
		'name'       => __( 'Overlay', 'video-background' ),
		'desc'       => __( 'Add an overlay over the video. This is useful if your text isn\'t readable with a video background.', 'video-background' ),
		'id'         => $prefix . 'overlay',
		'type'       => 'radio_inline',
		'default'    => 'off',
		'options' => array(
			'off' => __( 'Off', 'video-background' ),
			'on'  => __( 'On', 'video-background' ),
		),
		'before_row' => '
',
	) );

	$vidbg_metabox->add_field( array(
		'name'    => __( 'Overlay Color', 'video-background' ),
		'desc'    => __( 'If overlay is enabled, a color will be used for the overlay. You can specify the color here.', 'video-background' ),
		'id'      => $prefix . 'overlay_color',
		'type'    => 'colorpicker',
		'default' => '#000',
	) );

	$vidbg_metabox->add_field( array(
		'name'    => __( 'Overlay Opacity', 'video-background' ),
		'desc'    => __( 'Specify the opacity of the overlay with the left being mostly transparent and the right being hardly transparent.', 'video-background' ),
		'id'      => $prefix . 'overlay_alpha',
		'type'    => 'own_slider',
		'min'     => '10',
		'max'     => '99',
		'default' => '30',
		'after_row' => vidbg_disabled_pro_field(
										__( 'Overlay Texture', 'video-background' ),
										'overlay_texture',
										'input',
										__( 'To add overlay textures to your video background, please download the pro version!', 'video-background' )
									 ),
	) );

	$vidbg_metabox->add_field( array(
		'name'    => __( 'Turn off loop?', 'video-background' ),
		'desc'    => __( 'Turn off the loop for Video Background. Once the video is complete, it will display the last frame of the video.', 'video-background' ),
		'id'      => $prefix . 'no_loop',
		'type'    => 'radio_inline',
		'default' => 'off',
		'options' => array(
			'off' => __( 'Off', 'video-background' ),
			'on'  => __( 'On', 'video-background' ),
		),
	) );

	$vidbg_metabox->add_field( array(
		'name'      => __( 'Play the audio?', 'video-background' ),
		'desc'      => __( 'Enabling this will play the audio of the video.', 'video-background' ),
		'id'        => $prefix . 'unmute',
		'type'      => 'radio_inline',
		'default'   => 'off',
		'options'   => array(
			'off' => __( 'Off', 'video-background' ),
			'on'  => __( 'On', 'video-background' ),
		),
		'after_row' => vidbg_disabled_pro_field(
										__( 'Enable Play/Pause button', 'video-background' ),
										'play_button',
										'radio',
										__( 'To enable a play/pause button on the frontend, please download the pro version!', 'video-background' )
									 ) . vidbg_disabled_pro_field(
 										__( 'Enable Mute/Unmute button', 'video-background' ),
 										'volume_button',
 										'radio',
 										__( 'To enable a mute/unmute button on the frontend, please download the pro version!', 'video-background' )
 									 ) . '
',
	) );

	$vidbg_metabox->add_field( array(
		'before_field' => __( 'Show Advanced options', 'video-background' ),
		'type'         => 'title',
		'id'           => $prefix . 'advanced_button',
	) );

}
add_action( 'cmb2_admin_init', 'vidbg_register_metabox' );

/**
 * Add inline javascript to footer for video background
 *
 * @since 2.0.0
 *
 * @uses is_page()
 * @uses is_single()
 * @uses is_home()
 * @uses get_option()
 * @uses get_the_ID()
 * @uses get_post_meta()
 */
function vidbg_initialize_footer() {
	if( is_page() || is_single() || is_home() && get_option( 'show_on_front') == 'page' ) {

		if( is_page() || is_single() ) {
			$the_id = get_the_ID();
		} elseif( is_home() && get_option( 'show_on_front' ) == 'page' ) {
			$the_id = get_option( 'page_for_posts' );
		}

		$container_field = get_post_meta( $the_id, 'vidbg_metabox_field_container', true );
		$mp4_field = get_post_meta( $the_id, 'vidbg_metabox_field_mp4', true );
		$webm_field = get_post_meta( $the_id, 'vidbg_metabox_field_webm', true );
		$poster_field = get_post_meta( $the_id, 'vidbg_metabox_field_poster', true );
		$overlay = get_post_meta( $the_id, 'vidbg_metabox_field_overlay', true );
		$overlay_color = get_post_meta( $the_id, 'vidbg_metabox_field_overlay_color', true );
		$overlay_alpha = get_post_meta( $the_id, 'vidbg_metabox_field_overlay_alpha', true );
		$no_loop_field = get_post_meta( $the_id, 'vidbg_metabox_field_no_loop', true );
		$unmute_field = get_post_meta( $the_id, 'vidbg_metabox_field_unmute', true );

		if( !empty( $container_field ) ): ?>
		<?php

		/**
		 * Enqueue the vidbg script conditionally
		 */
		wp_enqueue_script( 'vidbg-video-background' );

		if( $unmute_field == 'on' ) {
			$boolean_mute = 'false';
		} else {
			$boolean_mute = 'true';
		}

		if( $no_loop_field == 'on' ) {
			$boolean_loop = 'false';
		} else {
			$boolean_loop = 'true';
		}

		if( $overlay == 'on' ) {
			$boolean_overlay = 'true';
		} else {
			$boolean_overlay = 'false';
		}

		$overlay_color_value = !empty($overlay_color) ? $overlay_color : '#000';
		$overlay_alpha_value = !empty($overlay_alpha) ? '0.' . $overlay_alpha : '0.3';
		?>

		<?php endif;

	}
}
add_action( 'wp_footer', 'vidbg_initialize_footer' );

/**
 * Shortcode for v1.0.x versions
 *
 * @since 1.0.0
 *
 * @uses shortcode_atts()
 * @uses do_shortcode()
 */
function candide_video_background( $atts , $content = null ) {
	// Attributes
	extract(
		shortcode_atts(
			array(
				'container' 			=> 'body',
				'mp4' 						=> '#',
				'webm' 						=> '#',
				'poster' 					=> '#',
				'muted' 					=> 'true',
				'loop' 						=> 'true',
				'overlay' 				=> 'false',
				'overlay_color' 	=> '#000',
				'overlay_alpha' 	=> '0.3',
			), $atts , 'vidbg'
		)
	);

		/**
		 * Enqueue vidbg conditionally
		 */
		wp_enqueue_script( 'vidbg-video-background' );

		// Put It Together
		ob_start(); ?>
		';

		//Return

		return $outputbefore . do_shortcode($content) . $outputafter;
}
add_shortcode( 'vidbg', 'candide_video_background' );

/**
 * Add getting started page
 *
 * @since 2.1.1
 *
 * @uses add_options_page()
 */
function vidbg_add_gettingstarted() {
	add_options_page(
		'Video Background',
		'Video Background',
		'manage_options',
		'html5-vidbg',
		'vidbg_gettingstarted_page'
	);
}
add_action( 'admin_menu', 'vidbg_add_gettingstarted' );

/**
 * Creates Video Background plugin settings
 *
 * @since 2.5.4
 *
 * @uses register_setting()
 * @uses add_settings_section()
 * @uses add_settings_field()
 */
function vidbg_register_settings() {
	register_setting( 'vidbg_settings', 'vidbg_disable_pro_fields' );

	add_settings_section(
		'vidbg_vidbg_settings_section',
		__( 'Hide Muted Pro Fields', 'video-background' ),
		'vidbg_disable_pro_fields_section_callback',
		'vidbg_settings'
	);

	add_settings_field(
		'vidbg_checkbox_disable_pro_field',
		__( 'Hide Muted Pro Fields', 'video-background' ),
		'vidbg_checkbox_disable_pro_field_render',
		'vidbg_settings',
		'vidbg_vidbg_settings_section'
	);
}
add_action( 'admin_init', 'vidbg_register_settings' );

/**
 * Creats the checkbox callback for Video Background options
 *
 * @since 2.5.4
 *
 * @uses get_option()
 * @uses checked()
 */
function vidbg_checkbox_disable_pro_field_render() {
	$options = get_option( 'vidbg_disable_pro_fields' );

	$output = '';
	$check = '';
	if ( $options ) {
		$check = checked( $options['vidbg_checkbox_disable_pro_field'], 1, false );
	}

	$output .= '<input type="checkbox" name="vidbg_disable_pro_fields[vidbg_checkbox_disable_pro_field]" ' . $check . ' value="1">';

	echo $output;
}

/**
 * Video Background plugin settings section callback
 *
 * @since 2.5.4
 *
 * @uses _e()
 */
function vidbg_disable_pro_fields_section_callback() {
	_e( 'Okay, Okay, some of you don\'t want/need Video Background Pro. I get that. That\'s why you can hide the muted pro fields below :)', 'video-background' );
}

/**
 * Getting started page content
 *
 * @since 2.1.1
 *
 * @uses _e()
 * @uses settings_fields()
 * @uses do_settings_sections()
 * @uses submit_button()
 */
function vidbg_gettingstarted_page() {
	echo '
';
		_e( '
Video Background
', 'video-background' );
		_e( '
Video background makes it easy to add responsive, great looking video backgrounds to any element on your website.
', 'video-background' );
		_e( '
Getting Started
', 'video-background' );
		_e( '
To implement Video Background on your website, please follow the instructions below.', 'video-background' );
		echo '
';
			_e( '
Edit the page or post you would like the video background to appear on.
', 'video-background' );
			_e( '
Below the content editor, you should see a metabox titled Video Background. Enter the values for the required fields and publish/update the page.
', 'video-background' );
			_e( '
Enjoy.
', 'video-background' );
		echo '
';
		_e( '
Alternatively, you can use the shortcode by placing the following code at the bottom of the content editor of the page or post you would like the video background to appear on. Here is how it works:
', 'video-background' );
		echo '
[vidbg container="body" mp4="#" webm="#" poster="#" loop="true" overlay="false" overlay_color="#000" overlay_alpha="0.3" muted="false"]
';
		_e( 'Further Documentation', 'video-background' );
		_e( '
Questions?
', 'video-background' );
		_e( '
If you have any feedback/questions regarding the plugin you can reach me here.', 'video-background' );
		_e( '
Supporting the Plugin
', 'video-background' );
		_e( '
If you like Video Background and want to show your support, consider purchasing the pro version. It comes with plenty of helpful features that make your life easier like:
', 'video-background' );
		echo '
';
			_e( '
YouTube Integration
', 'video-background' );
			_e( '
Visual Composer Integration
', 'video-background' );
			_e( '
Page Builder by SiteOrigin Integration
', 'video-background' );
			_e( '
Frontend Play/Pause Button Option
', 'video-background' );
			_e( '
Frontend Volume Button Option
', 'video-background' );
			_e( '
Overlay Image Textures
', 'video-background' );
			_e( '
Extensive Documentation
', 'video-background' );
			_e( '
Video Tutorials
', 'video-background' );
			_e( '
And Much More!
', 'video-background' );
		echo '
';
		_e( 'Learn More About Video Background Pro', 'video-background' );
		_e( ' Get Updates on Twitter', 'video-background' );
		echo '<form action="options.php" method="post">';
			settings_fields( 'vidbg_settings' );
			do_settings_sections( 'vidbg_settings' );
			submit_button();
		echo '</form>';
	echo '
';
}

/**
 * Add getting started link on plugin page
 *
 * @since 2.1.1
 *
 * @uses __()
 */
function vidbg_gettingstarted_link($links) {
	$gettingstarted_link = __( 'Getting Started', 'video-background' );
	array_unshift($links, $gettingstarted_link);
	return $links;
}
add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'vidbg_gettingstarted_link' );

/**
 * Create function to see if WordPress version is 4.2 or higher
 *
 * @since 2.5.1
 */
function vidbg_is_wp_version( $version = '4.2' ) {
	global $wp_version;

	if ( version_compare( $wp_version, $version, '>=' ) ) {
		return true;
	} else {
		return false;
	}
}

/**
 * If WP version is 4.2 or higher display premium notice message
 */
if( vidbg_is_wp_version() == true ) {
	require_once( plugin_dir_path( __FILE__ )  . '/admin_premium_notice.php' );
}


text:
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/** @fileoverview Unit tests for goog.labs.net.Image. */

goog.module('goog.labs.net.imageTest');
goog.setTestOnly();

const TestCase = goog.require('goog.testing.TestCase');
const googString = goog.require('goog.string');
const netImage = goog.require('goog.labs.net.image');
const recordFunction = goog.require('goog.testing.recordFunction');
const testSuite = goog.require('goog.testing.testSuite');

testSuite({
  setUpPage() {
    TestCase.getActiveTestCase().promiseTimeout = 10000;  // 10s
  },

  testValidImage() {
    const url = 'testdata/cleardot.gif';

    return netImage.load(url).then((value) => {
      assertEquals('IMG', value.tagName);
      assertTrue(googString.endsWith(value.src, url));
    });
  },

  testInvalidImage() {
    const url = 'testdata/invalid.gif';  // This file does not exist.

    return netImage.load(url).then(
        () => {
          fail('Invalid image should not resolve');
        },
        (errResult) => {
          assertNull(errResult);
        });
  },

  testImageFactory() {
    const returnedImage = new Image();
    const factory = () => returnedImage;
    const countedFactory = recordFunction(factory);

    const url = 'testdata/cleardot.gif';

    return netImage.load(url, countedFactory).then((value) => {
      assertEquals(returnedImage, value);
      assertEquals(1, countedFactory.getCallCount());
    });
  },

  testExistingImage() {
    const image = new Image();

    const url = 'testdata/cleardot.gif';

    return netImage.load(url, image).then((value) => {
      assertEquals(image, value);
    });
  },
});


text:
using SolrExpress.Search.Query;

namespace SolrExpress.Search.Parameter
{
    /// <summary>
    /// Facet query parameter
    /// </summary>
    public interface IFacetQueryParameter<TDocument> : IFacetParameter<TDocument>
        where TDocument : Document
    {
        /// <summary>
        /// Name of alias added in query
        /// </summary>
        string AliasName { get; set; }

        /// <summary>
        /// Query used to make facet
        /// </summary>
        SearchQuery<TDocument> Query { get; set; }
    }
}


text:
using Xunit;
using System.Configuration;
using System.DirectoryServices;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Web;
using System.Xaml.Permissions;

namespace System.Xaml.Permissions.Tests
{
    public class XamlLoadPermissionTests
    {
        [Fact]
        public static void XamlLoadPermissionCallMethods()
        {
            XamlAccessLevel accessLevel = XamlAccessLevel.AssemblyAccessTo(Assembly.GetExecutingAssembly().GetName());
            XamlLoadPermission xp = new XamlLoadPermission(accessLevel);
            XamlLoadPermission xp2 = new XamlLoadPermission(PermissionState.Unrestricted);
            XamlLoadPermission xp3 = new XamlLoadPermission(Array.Empty<XamlAccessLevel>());
            bool testbool = xp.IsUnrestricted();
            IPermission ip = xp.Copy();
            IPermission ip2 = xp.Intersect(ip);
            IPermission ip3 = xp.Union(ip);
            testbool = xp.IsSubsetOf(ip);
            testbool = xp.Equals(new object());
            testbool = xp.Includes(accessLevel);
            int hash = xp.GetHashCode();
            SecurityElement se = new SecurityElement("");
            xp.FromXml(se);
            se = xp.ToXml();
        }
    }
}


text:
package me.st28.flexseries.flexcore.message;

import me.st28.flexseries.flexcore.FlexCore;
import me.st28.flexseries.flexcore.logging.LogHelper;
import me.st28.flexseries.flexcore.plugin.module.FlexModule;
import me.st28.flexseries.flexcore.plugin.FlexPlugin;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public final class MessageManager extends FlexModule<FlexCore> {

    private static MessageManager getInstance() {
        return FlexPlugin.getRegisteredModule(MessageManager.class);
    }

    public static MessageProvider getMessageProvider(Class<? extends JavaPlugin> plugin) {
        MessageManager instance = getInstance();
        return !instance.messageProviders.containsKey(plugin) ? instance.invalidMessageProvider : instance.messageProviders.get(plugin);
    }

    public static String getGeneralMessage(JavaPlugin plugin, String path) {
        return getMessageProvider(FlexCore.class).getMessage(plugin, path);
    }

    /*public static String getGeneralMessage(JavaPlugin plugin, String path, Map<String, Object> replacements) {
        return getMessageProvider(FlexCore.class).getMessage(plugin, "general." + path, replacements);
    }*/

    /**
     * Registers a {@link MessageProvider} for a plugin.
     *
     * @param plugin The plugin to register.
     * @return The newly created or existing {@link MessageProvider} for the plugin.
     * @throws IllegalArgumentException Thrown if the plugin does not contain a messages.yml file within the jar.
     */
    public static MessageProvider registerMessageProvider(JavaPlugin plugin) {
        if (plugin.getResource("messages.yml") == null) {
            throw new IllegalArgumentException("Plugin '" + plugin.getName() + "' does not have a default messages.yml file in the jar.");
        }

        MessageManager instance = getInstance();
        Class<? extends JavaPlugin> clazz = plugin.getClass();

        if (instance.messageProviders.containsKey(clazz)) {
            return instance.messageProviders.get(clazz);
        } else {
            MessageProvider provider = new MessageProvider(plugin);
            instance.messageProviders.put(clazz, provider);
            instance.reloadMessageProvider(provider);
            return provider;
        }
    }

    private InvalidMessageProvider invalidMessageProvider;
    private Map<Class<? extends JavaPlugin>, MessageProvider> messageProviders = new HashMap<>();

    public MessageManager(FlexCore plugin) {
        super(plugin, "messages", "Handles customizable messages for plugins.", false);

        isDisableable = false;

        invalidMessageProvider = new InvalidMessageProvider();
    }

    @Override
    public void handleReload() {
        for (MessageProvider provider : messageProviders.values()) {
            reloadMessageProvider(provider);
        }
    }

    private void reloadMessageProvider(MessageProvider provider) {
        try {
            provider.reload();
        } catch (IOException ex) {
            LogHelper.warning(this, "An exception occurred while loading the MessageProvider for: " + provider.plugin.getName());
            ex.printStackTrace();
        }
    }

}


text:
package org.mpisws.p2p.transport.peerreview.statement;

import java.util.Map;

import rice.p2p.commonapi.rawserialization.RawSerializable;

public class IncompleteStatementInfo<Handle, Identifier extends RawSerializable> {
  public boolean finished;
  public Handle sender;
  public long currentTimeout;
  public Statement<Identifier> statement;
  public boolean isMissingCertificate;
  public Identifier missingCertificateID;
  public Map<String, Object> options;

  public IncompleteStatementInfo(boolean finished, Handle source, long currentTimeout,
      Statement<Identifier> statement, boolean isMissingCertificate, Identifier missingCertificateId, Map<String, Object> options) {
    this.finished = finished;
    this.sender = source;
    this.currentTimeout = currentTimeout;
    this.statement = statement;
    this.isMissingCertificate = isMissingCertificate;
    this.missingCertificateID = missingCertificateId;
    this.options = options;
  }

  public boolean isMissingCertificate() {
    return isMissingCertificate;
  }

  public boolean isFinished() {
    return finished;
  }

  public long getCurrentTimeout() {
    return currentTimeout;
  }
}


text:
package com.b2international.snowowl.core.request.suggest;

import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

import org.tartarus.snowball.ext.EnglishStemmer;

import com.b2international.commons.http.ExtendedLocale;
import com.b2international.index.compat.TextConstants;
import com.b2international.snowowl.core.codesystem.CodeSystemRequests;
import com.b2international.snowowl.core.events.util.Promise;
import com.b2international.snowowl.core.identity.User;
import com.b2international.snowowl.core.plugin.Component;
import com.b2international.snowowl.core.request.SearchIndexResourceRequest;
import com.b2international.snowowl.core.request.search.TermFilter;
import com.b2international.snowowl.eventbus.IEventBus;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;

/**
 * @since 8.5
 */
@Component
@JsonTypeName("term")
public final class TermConceptSuggester implements ConceptSuggester {

	// Split terms at delimiter or whitespace separators
	private static final Splitter TOKEN_SPLITTER = Splitter.on(TextConstants.WHITESPACE_OR_DELIMITER_MATCHER)
			.trimResults()
			.omitEmptyStrings();

	/**
	 * The number of most frequent tokens (words) to consider from the selected like text corpus. Default value is 9.
	 */
	@JsonProperty
	private Integer topTokenCount = 9;

	/**
	 * The number of most frequent tokens (topTokenCount) to match in order to be accepted as a suggestion. Default value is 3.
	 */
	@JsonProperty
	private Integer minOccurenceCount = 3;

	/**
	 * The minimum length for a token to be considered as potential top token. Default value is 0, accepting all token lengths.
	 */
	@JsonProperty
	private int minTokenLength = 0;

	/**
	 * Whether to ignore any stopwords in the selected text corpus or not. Default value is true.
	 */
	@JsonProperty
	private boolean ignoreStopwords = true;

	/**
	 * Whether to perform english word stemming on the tokens or not. Default value is false.
	 */
	@JsonProperty
	private boolean stemming = false;

	/**
	 * Whether to allow top tokens to fuzzy match among candidates. Default value is false.
	 */
	@JsonProperty
	private boolean fuzzy = false;

	@Override
	public Promise<Suggestions> suggest(ConceptSuggestionContext context, int limit, String display, List<ExtendedLocale> locales) {

		// Gather tokens
		final Multiset<String> tokenOccurrences = HashMultiset.create();
		final EnglishStemmer stemmer = new EnglishStemmer();

		context.streamLikes()
			.map(term -> term.toLowerCase(Locale.US))
			.flatMap(lowerCaseTerm -> TOKEN_SPLITTER.splitToList(lowerCaseTerm).stream())
			.filter(token -> token.length() >= minTokenLength) // skip short tokens
			.map(token -> stemToken(stemmer, token))
			.forEach(tokenOccurrences::add);

		final List<String> topTokens = Multisets.copyHighestCountFirst(tokenOccurrences)
			.elementSet()
			.stream()
			.limit(topTokenCount)
			.collect(Collectors.toList());

		// if there are no tokens to search for then shortcut here
		if (topTokens.isEmpty()) {
			return Promise.immediate(new Suggestions(topTokens, limit, 0));
		}

		final TermFilter termFilter = TermFilter.match()
				.term(String.join(" ", topTokens))
				.minShouldMatch(Math.min(minOccurenceCount, topTokens.size()))
				.ignoreStopwords(ignoreStopwords)
				.fuzziness(fuzzy ? "AUTO" : null)
				// TODO make fuzziness options configurable in term suggester settings
				.build();

		// get the ECL query of the from code system
		final String inclusionQuery = context.getInclusionQueries();
		// get the dynamically computed exclusion query set
		final Collection<String> exclusionQueries = context.exclusionQuery(context.from().getResourceUri());

		return CodeSystemRequests.prepareSearchConcepts()
				// always return active concepts only
				// TODO support in suggest API settings?
				.filterByActive(true)
				// configure from, resource and optional ECL query
				.filterByCodeSystemUri(context.from().getResourceUri())
				.filterByQuery(inclusionQuery)
				// make sure we won't suggest the same concepts as defined in like and unlike arrays (for the same code system)
				.filterByExclusions(exclusionQueries.isEmpty() ? null : exclusionQueries)
				// configure lexical match as basis of suggestion
				.filterByTerm(termFilter)
				// configure display, limit and locales
				.setPreferredDisplay(display)
				.setLimit(limit)
				.setLocales(locales)
				// always order by score
				.sortBy(SearchIndexResourceRequest.SCORE)
				.build()
				.async(Map.of(User.class, context.service(User.class)))
				.execute(context.service(IEventBus.class))
				.then(concepts -> {
					return new Suggestions(topTokens, concepts.getItems(), concepts.getSearchAfter(), limit, concepts.getTotal());
				});
	}

	private String stemToken(EnglishStemmer stemmer, String token) {
		if (stemming) {
			stemmer.setCurrent(token);
			stemmer.stem();
			return stemmer.getCurrent();
		} else {
			return token;
		}
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Quiz.Data.Context.EntityFramework;
using Quiz.Domain;

namespace Quiz.Data.Infrastructure.Repositories
{
    public class CategoryRepository : RepositoryBase<Category>
    {
        public CategoryRepository(QuizDbContext context) : base(context) { }

        public IEnumerable<Category> GetCategories(string sortOrder, string searchString)
        {
            var categories = Get();
            if (!String.IsNullOrEmpty(searchString))
            {
                categories = categories.Where(s => s.Name.Contains(searchString));
            }
            switch (sortOrder)
            {
                case "name_desc":
                    categories = categories.OrderByDescending(s => s.Name);
                    break;
                case "date":
                    categories = categories.OrderBy(s => s.DateCreated);
                    break;
                case "date_desc":
                    categories = categories.OrderByDescending(s => s.DateCreated);
                    break;
                default:  // Name ascending
                    categories = categories.OrderBy(s => s.Name);
                    break;
            }
            return categories;
        }
    }
}


text:
require 'action_view/helpers'

module FoundationRailsHelperMod
  class FormBuilder < ActionView::Helpers::FormBuilder
    include ActionView::Helpers::TagHelper

    %w(file_field email_field text_field text_area telephone_field phone_field url_field number_field).each do |method_name|
      define_method(method_name) do |*args|
        attribute = args[0]
        options   = args[1] || {}
        field(attribute, options) do |options|
          super(attribute, options)
        end
      end
    end

    def check_box(attribute, options = {})
      html = custom_label(attribute, options[:label], options[:label_options]) do
        options.delete(:label)
        options.delete(:label_options)
        super(attribute, options)
      end

      html += content_tag(:p, options[:description], :class => 'description') if options[:description].present?
      html += error_and_hint(attribute, options)
    end

    def radio_button(attribute, tag_value, options = {})
      options[:for] ||= "#{object.class.to_s.downcase}_#{attribute}_#{tag_value}"
      l = label(attribute, options)
      c = super(attribute, tag_value, options)
      l.gsub(/(for=\"\w*\"\>)/, "\\1#{c} ").html_safe
    end

    def password_field(attribute, options = {})
      field attribute, options do |options|
        super(attribute, options.merge(:autocomplete => :off))
      end
    end

    def datetime_select(attribute, options = {})
      field attribute, options do |options|
        super(attribute, {}, options.merge(:autocomplete => :off))
      end
    end

    def date_select(attribute, options = {}, html_options = {})
      field attribute, html_options do |html_options|
        super(attribute, options, html_options.merge(:autocomplete => :off))
      end
    end

    def time_zone_select(attribute, options = {})
      field attribute, options do |options|
        super(attribute, {}, options.merge(:autocomplete => :off))
      end
    end

    def select(attribute, choices, options = {}, html_options = {})
      field attribute, options do |options|
        html_options[:autocomplete] ||= :off
        super(attribute, choices, options, html_options)
      end
    end

    def autocomplete(attribute, url, options = {})
      field attribute, options do |options|
        autocomplete_field(attribute, url, options.merge(:update_elements => options[:update_elements],
                                                         :min_length => 0,
                                                         :value => object.send(attribute)))
      end
    end

    def submit(value=nil, options={})
      options[:class] ||= "small radius success button"
      super(value, options)
    end

  private
    def has_error?(attribute)
      object && !object.errors[attribute].blank?
    end

    def error_for(attribute, options = {})
      class_name = "error"
      class_name += " #{options[:class]}" if options[:class]
      content_tag(:small, object.errors[attribute].join(', '), :class => class_name) if has_error?(attribute)
    end

    def custom_label(attribute, text, options, &block)
      if text == false
        text = ""
      elsif text.nil?
        text = object.class.human_attribute_name(attribute)
      end
      text = block.call.html_safe + text if block_given?
      options ||= {}
      options[:class] ||= ""
      options[:class] += " error" if has_error?(attribute)
      label(attribute, text, options)
    end

    def error_and_hint(attribute, options = {})
      html = ""
      html += content_tag(:span, options[:hint], :class => :hint) if options[:hint]
      html += error_for(attribute, options) || ""
      html.html_safe
    end

    def field(attribute, options, &block)
      html = ''.html_safe
      html = custom_label(attribute, options[:label], options[:label_options]) if false != options[:label]
      options[:class] ||= "medium"
      options[:class] = "#{options[:class]} input-text"
      options[:class] += " error" if has_error?(attribute)
      options.delete(:label)
      options.delete(:label_options)
      html += '
'.html_safe
      html += yield(options)
      html += content_tag(:p, options[:description], :class => 'description') if options[:description].present?
      html += error_and_hint(attribute, options)
      html += '
'.html_safe
    end
  end
end


text:
The Back-to-Back User Agent (B2BUA) is a Session Initiation Protocol (SIP)
call-controlling component. Unlike a SIP proxy server, which only maintains a
transaction state, the B2BUA maintains the complete call state and participates
in all call requests. For this reason, the B2BUA can perform a number of
functions that are not possible to implement using the SIP proxy, such as
accurate call accounting, pre-paid rating & billing, failover call routing, and
so on.

The B2BUA is involved in call establishment, management, and termination.

## Architecture

B2BUA High Level Architecture

The B2BUA consists of the following three main logical components:

- Answering SIP User Agent
- Call Control Logic
- Originating SIP User Agent

The following diagram illustrates the B2BUA architecture and the primary
components.

![Figure 1 — B2BUA High Level Architecture.png](Fig1_B2BUA_Architecture.png)

The components interact with each other using abstract events. Each User Agent
(UA) represents a state machine, which receives SIP messages from the endpoint
and converts them into events based on the type of message and the agent's own
current state. The Call Control Logic acts as a go-between, passing events
between the UAs. Depending on its own current state and the states of the UAs,
the Call Control Logic could drop some events, convert event type in transition,
or inject additional events. It can also remove one of the UAs and replace it
with another one on different stages of the call, which allows implementing
such features as fail over call routing, controlled call transfer and so on.

Since the number of parameters passed by each event is well defined the B2BUA
can isolate call legs from each other, allowing only controlled amount of
information to pass through.

This architecture allows implementing different functionality by replacing the
Call Control Logic, which consists of a small fraction of the B2BUA code. Two
such implementations are described in the next section.

## Typical Call Process

A call is initiated when the Answering SIP UA receives an incoming INVITE
message from the Originating SIP Endpoint. After receiving this message, the
Answering SIP UA generates a Try event (2) and passes it to the Call Control
Logic, as illustrated in the following diagram.

![Figure 2 — Try Event (2) passed to Call Control Logic.png](Fig2_Try_Event.png)

The Call Control Logic receives the Try event, performs authentication and
authorization, creates the Originating SIP UA, modifies the Try event to
accommodate for any parameter translation logic, and passes it along with the
routing information to the Originating SIP UA (3). The Originating SIP UA
receives the Try event and generates INVITE message (4) as shown in the
following diagram.

![Figure 3 — Originating SIP UA generating INVITE Message (4).png](Fig3_Orig_SIP_UA_generating_INVITE_message_4.png)

After the Answering SIP endpoint receives the INVITE message, it starts ringing
and sends back an 18x SIP provisional response (5). The Originating SIP UA
receives the message, generates a Ringing event, and passes it to the Call
Control Logic (6). The Call Control Logic receives the Ringing event and
passes it to the Answering SIP UA (7), and in response, the Answering SIP UA
sends an 18x SIP provisional response to the Originating SIP endpoint (8).

![Figure 4 — Answering SIP UA sending response to Originating SIP endpoint.png](Fig4_Answering_SIP_UA_sending_response_to_originating_end_point.png)

When the user at the Answering SIP endpoint picks up the phone, the endpoint
generates a 200 OK SIP response and sends it back to the Originating SIP UA
(9). The UA generates a Connect event and passes it to the Call Control Logic
(10), following which the Call Control Logic hands the event over to the
Answering SIP UA (11). The UA sends a 200 OK message to the Originating SIP
endpoint (12). At this point, the session is established and endpoints start
exchanging RTP media (13).

![Figure 5 — Endpoints receiving RTP Media.png](Fig5_BYE_message_sent_to_originating_SIP_endpoint.png)

When either party hangs up, the respective SIP endpoint generates a SIP BYE
message and sends the message to the associated SIP UA (14). The UA generates
a Disconnect event, which propagates to the other side of the B2BUA via the
Call Control Logic (15), (16) and results in a BYE message, which is sent to
the other endpoint (17).

![Figure 6 — BYE message sent to Originating SIP endpoint.png](Fig5_Endpoints_receiving_RTP_media.png)

The session ends.

## B2BUA Implementations

### Simple B2BUA

#### Description

Simple B2BUA represents very basic SIP back to back user agent. It accepts
incoming SIP calls on the specified IP address and for each incoming call leg
establishes outgoing call leg to the pre-defined IP address. It does not
perform authentication or authorization for incoming calls and passes all
main parameters (CLD, CLI, SDP body, Caller Name, Callee Name) from incoming
call leg to outgoing call leg verbatim. The main purpose of this B2BUA is to
serve as an example for building more complex call control logic.

#### Depends on:
- Python 2.4 or later
- [Twisted](https://twistedmatrix.com/) framework event framework

#### Synopsis

To invoke the B2BUA use the following command:

```python b2bua_simple.py [-f] [-L logfile] [-l local_ip] [-p local_port] [-n
remote_ip]```

Options enclosed in square brackets are optional.

The following options are available:

- `-f` run in the foreground (by default B2BUA becomes daemon after
  invocation);
- `-L logfile` path to the file into which B2BUA should redirect its stdout and
  stderr (by default, B2BUA uses /var/log/b2bua.log)
- `-l local_ip` specific IP address on which B2BUA will listen
- `-p local_port` specific UDP port number for listening for incoming SIP
  messages at (by default the B2BUA uses port 5060);
- `-n remote_ip` IP address of the target for the outgoing call legs.

For example, the following command will instruct B2BUA to listen for incoming
SIP calls on IP address 192.168.0.15 and forward all outgoing calls to SIP
endpoint with IP address of 192.168.1.25:

`python b2bua_simple.py -l 192.168.0.15 -n 192.168.1.25`

There are several environment variables that can be used to control how B2BUA
logs its SIP-related activities:

- `SIPLOG_BEND` specifies which method of reporting to use. Available methods
  are logfile and stderr (default);
- `SIPLOG_LVL` specifies logging level, that is how detailed the log file
  should be. The following levels are available:
  - `DBUG`
  - `INFO` (default)
  - `WARN`
  - `ERR`
  - `CRIT` (from the most verbose to the least verbose);
- `SIPLOG_LOGFILE_FILE` when logfile method is selected allows specifying
  location of the logfile (`/var/log/sip.log` by default).

### RADIUS B2BUA

#### Description

RADIUS B2BUA represents advanced SIP back to back user agent designed to be
used with [RFC2865](http://tools.ietf.org/html/rfc2865) /
[RFC2866](http://tools.ietf.org/html/rfc2866) compliant RADIUS billing engines.
It accepts incoming SIP calls on the specified IP address, performs
authentication and authorization using RADIUS protocol and if it has been
successful establishes outgoing call leg to either pre-defined IP address or
address returned by the RADIUS server in a custom attribute. It also allows
RADIUS server to alter number of parameters in the outgoing call leg (CLD, CLI,
Caller Name, Callee Name). Once the call has been completed or has been failed
it can send RADIUS accounting.

The B2BUA uses RADIUS AAA attributes as per [Cisco CDR Accounting for Cisco IOS
Voice
Gateways](http://www.cisco.com/c/en/us/td/docs/ios/voice/cdr/developer/guide/cdrdev.html),
which provides compatibility with many billing platforms. The authentication
could be performed either using Cisco-compatible Remote IP method, or by using
secure digest method proposed in RADIUS Extension for Digest Authentication
IEFT draft.

#### Depends on:
- Python 2.4 or later
- [Twisted](https://twistedmatrix.com/) framework event framework
- radiusclient-ng 0.5.0 or later (Note, see [#12](https://github.com/sippy/b2bua/issues/12)
)

#### Synopsis

```python b2bua_radius.py [-fDu] [-l local_ip] [-p local_port] [-P pidfile] [-L
logfile] [-s static_route] [-a ip1[,..[,ipN]]] [-k 0-3] [-m max_ctime] [-A 0-2]
[-r rtp_proxy_contact1] [-r rtp_proxy_contact2] ... [-r rtp_proxy_contactN]```

Options enclosed in square brackets are optional. The following options are
available:

- `-f` run in the foreground (by default, B2BUA becomes the daemon after
  invocation)
- `-D` do not use secure digest authentication
- `-u` disable (do not send) RADIUS Authentication/Authorization. If this flag
  is specified, the B2BUA does not send any Authentication/Authorization
  requests to the RADIUS server. Unless the -a option is also specified, the
  B2BUA in this mode will accept incoming sessions from any IP address without
  any limitations. This flag depends on the -s flag, since in this case, B2BUA
  is not able to get routing information from the RADIUS replies.
- `-A 0-2` RADIUS accounting level. Argument in the range 0-2 specifies the
  level as follows:
  - 0 disable (do not send) RADIUS accounting
  - 1 enable sending Stop RADIUS accounting records (this mode is default)
  - 2 enable sending both Start and Stop RADIUS accounting records
- `-l local_ip` specific IP address to listen for incoming SIP messages
- `-p local_port` specific UDP port number to listen for incoming SIP messages
  (by default, B2BUA uses port 5060)
- `-P pidfile` path to the pidfile, that is, the file that contains the PID of
  the B2BUA (by default, B2BUA uses /var/run/b2bua.pid)
- `-L logfile` path to the file into which B2BUA should redirect its stdout and
  stderr (by default, B2BUA uses /var/log/b2bua.log)
- `-s static_route` instead of expecting RADIUS returning routing information
  in reply, use static_route as the single "static" route. Note See the section
  Call Routing for the exact format of the static_route parameter
- `-a ip1[,..[,ipN]]` accept incoming calls only from the IP addresses
  specified in the ip1[,..[,ipN]] list
- `-k 0-3` enable keep-alives, or re-INVITE messages, which are periodically
  sent to both parties participating in a call in order to detect if either
  party goes offline. Argument in the range 0-3 specifies mode:
  - 0 keep-alives disabled (default)
  - 1 enabled for answering call leg
  - 2 enabled for originate call leg
  - 3 enabled for both call legs
- `-m max_ctime` limit maximum duration of all calls to max_ctime seconds
- `-r rtp_proxy_contact` force media for all calls to go through RTP Proxy
  media relay specified by the rtp_proxy_contact parameter. The
  rtp_proxy_contact can either be the path to the local unix-domain socket at
  which the RTP Proxy listens for commands, or the address of the remote RTP
  Proxy in the format udp:hostname[:port] If the port is not specified, a
  default port value (22222) is used. It is possible to specify the -r option
  multiple times, in which case, B2BUA will select a particular RTP Proxy
  randomly for each call, effectively distributing the load evenly among all of
  them. In addition, the B2BUA periodically tests for and keeps track of the
  accessibility of each RTP Proxy and avoids sending new calls to ones that are
  not accessible at the moment.
- `-F pt1[,...[,ptN]]` list of numeric RTP payload types
  ([RFC3551](https://www.ietf.org/rfc/rfc3551.txt))that should only be allowed
  in the SDP offer of INVITE that the B2BUA sends to the egress call leg.
  Essentially this means that the B2BUA won't pass any payload types not in
  this list preventing answering party from using them. In the case when
  ingress INVITE doesn't have any payload types from this list in the SDP offer
  the request would be rejected with `488 Not Acceptable Here` response
- `-R radconf_path` path to `radiusclient.conf`
- `-h header1[,...[,headerN]]` list of SIP header field names that the B2BUA
  should pass verbatim from ingress to egress call leg
- `-c cmd_path` path to the control socket.

## Call Routing

The B2BUA routes incoming calls based on dynamic information returned by the
RADIUS server with each authentication accept response, or alternatively, by
statically using information provided in the command line. In the former case,
it is expected that any positive response should contain one or more routing
entries placed into the h323-ivr-in Cisco VSA attribute. The format of the
routing entries is as follows:

`h323-ivr-in=Routing:[[cld]@]hostname[:port][;credit-time=seconds][;expires=seconds][;auth=username:password][;cli=cli][;ash=ash][;np_expires=seconds]`

Options in square brackets are optional parameters. If more than a single routing
entry is present, routing entries will be tried one by one until either there
are no more routes left or the call is successfully connected. The following
parameters are available:

- `cld` CLD to be used for the outgoing call
- `hostname` IP address or hostname of the SIP peer to which the call must be
  sent
- `port` UDP port at which the SIP peer to which the call must be sent
  accepts SIP signaling messages
- `credit-time` maximum session time to be allowed before the call is
  forcefully disconnected by the B2BUA
- `expires` maximum time to wait until the call sent to a particular route is
  connected. If this time has been exceeded, the B2BUA proceeds to processing
  the next route if one or more routes is available, or reports a failure
  condition to the caller if no routes are available.
- `auth` username/password pair for SIP authentication with a remote SIP peer
  at hostname
- `cli` CLI to be used for the outgoing call
- `ash` insert arbitrary SIP header field into INVITE of the originate call
  leg. The parameter value should be a valid SIP header field in the format
  Name:Value, transformed using URL quoting rules set forth in
  [RFC1738](https://www.ietf.org/rfc/rfc1738.txt).
- `np_expires` maximum time to wait until non-100 provisional response on the
  call sent to a particular route is received or the call is connected
  (whichever happens first). If this time has been exceeded, the B2BUA proceeds
  to processing the next route if one or more routes is available, or reports a
  failure condition to the caller if not available.

The following is an example of a routing string in the RADIUS attribute:

`h323-ivr-in =
'Routing:200110508667@b2bua.org;cli=16046288900;rid=-1;expires=30;np_expires=5;ash=Name%3AValue'`

The same as the static route in the command line would be:

`b2bua_radius.py ... -s
'200110508667@b2bua.org;cli=16046288900;rid=-1;expires=30;np_expires=5;ash=Name%3AValue'
...`

## FAQ

### General

#### Why using Python? Isn't it slow?

For certain class of application Python provides adequate performance. Being
100% text based protocol, SIP appears to be one of such applications. Also,
when telecommunication applications are considered some other factors, such as
reliability and resilence, have much more importance than pure performance.
With the performance numbers outlined above (150-200 calls/second) one server
running Sippy B2BUA can handle tenth of millions billable minites per month.
Any network that operates with such vast amount of traffic has no choice but
become distributed to grow further, which limits usefullness of using unsafe
languages such as C or C++ to improve performance of a single B2BUA instance
beyond that point.

#### Can the Sippy B2BUA determine if one of the peer in a session gone without a BYE message (eg. disconnected the network interface) and then send a BYE message to the other peer?

Yes. There are two methods for determining that the one of the parties is gone:
the first is by sending periodical re-INVITE to both parties (so-called SIP
keep-alives), and another one is by monitoring state of the RTP session in the
proxy. The first one is already supported by the B2BUA.

## Installation and Configuration

### How to install and configure RADIUS client?

For radiusclient-ng you should do the following:

Install radiusclent-ng from source ``` ~# tar xvfz radiusclient-ng-X.Y.Z.tar.gz
~# cd radiusclient-ng-X.Y.Z ~# ./configure ~# make ~# make install ```

Edit /usr/local/etc/radiusclient-ng/radiusclient.conf and set address of
authentication and accounting servers
```
authserver      homero.lucio01.net
acctserver      homero.lucio01.net
```

Edit /usr/local/etc/radiusclient-ng/servers and add shared secret for each
server the client comunicates with.

`homero.lucio01.net                testing123`

Include dictionary included in sippy b2bua dist into radiusclient-ng by copying
dictionary file from Sippy distribution into /usr/local/etc/radiusclient-ng.

### How to install and configure RADIUS server?

There are many RADIUS servers, both open source and commercial ones. You should
refer to documentation of the selected server software on how to install and
configure it. For a good GPL RADIUS server you can check FreeRADIUS.

ImportError: No module named twisted.internet when trying to run B2BUA

As it is mentioned above, the B2BUA requires Twisted framework version 2.4 or
later to run.

## Troubleshooting

The B2BUA responds with 403 Auth Failed to all incoming calls, what's wrong?

There are two possible reasons for this negative response:

- RADIUS server rejects authentication request. In this case you should check
  the RADIUS server logs to find a problem.
- RADIUS client is not configured properly. This case can be identified by the
  following message in the B2BUA log: `07 Jan
  19:51:55/1231244226691@172.18.1.197/b2bua: Error sending AAA request (delay
  is 0.003)`

You should check your system log, usually /var/log/messages, to see detailed
error(s) generated by the RADIUS client in this case.