text:
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace AzXmpp.Transport.Sockets
{
    /// <summary>
    /// Represents a socket stream.
    /// </summary>
    internal sealed class SocketStream : Stream
    {
        public static readonly Task Completed = Task.FromResult<object>(null);

        /// <summary>
        /// Gets a value indicating whether the current stream supports reading.
        /// </summary>
        /// <returns>true if the stream supports reading; otherwise, false.</returns>
        public override bool CanRead
        {
            get { return true; }
        }

        /// <summary>
        /// Gets a value indicating whether the current stream supports seeking.
        /// </summary>
        /// <returns>true if the stream supports seeking; otherwise, false.</returns>
        public override bool CanSeek
        {
            get { return false; }
        }

        /// <summary>
        /// Gets a value indicating whether the current stream supports writing.
        /// </summary>
        /// <returns>true if the stream supports writing; otherwise, false.</returns>
        public override bool CanWrite
        {
            get { return true; }
        }

        /// <summary>
        /// Gets the length in bytes of the stream.
        /// </summary>
        /// <returns>A long value representing the length of the stream in bytes.</returns>
        /// <exception cref="System.NotSupportedException">Seeking is not supported on <see cref="SocketStream"/>.</exception>
        public override long Length
        {
            get { throw new NotSupportedException(Properties.Resources.InvalidOperation_SeekingNotSupported); }
        }

        /// <summary>
        /// When overridden in a derived class, gets or sets the position within the current stream.
        /// </summary>
        /// <returns>The current position within the stream.</returns>
        /// <exception cref="System.NotSupportedException">Seeking is not supported on <see cref="SocketStream"/>.</exception>
        public override long Position
        {
            get { throw new NotSupportedException(Properties.Resources.InvalidOperation_SeekingNotSupported); }
            set { throw new NotSupportedException(Properties.Resources.InvalidOperation_SeekingNotSupported); }
        }

        /// <summary>
        /// Gets a value that determines whether the current stream can time out.
        /// </summary>
        /// <returns>A value that determines whether the current stream can time out.</returns>
        public override bool CanTimeout
        {
            get { return true; }
        }

        /// <summary>
        /// Gets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out.
        /// </summary>
        /// <returns>A value, in miliseconds, that determines how long the stream will attempt to read before timing out.</returns>
        public override int ReadTimeout
        {
            get { return _socket.ReceiveTimeout; }
            set { _socket.ReceiveTimeout = value; }
        }

        /// <summary>
        /// Gets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out.
        /// </summary>
        /// <returns>A value, in miliseconds, that determines how long the stream will attempt to write before timing out.</returns>
        public override int WriteTimeout
        {
            get { return _socket.SendTimeout; }
            set { _socket.SendTimeout = value; }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is disposed.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is disposed; otherwise, <c>false</c>.
        /// </value>
        public bool IsDisposed
        {
            get { return _state != 0; }
        }

        /// <summary>
        /// Gets the socket.
        /// </summary>
        /// <value>
        /// The socket.
        /// </value>
        public ISocket Socket
        {
            get { return _socket; }
        }

        private readonly ISocket _socket;
        private volatile int _state;

        /// <summary>
        /// Initializes a new instance of the <see cref="SocketStream"/> class.
        /// </summary>
        public SocketStream(ISocket socket)
        {
            if (socket == null) throw new ArgumentNullException("socket");
            _socket = socket;
        }

        /// <summary>
        /// Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.
        /// </summary>
        /// <param name="buffer">The buffer to write the data into.</param>
        /// <param name="offset">The byte offset in <paramref name="buffer" /> at which to begin writing data from the stream.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="P:System.Threading.CancellationToken.None" />.</param>
        /// <returns>
        /// A task that represents the asynchronous read operation. The value of the <see name="Task{int}.Result" /> parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached.
        /// </returns>
        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            return DataSocketAsyncEventArgs.CheckOut().ReadAsync(_socket, buffer, offset, count, cancellationToken);
        }

        /// <summary>
        /// Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.
        /// </summary>
        /// <param name="buffer">The buffer to write data from.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> from which to begin copying bytes to the stream.</param>
        /// <param name="count">The maximum number of bytes to write.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="P:System.Threading.CancellationToken.None" />.</param>
        /// <returns>
        /// A task that represents the asynchronous write operation.
        /// </returns>
        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            return DataSocketAsyncEventArgs.CheckOut().WriteAsync(_socket, buffer, offset, count, cancellationToken);
        }

        /// <summary>
        /// Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.
        /// </summary>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="P:System.Threading.CancellationToken.None" />.</param>
        /// <returns>
        /// A task that represents the asynchronous flush operation.
        /// </returns>
        public override Task FlushAsync(CancellationToken cancellationToken)
        {
            return Completed;
        }

        #region Simple Wrappers
        /// <summary>
        /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
        /// </summary>
        public override void Flush()
        {

        }

        /// <summary>
        /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset" /> and (<paramref name="offset" /> + <paramref name="count" /> - 1) replaced by the bytes read from the current source.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin storing the data read from the current stream.</param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <returns>
        /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
        /// </returns>
        public override int Read(byte[] buffer, int offset, int count)
        {
            return ReadAsync(buffer, offset, count).Result;
        }

        /// <summary>
        /// Begins an asynchronous read operation. (Consider using <see cref="M:System.IO.Stream.ReadAsync(System.Byte[],System.Int32,System.Int32)" /> instead; see the Remarks section.)
        /// </summary>
        /// <param name="buffer">The buffer to read the data into.</param>
        /// <param name="offset">The byte offset in <paramref name="buffer" /> at which to begin writing data read from the stream.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <param name="callback">An optional asynchronous callback, to be called when the read is complete.</param>
        /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param>
        /// <returns>
        /// An <see cref="T:System.IAsyncResult" /> that represents the asynchronous read, which could still be pending.
        /// </returns>
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            return ReadAsync(buffer, offset, count).AsApm(callback, state);
        }

        /// <summary>
        /// Waits for the pending asynchronous read to complete. (Consider using <see cref="M:System.IO.Stream.ReadAsync(System.Byte[],System.Int32,System.Int32)" /> instead; see the Remarks section.)
        /// </summary>
        /// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param>
        /// <returns>
        /// The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams return zero (0) only at the end of the stream, otherwise, they should block until at least one byte is available.
        /// </returns>
        public override int EndRead(IAsyncResult asyncResult)
        {
            return ((Task<int>)asyncResult).Result;
        }

        /// <summary>
        /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
        /// </summary>
        /// <param name="buffer">An array of bytes. This method copies <paramref name="count" /> bytes from <paramref name="buffer" /> to the current stream.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin copying bytes to the current stream.</param>
        /// <param name="count">The number of bytes to be written to the current stream.</param>
        public override void Write(byte[] buffer, int offset, int count)
        {
            WriteAsync(buffer, offset, count).Wait();
        }

        /// <summary>
        /// Begins an asynchronous write operation. (Consider using <see cref="M:System.IO.Stream.WriteAsync(System.Byte[],System.Int32,System.Int32)" /> instead; see the Remarks section.)
        /// </summary>
        /// <param name="buffer">The buffer to write data from.</param>
        /// <param name="offset">The byte offset in <paramref name="buffer" /> from which to begin writing.</param>
        /// <param name="count">The maximum number of bytes to write.</param>
        /// <param name="callback">An optional asynchronous callback, to be called when the write is complete.</param>
        /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
        /// <returns>
        /// An IAsyncResult that represents the asynchronous write, which could still be pending.
        /// </returns>
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            return WriteAsync(buffer, offset, count).AsApm(callback, state);
        }

        /// <summary>
        /// Ends an asynchronous write operation. (Consider using <see cref="M:System.IO.Stream.WriteAsync(System.Byte[],System.Int32,System.Int32)" /> instead; see the Remarks section.)
        /// </summary>
        /// <param name="asyncResult">A reference to the outstanding asynchronous I/O request.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">asyncResult</exception>
        public override void EndWrite(IAsyncResult asyncResult)
        {
            ((Task)asyncResult).Wait();
        }

        /// <summary>
        /// When overridden in a derived class, sets the position within the current stream.
        /// </summary>
        /// <param name="offset">A byte offset relative to the <paramref name="origin" /> parameter.</param>
        /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin" /> indicating the reference point used to obtain the new position.</param>
        /// <returns>
        /// The new position within the current stream.
        /// </returns>
        /// <exception cref="System.NotSupportedException">Seeking is not supported on <see cref="SocketStream"/>.</exception>
        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException(Properties.Resources.InvalidOperation_SeekingNotSupported);
        }

        /// <summary>
        /// When overridden in a derived class, sets the length of the current stream.
        /// </summary>
        /// <param name="value">The desired length of the current stream in bytes.</param>
        /// <exception cref="System.NotSupportedException">Seeking is not supported on <see cref="SocketStream"/>.</exception>
        public override void SetLength(long value)
        {
            throw new NotSupportedException(Properties.Resources.InvalidOperation_SeekingNotSupported);
        }

        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="T:System.IO.Stream" /> and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ingoring termination from the remote party.")]
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (Interlocked.Exchange(ref _state, 1) == 0)
                {
                    try
                    {
                        _socket.Shutdown(SocketShutdown.Both);
                    }
                    catch { }
                }
                if (Interlocked.Exchange(ref _state, 2) == 1)
                {
                    try
                    {
                        _socket.Close(100);
                    }
                    catch { }
                }
                if (Interlocked.Exchange(ref _state, 3) == 2)
                {
                    try
                    {
                        _socket.Dispose();
                    }
                    catch { }
                }
            }
            base.Dispose(disposing);
        }
        #endregion
    }
}


text:
<?php
namespace Jacoz\ItunesApi\Exceptions;

class AlbumNotFoundException extends ItunesGenericException
{
}

redpajama_set_name: RedPajamaGithub


text:
package org.opensingular.form.validation;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.opensingular.form.SDictionary;
import org.opensingular.form.type.core.SIString;
import org.opensingular.form.type.core.STypeString;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

public class InstanceValidatorExampleTest {

    private SIString sistring;
    private InstanceValidator<SIString> identificadorValidator;

    @Before
    public void setUp() throws Exception {
        sistring = SDictionary.create().newInstance(STypeString.class);
        identificadorValidator = (stringInstanceValidatable) -> {
            if (!stringInstanceValidatable.getInstance().matches("^[a-z][\\dA-Za-z]+$")) {
                stringInstanceValidatable.error("Não é um identificador valido");
            }
        };
    }

    @Test
    public void verificarSeNaoExisteErros1() throws Exception {
        verify(preencherValorEValidar("nomeProprio123"), never()).error(anyString());
    }

    @Test
    public void verificarSeNaoExisteErros2() throws Exception {
        verify(preencherValorEValidar("nomeProprio"), never()).error(anyString());
    }

    @Test
    public void verificarSeExisteErros1() throws Exception {
        verify(preencherValorEValidar("123nomeProprio")).error(anyString());
    }

    @Test
    public void verificarSeExisteErros2() throws Exception {
        verify(preencherValorEValidar("#nomeProprio")).error(anyString());
    }

    private InstanceValidatable<SIString> preencherValorEValidar(String nomeProprio123) {
        InstanceValidatable<SIString> instanceValidatable = Mockito.mock(InstanceValidatable.class);
        Mockito.when(instanceValidatable.getInstance()).thenReturn(sistring);
        sistring.setValue(nomeProprio123);
        identificadorValidator.validate(instanceValidatable);
        return instanceValidatable;
    }

}


text:
from commitizen import out
from commitizen.config import BaseConfig
from commitizen.cz import registry

class ListCz:
    """List currently installed rules."""

    def __init__(self, config: BaseConfig, *args):
        self.config: BaseConfig = config

    def __call__(self):
        out.write("\n".join(registry.keys()))


text:
{% extends "base.html" %}
{% set page_title = _('Your profile') %}

{% block content %}
{% from 'auth/macros.html' import subnav with context%}
{{ subnav('profile') }}

{{ _("Social profiles") }}

{{ _("You are logged in as %(user)s!", user = user.username) }}!

{{ _("Associate to this profile: ") }}

{% from 'auth/macros.html' import login_button with context%}

{{ _("For your convenience, add new social services to your account")}}

{% for name in backends.not_associated %}
{{ login_button(provider=name) }}
{% else %}

{{ _("Wee! You connected all available social services!") }}

{% endfor %}

{{ _("Associated: ") }}

{{ _("If you want to disconnect any service from the list then click item from the list") }}

{% from 'auth/macros.html' import logout_button with context%}

{% for assoc in backends.associated %}
{{ logout_button(provider=assoc.provider, id=assoc.id) }}
{% endfor %}

{% endblock %}


text:
#include <boost/thread/thread.hpp>
#include <boost/asio.hpp>
#include <boost/noncopyable.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/array.hpp>
#include <deque>
#include "latch.h"
#include "asiothread_message.h"

class asiothread_session;
typedef boost::asio::local::stream_protocol::socket localsocket;
typedef std::deque<asiothread_message> asiothread_message_queue;
typedef boost::function<void(asiothread_session*, asiothread_message&)> asiothread_message_callback;

class asiothread_session
{
public:
	asiothread_session(boost::asio::io_service& ios, asiothread_message_callback cb);
	~asiothread_session();
	void start();
	localsocket& sock() { return socket_; }
	void make_conn_pair(localsocket& mainsock);
	void send_from_this_thread(const asiothread_message& msg);
	void close_from_other_thread();

protected:
	void handle_read_header(const boost::system::error_code& error);
	void handle_read_body(const boost::system::error_code& error);
	void handle_write(const boost::system::error_code& error);

	void do_write(asiothread_message msg);
	void do_close();

private:
	boost::asio::io_service& io_service_;
	localsocket socket_;
	asiothread_message read_msg_;
	asiothread_message_queue write_msgs_;
	asiothread_message_callback on_message_;
};

#endif


text:
package pucminas.br.cc.lddm.wifieasytransfer;

import android.app.IntentService;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import pucminas.br.cc.lddm.tp_final.R;

/**
 * Created by josue on 07/06/15.
 */
public class ClientService extends IntentService {

    private int port;
    private File fileToSend;
    private String address;
    private String data;

    public ClientService() {
        super("ClientService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        port = (Integer) intent.getExtras().get("port");
        //fileToSend = (File) intent.getExtras().get("file");
        data = (String) intent.getExtras().get("data");
        address = (String) intent.getExtras().get("address");

        if (data != null && !data.equals("-")) {
            Context context = getApplicationContext();

            Socket clientSocket = new Socket();
            OutputStream os = null;

            try {
                clientSocket.bind(null);
                clientSocket.connect((new InetSocketAddress(address, port)), 5000);

                // send file
                OutputStream stream = clientSocket.getOutputStream();

                ContentResolver cr = context.getContentResolver();
                InputStream is = null;

                try {
                    is = cr.openInputStream(Uri.parse(data));
                } catch (FileNotFoundException e) {
                    Log.d("Wp2p", e.toString());
                }

                NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);;
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());

                // start notification
                mBuilder.setContentTitle("Upload file")
                        .setContentText("Upload in progress")
                        .setSmallIcon(R.drawable.cellphone_img);
                mBuilder.setProgress(0, 0, true);

                byte buf[] = new byte[1024];
                //byte buf[] = new byte[4096];
                int len;
                int c = 0;

                try {

                    while ((len = is.read(buf)) != -1) {
                        stream.write(buf, 0, len);
                        c++;
                        Log.d("Wp2p", "send part -> "+c);
                    }

                    stream.close();
                    is.close();

                } catch (IOException e) {
                    Log.d("Wp2p", e.toString());
                }

                mBuilder.setContentText("Upload complete");

                // Removes the progress bar
                mBuilder.setProgress(0, 0, false);
                mNotifyManager.notify(1, mBuilder.build());

//            byte[] buffer = new byte[4096];
//
//            Log.d("Wp2p", "Uploading file...");
//            while (true) {
//
//                int bytesRead = bis.read(buffer, 0, buffer.length);
//
//                if (bytesRead == -1) {
//                    break;
//                }
//
//                os.write(buffer, 0, bytesRead);
//                os.flush();
//            }
//
//            fis.close();
//            bis.close();
//
//            br.close();
//            isr.close();
//            is.close();
//
//            os.close();

                clientSocket.close();

                Log.d("Wp2p", "File uploaded...");
                Toast.makeText(getApplicationContext(), "File uploaded", Toast.LENGTH_SHORT).show();

            } catch (IOException e) {
                Log.d("Wp2p", "Erro in Socket Client");
                Log.d("Wp2p", e.getMessage());
                e.printStackTrace();
            }
        }
    }
}


text:
package diff

import (
	"bytes"
	"io/ioutil"
	"path/filepath"
	"reflect"
	"strings"
	"testing"
)

func TestParseHunkNoChunksize(t *testing.T) {
	filename := "sample_no_chunksize.diff"
	diffData, err := ioutil.ReadFile(filepath.Join("testdata", filename))
	if err != nil {
		t.Fatal(err)
	}
	diff, err := ParseHunks(diffData)
	if err != nil {
		t.Errorf("%s: got ParseHunks err %v,  want %v", filename, err, nil)
	}
	if len(diff) != 1 {
		t.Errorf("%s: Got %d hunks, want only one", filename, len(diff))
	}

	correct := &Hunk{
		NewLines:      1,
		NewStartLine:  1,
		OrigLines:     0,
		OrigStartLine: 0,
	}
	h := diff[0]
	h.Body = nil // We're not testing the body.
	if !reflect.DeepEqual(h, correct) {
		t.Errorf("%s: Got %#v, want %#v", filename, h, correct)
	}
}

func TestParseHunksAndPrintHunks(t *testing.T) {
	tests := []struct {
		filename     string
		wantParseErr error
	}{
		{
			filename: "sample_hunk.diff",
		},
		{
			filename: "sample_hunks.diff",
		},
		{
			filename:     "sample_bad_hunks.diff",
			wantParseErr: nil,
		},
		{
			filename: "sample_hunks_no_newline.diff",
		},
		{filename: "no_newline_both.diff"},
		{filename: "no_newline_both2.diff"},
		{filename: "no_newline_orig.diff"},
		{filename: "no_newline_new.diff"},
		{filename: "empty_orig.diff"},
		{filename: "empty_new.diff"},
		{filename: "oneline_hunk.diff"},
		{filename: "empty.diff"},
	}
	for _, test := range tests {
		diffData, err := ioutil.ReadFile(filepath.Join("testdata", test.filename))
		if err != nil {
			t.Fatal(err)
		}
		diff, err := ParseHunks(diffData)
		if err != test.wantParseErr {
			t.Errorf("%s: got ParseHunks err %v, want %v", test.filename, err, test.wantParseErr)
			continue
		}
		if test.wantParseErr != nil {
			continue
		}

		printed, err := PrintHunks(diff)
		if err != nil {
			t.Errorf("%s: PrintHunks: %s", test.filename, err)
		}
		if !bytes.Equal(printed, diffData) {
			t.Errorf("%s: printed diff hunks != original diff hunks\n\n# PrintHunks output:\n%s\n\n# Original:\n%s", test.filename, printed, diffData)
		}
	}
}

func TestParseFileDiffAndPrintFileDiff(t *testing.T) {
	tests := []struct {
		filename     string
		wantParseErr error
	}{
		{
			filename: "sample_file.diff",
		},
		{
			filename: "sample_file_no_timestamp.diff",
		},
		{
			filename: "sample_file_extended.diff",
		},
		{
			filename:     "empty.diff",
			wantParseErr: &ParseError{0, 0, ErrExtendedHeadersEOF},
		},
	}
	for _, test := range tests {
		diffData, err := ioutil.ReadFile(filepath.Join("testdata", test.filename))
		if err != nil {
			t.Fatal(err)
		}
		diff, err := ParseFileDiff(diffData)
		if !reflect.DeepEqual(err, test.wantParseErr) {
			t.Errorf("%s: got ParseFileDiff err %v, want %v", test.filename, err, test.wantParseErr)
			continue
		}
		if test.wantParseErr != nil {
			continue
		}

		printed, err := PrintFileDiff(diff)
		if err != nil {
			t.Errorf("%s: PrintFileDiff: %s", test.filename, err)
		}
		if !bytes.Equal(printed, diffData) {
			t.Errorf("%s: printed file diff != original file diff\n\n# PrintFileDiff output:\n%s\n\n# Original:\n%s", test.filename, printed, diffData)
		}
	}
}

func TestParseMultiFileDiffAndPrintMultiFileDiff(t *testing.T) {
	tests := []struct {
		filename     string
		wantParseErr error
	}{
		{
			filename: "sample_multi_file.diff",
		},
		{
			filename: "sample_multi_file_single.diff",
		},
		{filename: "empty.diff"},
		{filename: "empty_multi.diff"},
	}
	for _, test := range tests {
		diffData, err := ioutil.ReadFile(filepath.Join("testdata", test.filename))
		if err != nil {
			t.Fatal(err)
		}
		diff, err := ParseMultiFileDiff(diffData)
		if err != test.wantParseErr {
			t.Errorf("%s: got ParseMultiFileDiff err %v, want %v", test.filename, err, test.wantParseErr)
			continue
		}
		if test.wantParseErr != nil {
			continue
		}

		printed, err := PrintMultiFileDiff(diff)
		if err != nil {
			t.Errorf("%s: PrintMultiFileDiff: %s", test.filename, err)
		}
		if !bytes.Equal(printed, diffData) {
			t.Errorf("%s: printed multi-file diff != original multi-file diff\n\n# PrintMultiFileDiff output:\n%s\n\n# Original:\n%s", test.filename, printed, diffData)
		}
	}
}

func TestNoNewlineAtEnd(t *testing.T) {
	diffs := map[string]struct {
		diff              string
		trailingNewlineOK bool
	}{
		"orig": {
			diff: `@@ -1,1 +1,1 @@
-a
\ No newline at end of file
+b
`,
			trailingNewlineOK: true,
		},
		"new": {
			diff: `@@ -1,1 +1,1 @@
-a
+b
\ No newline at end of file
`,
		},
		"both": {
			diff: `@@ -1,1 +1,1 @@
-a
\ No newline at end of file
+b
\ No newline at end of file
`,
		},
	}

	for label, test := range diffs {
		hunks, err := ParseHunks([]byte(test.diff))
		if err != nil {
			t.Errorf("%s: ParseHunks: %s", label, err)
			continue
		}

		for _, hunk := range hunks {
			if body := string(hunk.Body); strings.Contains(body, "No newline") {
				t.Errorf("%s: after parse, hunk body contains 'No newline...' string\n\nbody is:\n%s", label, body)
			}
			if !test.trailingNewlineOK {
				if bytes.HasSuffix(hunk.Body, []byte{'\n'}) {
					t.Errorf("%s: after parse, hunk body ends with newline\n\nbody is:\n%s", label, hunk.Body)
				}
			}
			if dontWant := []byte("-a+b"); bytes.Contains(hunk.Body, dontWant) {
				t.Errorf("%s: hunk body contains %q\n\nbody is:\n%s", label, dontWant, hunk.Body)
			}

			printed, err := PrintHunks(hunks)
			if err != nil {
				t.Errorf("%s: PrintHunks: %s", label, err)
				continue
			}
			if printed := string(printed); printed != test.diff {
				t.Errorf("%s: printed diff hunks != original diff hunks\n\n# PrintHunks output:\n%s\n\n# Original:\n%s", label, printed, test.diff)
			}
		}
	}
}

func TestFileDiff_Stat(t *testing.T) {
	tests := map[string]struct {
		hunks []*Hunk
		want  Stat
	}{
		"no change": {
			hunks: []*Hunk{
				{Body: []byte(`@@ -0,0 +0,0
 a
 b
`)},
			},
			want: Stat{},
		},
		"added/deleted": {
			hunks: []*Hunk{
				{Body: []byte(`@@ -0,0 +0,0
+a
 b
-c
 d
`)},
			},
			want: Stat{Added: 1, Deleted: 1},
		},
		"changed": {
			hunks: []*Hunk{
				{Body: []byte(`@@ -0,0 +0,0
+a
+b
-c
-d
 e
`)},
			},
			want: Stat{Added: 1, Changed: 1, Deleted: 1},
		},
		"many changes": {
			hunks: []*Hunk{
				{Body: []byte(`@@ -0,0 +0,0
+a
-b
+c
-d
 e
`)},
			},
			want: Stat{Added: 0, Changed: 2, Deleted: 0},
		},
	}
	for label, test := range tests {
		fdiff := &FileDiff{Hunks: test.hunks}
		stat := fdiff.Stat()
		if !reflect.DeepEqual(stat, test.want) {
			t.Errorf("%s: got diff stat %+v, want %+v", label, stat, test.want)
			continue
		}
	}
}


text:
package com.wanke.ui.adapter;

import java.util.Hashtable;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;

import com.wanke.ui.fragment.FragmentGame;
import com.wanke.ui.fragment.FragmentLive;
import com.wanke.ui.fragment.FragmentMy;
import com.wanke.ui.fragment.FragmentRecommend;

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
    private Hashtable<Integer, Fragment> mFragmentTable = new Hashtable<Integer, Fragment>();

    private Class<?> mFragmentClass[] = { FragmentRecommend.class,
            FragmentLive.class, FragmentGame.class, FragmentMy.class };

    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    public CharSequence getPageTitle(int position) {
        return "";
    }

    @Override
    public int getCount() {
        return mFragmentClass.length;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = mFragmentTable.get(position);
        if (fragment == null) {
            Class<?> fragmentClass = mFragmentClass[position];
            try {
                fragment = (Fragment) fragmentClass.newInstance();
            } catch (Exception e) {
                Log.d("excetpion", "MyFragmentPagerAdapter:" + e.toString());
            }
        }
        return fragment;
    }

}


text:
namespace v8 {
namespace internal {

#define __ ACCESS_MASM(masm)

void DebugCodegen::GenerateHandleDebuggerStatement(MacroAssembler* masm) {
  {
    FrameScope scope(masm, StackFrame::INTERNAL);
    __ CallRuntime(Runtime::kHandleDebuggerStatement, 0);
  }
  __ MaybeDropFrames();

  // Return to caller.
  __ Ret();
}

void DebugCodegen::GenerateFrameDropperTrampoline(MacroAssembler* masm) {
  // Frame is being dropped:
  // - Drop to the target frame specified by x1.
  // - Look up current function on the frame.
  // - Leave the frame.
  // - Restart the frame by calling the function.
  __ Mov(fp, x1);
  __ Ldr(x1, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));

  __ Mov(sp, fp);
  __ Pop(fp, lr);  // Frame, Return address.

  __ Ldr(x0, FieldMemOperand(x1, JSFunction::kSharedFunctionInfoOffset));
  __ Ldr(x0,
         FieldMemOperand(x0, SharedFunctionInfo::kFormalParameterCountOffset));
  __ mov(x2, x0);

  ParameterCount dummy1(x2);
  ParameterCount dummy2(x0);
  __ InvokeFunction(x1, dummy1, dummy2, JUMP_FUNCTION);
}

const bool LiveEdit::kFrameDropperSupported = true;

}  // namespace internal
}  // namespace v8

#undef __

#endif  // V8_TARGET_ARCH_ARM64


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Requêtes sur un fichier (SNDINFO)</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="Manuel de référence canonique de Csound" />
    <link rel="up" href="UtilitySoundfile.html" title="Formats des fichiers son." />
    <link rel="prev" href="pvanal.html" title="pvanal" />
    <link rel="next" href="sndinfo.html" title="sndinfo" />

          Requêtes sur un fichier (SNDINFO)

          Précédent
          Formats des fichiers son.
           Suivant

Requêtes sur un fichier (SNDINFO)

L'utilitaire suivant existe pour les requêtes sur un fichier son :

          SNDINFO: affiche de l'information sur un
          fichier son.

          Précédent

            Niveau supérieur

           Suivant

          pvanal

            Sommaire

           sndinfo


text:
package com.tuenti.deferred;

class ImmediatelyPipeStrategy implements PipeStrategy {

	@Override
	public <D, F, P, D_OUT, F_OUT, P_OUT> void onDone(PipedPromise<D, F, P, D_OUT, F_OUT, P_OUT> pipedPromise,
			DonePipe<D, D_OUT, F_OUT, P_OUT> donePipe, D result) {

		pipedPromise.pipe(donePipe.pipeDone(result));
	}

	@Override
	public <D, F, P, D_OUT, F_OUT, P_OUT> void onProgress(PipedPromise<D, F, P, D_OUT, F_OUT, P_OUT> pipedPromise,
			ProgressPipe<P, D_OUT, F_OUT, P_OUT> progressPipe, P progress) {

		pipedPromise.pipe(progressPipe.pipeProgress(progress));
	}

	@Override
	public <D, F, P, D_OUT, F_OUT, P_OUT> void onFail(PipedPromise<D, F, P, D_OUT, F_OUT, P_OUT> pipedPromise,
			FailPipe<F, D_OUT, F_OUT, P_OUT> failPipe, F fail) {

		pipedPromise.pipe(failPipe.pipeFail(fail));
	}
}


text:
VariableIdList::VariableIdList(void)
{
}

VariableIdList::operator QStringList(void) const
{
    QStringList result;
    int x = 0;
    while (x < size())
        result << at(x++);
    return result;
}


text:
import { Parser, succeed } from 'parsimmon';
import * as vscode from 'vscode';
import { VimState } from '../../state/vimState';
import { ExCommand } from '../../vimscript/exCommand';

export class TerminalCommand extends ExCommand {
  public static readonly argParser: Parser<TerminalCommand> = succeed(new TerminalCommand());

  async execute(vimState: VimState): Promise<void> {
    await vscode.commands.executeCommand('workbench.action.createTerminalEditor');
  }
}


text:
var   assert 		= require("assert")
	, chai 			= require("chai");

var status = require("../index");

describe('Module http-status-name', function(){
 	it('should return a name Moved_Permanently for statuscode 301', function(){
    	name = status(301);

    	chai.expect( name ).to.be.a('String');
    	chai.expect( name ).to.equal('Moved_Permanently');
 	});

 });


text:
using System;
using System.Collections.Generic;
using Server;
using Server.Multis;
using Server.Network;

namespace Server.Items
{
	[Flipable( 0x2815, 0x2816 )]
	public class TallCabinet : BaseContainer
	{
		[Constructable]
		public TallCabinet() : base( 0x2815 )
		{
			Weight = 1.0;
		}

		public TallCabinet( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}

	[Flipable( 0x2817, 0x2818 )]
	public class ShortCabinet : BaseContainer
	{
		[Constructable]
		public ShortCabinet() : base( 0x2817 )
		{
			Weight = 1.0;
		}

		public ShortCabinet( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}

	[Flipable( 0x2857, 0x2858 )]
	public class RedArmoire : BaseContainer
	{
		[Constructable]
		public RedArmoire() : base( 0x2857 )
		{
			Weight = 1.0;
		}

		public RedArmoire( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}

	[Flipable( 0x285D, 0x285E )]
	public class CherryArmoire : BaseContainer
	{
		[Constructable]
		public CherryArmoire() : base( 0x285D )
		{
			Weight = 1.0;
		}

		public CherryArmoire( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}

	[Flipable( 0x285B, 0x285C )]
	public class MapleArmoire : BaseContainer
	{
		[Constructable]
		public MapleArmoire() : base( 0x285B )
		{
			Weight = 1.0;
		}

		public MapleArmoire( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}

	[Flipable( 0x2859, 0x285A )]
	public class ElegantArmoire : BaseContainer
	{
		[Constructable]
		public ElegantArmoire() : base( 0x2859 )
		{
			Weight = 1.0;
		}

		public ElegantArmoire( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}

	[Flipable( 0xa97, 0xa99, 0xa98, 0xa9a, 0xa9b, 0xa9c )]
	public class FullBookcase : BaseContainer
	{
		[Constructable]
		public FullBookcase() : base( 0xA97 )
		{
			Weight = 1.0;
		}

		public FullBookcase( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}

	[Flipable( 0xa9d, 0xa9e )]
	public class EmptyBookcase : BaseContainer
	{
		[Constructable]
		public EmptyBookcase() : base( 0xA9D )
		{
		}

		public EmptyBookcase( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 1 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();

			if ( version == 0 && Weight == 1.0 )
				Weight = -1;
		}
	}

	[Flipable( 0xa2c, 0xa34 )]
	public class Drawer : BaseContainer
	{
		[Constructable]
		public Drawer() : base( 0xA2C )
		{
			Weight = 1.0;
		}

		public Drawer( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}

	[Flipable( 0xa30, 0xa38 )]
	public class FancyDrawer : BaseContainer
	{
		[Constructable]
		public FancyDrawer() : base( 0xA30 )
		{
			Weight = 1.0;
		}

		public FancyDrawer( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}

	[Flipable( 0xa4f, 0xa53 )]
	public class Armoire : BaseContainer
	{
		[Constructable]
		public Armoire() : base( 0xA4F )
		{
			Weight = 1.0;
		}

		public override void DisplayTo( Mobile m )
		{
			if ( DynamicFurniture.Open( this, m ) )
				base.DisplayTo( m );
		}

		public Armoire( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();

			DynamicFurniture.Close( this );
		}
	}

	[Flipable( 0xa4d, 0xa51 )]
	public class FancyArmoire : BaseContainer
	{
		[Constructable]
		public FancyArmoire() : base( 0xA4D )
		{
			Weight = 1.0;
		}

		public override void DisplayTo( Mobile m )
		{
			if ( DynamicFurniture.Open( this, m ) )
				base.DisplayTo( m );
		}

		public FancyArmoire( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();

			DynamicFurniture.Close( this );
		}
	}

	public class DynamicFurniture
	{
		private static Dictionary<Container, Timer> m_Table = new Dictionary<Container, Timer>();

		public static bool Open( Container c, Mobile m )
		{
			if ( m_Table.ContainsKey( c ) )
			{
				c.SendRemovePacket();
				Close( c );
				c.Delta( ItemDelta.Update );
				c.ProcessDelta();
				return false;
			}

			if ( c is Armoire || c is FancyArmoire )
			{
				Timer t = new FurnitureTimer( c, m );
				t.Start();
				m_Table[c] = t;

				switch ( c.ItemID )
				{
					case 0xA4D: c.ItemID = 0xA4C; break;
					case 0xA4F: c.ItemID = 0xA4E; break;
					case 0xA51: c.ItemID = 0xA50; break;
					case 0xA53: c.ItemID = 0xA52; break;
				}
			}

			return true;
		}

		public static void Close( Container c )
		{
			Timer t = null;

			m_Table.TryGetValue( c, out t );

			if ( t != null )
			{
				t.Stop();
				m_Table.Remove( c );
			}

			if ( c is Armoire || c is FancyArmoire )
			{
				switch ( c.ItemID )
				{
					case 0xA4C: c.ItemID = 0xA4D; break;
					case 0xA4E: c.ItemID = 0xA4F; break;
					case 0xA50: c.ItemID = 0xA51; break;
					case 0xA52: c.ItemID = 0xA53; break;
				}
			}
		}
	}

	public class FurnitureTimer : Timer
	{
		private Container m_Container;
		private Mobile m_Mobile;

		public FurnitureTimer( Container c, Mobile m ) : base( TimeSpan.FromSeconds( 0.5 ), TimeSpan.FromSeconds( 0.5 ) )
		{
			Priority = TimerPriority.TwoFiftyMS;

			m_Container = c;
			m_Mobile = m;
		}

		protected override void OnTick()
		{
			if ( m_Mobile.Map != m_Container.Map || !m_Mobile.InRange( m_Container.GetWorldLocation(), 3 ) )
				DynamicFurniture.Close( m_Container );
		}
	}
}


text:
import ransac
import numpy as np
import json
import sys
import matplotlib.pyplot as plt
from matplotlib import collections as mc

def main(jsonfile):
    with open(jsonfile) as data_file1:
        data1 = json.load(data_file1)

    pms = data1['pointmatches']
    points1 = np.array([p['point1'] for p in pms])
    points2 = np.array([p['point2'] for p in pms])

    try:
        if points1.shape[1] != 2:
            return
    except:
        return

    centroid1 = points1.mean(axis=0, keepdims=True)
    centroid2 = points2.mean(axis=0, keepdims=True)

    model_index = 1
    iterations = 500
    max_epsilon = 100
    min_inlier_ratio = 0
    min_num_inlier = 7
    max_trust = 3
    det_delta = 0.3
    pointmatchesr = (points1, points2)
    try:
        model, filtered_matches = ransac.filter_matches(pointmatchesr, model_index, iterations, max_epsilon, min_inlier_ratio, min_num_inlier, max_trust, det_delta)
        R = model.get_matrix()[0:2, 0:2]
    except:
        return
    '''
    h = np.matrix(np.zeros((2,2)))
    for i in range(0, len(point1s)):
        sumpart = (np.matrix(point1s[i]) - centroid1).dot((np.matrix(point2s[i]) - centroid2).T)
        h = h + sumpart
    U, S, Vt = np.linalg.svd(h)
    R = Vt.T.dot(U.T)
    print R
    '''

    new_points1 = np.dot(R, (points1 - centroid1).T).T
    new_points2 = points2 - centroid2
    lines = [[p1, p2] for p1, p2 in zip(new_points1, new_points2)]
    lc = mc.LineCollection(lines)
    plt.figure()
    plt.gca().add_collection(lc)
    plt.scatter(new_points1[:, 0], new_points1[:, 1])
    plt.gca().autoscale()
    plt.axis('equal')
    plt.title(jsonfile)
    return model.get_matrix()

if __name__ == '__main__':
    transforms = [main(arg) for arg in sys.argv[1:]]
    if len(transforms) == 2:
        RT1, RT2 = transforms
        print "Composed transform, last column should be [0, 0, 1].T:\n", np.dot(RT1, RT2)
    plt.show()


text:
layout: post
title: "python-zarafa monthly update June"
date: 2014-06-29 20:00
comments: false
categories: [Zarafa, Python, update, June]
---

It's been almost a month since [python-zarafa](https://github.com/zarafagroupware/python-zarafa) has been released on Github. Although the initial commit already contained a lot of features, we added a few nice new features in the month June.
In this post I will describe the new features we added and I will hopefully provide a new post about improvements on a monthly basis.

Maildir
-------
The first new feature is maildir support for folders and was added 20 days ago in this [commit](https://github.com/zarafagroupware/python-zarafa/commit/2aaf7faa775e443cd94e986ea8ad3916cf849f4d).

{% highlight python %}
import zarafa
user = zarafa.Server().user('username')
# Export inbox to maildir in current working directory
user.store.inbox.maildir()

# Import maildir to inbox
user.store.inbox.read_maildir('Maildir')
{% endhighlight %}

Named properties
----------------
The second new feature is support for named properties, named properties are described in [this post](http://blogs.technet.com/b/exchange/archive/2009/04/06/3407221.aspx) on Microsoft's technet. These properties are for example set on mail messages:

* x-viruschecked
* x-env-sender

These properties now show up in item.properties().

Quota support
-------------
The third feature is support for quotas, Zarafa is capable of setting quota's (hard/soft/warning) globally, per company and per user. For example:

{% highlight python %}
import zarafa

# User quota
user = zarafa.Server().user('username')
print "User store size ",user.store.size
print "User quota warning limit ",user.quota.warn_limit
print "User quota soft warning limit ",user.quota.soft_limit
print "User quota hard warning limit ",user.quota.hard_limit

# Company quota
companies = zarafa.Server().companies()
for company in companies:
	print "Company warning limit ",company.quota.warn_limit
{% endhighlight %}

Address Class
-------------
The last big feature adds an Address class which contains information about for example the sender of an email.
{% highlight python %}
import zarafa
user = zarafa.Server().user('username')
for mail in user.store.inbox.items():
	print "Sender of email " mail.sender.name
	print "From email " mail.sender.email
{% endhighlight %}

Smaller changes are:

* support for http:// socket
* user.fullname
* support for accessing PR_EC_STATSTABLE's (these tables contain information displayed by zarafa-stats)
* public folder support
* bugfixes

Please note that the API is still a work in progress and a lot of functionality might get renamed and refactored in the future. In the future we hope to eventually provide a stable API and online documentation.
If there are any questions, feel free to contact me via email!


text:
layout: blog_by_tag
title: 'Articles by tag: grunt'
tag: grunt
permalink: /tag/grunt/
---


text:
package com.simonevertsson.columbus.dummy;

import com.simonevertsson.columbus.Mapping;

public class TicketViewModel {

  @Mapping(clazz = Movie.class, field = "title")
  private String movie;

  @Mapping(clazz = Movie.class, field = "cost")
  private float cost;

  @Mapping(clazz = Person.class, field = "name")
  private String boughtBy;

  public String getMovie() {
    return movie;
  }

  public void setMovie(String movie) {
    this.movie = movie;
  }

  public float getCost() {
    return cost;
  }

  public void setCost(float cost) {
    this.cost = cost;
  }

  public String getBoughtBy() {
    return boughtBy;
  }

  public void setBoughtBy(String boughtBy) {
    this.boughtBy = boughtBy;
  }
}


text:
package org.springframework.security.access.intercept;

import java.util.Collection;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;

/**
 * A return object received by {@link AbstractSecurityInterceptor} subclasses.
 * <p>
 * This class reflects the status of the security interception, so that the final call to
 * {@link org.springframework.security.access.intercept.AbstractSecurityInterceptor#afterInvocation(InterceptorStatusToken, Object)}
 * can tidy up correctly.
 *
 * @author Ben Alex
 */
public class InterceptorStatusToken {
    //~ Instance fields ================================================================================================

    private Authentication authentication;
    private Collection<ConfigAttribute> attr;
    private Object secureObject;
    private boolean contextHolderRefreshRequired;

    //~ Constructors ===================================================================================================

    public InterceptorStatusToken(Authentication authentication, boolean contextHolderRefreshRequired,
            Collection<ConfigAttribute> attributes, Object secureObject) {
        this.authentication = authentication;
        this.contextHolderRefreshRequired = contextHolderRefreshRequired;
        this.attr = attributes;
        this.secureObject = secureObject;
    }

    //~ Methods ========================================================================================================

    public Collection<ConfigAttribute> getAttributes() {
        return attr;
    }

    public Authentication getAuthentication() {
        return authentication;
    }

    public Object getSecureObject() {
        return secureObject;
    }

    public boolean isContextHolderRefreshRequired() {
        return contextHolderRefreshRequired;
    }
}


text:
//Welcome to your MAIN PROJECT...
//THIS IS THE MOST relevant code for you!
//this is an important file, raytracing.cpp is what you need to fill out
//In principle, you can do the entire project ONLY by working in these two files

extern Mesh MyMesh; //Main mesh
extern std::vector<Vec3Dd> MyLightPositions;
extern Vec3Dd MyCameraPosition; //currCamera
extern unsigned int WindowSize_X;//window resolution width
extern unsigned int WindowSize_Y;//window resolution height
extern unsigned int RayTracingResolutionX;  // largeur fenetre
extern unsigned int RayTracingResolutionY;  // largeur fenetre

//use this function for any preprocessing of the mesh.
void init();

//you can use this function to transform a click to an origin and destination
//the last two values will be changed. There is no need to define this function.
//it is defined elsewhere
void produceRay(int x_I, int y_I, Vec3Dd & origin, Vec3Dd & dest);

bool   rayBoxIntersect(const Vec3Dd &orig, const Vec3Dd &dir, const Vec3Dd &lb, const Vec3Dd &rb);
Vec3Dd rayTriangleIntersect(const Vec3Dd &orig, const Vec3Dd &dir, const Triangle &triangle, double &depth);

//your main function to rewrite
Vec3Dd performRayTracing(const Vec3Dd & origin, const Vec3Dd & dest);
Vec3Dd trace(const Vec3Dd & origin, const Vec3Dd & dir, int level);

//a function to debug --- you can draw in OpenGL here
void yourDebugDraw();

//want keyboard interaction? Here it is...
void yourKeyboardFunc(char t, int x, int y, const Vec3Dd & rayOrigin, const Vec3Dd & rayDestination);
void yourSpecialKeyboardFunc(int t, int x, int y, const Vec3Dd & rayOrigin, const Vec3Dd & rayDestination);
void clearDebugVector();
void toggleDebug();
void toggleFillColor();
void toggleBackgroundColor();
void toggleSelectAll();

//Shadow Functions
bool inShadow(const Vec3Dd intersection, const Vec3Dd lightDirection);

// Shading functions
Vec3Dd shade(const Vec3Dd origin, const Vec3Dd intersection, int level, int triangleIndex, Vec3Dd normal);
Vec3Dd diffuse(const Vec3Dd light, Vec3Dd normal,  int triangleIndex);
Vec3Dd ambient(int triangleIndex);
Vec3Dd speculair(const Vec3Dd lightDirection, const Vec3Dd viewDirectionN, int triangleIndex, const Vec3Dd N);
Vec3Dd lightVector(const Vec3Dd point, const Vec3Dd lightPoint);

// Reflection functions
Vec3Dd reflectionVector(const Vec3Dd viewDirection, const Vec3Dd normalVector);
Vec3Dd computeReflectionVector(const Vec3Dd viewDirection, const Vec3Dd intersection, const Vec3Dd normalVector, int level);

// Refraction functions
Vec3Dd computeRefraction(const Vec3Dd dir, const Vec3Dd intersection, int level, int triangleIndex);


text:
namespace math {

    typedef Vec2f Vec2;

}

#endif


text:
import {Component, OnInit} from '@angular/core';
import {FormControl, ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";
import {DatePipe} from "@angular/common";

@Component({
  selector: 'custom-date',
  styleUrls: [
    './customDate.scss'
  ],
  templateUrl: './customDate.template.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: CustomDateComponent,
      multi: true
    }
  ]
})
export class CustomDateComponent implements ControlValueAccessor {

  private dateRegexStartSymbol = '^';
  private dateRegexEndSymbol = '$';
  private dateDayRegex = '(?:0?[1-9]?|1\\d?|2\\d?|3[1-2]?)';
  private dateMonthRegex = '(?:(?:0[1-9]?)|(?:1[0-2]?))';
  private dateYearRegex = '(\\d){1,4}';
  private datePointRegex = '(\\.)';

  private _date;
  private oldDate = null;

  constructor() {
  }

  propagateChange = (_: any) => {};
  propagateTouch = (_: any) => {};

  writeValue(obj: any): void {
    let stringDate = new DatePipe('ru').transform(obj, 'dd.MM.yyyy');
    let result = this.checkInputedValue(stringDate);
    if (obj !== undefined) {
      if (result.isFullyCollect) {
        this._date = stringDate;
        this.oldDate = stringDate;
      }
    } else {
      this._date = "";
      this.oldDate = this._date;
    }
  }

  registerOnChange(fn) {
    this.propagateChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.propagateTouch = fn;
  }

  get date() {
    return this._date;
  }

  set date(value) {
    let finalDate = null;
    if (value){
      this._date = value;
      let dateArray = value.split('.');
      dateArray.splice(0,0, dateArray.splice(1,1)[0]).join('/');
      finalDate = new Date(dateArray);
    }
    this.propagateChange(finalDate);
  }

  onInputHandler(event: KeyboardEvent) {
    const target = event.target as HTMLInputElement;
    let result = this.checkInputedValue(target.value);
    if (result.isPartiallyCorrect) {
      this._date = target.value;
      this.oldDate = this._date;
      if (target.value == ""){
        this.date = target.value;
      }
    } else if (result.isFullyCollect) {
      this.date = target.value;
      this.oldDate = target.value;
    } else {
      target.value = this.oldDate;
    }
  }

  onTouchHandler(){
    this.propagateTouch(null);
  }

  checkInputedValue(value): CheckingResult {
    let result = new CheckingResult();
    if (new RegExp(this.dateRegexStartSymbol +
        this.dateRegexEndSymbol).test(value)) {
      result.isPartiallyCorrect = true;
    } else if (new RegExp(this.dateRegexStartSymbol +
        this.dateDayRegex +
        this.dateRegexEndSymbol).test(value)) {
      result.isPartiallyCorrect = true;
    } else if (new RegExp(this.dateRegexStartSymbol +
        this.dateDayRegex +
        this.datePointRegex +
        this.dateRegexEndSymbol).test(value)) {
      result.isPartiallyCorrect = true;
    } else if (new RegExp(this.dateRegexStartSymbol +
        this.dateDayRegex +
        this.datePointRegex +
        this.dateMonthRegex +
        this.dateRegexEndSymbol).test(value)) {
      result.isPartiallyCorrect = true;
    } else if (new RegExp(this.dateRegexStartSymbol +
        this.dateDayRegex +
        this.datePointRegex +
        this.dateMonthRegex +
        this.datePointRegex +
        this.dateRegexEndSymbol).test(value)) {
      result.isPartiallyCorrect = true;
    } else if (new RegExp(this.dateRegexStartSymbol +
        this.dateDayRegex +
        this.datePointRegex +
        this.dateMonthRegex +
        this.datePointRegex +
        this.dateYearRegex +
        this.dateRegexEndSymbol).test(value)) {
      value.length === 10 ?
        result.isFullyCollect = true :
        result.isPartiallyCorrect = true;
    }
    return result;
  }
}

class CheckingResult {
  isPartiallyCorrect: boolean = false;
  isFullyCollect: boolean = false;
}


text:
/* *
 *
 *  (c) 2010-2021 Torstein Honsi
 *
 *  License: www.highcharts.com/license
 *
 *  !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
 *
 * */
'use strict';
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
import A from '../Animation/AnimationUtilities.js';
var animObject = A.animObject;
import Axis from '../Axis/Axis.js';
import Chart from '../Chart/Chart.js';
import F from '../../Core/FormatUtilities.js';
var format = F.format;
import D from '../DefaultOptions.js';
var getOptions = D.getOptions;
import Palette from '../../Core/Color/Palette.js';
import Point from '../Series/Point.js';
var pointTooltipFormatter = Point.prototype.tooltipFormatter;
import Series from '../Series/Series.js';
var _a = Series.prototype, seriesInit = _a.init, seriesProcessData = _a.processData;
import SVGRenderer from '../Renderer/SVG/SVGRenderer.js';
import U from '../Utilities.js';
var addEvent = U.addEvent, arrayMax = U.arrayMax, arrayMin = U.arrayMin, clamp = U.clamp, defined = U.defined, extend = U.extend, find = U.find, isNumber = U.isNumber, isString = U.isString, merge = U.merge, pick = U.pick, splat = U.splat;
import '../Pointer.js';
// Has a dependency on Navigator due to the use of
// defaultOptions.navigator
import '../Navigator.js';
// Has a dependency on Scrollbar due to the use of
// defaultOptions.scrollbar
import '../Scrollbar.js';
// Has a dependency on RangeSelector due to the use of
// defaultOptions.rangeSelector
import '../../Extensions/RangeSelector.js';
/* *
 *
 *  Class
 *
 * */
/**
 * Stock-optimized chart. Use {@link Highcharts.Chart|Chart} for common charts.
 *
 * @requires modules/stock
 *
 * @class
 * @name Highcharts.StockChart
 * @extends Highcharts.Chart
 */
var StockChart = /** @class */ (function (_super) {
    __extends(StockChart, _super);
    function StockChart() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Initializes the chart. The constructor's arguments are passed on
     * directly.
     *
     * @function Highcharts.StockChart#init
     *
     * @param {Highcharts.Options} userOptions
     *        Custom options.
     *
     * @param {Function} [callback]
     *        Function to run when the chart has loaded and and all external
     *        images are loaded.
     *
     * @return {void}
     *
     * @fires Highcharts.StockChart#event:init
     * @fires Highcharts.StockChart#event:afterInit
     */
    StockChart.prototype.init = function (userOptions, callback) {
        var defaultOptions = getOptions(), xAxisOptions = userOptions.xAxis, yAxisOptions = userOptions.yAxis,
        // Always disable startOnTick:true on the main axis when the
        // navigator is enabled (#1090)
        navigatorEnabled = pick(userOptions.navigator && userOptions.navigator.enabled, defaultOptions.navigator.enabled, true);
        // Avoid doing these twice
        userOptions.xAxis = userOptions.yAxis = void 0;
        var options = merge({
            chart: {
                panning: {
                    enabled: true,
                    type: 'x'
                },
                pinchType: 'x'
            },
            navigator: {
                enabled: navigatorEnabled
            },
            scrollbar: {
                // #4988 - check if setOptions was called
                enabled: pick(defaultOptions.scrollbar && defaultOptions.scrollbar.enabled, true)
            },
            rangeSelector: {
                // #4988 - check if setOptions was called
                enabled: pick(defaultOptions.rangeSelector.enabled, true)
            },
            title: {
                text: null
            },
            tooltip: {
                split: pick(defaultOptions.tooltip.split, true),
                crosshairs: true
            },
            legend: {
                enabled: false
            }
        }, userOptions, // user's options
        {
            isStock: true // internal flag
        });
        userOptions.xAxis = xAxisOptions;
        userOptions.yAxis = yAxisOptions;
        // apply X axis options to both single and multi y axes
        options.xAxis = splat(userOptions.xAxis || {}).map(function (xAxisOptions, i) {
            return merge(getDefaultAxisOptions('xAxis', xAxisOptions), defaultOptions.xAxis, // #3802
            defaultOptions.xAxis && defaultOptions.xAxis[i], // #7690
            xAxisOptions, // user options
            getForcedAxisOptions('xAxis', userOptions));
        });
        // apply Y axis options to both single and multi y axes
        options.yAxis = splat(userOptions.yAxis || {}).map(function (yAxisOptions, i) {
            return merge(getDefaultAxisOptions('yAxis', yAxisOptions), defaultOptions.yAxis, // #3802
            defaultOptions.yAxis && defaultOptions.yAxis[i], // #7690
            yAxisOptions // user options
            );
        });
        _super.prototype.init.call(this, options, callback);
    };
    /**
     * Factory for creating different axis types.
     * Extended to add stock defaults.
     *
     * @private
     * @function Highcharts.StockChart#createAxis
     *
     * @param {string} type
     *        An axis type.
     *
     * @param {Chart.CreateAxisOptionsObject} options
     *        The axis creation options.
     *
     * @return {Highcharts.Axis | Highcharts.ColorAxis}
     */
    StockChart.prototype.createAxis = function (type, options) {
        options.axis = merge(getDefaultAxisOptions(type, options.axis), options.axis, getForcedAxisOptions(type, this.userOptions));
        return _super.prototype.createAxis.call(this, type, options);
    };
    return StockChart;
}(Chart));
/* eslint-disable no-invalid-this, valid-jsdoc */
(function (StockChart) {
    /**
     * Factory function for creating new stock charts. Creates a new
     * {@link Highcharts.StockChart|StockChart} object with different default
     * options than the basic Chart.
     *
     * @example
     * let chart = Highcharts.stockChart('container', {
     *     series: [{
     *         data: [1, 2, 3, 4, 5, 6, 7, 8, 9],
     *         pointInterval: 24 * 60 * 60 * 1000
     *     }]
     * });
     *
     * @function Highcharts.stockChart
     *
     * @param {string|Highcharts.HTMLDOMElement} [renderTo]
     *        The DOM element to render to, or its id.
     *
     * @param {Highcharts.Options} options
     *        The chart options structure as described in the
     *        [options reference](https://api.highcharts.com/highstock).
     *
     * @param {Highcharts.ChartCallbackFunction} [callback]
     *        A function to execute when the chart object is finished loading
     *        and rendering. In most cases the chart is built in one thread,
     *        but in Internet Explorer version 8 or less the chart is sometimes
     *        initialized before the document is ready, and in these cases the
     *        chart object will not be finished synchronously. As a
     *        consequence, code that relies on the newly built Chart object
     *        should always run in the callback. Defining a
     *        [chart.events.load](https://api.highcharts.com/highstock/chart.events.load)
     *        handler is equivalent.
     *
     * @return {Highcharts.StockChart}
     *         The chart object.
     */
    function stockChart(a, b, c) {
        return new StockChart(a, b, c);
    }
    StockChart.stockChart = stockChart;
})(StockChart || (StockChart = {}));
/**
 * Get stock-specific default axis options.
 *
 * @private
 * @function getDefaultAxisOptions
 * @param {string} type
 * @param {Highcharts.AxisOptions} options
 * @return {Highcharts.AxisOptions}
 */
function getDefaultAxisOptions(type, options) {
    if (type === 'xAxis') {
        return {
            minPadding: 0,
            maxPadding: 0,
            overscroll: 0,
            ordinal: true,
            title: {
                text: null
            },
            labels: {
                overflow: 'justify'
            },
            showLastLabel: true
        };
    }
    if (type === 'yAxis') {
        return {
            labels: {
                y: -2
            },
            opposite: pick(options.opposite, true),
            /**
             * @default {highcharts} true
             * @default {highstock} false
             * @apioption yAxis.showLastLabel
             *
             * @private
             */
            showLastLabel: !!(
            // #6104, show last label by default for category axes
            options.categories ||
                options.type === 'category'),
            title: {
                text: null
            }
        };
    }
    return {};
}
/**
 * Get stock-specific forced axis options.
 *
 * @private
 * @function getForcedAxisOptions
 * @param {string} type
 * @param {Highcharts.Options} chartOptions
 * @return {Highcharts.AxisOptions}
 */
function getForcedAxisOptions(type, chartOptions) {
    if (type === 'xAxis') {
        var defaultOptions = getOptions(),
        // Always disable startOnTick:true on the main axis when the
        // navigator is enabled (#1090)
        navigatorEnabled = pick(chartOptions.navigator && chartOptions.navigator.enabled, defaultOptions.navigator.enabled, true);
        var axisOptions = {
            type: 'datetime',
            categories: void 0
        };
        if (navigatorEnabled) {
            axisOptions.startOnTick = false;
            axisOptions.endOnTick = false;
        }
        return axisOptions;
    }
    return {};
}
/* *
 *
 *  Compositions
 *
 * */
// Handle som Stock-specific series defaults, override the plotOptions before
// series options are handled.
addEvent(Series, 'setOptions', function (e) {
    var overrides;
    if (this.chart.options.isStock) {
        if (this.is('column') || this.is('columnrange')) {
            overrides = {
                borderWidth: 0,
                shadow: false
            };
        }
        else if (!this.is('scatter') && !this.is('sma')) {
            overrides = {
                marker: {
                    enabled: false,
                    radius: 2
                }
            };
        }
        if (overrides) {
            e.plotOptions[this.type] = merge(e.plotOptions[this.type], overrides);
        }
    }
});
// Override the automatic label alignment so that the first Y axis' labels
// are drawn on top of the grid line, and subsequent axes are drawn outside
addEvent(Axis, 'autoLabelAlign', function (e) {
    var chart = this.chart, options = this.options, panes = chart._labelPanes = chart._labelPanes || {}, key, labelOptions = this.options.labels;
    if (this.chart.options.isStock && this.coll === 'yAxis') {
        key = options.top + ',' + options.height;
        // do it only for the first Y axis of each pane
        if (!panes[key] && labelOptions.enabled) {
            if (labelOptions.x === 15) { // default
                labelOptions.x = 0;
            }
            if (typeof labelOptions.align === 'undefined') {
                labelOptions.align = 'right';
            }
            panes[key] = this;
            e.align = 'right';
            e.preventDefault();
        }
    }
});
// Clear axis from label panes (#6071)
addEvent(Axis, 'destroy', function () {
    var chart = this.chart, key = this.options && (this.options.top + ',' + this.options.height);
    if (key && chart._labelPanes && chart._labelPanes[key] === this) {
        delete chart._labelPanes[key];
    }
});
// Override getPlotLinePath to allow for multipane charts
addEvent(Axis, 'getPlotLinePath', function (e) {
    var axis = this, series = (this.isLinked && !this.series ?
        this.linkedParent.series :
        this.series), chart = axis.chart, renderer = chart.renderer, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, result = [], axes = [], // #3416 need a default array
    axes2, uniqueAxes, translatedValue = e.translatedValue, value = e.value, force = e.force, transVal;
    /**
     * Return the other axis based on either the axis option or on related
     * series.
     * @private
     */
    function getAxis(coll) {
        var otherColl = coll === 'xAxis' ? 'yAxis' : 'xAxis', opt = axis.options[otherColl];
        // Other axis indexed by number
        if (isNumber(opt)) {
            return [chart[otherColl][opt]];
        }
        // Other axis indexed by id (like navigator)
        if (isString(opt)) {
            return [chart.get(opt)];
        }
        // Auto detect based on existing series
        return series.map(function (s) {
            return s[otherColl];
        });
    }
    if ( // For stock chart, by default render paths across the panes
    // except the case when `acrossPanes` is disabled by user (#6644)
    (chart.options.isStock && e.acrossPanes !== false) &&
        // Ignore in case of colorAxis or zAxis. #3360, #3524, #6720
        axis.coll === 'xAxis' || axis.coll === 'yAxis') {
        e.preventDefault();
        // Get the related axes based on series
        axes = getAxis(axis.coll);
        // Get the related axes based options.*Axis setting #2810
        axes2 = (axis.isXAxis ? chart.yAxis : chart.xAxis);
        axes2.forEach(function (A) {
            if (defined(A.options.id) ?
                A.options.id.indexOf('navigator') === -1 :
                true) {
                var a = (A.isXAxis ? 'yAxis' : 'xAxis'), rax = (defined(A.options[a]) ?
                    chart[a][A.options[a]] :
                    chart[a][0]);
                if (axis === rax) {
                    axes.push(A);
                }
            }
        });
        // Remove duplicates in the axes array. If there are no axes in the axes
        // array, we are adding an axis without data, so we need to populate
        // this with grid lines (#2796).
        uniqueAxes = axes.length ?
            [] :
            [axis.isXAxis ? chart.yAxis[0] : chart.xAxis[0]]; // #3742
        axes.forEach(function (axis2) {
            if (uniqueAxes.indexOf(axis2) === -1 &&
                // Do not draw on axis which overlap completely. #5424
                !find(uniqueAxes, function (unique) {
                    return unique.pos === axis2.pos && unique.len === axis2.len;
                })) {
                uniqueAxes.push(axis2);
            }
        });
        transVal = pick(translatedValue, axis.translate(value, null, null, e.old));
        if (isNumber(transVal)) {
            if (axis.horiz) {
                uniqueAxes.forEach(function (axis2) {
                    var skip;
                    y1 = axis2.pos;
                    y2 = y1 + axis2.len;
                    x1 = x2 = Math.round(transVal + axis.transB);
                    // outside plot area
                    if (force !== 'pass' &&
                        (x1 < axisLeft || x1 > axisLeft + axis.width)) {
                        if (force) {
                            x1 = x2 = clamp(x1, axisLeft, axisLeft + axis.width);
                        }
                        else {
                            skip = true;
                        }
                    }
                    if (!skip) {
                        result.push(['M', x1, y1], ['L', x2, y2]);
                    }
                });
            }
            else {
                uniqueAxes.forEach(function (axis2) {
                    var skip;
                    x1 = axis2.pos;
                    x2 = x1 + axis2.len;
                    y1 = y2 = Math.round(axisTop + axis.height - transVal);
                    // outside plot area
                    if (force !== 'pass' &&
                        (y1 < axisTop || y1 > axisTop + axis.height)) {
                        if (force) {
                            y1 = y2 = clamp(y1, axisTop, axisTop + axis.height);
                        }
                        else {
                            skip = true;
                        }
                    }
                    if (!skip) {
                        result.push(['M', x1, y1], ['L', x2, y2]);
                    }
                });
            }
        }
        e.path = result.length > 0 ?
            renderer.crispPolyLine(result, e.lineWidth || 1) :
            // #3557 getPlotLinePath in regular Highcharts also returns null
            null;
    }
});
/**
 * Function to crisp a line with multiple segments
 *
 * @private
 * @function Highcharts.SVGRenderer#crispPolyLine
 * @param {Highcharts.SVGPathArray} points
 * @param {number} width
 * @return {Highcharts.SVGPathArray}
 */
SVGRenderer.prototype.crispPolyLine = function (points, width) {
    // points format: [['M', 0, 0], ['L', 100, 0]]
    // normalize to a crisp line
    for (var i = 0; i < points.length; i = i + 2) {
        var start = points[i], end = points[i + 1];
        if (start[1] === end[1]) {
            // Substract due to #1129. Now bottom and left axis gridlines behave
            // the same.
            start[1] = end[1] =
                Math.round(start[1]) - (width % 2 / 2);
        }
        if (start[2] === end[2]) {
            start[2] = end[2] =
                Math.round(start[2]) + (width % 2 / 2);
        }
    }
    return points;
};
// Wrapper to hide the label
addEvent(Axis, 'afterHideCrosshair', function () {
    if (this.crossLabel) {
        this.crossLabel = this.crossLabel.hide();
    }
});
// Extend crosshairs to also draw the label
addEvent(Axis, 'afterDrawCrosshair', function (event) {
    // Check if the label has to be drawn
    if (!this.crosshair ||
        !this.crosshair.label ||
        !this.crosshair.label.enabled ||
        !this.cross ||
        !isNumber(this.min) ||
        !isNumber(this.max)) {
        return;
    }
    var chart = this.chart, log = this.logarithmic, options = this.crosshair.label, // the label's options
    horiz = this.horiz, // axis orientation
    opposite = this.opposite, // axis position
    left = this.left, // left position
    top = this.top, // top position
    crossLabel = this.crossLabel, // the svgElement
    posx, posy, crossBox, formatOption = options.format, formatFormat = '', limit, align, tickInside = this.options.tickPosition === 'inside', snap = this.crosshair.snap !== false, offset = 0,
    // Use last available event (#5287)
    e = event.e || (this.cross && this.cross.e), point = event.point, min = this.min, max = this.max;
    if (log) {
        min = log.lin2log(min);
        max = log.lin2log(max);
    }
    align = (horiz ? 'center' : opposite ?
        (this.labelAlign === 'right' ? 'right' : 'left') :
        (this.labelAlign === 'left' ? 'left' : 'center'));
    // If the label does not exist yet, create it.
    if (!crossLabel) {
        crossLabel = this.crossLabel = chart.renderer
            .label('', 0, void 0, options.shape || 'callout')
            .addClass('highcharts-crosshair-label highcharts-color-' + (point ?
            point.series.colorIndex :
            this.series[0] && this.series[0].colorIndex))
            .attr({
            align: options.align || align,
            padding: pick(options.padding, 8),
            r: pick(options.borderRadius, 3),
            zIndex: 2
        })
            .add(this.labelGroup);
        // Presentational
        if (!chart.styledMode) {
            crossLabel
                .attr({
                fill: options.backgroundColor ||
                    point && point.series && point.series.color || // #14888
                    Palette.neutralColor60,
                stroke: options.borderColor || '',
                'stroke-width': options.borderWidth || 0
            })
                .css(extend({
                color: Palette.backgroundColor,
                fontWeight: 'normal',
                fontSize: '11px',
                textAlign: 'center'
            }, options.style || {}));
        }
    }
    if (horiz) {
        posx = snap ? (point.plotX || 0) + left : e.chartX;
        posy = top + (opposite ? 0 : this.height);
    }
    else {
        posx = opposite ? this.width + left : 0;
        posy = snap ? (point.plotY || 0) + top : e.chartY;
    }
    if (!formatOption && !options.formatter) {
        if (this.dateTime) {
            formatFormat = '%b %d, %Y';
        }
        formatOption =
            '{value' + (formatFormat ? ':' + formatFormat : '') + '}';
    }
    // Show the label
    var value = snap ?
        (this.isXAxis ? point.x : point.y) :
        this.toValue(horiz ? e.chartX : e.chartY);
    // Crosshair should be rendered within Axis range (#7219). Also, the point
    // of currentPriceIndicator should be inside the plot area, #14879.
    var isInside = point ?
        point.series.isPointInside(point) :
        (isNumber(value) && value > min && value < max);
    var text = '';
    if (formatOption) {
        text = format(formatOption, { value: value }, chart);
    }
    else if (options.formatter && isNumber(value)) {
        text = options.formatter.call(this, value);
    }
    crossLabel.attr({
        text: text,
        x: posx,
        y: posy,
        visibility: isInside ? 'visible' : 'hidden'
    });
    crossBox = crossLabel.getBBox();
    // now it is placed we can correct its position
    if (isNumber(crossLabel.y)) {
        if (horiz) {
            if ((tickInside && !opposite) || (!tickInside && opposite)) {
                posy = crossLabel.y - crossBox.height;
            }
        }
        else {
            posy = crossLabel.y - (crossBox.height / 2);
        }
    }
    // check the edges
    if (horiz) {
        limit = {
            left: left - crossBox.x,
            right: left + this.width - crossBox.x
        };
    }
    else {
        limit = {
            left: this.labelAlign === 'left' ? left : 0,
            right: this.labelAlign === 'right' ?
                left + this.width :
                chart.chartWidth
        };
    }
    // left edge
    if (crossLabel.translateX < limit.left) {
        offset = limit.left - crossLabel.translateX;
    }
    // right edge
    if (crossLabel.translateX + crossBox.width >= limit.right) {
        offset = -(crossLabel.translateX + crossBox.width - limit.right);
    }
    // show the crosslabel
    crossLabel.attr({
        x: posx + offset,
        y: posy,
        // First set x and y, then anchorX and anchorY, when box is actually
        // calculated, #5702
        anchorX: horiz ?
            posx :
            (this.opposite ? 0 : chart.chartWidth),
        anchorY: horiz ?
            (this.opposite ? chart.chartHeight : 0) :
            posy + crossBox.height / 2
    });
});
/* ************************************************************************** *
 *  Start value compare logic                                                 *
 * ************************************************************************** */
/**
 * Extend series.init by adding a method to modify the y value used for plotting
 * on the y axis. This method is called both from the axis when finding dataMin
 * and dataMax, and from the series.translate method.
 *
 * @ignore
 * @function Highcharts.Series#init
 */
Series.prototype.init = function () {
    // Call base method
    seriesInit.apply(this, arguments);
    // Set comparison mode
    this.initCompare(this.options.compare);
};
/**
 * Highcharts Stock only. Set the
 * [compare](https://api.highcharts.com/highstock/plotOptions.series.compare)
 * mode of the series after render time. In most cases it is more useful running
 * {@link Axis#setCompare} on the X axis to update all its series.
 *
 * @function Highcharts.Series#setCompare
 *
 * @param {string} [compare]
 *        Can be one of `null` (default), `"percent"` or `"value"`.
 */
Series.prototype.setCompare = function (compare) {
    this.initCompare(compare);
    // Survive to export, #5485
    this.userOptions.compare = compare;
};
/**
 * @ignore
 * @function Highcharts.Series#initCompare
 *
 * @param {string} [compare]
 *        Can be one of `null` (default), `"percent"` or `"value"`.
 */
Series.prototype.initCompare = function (compare) {
    // Set or unset the modifyValue method
    this.modifyValue = (compare === 'value' || compare === 'percent') ?
        function (value, point) {
            var compareValue = this.compareValue;
            if (typeof value !== 'undefined' &&
                typeof compareValue !== 'undefined') { // #2601, #5814
                // Get the modified value
                if (compare === 'value') {
                    value -= compareValue;
                    // Compare percent
                }
                else {
                    value = 100 * (value / compareValue) -
                        (this.options.compareBase === 100 ? 0 : 100);
                }
                // record for tooltip etc.
                if (point) {
                    point.change = value;
                }
                return value;
            }
            return 0;
        } :
        null;
    // Mark dirty
    if (this.chart.hasRendered) {
        this.isDirty = true;
    }
};
/**
 * Based on the data grouping options decides whether
 * the data should be cropped while processing.
 *
 * @ignore
 * @function Highcharts.Series#forceCropping
 */
Series.prototype.forceCropping = function () {
    var chart = this.chart, options = this.options, dataGroupingOptions = options.dataGrouping, groupingEnabled = this.allowDG !== false && dataGroupingOptions &&
        pick(dataGroupingOptions.enabled, chart.options.isStock);
    return groupingEnabled;
};
/**
 * Extend series.processData by finding the first y value in the plot area,
 * used for comparing the following values
 *
 * @ignore
 * @function Highcharts.Series#processData
 */
Series.prototype.processData = function (force) {
    var series = this, i, keyIndex = -1, processedXData, processedYData, compareStart = series.options.compareStart === true ? 0 : 1, length, compareValue;
    // call base method
    seriesProcessData.apply(this, arguments);
    if (series.xAxis && series.processedYData) { // not pies
        // local variables
        processedXData = series.processedXData;
        processedYData = series.processedYData;
        length = processedYData.length;
        // For series with more than one value (range, OHLC etc), compare
        // against close or the pointValKey (#4922, #3112, #9854)
        if (series.pointArrayMap) {
            keyIndex = series.pointArrayMap.indexOf(series.options.pointValKey || series.pointValKey || 'y');
        }
        // find the first value for comparison
        for (i = 0; i < length - compareStart; i++) {
            compareValue = processedYData[i] && keyIndex > -1 ?
                processedYData[i][keyIndex] :
                processedYData[i];
            if (isNumber(compareValue) &&
                processedXData[i + compareStart] >=
                    series.xAxis.min &&
                compareValue !== 0) {
                series.compareValue = compareValue;
                break;
            }
        }
    }
    return;
};
// Modify series extremes
addEvent(Series, 'afterGetExtremes', function (e) {
    var dataExtremes = e.dataExtremes;
    if (this.modifyValue && dataExtremes) {
        var extremes = [
            this.modifyValue(dataExtremes.dataMin),
            this.modifyValue(dataExtremes.dataMax)
        ];
        dataExtremes.dataMin = arrayMin(extremes);
        dataExtremes.dataMax = arrayMax(extremes);
    }
});
/**
 * Highcharts Stock only. Set the compare mode on all series
 * belonging to an Y axis after render time.
 *
 * @see [series.plotOptions.compare](https://api.highcharts.com/highstock/series.plotOptions.compare)
 *
 * @sample stock/members/axis-setcompare/
 *         Set compoare
 *
 * @function Highcharts.Axis#setCompare
 *
 * @param {string} [compare]
 *        The compare mode. Can be one of `null` (default), `"value"` or
 *        `"percent"`.
 *
 * @param {boolean} [redraw=true]
 *        Whether to redraw the chart or to wait for a later call to
 *        {@link Chart#redraw}.
 */
Axis.prototype.setCompare = function (compare, redraw) {
    if (!this.isXAxis) {
        this.series.forEach(function (series) {
            series.setCompare(compare);
        });
        if (pick(redraw, true)) {
            this.chart.redraw();
        }
    }
};
/**
 * Extend the tooltip formatter by adding support for the point.change variable
 * as well as the changeDecimals option.
 *
 * @ignore
 * @function Highcharts.Point#tooltipFormatter
 *
 * @param {string} pointFormat
 */
Point.prototype.tooltipFormatter = function (pointFormat) {
    var point = this;
    var numberFormatter = point.series.chart.numberFormatter;
    pointFormat = pointFormat.replace('{point.change}', (point.change > 0 ? '+' : '') + numberFormatter(point.change, pick(point.series.tooltipOptions.changeDecimals, 2)));
    return pointTooltipFormatter.apply(this, [pointFormat]);
};
/* ************************************************************************** *
 *  End value compare logic                                                   *
 * ************************************************************************** */
// Extend the Series prototype to create a separate series clip box. This is
// related to using multiple panes, and a future pane logic should incorporate
// this feature (#2754).
addEvent(Series, 'render', function () {
    var chart = this.chart, clipHeight;
    // Only do this on not 3d (#2939, #5904) nor polar (#6057) charts, and only
    // if the series type handles clipping in the animate method (#2975).
    if (!(chart.is3d && chart.is3d()) &&
        !chart.polar &&
        this.xAxis &&
        !this.xAxis.isRadial && // Gauge, #6192
        this.options.clip !== false // #15128
    ) {
        clipHeight = this.yAxis.len;
        // Include xAxis line width (#8031) but only if the Y axis ends on the
        // edge of the X axis (#11005).
        if (this.xAxis.axisLine) {
            var dist = chart.plotTop + chart.plotHeight -
                this.yAxis.pos - this.yAxis.len, lineHeightCorrection = Math.floor(this.xAxis.axisLine.strokeWidth() / 2);
            if (dist >= 0) {
                clipHeight -= Math.max(lineHeightCorrection - dist, 0);
            }
        }
        // First render, initial clip box. clipBox also needs to be updated if
        // the series is rendered again before starting animating, in
        // compliance with a responsive rule (#13858).
        if (!chart.hasLoaded || (!this.clipBox && this.isDirty && !this.isDirtyData)) {
            this.clipBox = this.clipBox || merge(chart.clipBox);
            this.clipBox.width = this.xAxis.len;
            this.clipBox.height = clipHeight;
        }
        if (chart.hasRendered) {
            var animation = animObject(this.options.animation);
            // #15435: this.sharedClipKey might not have been set yet, for
            // example when updating the series, so we need to use this
            // function instead
            var sharedClipKey = this.getSharedClipKey(animation);
            var clipRect = chart.sharedClips[sharedClipKey];
            // On redrawing, resizing etc, update the clip rectangle.
            //
            // #15435: Update it even when we are creating/updating clipBox,
            // since there could be series updating and pane size changes
            // happening at the same time and we dont destroy shared clips in
            // stock.
            if (clipRect) {
                // animate in case resize is done during initial animation
                clipRect.animate({
                    width: this.xAxis.len,
                    height: clipHeight
                });
                var markerClipRect = chart.sharedClips[sharedClipKey + 'm'];
                // also change markers clip animation for consistency
                // (marker clip rects should exist only on chart init)
                if (markerClipRect) {
                    markerClipRect.animate({
                        width: this.xAxis.len
                    });
                }
            }
        }
    }
});
addEvent(Chart, 'update', function (e) {
    var options = e.options;
    // Use case: enabling scrollbar from a disabled state.
    // Scrollbar needs to be initialized from a controller, Navigator in this
    // case (#6615)
    if ('scrollbar' in options && this.navigator) {
        merge(true, this.options.scrollbar, options.scrollbar);
        this.navigator.update({}, false);
        delete options.scrollbar;
    }
});
/* *
 *
 *  Default Export
 *
 * */
export default StockChart;
/* *
 *
 *  API Options
 *
 * */
/**
 * Compare the values of the series against the first non-null, non-
 * zero value in the visible range. The y axis will show percentage
 * or absolute change depending on whether `compare` is set to `"percent"`
 * or `"value"`. When this is applied to multiple series, it allows
 * comparing the development of the series against each other. Adds
 * a `change` field to every point object.
 *
 * @see [compareBase](#plotOptions.series.compareBase)
 * @see [Axis.setCompare()](/class-reference/Highcharts.Axis#setCompare)
 *
 * @sample {highstock} stock/plotoptions/series-compare-percent/
 *         Percent
 * @sample {highstock} stock/plotoptions/series-compare-value/
 *         Value
 *
 * @type      {string}
 * @since     1.0.1
 * @product   highstock
 * @apioption plotOptions.series.compare
 */
/**
 * Defines if comparison should start from the first point within the visible
 * range or should start from the first point **before** the range.
 *
 * In other words, this flag determines if first point within the visible range
 * will have 0% (`compareStart=true`) or should have been already calculated
 * according to the previous point (`compareStart=false`).
 *
 * @sample {highstock} stock/plotoptions/series-comparestart/
 *         Calculate compare within visible range
 *
 * @type      {boolean}
 * @default   false
 * @since     6.0.0
 * @product   highstock
 * @apioption plotOptions.series.compareStart
 */
/**
 * When [compare](#plotOptions.series.compare) is `percent`, this option
 * dictates whether to use 0 or 100 as the base of comparison.
 *
 * @sample {highstock} stock/plotoptions/series-comparebase/
 *         Compare base is 100
 *
 * @type       {number}
 * @default    0
 * @since      5.0.6
 * @product    highstock
 * @validvalue [0, 100]
 * @apioption  plotOptions.series.compareBase
 */
''; // keeps doclets above in transpiled file


text:
/* The original from which this derives bore the following: */

/*

   Derby - Class org.apache.derby.iapi.sql.StatementType

   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to you 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.

 */

package com.bj58.sql.parser;

/**
 * Different types of statements
 *
 */
public interface StatementType
{
    // TODO: A bunch of separate enums.

    public static final int UNKNOWN = 0;
    public static final int INSERT = 1;
    public static final int BULK_INSERT_REPLACE = 2;
    public static final int UPDATE = 3;
    public static final int DELETE = 4;
    public static final int ENABLED = 5;
    public static final int DISABLED = 6;

    public static final int DROP_CASCADE = 0;
    public static final int DROP_RESTRICT = 1;
    public static final int DROP_DEFAULT = 2;

    public static final int RA_CASCADE = 0;
    public static final int RA_RESTRICT = 1;
    public static final int RA_NOACTION = 2;    //default value
    public static final int RA_SETNULL = 3;
    public static final int RA_SETDEFAULT = 4;

    public static final int SET_SCHEMA_USER = 1;
    public static final int SET_SCHEMA_DYNAMIC = 2;

    public static final int SET_ROLE_DYNAMIC = 1;

}


text:
// source:

package test.vrs.vfs;

import org.junit.Before;

import test.TestSettings;
import test.TestSettings.TestLocation;
import nl.esciencecenter.vbrowser.vrs.vrl.VRL;
import nl.esciencecenter.vlet.vrs.ServerInfo;
//import nl.uva.vlet.gui.dialog.AuthenticationDialog;

/**
 * SRM.
 *
 */
public class TestVFS_SRMsara extends TestVFS_SRM
{
    static private ServerInfo info;

    static
    {
        TestVFS_LocalFS.initLocalFS();
    }

    public TestVFS_SRMsara()
    {
        // this.doRename=false;
        // this.doWrites=false;
    }

    @Override
    public VRL getRemoteLocation()
    {
        return TestSettings.getTestLocation(TestLocation.VFS_SRM_DCACHE_SARA_LOCATION);
    }

    @Before
    public void testSetup()
    {

    }

}