text:
package org.springframework.boot.rsocket.netty;

import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.Arrays;

import io.netty.buffer.PooledByteBufAllocator;
import io.rsocket.AbstractRSocket;
import io.rsocket.ConnectionSetupPayload;
import io.rsocket.Payload;
import io.rsocket.RSocket;
import io.rsocket.RSocketFactory;
import io.rsocket.SocketAcceptor;
import io.rsocket.transport.netty.client.TcpClientTransport;
import io.rsocket.transport.netty.client.WebsocketClientTransport;
import io.rsocket.util.DefaultPayload;
import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InOrder;
import reactor.core.publisher.Mono;

import org.springframework.boot.rsocket.server.RSocketServer;
import org.springframework.boot.rsocket.server.ServerRSocketFactoryCustomizer;
import org.springframework.boot.testsupport.rule.OutputCapture;
import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.core.codec.StringDecoder;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.messaging.rsocket.RSocketRequester;
import org.springframework.messaging.rsocket.RSocketStrategies;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.SocketUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;

/**
 * Tests for {@link NettyRSocketServerFactory}
 *
 * @author Brian Clozel
 */
public class NettyRSocketServerFactoryTests {

	@Rule
	public OutputCapture output = new OutputCapture();

	private NettyRSocketServer rSocketServer;

	private RSocketRequester requester;

	private static final Duration TIMEOUT = Duration.ofSeconds(3);

	@After
	public void tearDown() {
		if (this.rSocketServer != null) {
			try {
				this.rSocketServer.stop();
			}
			catch (Exception ex) {
				// Ignore
			}
		}
		if (this.requester != null) {
			this.requester.rsocket().dispose();
		}
	}

	private NettyRSocketServerFactory getFactory() {
		return new NettyRSocketServerFactory();
	}

	@Test
	public void specificPort() {
		NettyRSocketServerFactory factory = getFactory();
		int specificPort = SocketUtils.findAvailableTcpPort(41000);
		factory.setPort(specificPort);
		this.rSocketServer = factory.create(new EchoRequestResponseAcceptor());
		this.rSocketServer.start();
		this.requester = getRSocketRequester(createRSocketTcpClient());
		String payload = "test payload";
		String response = this.requester.route("test").data(payload)
				.retrieveMono(String.class).block(TIMEOUT);

		assertThat(response).isEqualTo(payload);
		assertThat(this.rSocketServer.address().getPort()).isEqualTo(specificPort);
	}

	@Test
	public void websocketTransport() {
		NettyRSocketServerFactory factory = getFactory();
		factory.setTransport(RSocketServer.TRANSPORT.WEBSOCKET);
		this.rSocketServer = factory.create(new EchoRequestResponseAcceptor());
		this.rSocketServer.start();
		this.requester = getRSocketRequester(createRSocketWebSocketClient());
		String payload = "test payload";
		String response = this.requester.route("test").data(payload)
				.retrieveMono(String.class).block(TIMEOUT);
		assertThat(response).isEqualTo(payload);
	}

	@Test
	public void serverCustomizers() {
		NettyRSocketServerFactory factory = getFactory();
		ServerRSocketFactoryCustomizer[] customizers = new ServerRSocketFactoryCustomizer[2];
		for (int i = 0; i < customizers.length; i++) {
			customizers[i] = mock(ServerRSocketFactoryCustomizer.class);
			given(customizers[i].apply(any(RSocketFactory.ServerRSocketFactory.class)))
					.will((invocation) -> invocation.getArgument(0));
		}
		factory.setServerCustomizers(Arrays.asList(customizers[0], customizers[1]));
		this.rSocketServer = factory.create(new EchoRequestResponseAcceptor());
		InOrder ordered = inOrder((Object[]) customizers);
		for (ServerRSocketFactoryCustomizer customizer : customizers) {
			ordered.verify(customizer)
					.apply(any(RSocketFactory.ServerRSocketFactory.class));
		}
	}

	private RSocket createRSocketTcpClient() {
		Assertions.assertThat(this.rSocketServer).isNotNull();
		InetSocketAddress address = this.rSocketServer.address();
		return RSocketFactory.connect().dataMimeType(MimeTypeUtils.TEXT_PLAIN_VALUE)
				.transport(TcpClientTransport.create(address)).start().block();
	}

	private RSocket createRSocketWebSocketClient() {
		Assertions.assertThat(this.rSocketServer).isNotNull();
		InetSocketAddress address = this.rSocketServer.address();
		return RSocketFactory.connect().dataMimeType(MimeTypeUtils.TEXT_PLAIN_VALUE)
				.transport(WebsocketClientTransport.create(address)).start().block();
	}

	private RSocketRequester getRSocketRequester(RSocket rSocketClient) {
		RSocketStrategies strategies = RSocketStrategies.builder()
				.decoder(StringDecoder.allMimeTypes())
				.encoder(CharSequenceEncoder.allMimeTypes())
				.dataBufferFactory(
						new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT))
				.build();
		return RSocketRequester.create(rSocketClient, MimeTypeUtils.TEXT_PLAIN,
				strategies);
	}

	static class EchoRequestResponseAcceptor implements SocketAcceptor {

		@Override
		public Mono<RSocket> accept(ConnectionSetupPayload setupPayload,
				RSocket rSocket) {
			return Mono.just(new AbstractRSocket() {
				@Override
				public Mono<Payload> requestResponse(Payload payload) {
					return Mono.just(DefaultPayload.create(payload));
				}
			});
		}

	}

}


text:
//-----------------------------------------------------------------------
// <copyright file="WriteAggregatorSpec.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Akka.Actor;
using Akka.Configuration;
using Akka.DistributedData.Internal;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;

namespace Akka.DistributedData.Tests
{
    [Collection("DistributedDataSpec")]
    public class WriteAggregatorSpec : Akka.TestKit.Xunit2.TestKit
    {
        internal class TestWriteAggregator<T> : WriteAggregator where T : IReplicatedData
        {
            private readonly IImmutableDictionary<Address, IActorRef> _probes;

            public TestWriteAggregator(
                IKey<T> key,
                T data,
                Delta delta,
                IWriteConsistency consistency,
                IImmutableDictionary<Address, IActorRef> probes,
                IImmutableSet<Address> nodes,
                IImmutableSet<Address> unreachable,
                IActorRef replyTo,
                bool durable)
                : base(key, new DataEnvelope(data), delta, consistency, null, nodes, unreachable, replyTo, durable)
            {
                _probes = probes;
            }

            protected override ActorSelection Replica(Address address) => Context.ActorSelection(_probes[address].Path);
            protected override Address SenderAddress => _probes.First(kv => Equals(kv.Value, Sender)).Key;
        }

        internal class WriteAckAdapter : ReceiveActor
        {
            public WriteAckAdapter(IActorRef replica)
            {
                IActorRef replicator = null;
                Receive<WriteAck>(ack => replicator?.Tell(ack));
                Receive<WriteNack>(ack => replicator?.Tell(ack));
                Receive<DeltaNack>(ack => replicator?.Tell(ack));
                ReceiveAny(msg =>
                {
                    replicator = Sender;
                    replica.Tell(msg);
                });
            }
        }

        private static Props TestWriteAggregatorProps(GSet<string> data,
            IWriteConsistency consistency,
            IImmutableDictionary<Address, IActorRef> probes,
            IImmutableSet<Address> nodes,
            IImmutableSet<Address> unreachable,
            IActorRef replyTo,
            bool durable) => Actor.Props.Create(() => new TestWriteAggregator<GSet<string>>(KeyA, data, null, consistency, probes, nodes, unreachable, replyTo, durable));

        private static Props TestWriteAggregatorPropsWithDelta(ORSet<string> data,
            Delta delta,
            IWriteConsistency consistency,
            IImmutableDictionary<Address, IActorRef> probes,
            IImmutableSet<Address> nodes,
            IImmutableSet<Address> unreachable,
            IActorRef replyTo,
            bool durable) => Actor.Props.Create(() => new TestWriteAggregator<ORSet<string>>(KeyB, data, delta, consistency, probes, nodes, unreachable, replyTo, durable));

        private static readonly GSetKey<string> KeyA = new GSetKey<string>("a");
        private static readonly ORSetKey<string> KeyB = new ORSetKey<string>("b");

        private readonly Address _nodeA = new Address("akka.tcp", "Sys", "a", 2552);
        private readonly Address _nodeB = new Address("akka.tcp", "Sys", "b", 2552);
        private readonly Address _nodeC = new Address("akka.tcp", "Sys", "c", 2552);
        private readonly Address _nodeD = new Address("akka.tcp", "Sys", "d", 2552);
        private readonly IImmutableSet<Address> _nodes;

        private readonly GSet<string> _data = GSet.Create("A", "B");
        private readonly WriteTo _writeThree = new WriteTo(3, TimeSpan.FromSeconds(3));
        private readonly WriteMajority _writeMajority = new WriteMajority(TimeSpan.FromSeconds(3));
        private readonly WriteAll _writeAll;

        private readonly ORSet<string> _fullState1;
        private readonly ORSet<string> _fullState2;
        private readonly Delta _delta;

        public WriteAggregatorSpec(ITestOutputHelper output) : base(ConfigurationFactory.ParseString($@"
            akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
            akka.remote.dot-netty.tcp.port = 0
            akka.cluster.distributed-data.durable.lmdb {{
                dir = ""target/WriteAggregatorSpec-{DateTime.UtcNow.Ticks}-ddata""
                map-size = 10MiB
            }}"), "WriteAggregatorSpec", output)
        {
            _nodes = ImmutableHashSet.CreateRange(new[] {_nodeA, _nodeB, _nodeC, _nodeD});

            var cluster = Akka.Cluster.Cluster.Get(Sys);
            _fullState1 = ORSet<string>.Empty.Add(cluster, "a").Add(cluster, "b");
            _fullState2 = _fullState1.ResetDelta().Add(cluster, "c");
            _delta = new Delta(new DataEnvelope(_fullState2.Delta), 2L, 2L);
            _writeAll = new WriteAll(Dilated(TimeSpan.FromSeconds(3)));
        }

        [Fact]
        public void WriteAggregator_must_send_at_least_half_N_plus_1_replicas_when_WriteMajority()
        {
            var probe = CreateTestProbe();
            var aggregator = Sys.ActorOf(TestWriteAggregatorProps(_data, _writeMajority, Probes(probe.Ref), _nodes, ImmutableHashSet<Address>.Empty, TestActor, false));

            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            ExpectMsg(new UpdateSuccess(KeyA, null));
            Watch(aggregator);
            ExpectTerminated(aggregator);
        }

        [Fact]
        public void WriteAggregator_must_send_to_more_when_no_immediate_reply()
        {
            var probe = CreateTestProbe();
            var aggregator = Sys.ActorOf(TestWriteAggregatorProps(_data, _writeMajority, Probes(probe.Ref), _nodes, ImmutableHashSet<Address>.Empty, TestActor, false));

            probe.ExpectMsg<Write>();
            // no reply
            probe.ExpectMsg<Write>();
            // no reply
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            ExpectMsg(new UpdateSuccess(KeyA, null));
            Watch(aggregator);
            ExpectTerminated(aggregator);
        }

        [Fact]
        public void WriteAggregator_must_timeout_when_less_than_required_ACKs()
        {
            var probe = CreateTestProbe();
            var aggregator = Sys.ActorOf(TestWriteAggregatorProps(_data, _writeMajority, Probes(probe.Ref), _nodes, ImmutableHashSet<Address>.Empty, TestActor, false));

            probe.ExpectMsg<Write>();
            // no reply
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<Write>();
            // no reply
            probe.ExpectMsg<Write>();
            // no reply

            Within(Dilated(TimeSpan.FromSeconds(10)), () => // have to pad the time here, since default timeout is ~3s which is also default wait time
            {
                ExpectMsg(new UpdateTimeout(KeyA, null));
                Watch(aggregator);
                ExpectTerminated(aggregator);
            });

        }

        [Fact]
        public void WriteAggregator_must_callculate_majority_with_min_capactiy()
        {
            var minCap = 5;

            ReadWriteAggregator.CalculateMajorityWithMinCapacity(minCap, 3).Should().Be(3);
            ReadWriteAggregator.CalculateMajorityWithMinCapacity(minCap, 4).Should().Be(4);
            ReadWriteAggregator.CalculateMajorityWithMinCapacity(minCap, 5).Should().Be(5);
            ReadWriteAggregator.CalculateMajorityWithMinCapacity(minCap, 6).Should().Be(5);
            ReadWriteAggregator.CalculateMajorityWithMinCapacity(minCap, 7).Should().Be(5);
            ReadWriteAggregator.CalculateMajorityWithMinCapacity(minCap, 8).Should().Be(5);
            ReadWriteAggregator.CalculateMajorityWithMinCapacity(minCap, 9).Should().Be(5);
            ReadWriteAggregator.CalculateMajorityWithMinCapacity(minCap, 10).Should().Be(6);
            ReadWriteAggregator.CalculateMajorityWithMinCapacity(minCap, 11).Should().Be(6);
            ReadWriteAggregator.CalculateMajorityWithMinCapacity(minCap, 12).Should().Be(7);
        }

        [Fact]
        public void WriteAggregator_with_delta_must_send_delta_first()
        {
            var probe = CreateTestProbe();
            var aggregator = Sys.ActorOf(TestWriteAggregatorPropsWithDelta(_fullState2, _delta, _writeMajority, Probes(probe.Ref), _nodes, ImmutableHashSet<Address>.Empty, TestActor, false));

            Watch(aggregator);

            probe.ExpectMsg<DeltaPropagation>();
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<DeltaPropagation>();
            probe.LastSender.Tell(WriteAck.Instance);
            ExpectMsg(new UpdateSuccess(KeyB, null));

            ExpectTerminated(aggregator);
        }

        [Fact]
        public void WriteAggregator_with_delta_must_retry_with_full_state_when_no_immediate_reply_or_nack()
        {
            var testProbes = Probes();
            var testProbeRefs = testProbes.ToImmutableDictionary(kv => kv.Key, kv => kv.Value.Item2);
            var aggregator = Sys.ActorOf(TestWriteAggregatorPropsWithDelta(_fullState2, _delta, _writeAll, testProbeRefs, _nodes, ImmutableHashSet<Address>.Empty, TestActor, false));

            Watch(aggregator);

            testProbes[_nodeA].Item1.ExpectMsg<DeltaPropagation>();
            // no reply
            testProbes[_nodeB].Item1.ExpectMsg<DeltaPropagation>();
            testProbes[_nodeB].Item1.LastSender.Tell(WriteAck.Instance);
            testProbes[_nodeC].Item1.ExpectMsg<DeltaPropagation>();
            testProbes[_nodeC].Item1.LastSender.Tell(WriteAck.Instance);
            testProbes[_nodeD].Item1.ExpectMsg<DeltaPropagation>();
            testProbes[_nodeD].Item1.LastSender.Tell(DeltaNack.Instance);

            // second round
            testProbes[_nodeA].Item1.ExpectMsg<Write>();
            testProbes[_nodeA].Item1.LastSender.Tell(WriteAck.Instance);
            testProbes[_nodeD].Item1.ExpectMsg<Write>();
            testProbes[_nodeD].Item1.LastSender.Tell(WriteAck.Instance);
            testProbes[_nodeB].Item1.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
            testProbes[_nodeC].Item1.ExpectNoMsg(TimeSpan.FromMilliseconds(100));

            ExpectMsg(new UpdateSuccess(KeyB, null));
            ExpectTerminated(aggregator);
        }

        [Fact]
        public void WriteAggregator_with_delta_must_timeout_when_less_than_required_ACKs()
        {
            var probe = CreateTestProbe();
            var aggregator = Sys.ActorOf(TestWriteAggregatorPropsWithDelta(_fullState2, _delta, _writeAll, Probes(probe.Ref), _nodes, ImmutableHashSet<Address>.Empty, TestActor, false));

            Watch(aggregator);

            probe.ExpectMsg<DeltaPropagation>();
            // no reply
            probe.ExpectMsg<DeltaPropagation>();
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<DeltaPropagation>();
            // nack
            probe.LastSender.Tell(DeltaNack.Instance);
            probe.ExpectMsg<DeltaPropagation>();
            // no reply

            // only 1 ack so we expect 3 full state Write
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<Write>();
            probe.ExpectMsg<Write>();

            // still not enough acks
            Within(Dilated(TimeSpan.FromSeconds(10)), () => // have to pad the time here, since default timeout is ~3s which is also default wait time
            {
                ExpectMsg(new UpdateTimeout(KeyB, null));
                ExpectTerminated(aggregator);
            });
        }

        [Fact]
        public void Durable_WriteAggregator_must_not_reply_before_local_confirmation()
        {
            var probe = CreateTestProbe();
            var aggregator = Sys.ActorOf(TestWriteAggregatorProps(_data, _writeThree, Probes(probe.Ref), _nodes, ImmutableHashSet<Address>.Empty, TestActor, true));
            Watch(aggregator);

            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            ExpectNoMsg(TimeSpan.FromMilliseconds(200));

            // the local write
            aggregator.Tell(new UpdateSuccess(KeyA, null));

            ExpectMsg(new UpdateSuccess(KeyA, null));
            ExpectTerminated(aggregator);
        }

        [Fact]
        public void Durable_WriteAggregator_must_tolerate_WriteNack_if_enough_WriteAck()
        {
            var probe = CreateTestProbe();
            var aggregator = Sys.ActorOf(TestWriteAggregatorProps(_data, _writeThree, Probes(probe.Ref), _nodes, ImmutableHashSet<Address>.Empty, TestActor, true));
            Watch(aggregator);

            aggregator.Tell(new UpdateSuccess(KeyA, null));
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteNack.Instance);
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);

            ExpectMsg(new UpdateSuccess(KeyA, null));
            ExpectTerminated(aggregator);
        }

        [Fact]
        public void Durable_WriteAggregator_must_reply_with_StoreFailure_when_too_many_nacks()
        {
            var probe = CreateTestProbe();
            var aggregator = Sys.ActorOf(TestWriteAggregatorProps(_data, _writeMajority, Probes(probe.Ref), _nodes, ImmutableHashSet<Address>.Empty, TestActor, true));
            Watch(aggregator);

            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteNack.Instance);
            aggregator.Tell(new UpdateSuccess(KeyA, null));
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteNack.Instance);
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteNack.Instance);

            ExpectMsg(new StoreFailure(KeyA, null));
            ExpectTerminated(aggregator);
        }

        [Fact]
        public void Durable_WriteAggregator_must_timeout_when_less_than_required_ACKs()
        {
            var probe = CreateTestProbe();
            var aggregator = Sys.ActorOf(TestWriteAggregatorProps(_data, _writeMajority, Probes(probe.Ref), _nodes, ImmutableHashSet<Address>.Empty, TestActor, true));
            Watch(aggregator);

            probe.ExpectMsg<Write>();
            // no reply
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteAck.Instance);
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteNack.Instance);
            probe.ExpectMsg<Write>();
            probe.LastSender.Tell(WriteNack.Instance);

            Within(Dilated(TimeSpan.FromSeconds(10)), () => // have to pad the time here, since default timeout is ~3s which is also default wait time
            {
                ExpectMsg(new UpdateTimeout(KeyA, null));
                ExpectTerminated(aggregator);
            });
        }

        private IImmutableDictionary<Address, IActorRef> Probes(IActorRef probe) =>
            _nodes.Select(address =>
                new KeyValuePair<Address, IActorRef>(
                    address,
                    Sys.ActorOf(Props.Create(() => new WriteAckAdapter(probe)))))
                .ToImmutableDictionary();

        private IImmutableDictionary<Address, (TestProbe, IActorRef)> Probes() =>
            _nodes.Select(address =>
                {
                    var probe = CreateTestProbe("probe-" + address.Host);
                    return new KeyValuePair<Address, (TestProbe, IActorRef)>(address,
                        (probe, Sys.ActorOf(Props.Create(() => new WriteAckAdapter(probe.Ref)))));
                })
                .ToImmutableDictionary();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!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" />

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <meta name="robots" content="static pages, follow" />
  <meta name="keywords" content="deepak gaur,prashant gaur,python; django  ,html ,website designing,consultancy ,website maintenance ." />

  <meta name="author" content="Administrator" />
  <meta name="description" content="prashant gaur." />

<title>static pages
</title>

<link href="css/style.css" rel="stylesheet" type="text/css" />

icckundli.com

CALL @ +91-8810093833

Welcome to Static Pages . we are newborn website development team for Website Designing and development .

Website Design plays a very important role in managing a business.

The success of an organization depends on its website . so we provide all kind of websites in PHP , JAVA , PYTHON ,.NET and many other platforms also .

we also provide life time maintenance at a  very low cost .

please call ur +91 8810093833 or  mail at deepak86gaur@gmail.com for any kind of website design and development .

   Contact Us:

   Mail Id : 	deepak86gaur@gmail.com

Phone No. :	 +91 8810093833

Copyright @ 2012 Indian Carrying Corporation  All right Reserved ||

website Designed and Maintained by- Static Page


text:
package io.cyberstock.tcdop.ssh.impl;

import com.jcraft.jsch.*;
import io.cyberstock.tcdop.ssh.SSHChannelWrapper;
import io.cyberstock.tcdop.ssh.SSHClientService;
import io.cyberstock.tcdop.ssh.SSHClientWrapper;
import io.cyberstock.tcdop.ssh.SSHSessionWrapper;
import io.cyberstock.tcdop.ssh.error.FatalSshError;

import java.io.InputStream;

/**
 * Created by beolnix on 17/08/15.
 */
public class SSHClientServiceImpl implements SSHClientService {

    // dependencies
    private final SSHClientWrapper jsch;
    private final Long connectionThreshold;
    private final Long attemptDelay;
    private final String ipv4;
    private final String user;

    // state
    private SSHSessionWrapper session;

    SSHClientServiceImpl(SSHClientWrapper jsch, Long connectionThreshold, Long attemptDelay, String ipv4, String user) {
        this.jsch = jsch;
        this.connectionThreshold = connectionThreshold;
        this.attemptDelay = attemptDelay;
        this.ipv4 = ipv4;
        this.user = user;
    }

    private void configureSession() throws FatalSshError {
        try {
            session = jsch.getSession(user, ipv4);

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
        } catch (JSchException e) {
            throw new FatalSshError("Can't configure ssh session.", e);
        }
    }

    private void establishConnection() throws FatalSshError {
        long start = System.currentTimeMillis();
        int attempts = 0;
        while (!session.isConnected()) {
            ++attempts;
            if ((System.currentTimeMillis() - start) > connectionThreshold) {
                throw new FatalSshError("Can't establish connection with " + ipv4 + " in " + connectionThreshold + " millis within " + attempts);
            }

            try {
                session.connect();
            } catch (JSchException e) {
                connectionDelay();
            }
        }
    }

    private void connectionDelay() {
        try {
            Thread.sleep(attemptDelay);
        } catch (InterruptedException ee) {
            //nop
        }
    }

    private void initIfRequired() throws FatalSshError {
        if (session == null) {
            configureSession();
        }

        if (!session.isConnected()) {
            session.disconnect();
            establishConnection();
        }
    }

    public String executeRemote(String command) throws FatalSshError {
        initIfRequired();

        String result = runCommand(command, session);

        return result;
    }

    private String runCommand(String command, SSHSessionWrapper session) {
        try {
            SSHChannelWrapper channel = session.openChannel("exec");
            channel.setCommand(command);

            channel.connect();

            InputStream inc = channel.getInputStream();

            byte[] tmp = new byte[1024];
            StringBuilder resultBuilder = new StringBuilder();
            while (true) {
                while (inc.available() > 0) {
                    int i = inc.read(tmp, 0, 1024);
                    if (i < 0) {
                        break;
                    }
                    resultBuilder.append(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ee) {
                    //nop
                }
            }
            channel.disconnect();
            return resultBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Hangman</title>

        <link rel="stylesheet" href="css/screen.css">
        <link href='https://fonts.googleapis.com/css?family=Droid+Sans+Mono|Cutive+Mono|Source+Code+Pro' rel='stylesheet' type='text/css'>

        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

                <canvas width="30" height="30" class="canvas" id="canvas"></canvas>

                       <button class="keyboard-key" id="q">q</button><button class="keyboard-key" id="w">w</button><button class="keyboard-key" id="e">e</button><button class="keyboard-key" id="r">r</button><button class="keyboard-key" id="t">t</button><button class="keyboard-key" id="y">y</button><button class="keyboard-key" id="u">u</button><button class="keyboard-key" id="i">i</button><button class="keyboard-key" id="o">o</button><button class="keyboard-key" id="p">p</button>

                       <button class="keyboard-key" id="a">a</button><button class="keyboard-key" id="s">s</button><button class="keyboard-key" id="d">d</button><button class="keyboard-key" id="f">f</button><button class="keyboard-key" id="g">g</button><button class="keyboard-key" id="h">h</button><button class="keyboard-key" id="j">j</button><button class="keyboard-key" id="k">k</button><button class="keyboard-key" id="l">l</button>

                       <button class="keyboard-key" id="z">z</button><button class="keyboard-key" id="x">x</button><button class="keyboard-key" id="c">c</button><button class="keyboard-key" id="v">v</button><button class="keyboard-key" id="b">b</button><button class="keyboard-key" id="n">n</button><button class="keyboard-key" id="m">m</button>


text:
package org.apache.flink.api.connector.source.lib;

import org.apache.flink.annotation.Public;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.connector.source.Boundedness;
import org.apache.flink.api.connector.source.Source;
import org.apache.flink.api.connector.source.SourceReader;
import org.apache.flink.api.connector.source.SourceReaderContext;
import org.apache.flink.api.connector.source.SplitEnumerator;
import org.apache.flink.api.connector.source.SplitEnumeratorContext;
import org.apache.flink.api.connector.source.lib.util.IteratorSourceEnumerator;
import org.apache.flink.api.connector.source.lib.util.IteratorSourceReader;
import org.apache.flink.api.connector.source.lib.util.IteratorSourceSplit;
import org.apache.flink.api.java.typeutils.ResultTypeQueryable;
import org.apache.flink.core.io.SimpleVersionedSerializer;
import org.apache.flink.core.memory.DataInputDeserializer;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputSerializer;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.util.NumberSequenceIterator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * A data source that produces a sequence of numbers (longs). This source is useful for testing and
 * for cases that just need a stream of N events of any kind.
 *
 *
The source splits the sequence into as many parallel sub-sequences as there are parallel
 * source readers. Each sub-sequence will be produced in order. Consequently, if the parallelism is
 * limited to one, this will produce one sequence in order.
 *
 *
This source is always bounded. For very long sequences (for example over the entire domain of
 * long integer values), user may want to consider executing the application in a streaming manner,
 * because, despite the fact that the produced stream is bounded, the end bound is pretty far away.
 */
@Public
public class NumberSequenceSource
        implements Source<
                        Long,
                        NumberSequenceSource.NumberSequenceSplit,
                        Collection<NumberSequenceSource.NumberSequenceSplit>>,
                ResultTypeQueryable<Long> {

    private static final long serialVersionUID = 1L;

    /** The starting number in the sequence, inclusive. */
    private final long from;

    /** The end number in the sequence, inclusive. */
    private final long to;

    /**
     * Creates a new {@code NumberSequenceSource} that produces parallel sequences covering the
     * range {@code from} to {@code to} (both boundaries are inclusive).
     */
    public NumberSequenceSource(long from, long to) {
        checkArgument(from <= to, "'from' must be <= 'to'");
        this.from = from;
        this.to = to;
    }

    public long getFrom() {
        return from;
    }

    public long getTo() {
        return to;
    }

    // ------------------------------------------------------------------------
    //  source methods
    // ------------------------------------------------------------------------

    @Override
    public TypeInformation<Long> getProducedType() {
        return Types.LONG;
    }

    @Override
    public Boundedness getBoundedness() {
        return Boundedness.BOUNDED;
    }

    @Override
    public SourceReader<Long, NumberSequenceSplit> createReader(SourceReaderContext readerContext) {
        return new IteratorSourceReader<>(readerContext);
    }

    @Override
    public SplitEnumerator<NumberSequenceSplit, Collection<NumberSequenceSplit>> createEnumerator(
            final SplitEnumeratorContext<NumberSequenceSplit> enumContext) {

        final List<NumberSequenceSplit> splits =
                splitNumberRange(from, to, enumContext.currentParallelism());
        return new IteratorSourceEnumerator<>(enumContext, splits);
    }

    @Override
    public SplitEnumerator<NumberSequenceSplit, Collection<NumberSequenceSplit>> restoreEnumerator(
            final SplitEnumeratorContext<NumberSequenceSplit> enumContext,
            Collection<NumberSequenceSplit> checkpoint) {
        return new IteratorSourceEnumerator<>(enumContext, checkpoint);
    }

    @Override
    public SimpleVersionedSerializer<NumberSequenceSplit> getSplitSerializer() {
        return new SplitSerializer();
    }

    @Override
    public SimpleVersionedSerializer<Collection<NumberSequenceSplit>>
            getEnumeratorCheckpointSerializer() {
        return new CheckpointSerializer();
    }

    protected List<NumberSequenceSplit> splitNumberRange(long from, long to, int numSplits) {
        final NumberSequenceIterator[] subSequences =
                new NumberSequenceIterator(from, to).split(numSplits);
        final ArrayList<NumberSequenceSplit> splits = new ArrayList<>(subSequences.length);

        int splitId = 1;
        for (NumberSequenceIterator seq : subSequences) {
            if (seq.hasNext()) {
                splits.add(
                        new NumberSequenceSplit(
                                String.valueOf(splitId++), seq.getCurrent(), seq.getTo()));
            }
        }

        return splits;
    }

    // ------------------------------------------------------------------------
    //  splits & checkpoint
    // ------------------------------------------------------------------------

    /** A split of the source, representing a number sub-sequence. */
    public static class NumberSequenceSplit
            implements IteratorSourceSplit<Long, NumberSequenceIterator> {

        private final String splitId;
        private final long from;
        private final long to;

        public NumberSequenceSplit(String splitId, long from, long to) {
            checkArgument(from <= to, "'from' must be <= 'to'");
            this.splitId = checkNotNull(splitId);
            this.from = from;
            this.to = to;
        }

        @Override
        public String splitId() {
            return splitId;
        }

        public long from() {
            return from;
        }

        public long to() {
            return to;
        }

        @Override
        public NumberSequenceIterator getIterator() {
            return new NumberSequenceIterator(from, to);
        }

        @Override
        public IteratorSourceSplit<Long, NumberSequenceIterator> getUpdatedSplitForIterator(
                final NumberSequenceIterator iterator) {
            return new NumberSequenceSplit(splitId, iterator.getCurrent(), iterator.getTo());
        }

        @Override
        public String toString() {
            return String.format("NumberSequenceSplit [%d, %d] (%s)", from, to, splitId);
        }
    }

    private static final class SplitSerializer
            implements SimpleVersionedSerializer<NumberSequenceSplit> {

        private static final int CURRENT_VERSION = 1;

        @Override
        public int getVersion() {
            return CURRENT_VERSION;
        }

        @Override
        public byte[] serialize(NumberSequenceSplit split) throws IOException {
            checkArgument(
                    split.getClass() == NumberSequenceSplit.class, "cannot serialize subclasses");

            // We will serialize 2 longs (16 bytes) plus the UFT representation of the string (2 +
            // length)
            final DataOutputSerializer out =
                    new DataOutputSerializer(split.splitId().length() + 18);
            serializeV1(out, split);
            return out.getCopyOfBuffer();
        }

        @Override
        public NumberSequenceSplit deserialize(int version, byte[] serialized) throws IOException {
            if (version != CURRENT_VERSION) {
                throw new IOException("Unrecognized version: " + version);
            }
            final DataInputDeserializer in = new DataInputDeserializer(serialized);
            return deserializeV1(in);
        }

        static void serializeV1(DataOutputView out, NumberSequenceSplit split) throws IOException {
            out.writeUTF(split.splitId());
            out.writeLong(split.from());
            out.writeLong(split.to());
        }

        static NumberSequenceSplit deserializeV1(DataInputView in) throws IOException {
            return new NumberSequenceSplit(in.readUTF(), in.readLong(), in.readLong());
        }
    }

    private static final class CheckpointSerializer
            implements SimpleVersionedSerializer<Collection<NumberSequenceSplit>> {

        private static final int CURRENT_VERSION = 1;

        @Override
        public int getVersion() {
            return CURRENT_VERSION;
        }

        @Override
        public byte[] serialize(Collection<NumberSequenceSplit> checkpoint) throws IOException {
            // Each split needs 2 longs (16 bytes) plus the UFT representation of the string (2 +
            // length)
            // Assuming at most 4 digit split IDs, 22 bytes per split avoids any intermediate array
            // resizing.
            // plus four bytes for the length field
            final DataOutputSerializer out = new DataOutputSerializer(checkpoint.size() * 22 + 4);
            out.writeInt(checkpoint.size());
            for (NumberSequenceSplit split : checkpoint) {
                SplitSerializer.serializeV1(out, split);
            }
            return out.getCopyOfBuffer();
        }

        @Override
        public Collection<NumberSequenceSplit> deserialize(int version, byte[] serialized)
                throws IOException {
            if (version != CURRENT_VERSION) {
                throw new IOException("Unrecognized version: " + version);
            }
            final DataInputDeserializer in = new DataInputDeserializer(serialized);
            final int num = in.readInt();
            final ArrayList<NumberSequenceSplit> result = new ArrayList<>(num);
            for (int remaining = num; remaining > 0; remaining--) {
                result.add(SplitSerializer.deserializeV1(in));
            }
            return result;
        }
    }
}


text:
package goriak

import (
	"errors"
	riak "github.com/basho/riak-go-client"
)

type MapOperationCommand struct {
	c       *Command
	builder *riak.UpdateMapCommandBuilder
}

// MapOperation takes a riak.MapOperation so that you can run custom commands on your Riak Maps
func (c *Command) MapOperation(op riak.MapOperation) *MapOperationCommand {
	builder := riak.NewUpdateMapCommandBuilder().
		WithBucket(c.bucket).
		WithBucketType(c.bucketType).
		WithMapOperation(&op)

	return &MapOperationCommand{
		c:       c,
		builder: builder,
	}
}

func (c *MapOperationCommand) Context(ctx []byte) *MapOperationCommand {
	c.builder.WithContext(ctx)
	return c
}

func (c *MapOperationCommand) Key(key string) *MapOperationCommand {
	c.builder.WithKey(key)
	return c
}

func (c *MapOperationCommand) Run(session *Session) (*Result, error) {
	cmd, err := c.builder.Build()
	if err != nil {
		return nil, err
	}

	err = session.riak.Execute(cmd)
	if err != nil {
		return nil, err
	}

	res := cmd.(*riak.UpdateMapCommand)

	if !res.Success() {
		return nil, errors.New("Not successful")
	}

	return &Result{}, nil
}

// NewMapOperation returns a new riak.MapOperation that you can for advanced Riak operations
func NewMapOperation() riak.MapOperation {
	return riak.MapOperation{}
}


text:
import { lazyComponent } from '@waldur/core/lazyComponent';
import type { Section, Offering } from '@waldur/marketplace/types';
import { openModalDialog } from '@waldur/modal/actions';

const AttributeFilterListDialog = lazyComponent(
  () =>
    import(
      /* webpackChunkName: "AttributeFilterListDialog" */ '../filters/AttributeFilterListDialog'
    ),
  'AttributeFilterListDialog',
);

import * as constants from './constants';

export const showAttributeFilter = () =>
  openModalDialog(AttributeFilterListDialog, { size: 'sm' });

export const setFilterQuery = (filterQuery: string) => ({
  type: constants.SET_FILTER_QUERY,
  payload: {
    filterQuery,
  },
});

export const loadDataStart = () => ({
  type: constants.LOAD_DATA_START,
});

export const loadDataSuccess = (sections: Section[]) => ({
  type: constants.LOAD_DATA_SUCCESS,
  payload: {
    sections,
  },
});

export const loadDataError = () => ({
  type: constants.LOAD_DATA_ERROR,
});

export const loadOfferingsStart = () => ({
  type: constants.LOAD_OFFERINGS_START,
});

export const loadOfferingsSuccess = (items: Offering[]) => ({
  type: constants.LOAD_OFFERINGS_SUCCESS,
  payload: {
    items,
  },
});

export const loadOfferingsError = () => ({
  type: constants.LOAD_OFFERINGS_ERROR,
});


text:
module('testLayouter');

test('testGeneral', function() {
  var Layouter = require('net/meisen/ui/metro/Layouter');
  notEqual(Layouter, undefined, 'Layouter prototype available');

  // instantiate an app
  notEqual(new Layouter(), undefined, 'could instantiate a Layouter');
});

test('testBindWithoutConfig', function() {
  var $ = require('jquery');
  var Layouter = require('net/meisen/ui/metro/Layouter');

  var layouter = new Layouter();
  layouter.bind("#qunit-fixture", false);

  equal($("#qunit-fixture").children().size(), 0, 'no elements');
});

test('testConfiguration', function() {
  var Layouter = require('net/meisen/ui/metro/Layouter');

  var layouter = new Layouter();
  throws(function() {
    layouter.config(5);
  }, /configuration must be a plain JavaScript object/, 'invalid configuration type detected');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }]
    });
  }, /configuration needs at least one specified layout/, 'found configuration without layout');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: []
    });
  }, /configuration needs at least one specified layout/, 'found configuration with invalid layout');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { first: [], second: [] }
    });
  }, /Invalid type of layout's configuration/, 'found invalid layout types');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: {} }
    });
  }, /must be specified if the layout is a single tile layout/, 'found invalid layout definition');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: { singleTile: false } }
    });
  }, /panelCss must be defined for any LayoutStyle/, 'found invalid panel-css definition (missing)');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: { singleTile: false, panelCss: {} } }
    });
  }, /tileCss must be defined for any LayoutStyle/, 'found invalid tile-css definition (missing)');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: { singleTile: false, panelCss: [] } }
    });
  }, /defined panelCss is invalid/, 'found invalid panel-css definition (array)');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: { singleTile: false, panelCss: {}, tileCss: [] } }
    });
  }, /defined tileCss is invalid/, 'found invalid tile-css definition (array)');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: { singleTile: false, panelCss: {}, tileCss: {} } }
    });
  }, /configuration must specify at least two layouts/, 'found invalid amount of layouts');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layoutSingle1: { singleTile: true, panelCss: {}, tileCss: {} }, layoutSingle2: { singleTile: true, panelCss: {}, tileCss: {} } }
    });
  }, /configuration must specify at least one layout to be used for the panel/, 'found invalid layouts (no panel layout)');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layoutSingle1: { singleTile: false, panelCss: {}, tileCss: {} }, layoutSingle2: { singleTile: false, panelCss: {}, tileCss: {} } }
    });
  }, /configuration must specify at least one layout to be used for a single tile/, 'found invalid layouts (no single-tile layout)');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: { singleTile: false, panelCss: {}, tileCss: {} }, tileLayout: { singleTile: true, panelCss: {}, tileCss: {} } }
    });
  }, /configuration must specify the rules for the different layouts/, 'found invalid rules definition (missing)');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: { singleTile: false, panelCss: {}, tileCss: {} }, tileLayout: { singleTile: true, panelCss: {}, tileCss: {} } },
      rules: []
    });
  }, /configuration must specify the rules for the different layouts/, 'found invalid rules definition (array)');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: { singleTile: false, panelCss: {}, tileCss: {} }, tileLayout: { singleTile: true, panelCss: {}, tileCss: {} } },
      rules: {}
    });
  }, /rule for the panelLayout must be specified/, 'found invalid rules definition (empty object)');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: { singleTile: false, panelCss: {}, tileCss: {} }, tileLayout: { singleTile: true, panelCss: {}, tileCss: {} } },
      rules: { panelLayout: 5 }
    });
  }, /rule for the panelLayout is invalid/, 'found invalid rules definition (invalid rule)');

  throws(function() {
    layouter.config({
      tiles: [{ url: 'about:blank' }],
      layouts: { layout: { singleTile: false, panelCss: {}, tileCss: {} }, tileLayout: { singleTile: true, panelCss: {}, tileCss: {} } },
      rules: { panelLayout: function() {} }
    });
  }, /rule for the singleLayout must be specified/, 'found invalid rules definition (missing)');

  layouter.config({
    tiles: [{ url: 'about:blank' }],
    layouts: { layout: { singleTile: false, panelCss: {}, tileCss: {} }, tileLayout: { singleTile: true, panelCss: {}, tileCss: {} } },
    rules: { singleLayout: '', panelLayout: function() {} }
  });
  ok(true, 'loaded empty configuration');
});

test('testBinding', function() {
  var $ = require('jquery');
  var Layouter = require('net/meisen/ui/metro/Layouter');

  var layouter = new Layouter();
  layouter.config({
    tiles: [{ url: 'about:blank' }],
    layouts: { layout: { singleTile: false, panelCss: {}, tileCss: {} }, tileLayout: { singleTile: true, panelCss: {}, tileCss: {} } },
    rules: { singleLayout: 'tileLayout', panelLayout: 'tileLayout' }
  });
  throws(function() {
    layouter.bind("#qunit-fixture");
  }, /specified layout for a panel cannot be a singleTile-layout/, 'detected invalid layout-binding (used singleTile)');

  var layouter = new Layouter();
  layouter.config({
    tiles: [{ url: 'about:blank' }],
    layouts: { layout: { singleTile: false, panelCss: {}, tileCss: {} }, tileLayout: { singleTile: true, panelCss: {}, tileCss: {} } },
    rules: { singleLayout: 'layout', panelLayout: 'unknown' }
  });
  throws(function() {
    layouter.bind("#qunit-fixture");
  }, /layout 'unknown' cannot be found/, 'detected invalid layout-binding (not found)');

  var layouter = new Layouter();
  layouter.config({
    tiles: [{ url: 'about:blank' }],
    layouts: { layout: { singleTile: false, panelCss: {}, tileCss: {} }, tileLayout: { singleTile: true, panelCss: {}, tileCss: {} } },
    rules: { singleLayout: 'tileLayout', panelLayout: 'layout' }
  });
  layouter.bind("#qunit-fixture");

  equal($("#qunit-fixture > div.placeholder.layout").size(), 1, 'found iframe');
  equal($("#qunit-fixture > div > iframe.content").size(), 1, 'found iframe');
});


text:
package com.taobao.tddl.repo.demo.spi;

import com.taobao.tddl.common.exception.TddlException;
import com.taobao.tddl.executor.common.ExecutionContext;
import com.taobao.tddl.executor.spi.ITHLog;
import com.taobao.tddl.executor.spi.ITransaction;

/**
 * @author danchen
 */
public class DemoTransaction implements ITransaction {

    private ExecutionContext executionContext;

    @Override
    public long getId() {
        return 0;
    }

    @Override
    public void commit() throws TddlException {
    }

    @Override
    public void rollback() throws TddlException {
    }

    @Override
    public boolean isAutoCommit() {

        return false;
    }

    @Override
    public ITHLog getHistoryLog() {
        return null;
    }

    @Override
    public void close() throws TddlException {
    }

    @Override
    public void setAutoCommit(boolean autoCommit) {
    }

    @Override
    public void beginTransaction() throws TddlException {
    }

    @Override
    public void setExecutionContext(ExecutionContext executionContext) {
        this.executionContext = executionContext;

    }

    public ExecutionContext getExecutionContext() {
        return executionContext;
    }

}


text:
global.requestAnimationFrame = function (callback) {
  setTimeout(callback, 0)
}


text:
package org.apache.hadoop.io.compress;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

/**
 * A {@link org.apache.hadoop.io.compress.DecompressorStream} which works
 * with 'block-based' based compression algorithms, as opposed to
 * 'stream-based' compression algorithms.
 *
 */
public class BlockDecompressorStream extends DecompressorStream {
  private int originalBlockSize = 0;
  private int noUncompressedBytes = 0;

  /**
   * Create a {@link BlockDecompressorStream}.
   *
   * @param in input stream
   * @param decompressor decompressor to use
   * @param bufferSize size of buffer
   */
  public BlockDecompressorStream(InputStream in, Decompressor decompressor,
                                 int bufferSize) {
    super(in, decompressor, bufferSize);
  }

  /**
   * Create a {@link BlockDecompressorStream}.
   *
   * @param in input stream
   * @param decompressor decompressor to use
   */
  public BlockDecompressorStream(InputStream in, Decompressor decompressor) {
    super(in, decompressor);
  }

  protected BlockDecompressorStream(InputStream in) {
    super(in);
  }

  protected int decompress(byte[] b, int off, int len) throws IOException {
    // Check if we are the beginning of a block
    if (noUncompressedBytes == originalBlockSize) {
      // Get original data size
      do {
        try {
          originalBlockSize =  rawReadInt();
        } catch (IOException ioe) {
          return -1;
        }
      } while (originalBlockSize == 0);

      noUncompressedBytes = 0;
    }

    int n = 0;
    while ((n = decompressor.decompress(b, off, len)) == 0) {
      if (decompressor.finished() || decompressor.needsDictionary()) {
        if (noUncompressedBytes >= originalBlockSize) {
          eof = true;
          return -1;
        }
      }
      if (decompressor.needsInput()) {
        getCompressedData();
      }
    }

    // Note the no. of decompressed bytes read from 'current' block
    noUncompressedBytes += n;

    return n;
  }

  protected void getCompressedData() throws IOException {
    checkStream();

    // Get the size of the compressed chunk
    int len = rawReadInt();

    // Read len bytes from underlying stream
    if (len > buffer.length) {
      buffer = new byte[len];
    }
    int n = 0, off = 0;
    while (n < len) {
      int count = in.read(buffer, off + n, len - n);
      if (count < 0) {
        throw new CodecPrematureEOFException(
            "Unexpected end of input stream, this is typically because of" +
            " truncated compressed file.");
      }
      n += count;
    }

    // Send the read data to the decompressor
    decompressor.setInput(buffer, 0, len);
  }

  public void resetState() throws IOException {
    super.resetState();
  }

  private int rawReadInt() throws IOException {
    int b1 = in.read();
    int b2 = in.read();
    int b3 = in.read();
    int b4 = in.read();
    // Test if any of bi is negative. If any of bi is negative, the result of
    // bitwise or will be native as well, so this works. And this has better
    // performance than testing each bi separately.
    if ((b1 | b2 | b3 | b4) < 0) {
      throw new CodecPrematureEOFException(
          "Unexpected end of input stream, this is typically because of" +
          " truncated compressed file.");
    }
    return ((b1 << 24) + (b2 << 16) + (b3 << 8) + (b4 << 0));
  }
}


text:
package org.apache.flink.runtime.rest.messages.json;

import org.apache.flink.api.common.JobID;

import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.DeserializationContext;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.deser.std.StdDeserializer;

import java.io.IOException;

/** Json deserializer for {@link JobID}. */
public class JobIDDeserializer extends StdDeserializer<JobID> {
    private static final long serialVersionUID = -130167416771003559L;

    protected JobIDDeserializer() {
        super(JobID.class);
    }

    @Override
    public JobID deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return JobID.fromHexString(p.getValueAsString());
    }
}


text:
title: angular routes intro and parameterization
date: 2018-03-02 09:06:25
---

### Angular Routes
- Angular routes allows the user to navigate from one view to another via the browser's URL.

### Angular Routes Configuration

- **app.module.ts**

    ```
    import { Routes, RouterModule } from '@angular/router';

    const appRoutes: Routes = [
    {path: '', component: HomeComponent},
    {path: 'users', component: UsersComponent},
    {path: 'servers', component: ServerComponent},
    ];

    imports:[
        RouterModule.forRoot(appRoutes)
    ]

    ```

### Angular Routes Consumption
- add the `<router-outlet></router-outlet>` as a placeholder for your routers component
- add the `routerLink` property and set it to one of the routes defined in `app.module.ts`
    - can pass parameters to the `routerLink` property by:
        `<a [routerLink]="['/users', 3, 'Anna']">Example for /users/:id/:name</a>`

- **app.component.html**

    ```
    <div class="container">
        <div class="row">
            <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
            <ul class="nav nav-tabs">
                <li role="presentation" class="active"><a routerLink="/">Home</a></li>
                <li role="presentation"><a routerLink="/servers">Servers</a></li>
                <li role="presentation"><a [routerLink]="['/users']">Users</a></li>
            </ul>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
            <router-outlet></router-outlet>
            </div>
        </div>
    </div>

    ```
    - the above code creates a tab navigation for:
        * Home => '/'
        * Servers => '/servers'
        * Users => '/users'

### Absolute Paths vs Relative Paths
- **absolute paths** are denoted by `/PATHNAME`
- **relative paths** are denoted by `"./PATHNAME"` or `"PATHNAME"` or `"../../../PATHNAME"`

- routes defined in `app.module.ts` is preceeded by `localhost:4200/` or `yourdomain.com/`

### Parameterizing Routes
- denoted by `:`

- **app.module.ts**

    ```
    import { Routes, RouterModule } from '@angular/router';

    const appRoutes: Routes = [
    {path: '', component: HomeComponent},
    {path: 'users', component: UsersComponent},
    {path: 'users/:id/:name', component: UsersComponent},
    {path: 'servers', component: ServerComponent},
    ];

    imports:[
        RouterModule.forRoot(appRoutes)
    ]

    ```

- **user.component.ts**

    ```
    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute, Params } from '@angular/router';

    @Component({
    selector: 'app-user',
    templateUrl: './user.component.html',
    styleUrls: ['./user.component.css']
    })
    export class UserComponent implements OnInit {
        user: {id: number, name: string};

        constructor(private route: ActivatedRoute) { }

        ngOnInit() {
            this.user = {
            id: this.route.snapshot.params['id'],
            name: this.route.snapshot.params['name']
            };
        };
    }
    ```
- the `route.snapshot.params` takes a "snapshot" of the current route displayed in the browser via the params key defined in `Routes` in the `app.module.ts`.

- **user.component.html**

    ```
    <p>User with ID {{ user.id }} loaded.</p>
    <p>User name is {{ user.name }}</p>
    ```

- in the above example, `'users/:id/:name'` is a parameterized path for users with a parameterized id and name.

    ![sample image](../images/parameterized-routes.png)

### Routes as an Observable
- use the observable `Params` from `@angular/router` library to subscribe to the routes parameters being changed.
- example:
    ```
    import { ActivatedRoute, Params } from '@angular/router';

    constructor(private route: ActivatedRoute) { }

    public ngOnInit(): void {
        this.route.params.subscribe((params: Params) => {
            this.user.id = params['id'],
            this.user.name = params['name']
        });
    }
    ```


text:
package com.microf.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

@JsonIgnoreProperties(ignoreUnknown = true)
public class IEAddress extends Address {

    private String what3words;

    public IEAddress(String latitude, String longitude, String addressline1, String addressline2, String addressline3, String summaryline, String buildingname, String organisation, String number, String premise, String dependentstreet, String street, String doubledependentlocality, String dependentlocality, String posttown, String county, String postcode, String what3words) {
        super(latitude, longitude, addressline1, addressline2, addressline3, summaryline, buildingname, organisation, number, premise, dependentstreet, street, doubledependentlocality, dependentlocality, posttown, county, postcode);
        this.what3words = what3words;
    }

    public IEAddress(final String latitude, final String longitude, final String what3words) {
        super(latitude, longitude);
        this.what3words = what3words;
    }

    public String getWhat3words() {
        return what3words;
    }

    public void setWhat3words(String what3words) {
        this.what3words = what3words;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (!(o instanceof IEAddress)) return false;

        IEAddress ieAddress = (IEAddress) o;

        return new EqualsBuilder()
                .appendSuper(super.equals(o))
                .append(getWhat3words(), ieAddress.getWhat3words())
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .appendSuper(super.hashCode())
                .append(getWhat3words())
                .toHashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("what3words", what3words)
                .toString();
    }
}


text:
package org.adaptlab.chpir.android.survey.Models;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.adaptlab.chpir.android.activerecordcloudsync.SendModel;
import org.adaptlab.chpir.android.survey.AppUtil;
import org.adaptlab.chpir.android.survey.R;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.res.Resources;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;

@Table(name = "Surveys")
public class Survey extends SendModel {
    private static final String TAG = "Survey";

    @Column(name = "Instrument")
    private Instrument mInstrument;
    @Column(name = "UUID")
    private String mUUID;
    @Column(name = "SentToRemote")
    private boolean mSent;
    @Column(name = "Complete")
    private boolean mComplete;
    @Column(name = "Latitude")
    private String mLatitude;
    @Column(name= "Longitude")
    private String mLongitude;
    @Column(name = "LastUpdated")
    private Date mLastUpdated;
    @Column(name = "LastQuestion")
    private Question mLastQuestion;
    @Column(name = "Metadata")
    private String mMetadata;
    @Column(name = "ProjectId")
    private Long mProjectId;

    public Survey() {
        super();
        mSent = false;
        mComplete = false;
        mUUID = UUID.randomUUID().toString();
        mLastUpdated = new Date();
    }

    @Override
    public JSONObject toJSON() {
        JSONObject json = new JSONObject();

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("instrument_id", getInstrument().getRemoteId());
            jsonObject.put("instrument_version_number", getInstrument().getVersionNumber());
            jsonObject.put("device_uuid", getAdminInstanceDeviceIdentifier());
            jsonObject.put("device_label", AppUtil.getAdminSettingsInstance().getDeviceLabel());
            jsonObject.put("uuid", mUUID);
            jsonObject.put("instrument_title", getInstrument().getTitle());
            jsonObject.put("latitude", mLatitude);
            jsonObject.put("longitude", mLongitude);
            jsonObject.put("metadata", mMetadata);

            json.put("survey", jsonObject);
        } catch (JSONException je) {
            Log.e(TAG, "JSON exception", je);
        }
        return json;
    }

    public String getAdminInstanceDeviceIdentifier() {
    	return AppUtil.getAdminSettingsInstance().getDeviceIdentifier();
    }

    @Override
    public boolean isPersistent() { return true; }

    /*
     * The identifier to display to the user to identify a Survey.
     * Return Unidentified Survey string if no response for identifier questions.
     */
    public String identifier(Context context) {
    	String surveyLabel = null;
    	String identifier = "";

    	if (!TextUtils.isEmpty(getMetadata())) { surveyLabel = getMetadataLabel(); }
    	if (!TextUtils.isEmpty(surveyLabel))  { return surveyLabel; }

    	for (Response response : responses()) {
    		if (response.getQuestion().identifiesSurvey()) {
    			identifier += response.getText() + " ";
    		}
    	}

    	if (identifier.trim().isEmpty())
    		return context.getString(R.string.unidentified_survey) + " " + getId();
    	else
    		return identifier;
    }

    /*
     * Finders
     */
    public Response getResponseByQuestion(Question question) {
        return new Select().from(Response.class).where(
                "Question = ? AND Survey = ?",
                question.getId(),
                getId()).executeSingle();
    }

    public static List<Survey> getAll() {
        return new Select().from(Survey.class).orderBy("LastUpdated DESC").execute();
    }

    public static List<Survey> getAllProjectSurveys(Long projectId) {
    	return new Select("Surveys.*")
    			.from(Survey.class)
    			.innerJoin(Instrument.class)
    			.on("Surveys.Instrument=Instruments.Id AND Instruments.Published=" + 1)
    			.where("Surveys.ProjectId = ?", projectId)
    			.orderBy("Surveys.LastUpdated DESC")
    			.execute();
    }

    /*
     * Relationships
     */
    public List<Response> responses() {
        return getMany(Response.class, "Survey");
    }

    /*
     * Getters/Setters
     */

    public Instrument getInstrument() {
        return mInstrument;
    }

    public void setInstrument(Instrument instrument) {
        mInstrument = instrument;
    }

    public String getUUID() {
        return mUUID;
    }

    public void setAsComplete() {
        mComplete = true;
    }

    @Override
    public boolean isSent() {
        return mSent;
    }

    @Override
    public void setAsSent(Context context) {
        mSent = true;
        this.save();

        EventLog eventLog = new EventLog(EventLog.EventType.SENT_SURVEY, context);
        eventLog.setInstrument(mInstrument);
        eventLog.setSurveyIdentifier(identifier(context));
        eventLog.save();

        Resources r = context.getResources();

        Notification notification = new NotificationCompat.Builder(context)
            .setTicker(r.getString(R.string.app_name))
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle(r.getString(R.string.app_name))
            .setContentText(eventLog.getLogMessage(context))
            .setAutoCancel(true)
            .build();

        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(eventLog.getLogMessage(context), 1, notification);
    }

    @Override
    public boolean readyToSend() {
        return mComplete;
    }

    public void setLatitude(String latitude) {
    	mLatitude = latitude;
    }

    public String getLatitude() {
    	return mLatitude;
    }

    public void setLongitude(String longitude) {
    	mLongitude = longitude;
    }

    public String getLongitude() {
    	return mLongitude;
    }

    public Date getLastUpdated() {
        return mLastUpdated;
    }

    public void setLastUpdated(Date lastUpdate) {
        mLastUpdated = lastUpdate;
    }

    public Question getLastQuestion() {
        return mLastQuestion;
    }

    public void setLastQuestion(Question question) {
        mLastQuestion = question;
    }

    public void deleteIfComplete() {
		if (this.responses().size() == 0) {
			this.delete();
		}
    }

    public void setMetadata(String metadata) {
        mMetadata = metadata;
    }

    public String getMetadata() {
        return mMetadata;
    }

    public void setProjectId(Long id) {
    	mProjectId = id;
    }

    public Long getProjectId() {
    	return mProjectId;
    }

    private String getMetadataLabel() {
        try {
            JSONObject metadata = new JSONObject(getMetadata());
            if (metadata.has("survey_label")) {
                return metadata.getString("survey_label");
            }
        } catch (JSONException er) {
            Log.e(TAG, er.getMessage());
        }

        return "";
    }
}


text:
#ifndef QPIXMAP_RASTER_P_H
#define QPIXMAP_RASTER_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <QtGui/private/qtguiglobal_p.h>
#include <qpa/qplatformpixmap.h>

QT_BEGIN_NAMESPACE

class Q_GUI_EXPORT QRasterPlatformPixmap : public QPlatformPixmap
{
public:
    QRasterPlatformPixmap(PixelType type);
    ~QRasterPlatformPixmap();

    QPlatformPixmap *createCompatiblePlatformPixmap() const Q_DECL_OVERRIDE;

    void resize(int width, int height) Q_DECL_OVERRIDE;
    bool fromData(const uchar *buffer, uint len, const char *format, Qt::ImageConversionFlags flags) Q_DECL_OVERRIDE;
    void fromImage(const QImage &image, Qt::ImageConversionFlags flags) Q_DECL_OVERRIDE;
    void fromImageInPlace(QImage &image, Qt::ImageConversionFlags flags) Q_DECL_OVERRIDE;
    void fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags) Q_DECL_OVERRIDE;

    void copy(const QPlatformPixmap *data, const QRect &rect) Q_DECL_OVERRIDE;
    bool scroll(int dx, int dy, const QRect &rect) Q_DECL_OVERRIDE;
    void fill(const QColor &color) Q_DECL_OVERRIDE;
    bool hasAlphaChannel() const Q_DECL_OVERRIDE;
    QImage toImage() const Q_DECL_OVERRIDE;
    QImage toImage(const QRect &rect) const Q_DECL_OVERRIDE;
    QPaintEngine* paintEngine() const Q_DECL_OVERRIDE;
    QImage* buffer() Q_DECL_OVERRIDE;
    qreal devicePixelRatio() const Q_DECL_OVERRIDE;
    void setDevicePixelRatio(qreal scaleFactor) Q_DECL_OVERRIDE;

protected:
    int metric(QPaintDevice::PaintDeviceMetric metric) const Q_DECL_OVERRIDE;
    void createPixmapForImage(QImage &sourceImage, Qt::ImageConversionFlags flags, bool inPlace);
    void setImage(const QImage &image);
    QImage image;
    static QImage::Format systemOpaqueFormat();

private:
    friend class QPixmap;
    friend class QBitmap;
    friend class QPixmapCacheEntry;
    friend class QRasterPaintEngine;
};

QT_END_NAMESPACE

#endif // QPIXMAP_RASTER_P_H


text:
EbayListingViewGridHandler = Class.create(ListingGridHandler, {

    // ---------------------------------------

    selectedProductsIds: [],
    selectedCategoriesData: {},

    // ---------------------------------------

    prepareActions: function($super)
    {
        this.actionHandler = new EbayListingActionHandler(this);

        this.actions = {
            listAction: this.actionHandler.listAction.bind(this.actionHandler),
            relistAction: this.actionHandler.relistAction.bind(this.actionHandler),
            reviseAction: this.actionHandler.reviseAction.bind(this.actionHandler),
            stopAction: this.actionHandler.stopAction.bind(this.actionHandler),
            stopAndRemoveAction: this.actionHandler.stopAndRemoveAction.bind(this.actionHandler),
            previewItemsAction: this.actionHandler.previewItemsAction.bind(this.actionHandler),
            startTranslateAction: this.actionHandler.startTranslateAction.bind(this.actionHandler),
            stopTranslateAction: this.actionHandler.stopTranslateAction.bind(this.actionHandler)
        };

        this.variationProductManageHandler = new EbayListingVariationProductManageHandler(this);
        this.listingProductBidsHandler = new EbayListingProductBidsHandler(this);

        this.actions = Object.extend(this.actions, {

            editCategorySettingsAction: function(id) {
                this.editCategorySettings(id);
            }.bind(this)

        });

    },

    massActionSubmitClick: function($super)
    {
        if (this.getSelectedProductsString() == '' || this.getSelectedProductsArray().length == 0) {
            alert(M2ePro.translator.translate('Please select the Products you want to perform the Action on.'));
            return;
        }
        $super();
    },

    // ---------------------------------------

    editCategorySettings: function(id)
    {
        this.selectedProductsIds = id ? [id] : this.getSelectedProductsArray();

        new Ajax.Request(M2ePro.url.get('adminhtml_ebay_listing/getCategoryChooserHtml'), {
            method: 'post',
            asynchronous: true,
            parameters: {
                ids: this.selectedProductsIds.join(',')
            },
            onSuccess: function(transport) {

                this.unselectAll();

                var title = M2ePro.translator.translate('eBay Categories');

                if (this.selectedProductsIds.length == 1) {
                    var productName = this.getProductNameByRowId(this.selectedProductsIds[0]);
                    title += ' ' + M2ePro.translator.translate('of Product') + ' "' + productName + '"';
                }

                this.openPopUp(title, transport.responseText);

                $('cancel_button').observe('click', function() { Windows.getFocusedWindow().close(); });

                $('done_button').observe('click', function() {
                    if (!EbayListingCategoryChooserHandlerObj.validate()) {
                        return;
                    }

                    this.selectedCategoriesData = EbayListingCategoryChooserHandlerObj.getInternalData();
                    this.editSpecificSettings();
                }.bind(this));
            }.bind(this)
        });
    },

    // ---------------------------------------

    editSpecificSettings: function()
    {
        var typeEbayMain = M2ePro.php.constant('Ess_M2ePro_Helper_Component_Ebay_Category::TYPE_EBAY_MAIN');

        new Ajax.Request(M2ePro.url.get('adminhtml_ebay_listing/getCategorySpecificHtml'), {
            method: 'post',
            asynchronous: true,
            parameters: {
                ids: this.selectedProductsIds.join(','),
                category_mode: EbayListingCategoryChooserHandlerObj.getSelectedCategory(typeEbayMain)['mode'],
                category_value: EbayListingCategoryChooserHandlerObj.getSelectedCategory(typeEbayMain)['value']
            },
            onSuccess: function(transport) {

                var title = M2ePro.translator.translate('Specifics');

                this.openPopUp(title, transport.responseText);

                $('cancel_button').observe('click', function() { Windows.getFocusedWindow().close(); });
                $('done_button').observe('click', this.saveCategoryTemplate.bind(this));
            }.bind(this)
        });
    },

    // ---------------------------------------

    saveCategoryTemplate: function()
    {
        if (!EbayListingCategorySpecificHandlerObj.validate()) {
            return;
        }

        var categoryTemplateData = {};
        categoryTemplateData = Object.extend(categoryTemplateData, this.selectedCategoriesData);
        categoryTemplateData = Object.extend(categoryTemplateData, EbayListingCategorySpecificHandlerObj.getInternalData());

        new Ajax.Request(M2ePro.url.get('adminhtml_ebay_listing/saveCategoryTemplate'), {
            method: 'post',
            asynchronous: true,
            parameters: {
                ids: this.selectedProductsIds.join(','),
                template_category_data: Object.toJSON(categoryTemplateData)
            },
            onSuccess: function(transport) {
                Windows.getFocusedWindow().close();
                this.getGridObj().doFilter();
            }.bind(this)
        });
    },

    // ---------------------------------------

    getComponent: function()
    {
        return 'ebay';
    },

    // ---------------------------------------

    openPopUp: function(title, content, params)
    {
        var self = this;
        params = params || {};

        var config = Object.extend({
            draggable: true,
            resizable: true,
            closable: true,
            className: "magento",
            windowClassName: "popup-window",
            top: 50,
            maxHeight: 500,
            height: 500,
            width: 1000,
            zIndex: 100,
            recenterAuto: true,
            hideEffect: Element.hide,
            showEffect: Element.show,
            closeCallback: function() {
                self.selectedProductsIds = [];
                self.selectedCategoriesData = {};

                $('excludeListPopup') && Windows.getWindow('excludeListPopup').destroy();

                self.getGridObj().reload();

                return true;
            }
        }, params);

        try {
            if (!Windows.getFocusedWindow() || !$('modal_dialog_message')) {
                Dialog.info(null, config);
            }
            Windows.getFocusedWindow().setTitle(title);
            $('modal_dialog_message').innerHTML = content;
            $('modal_dialog_message').innerHTML.evalScripts();
        } catch (ignored) {}
    }

    // ---------------------------------------
});


text:
#include "stdafx.h"
#include "vmmngr.h"
#include "Object.h"
#include "spinlock.h"
#include "pagingdefs.h"
#include "terminal.h"
#include "memory.h"

static uint_fast16_t mmu_recursive_slot = 0;
//Trick to use pagingdefs.h:
#undef MMU_RECURSIVE_SLOT
#define MMU_RECURSIVE_SLOT mmu_recursive_slot

#define PAGE_NUM_ROUND_UP(x) \
	((x - 1) / PAGESIZE + 1)

static size_t& PML4_entry(size_t addr, size_t n)
{
	return MMU_PML4(addr)[n];
}

static size_t& PDPT_entry(size_t addr, size_t n)
{
	return MMU_PDPT(addr)[n];
}

static size_t& PDIR_entry(size_t addr, size_t n)
{
	return MMU_PD(addr)[n];
}

static size_t& PTBL_entry(size_t addr, size_t n)
{
	return MMU_PT(addr)[n];
}

enum errors {
	NO_ERROR,
	PHYMEM,
	TABLE_FULL,
	SWAP_ERROR,
	PSE_ERROR
};
static size_t lastErr = 0;

#define PAGING_SEARCH_ERROR 0xFFFF
size_t paging_search(size_t&(*entFunc)(size_t, size_t), size_t&(*entFuncOneDown)(size_t, size_t), size_t ShiftVal, const CVMemMngr::PAGING_ATTRIBUTES& attr, size_t addr, size_t entMin, size_t entMax, bool& pDirUser)
{
	size_t n = entMin;
	size_t entryVal = 0;
	if (entMax == 0)
		entMax = PAGE_TABLE_ENTRIES;
	for (; n < entMax; n++)
	{
		entryVal = entFunc(addr, n);
		if (((entryVal & PAGING_USER) == 0) && attr.isUser)	//Just prevent user page in kernel page dir
			continue;
		if (entryVal & PAGING_CHAIOS_SWAPPED)		//TODO: Support swapping
			continue;
		if (entryVal & PAGING_CHAIOS_FREEPAGES)
		{
			break;
		}
		else if ((entryVal & PAGING_PRESENT) == 0)		//Empty entry is fine
			break;
	}
	if ((entryVal & PAGING_PRESENT) == 0)
	{
		//Prepare attributes
		size_t attribs = 0;
		if (entFunc == &PTBL_entry)
		{
			attribs = (attr.isWriteable ? PAGING_WRITE : 0) | (attr.isUser ? PAGING_USER : 0) | (attr.isCacheable ? 0 : PAGING_CACHEDISABLE) | PAGING_PRESENT;
		}
		else
		{
			if (entFunc == &PML4_entry)
			{
				if (entryVal < PAGE_TABLE_ENTRIES / 2 || attr.isUser)
					pDirUser = true;
			}
			attribs = PAGING_WRITE | PAGING_CHAIOS_FREEPAGES | PAGING_PRESENT | (pDirUser ? PAGING_USER : 0);
		}
		//Create the entry
		physaddr physicalAddrTable = getMemoryManager()->getPMemMngr()->allocateSinglePage();
		if (physicalAddrTable == 0)
		{
			lastErr = PHYMEM;
			return PAGING_SEARCH_ERROR;
		}
		size_t entry = (size_t)physicalAddrTable | attribs;
		entFunc(addr, n) = entry;
		COMPILER_MEMORY_BARRIER();
		addr |= (n << ShiftVal);
		if (entFuncOneDown)		//i.e. if not page table
		{
			INVLPG(&entFuncOneDown(addr, 0));		//Flush the page table
			//Set page table to zero
			for (unsigned int x = 0; x < PAGE_TABLE_ENTRIES; x++)
			{
				entFuncOneDown(addr, x) = 0;
			}
		}
	}
	if (n == entMax)
	{
		if (entMin == 0 && entMax == PAGE_TABLE_ENTRIES)
			lastErr = TABLE_FULL;
		else
			lastErr = NO_ERROR;
		return PAGING_SEARCH_ERROR;
	}
	else
	{
		lastErr = NO_ERROR;
		return n;
	}
}

size_t paging_allocate_at(size_t&(*entFunc)(size_t, size_t), size_t&(*entFuncOneDown)(size_t, size_t), size_t ShiftVal, const CVMemMngr::PAGING_ATTRIBUTES& attr, size_t addr, bool pDirUser)
{
	size_t ent = (addr >> ShiftVal) & (PAGE_TABLE_ENTRIES - 1);
	if (entFunc == &PTBL_entry)
	{
		if ((entFunc(addr, ent) & (PAGING_CHAIOS_SWAPPED | PAGING_PRESENT)) != 0)		//in use
		{
			lastErr = TABLE_FULL;
			return PAGING_SEARCH_ERROR;
		}
		size_t attribBits = (attr.isWriteable ? PAGING_WRITE : 0) | (attr.isUser ? PAGING_USER : 0) | (attr.isCacheable ? 0 : PAGING_CACHEDISABLE) | PAGING_PRESENT;
		physaddr phyaddr = getMemoryManager()->getPMemMngr()->allocateSinglePage();
		if (phyaddr == NULL)
		{
			lastErr = PHYMEM;
			return PAGING_SEARCH_ERROR;
		}
		size_t entry = (size_t)phyaddr | attribBits;
		entFunc(addr,ent) = entry;
		COMPILER_MEMORY_BARRIER();
		//addr |= (ent << ShiftVal);
		INVLPG((void*)addr);
	}
	else
	{
		if ((entFunc(addr,ent) & PAGING_PRESENT) == 0)
		{
			if (entFunc(addr, ent) & PAGING_CHAIOS_SWAPPED)		//TODO: handle swapping
			{
				lastErr = SWAP_ERROR;
				return PAGING_SEARCH_ERROR;
			}
			physaddr ptAddr = getMemoryManager()->getPMemMngr()->allocateSinglePage();
			if (ptAddr == 0)
			{
				lastErr = PHYMEM;
				return PAGING_SEARCH_ERROR;
			}
			size_t attribs = PAGING_WRITE | PAGING_PRESENT | (pDirUser ? PAGING_USER : 0);
			entFunc(addr, ent) = (size_t)ptAddr | attribs;
			COMPILER_MEMORY_BARRIER();
			//addr |= (ent << ShiftVal);
			INVLPG(&entFuncOneDown(addr, 0));
			//Set page table to zero
			for (unsigned int x = 0; x < PAGE_TABLE_ENTRIES; x++)
			{
				entFuncOneDown(addr, x) = 0;
			}
			COMPILER_MEMORY_BARRIER();
		}
		if (entFunc(addr, ent) & PAGING_PSE)
		{
			lastErr = PSE_ERROR;
			return PAGING_SEARCH_ERROR;
		}
	}
	lastErr = NO_ERROR;
	return 0;
}

class CX64DefaultVMemMngr : public CVMemMngr
{
public:
	CX64DefaultVMemMngr()
	{

	}
	//Destruction
	virtual void CALLING_CONVENTION destroy();
	//API - Initialization
	virtual PVMMAP_TRANSFER CALLING_CONVENTION vmemTransfer();
	virtual bool CALLING_CONVENTION initialize(CVMemMngr* prevImpl);
	//API - Runtime
	virtual virtaddr CALLING_CONVENTION allocate(size_t len, const PAGING_ATTRIBUTES& attr);
	virtual virtaddr CALLING_CONVENTION allocateSinglePage(const PAGING_ATTRIBUTES& attr);
	virtual void CALLING_CONVENTION free(virtaddr addr, size_t len, bool freePhys = true);
	virtual void CALLING_CONVENTION freeSinglePage(virtaddr addr, bool freePhys = true);
	virtual physaddr CALLING_CONVENTION getPhysicalAddress(virtaddr vAddr);
	virtual virtaddr CALLING_CONVENTION mapPhysicalAddress(physaddr phAddr, size_t len, const PAGING_ATTRIBUTES& attrib);
	virtual virtaddr CALLING_CONVENTION mapSinglePhysicalPage(physaddr phAddr, const PAGING_ATTRIBUTES& attrib);
	virtual virtaddr CALLING_CONVENTION allocateAt(virtaddr allocLoc, size_t len, const PAGING_ATTRIBUTES& attrib);
	virtual virtaddr CALLING_CONVENTION allocateSingleAt(virtaddr allocLoc, const PAGING_ATTRIBUTES& attrib);
	virtual virtaddr CALLING_CONVENTION mapPhysicalAddressAt(virtaddr allocLoc, physaddr phAddr, size_t len, const PAGING_ATTRIBUTES& attrib);
	virtual virtaddr CALLING_CONVENTION mapSinglePhysicalAddressAt(virtaddr allocLoc, physaddr phAddr, const PAGING_ATTRIBUTES& attrib);
	virtual size_t CALLING_CONVENTION createNewAddressSpace();
	virtual size_t CALLING_CONVENTION loadAddressSpace(size_t space);
protected:
private:

	VMMAP_TRANSFER m_vmmtransfer;
	CSpinlock m_spinlock;
};

void CALLING_CONVENTION CX64DefaultVMemMngr::destroy()
{

}

CVMemMngr::PVMMAP_TRANSFER CALLING_CONVENTION CX64DefaultVMemMngr::vmemTransfer()
{
	return &m_vmmtransfer;
}

bool CALLING_CONVENTION CX64DefaultVMemMngr::initialize(CVMemMngr* lastMngr)
{
	PVMMAP_TRANSFER transf = lastMngr->vmemTransfer();
	//Copy across our data, and we're done
	mmu_recursive_slot = m_vmmtransfer.pagingrecursiveslot = transf->pagingrecursiveslot;
	m_vmmtransfer.pagingtoplevel = NULL;
	return true;
}

virtaddr CALLING_CONVENTION CX64DefaultVMemMngr::allocate(size_t len, const PAGING_ATTRIBUTES& attr)
{
	if (len == 0)
		return NULL;
	virtaddr returnAddr = 0;		//Address to return
	virtaddr allocateProg = 0;		//Progress (temporary var)
	size_t szAlloc = 0;
	PAGING_ATTRIBUTES attribs = attr;
	bool isFinished = true;
	do {
		isFinished = true;
		allocateProg = allocateSinglePage(attribs);
		szAlloc = (size_t)allocateProg;
		if ((szAlloc & (PAGESIZE - 1)) != 0)
		{
			//Error, return NULL
			return NULL;
		}
		if (len > PAGESIZE)
		{
			szAlloc += PAGESIZE;
			virtaddr allocAtAddr = (virtaddr)szAlloc;
			for (size_t n = 1; n < PAGE_NUM_ROUND_UP(len); n++)
			{
				virtaddr val = allocateSingleAt(allocAtAddr, attribs);
				if (val != allocAtAddr)
				{
					//Free what's currently allocated
					free(allocateProg, n*PAGESIZE, true);
					//Now move the allocation on. This is genius
					attribs.minAcceptableAddr = (virtaddr)(szAlloc + PAGESIZE);
					isFinished = false;
				}
				szAlloc += PAGESIZE;
				allocAtAddr = (virtaddr)szAlloc;
			}
			returnAddr = allocateProg;
		}
	} while (!isFinished);
	return returnAddr;
}

virtaddr CALLING_CONVENTION CX64DefaultVMemMngr::allocateSinglePage(const PAGING_ATTRIBUTES& attr)
{
	m_spinlock.acquireSpinlock();
	//First, scan the PML4T
	size_t non_canon_minAccept = CANONICAL_UNDO(attr.minAcceptableAddr);
	size_t non_canon_maxAccept = CANONICAL_UNDO(attr.maxAcceptableAddr);
	size_t pml4_min = (non_canon_minAccept >> 39);
	size_t pml4_max = (non_canon_maxAccept >> 39);

	size_t pdpt_min = ((non_canon_minAccept >> 30) & 0x1FF);
	size_t pdir_min = ((non_canon_minAccept >> 21) & 0x1FF);
	size_t ptab_min = ((non_canon_minAccept >> 12) & 0x1FF);
	bool pDirUser = false;
PML4search:
	size_t PML4ent = paging_search(&PML4_entry, &PDPT_entry, 39, attr, 0, pml4_min, pml4_max, pDirUser);
	if (PML4ent == PAGING_SEARCH_ERROR)
	{
		m_spinlock.releaseSpinlock();
		if (lastErr == PHYMEM)
			return ALLOC_OUT_OF_PHYMEM;
		return ALLOC_BOUNDS_ERROR;
	}
	size_t addr = (PML4ent << 39);
	COMPILER_MEMORY_BARRIER();
	//Now search PDPT
PDPTsearch:
	size_t PDPTent = paging_search(&PDPT_entry, &PDIR_entry, 30, attr, addr, pdpt_min, PAGE_TABLE_ENTRIES, pDirUser);
	if (PDPTent == PAGING_SEARCH_ERROR)
	{
		if (lastErr == TABLE_FULL)
			PML4_entry(addr, PML4ent) &= ~PAGING_CHAIOS_FREEPAGES;
		pml4_min = PML4ent + 1;
		pdpt_min = 0;
		goto PML4search;
	}
	addr |= (PDPTent << 30);
	if (non_canon_maxAccept)
	{
		if (addr > non_canon_maxAccept)
		{
			m_spinlock.releaseSpinlock();
			return ALLOC_BOUNDS_ERROR;
		}
	}
	//OK, we've got our PDPT entry
	COMPILER_MEMORY_BARRIER();
	//Now Search Page directory
PDIRsearch:
	size_t PDIRent = paging_search(&PDIR_entry, &PTBL_entry, 21, attr, addr, pdir_min, PAGE_TABLE_ENTRIES, pDirUser);
	if (PDIRent == PAGING_SEARCH_ERROR)
	{
		if (lastErr == TABLE_FULL)
			PDPT_entry(addr, PDPTent) &= ~PAGING_CHAIOS_FREEPAGES;
		pdpt_min = PDPTent + 1;
		pdir_min = 0;
		goto PDPTsearch;
	}
	addr |= (PDIRent << 21);
	//OK, we've got our PDPT entry
	COMPILER_MEMORY_BARRIER();
	//Now search page table
	size_t PTABent = paging_search(&PTBL_entry, NULL, 12, attr, addr, ptab_min, PAGE_TABLE_ENTRIES, pDirUser);
	if (PTABent == PAGING_SEARCH_ERROR)
	{
		if (lastErr == TABLE_FULL)
			PDIR_entry(addr, PDIRent) &= ~PAGING_CHAIOS_FREEPAGES;
		ptab_min = 0;
		pdir_min = PDIRent + 1;
		goto PDIRsearch;
	}
	//OK, we have a page table!
	addr |= (PTABent << 12);
	INVLPG((virtaddr)MAKE_CANONICAL(addr));
	m_spinlock.releaseSpinlock();
	return (virtaddr)MAKE_CANONICAL(addr);
}

void CALLING_CONVENTION CX64DefaultVMemMngr::free(virtaddr addr, size_t len, bool freePhys)
{
	if (len == 0)
		return;
	//Handle un-aligned
	size_t non_align = ((size_t)addr & 0xFFF);
	addr = (virtaddr)((size_t)addr ^ non_align);
	len += non_align;
	for (size_t n = 0; n < PAGE_NUM_ROUND_UP(len); n++)
	{
		freeSinglePage((virtaddr)((size_t)addr + (n*PAGESIZE)), freePhys);
	}
}

void CALLING_CONVENTION CX64DefaultVMemMngr::freeSinglePage(virtaddr addr, bool freePhys)
{
	physaddr paddr = (physaddr)(MMU_PT(addr)[MMU_PT_INDEX(addr)] & ~(0xFFF));
	m_spinlock.acquireSpinlock();
	MMU_PML4(addr)[MMU_PML4_INDEX(addr)] |= PAGING_CHAIOS_FREEPAGES;
	MMU_PDPT(addr)[MMU_PDPT_INDEX(addr)] |= PAGING_CHAIOS_FREEPAGES;
	MMU_PD(addr)[MMU_PD_INDEX(addr)] |= PAGING_CHAIOS_FREEPAGES;
	MMU_PT(addr)[MMU_PT_INDEX(addr)] = 0;
	INVLPG(addr);
	m_spinlock.releaseSpinlock();
	if (freePhys)
		getMemoryManager()->getPMemMngr()->freeSinglePage(paddr);
}

physaddr CALLING_CONVENTION CX64DefaultVMemMngr::getPhysicalAddress(virtaddr addr)
{
	if (MMU_PML4(addr)[MMU_PML4_INDEX(addr)] & PAGING_PRESENT)
	{
		if (MMU_PML4(addr)[MMU_PML4_INDEX(addr)] & PAGING_PSE)
		{
			size_t add = (MMU_PML4(addr)[MMU_PML4_INDEX(addr)] & ~(0xFFF));
			add |= ((size_t)addr & 0xFFFFFFF000);
			return (physaddr)add;
		}
		else
		{
			if (MMU_PDPT(addr)[MMU_PDPT_INDEX(addr)] & PAGING_PRESENT)
			{
				if (MMU_PDPT(addr)[MMU_PDPT_INDEX(addr)] & PAGING_PSE)
				{
					size_t add = (MMU_PDPT(addr)[MMU_PDPT_INDEX(addr)] & ~(0xFFF));
					add |= ((size_t)addr & 0x3FFFF000);
					return (physaddr)add;
				}
				else
				{
					if (MMU_PD(addr)[MMU_PD_INDEX(addr)] & PAGING_PRESENT)
					{
						if (MMU_PD(addr)[MMU_PD_INDEX(addr)] & PAGING_PSE)
						{
							size_t add = (MMU_PD(addr)[MMU_PD_INDEX(addr)] & ~(0xFFF));
							add |= ((size_t)addr & 0x1FF000);
							return (physaddr)add;
						}
						else
						{
							if (MMU_PT(addr)[MMU_PT_INDEX(addr)] & PAGING_PRESENT)
								return (physaddr)(MMU_PT(addr)[MMU_PT_INDEX(addr)] & ~(0xFFF));
							else	//Swapped out or not present
							{
								if (MMU_PT(addr)[MMU_PT_INDEX(addr)] & PAGING_CHAIOS_SWAPPED)
									return GET_PHYSADDR_SWAP_ERROR;
								else
									return GET_PHYSADDR_PRES_ERROR;
							}
						}
					}
					else	//Swapped out or not present
					{

						if (MMU_PD(addr)[MMU_PD_INDEX(addr)] & PAGING_CHAIOS_SWAPPED)
							return GET_PHYSADDR_SWAP_ERROR;
						else
							return GET_PHYSADDR_PRES_ERROR;
					}
				}
			}
			else	//Swapped out or not present
			{

				if (MMU_PDPT(addr)[MMU_PDPT_INDEX(addr)] & PAGING_CHAIOS_SWAPPED)
					return GET_PHYSADDR_SWAP_ERROR;
				else
					return GET_PHYSADDR_PRES_ERROR;
			}
		}
	}
	else	//Swapped out or not present
	{

		if (MMU_PML4(addr)[MMU_PML4_INDEX(addr)] & PAGING_CHAIOS_SWAPPED)
			return GET_PHYSADDR_SWAP_ERROR;
		else
			return GET_PHYSADDR_PRES_ERROR;
	}
}

virtaddr CALLING_CONVENTION CX64DefaultVMemMngr::mapPhysicalAddress(physaddr addr, size_t len, const PAGING_ATTRIBUTES& attr)
{
	virtaddr returnAddr = 0;		//Address to return
	virtaddr allocateProg = 0;		//Progress (temporary var)
	//Handle non-aligned addresses
	size_t non_align = (size_t)addr & 0xFFF;
	if (len == 0)
	{
		return NULL;
	}
	len += non_align;
	addr = (physaddr)((size_t)addr ^ non_align);		//XOR will clear bottom bits
	for (size_t n = 0; n < PAGE_NUM_ROUND_UP(len); n++)
	{
		allocateProg = mapSinglePhysicalPage(PHYSADDR_ADD(addr,n*PAGESIZE), attr);
		if (((size_t)allocateProg % PAGESIZE) != 0)		//Error
		{
			free(returnAddr, n*PAGESIZE, false);	//Free what we've allocated so far
			return NULL;						//Return error
		}
		if (n == 0)
		{
			returnAddr = allocateProg;
		}
		else
		{
			if (allocateProg != (virtaddr)((size_t)returnAddr + (n*PAGESIZE)))		//We want to allocate a contiguous region
			{
				virtaddr ret = mapPhysicalAddress(addr, len, attr);	//Recursion. Awesome.
				free(returnAddr, n*PAGESIZE, false);		//Free what we've allocated so far
				freeSinglePage(allocateProg, false);		//And what we've just allocated
				return ret;
			}
		}
	}
	//Now add our non-alignment
	returnAddr = (virtaddr)((size_t)returnAddr | non_align);
	return returnAddr;
}

virtaddr CALLING_CONVENTION CX64DefaultVMemMngr::mapSinglePhysicalPage(physaddr addr, const PAGING_ATTRIBUTES& attrib)
{
	//We will shorten this implementation by using allocateSingle, then freeing the physical and using the given address
	virtaddr vaddr = allocateSinglePage(attrib);
	if (((size_t)vaddr % PAGESIZE) != 0)		//All error codes must not be page-aligned
		return vaddr;
	if (MMU_PML4(vaddr)[MMU_PML4_INDEX(vaddr)] & PAGING_PSE)
	{
		freeSinglePage(vaddr);
		return MAP_PSE_ALLOC_ERROR;
	}
	if (MMU_PDPT(vaddr)[MMU_PDPT_INDEX(vaddr)] & PAGING_PSE)
	{
		freeSinglePage(vaddr);
		return MAP_PSE_ALLOC_ERROR;
	}
	if (MMU_PD(vaddr)[MMU_PD_INDEX(vaddr)] & PAGING_PSE)
	{
		freeSinglePage(vaddr);
		return MAP_PSE_ALLOC_ERROR;
	}
	else
	{
		m_spinlock.acquireSpinlock();
		physaddr physicalllyAllocated = (physaddr)((MMU_PT(vaddr)[MMU_PT_INDEX(vaddr)] & ~(0xFFF)));
		MMU_PT(vaddr)[MMU_PT_INDEX(vaddr)] &= 0xFFF;
		MMU_PT(vaddr)[MMU_PT_INDEX(vaddr)] |= (size_t)addr;
		INVLPG(vaddr);
		m_spinlock.releaseSpinlock();
		getMemoryManager()->getPMemMngr()->freeSinglePage(physicalllyAllocated);
		return vaddr;
	}
}

virtaddr CX64DefaultVMemMngr::allocateAt(virtaddr allocLoc, size_t len, const PAGING_ATTRIBUTES& attr)
{
	for (size_t n = 0; n < PAGE_NUM_ROUND_UP(len); n++)
	{
		virtaddr alloc = allocateSingleAt((virtaddr)((size_t)allocLoc + n*PAGESIZE), attr);
		if (alloc != (virtaddr)((size_t)allocLoc + n*PAGESIZE))		//Any error code will satisfy
		{
			//Free what currently allocated
			free(allocLoc, n*PAGESIZE);
			return alloc;
		}
	}
	return allocLoc;
}

virtaddr CX64DefaultVMemMngr::allocateSingleAt(virtaddr allocLoc, const PAGING_ATTRIBUTES& attr)
{
	bool pDirUser = false;
	if (attr.isUser)
	{
		pDirUser = true;
	}
	if ((size_t)allocLoc < KERNEL_MEMORY_BASE)
		pDirUser = true;

	size_t addr = (size_t)allocLoc;

	m_spinlock.acquireSpinlock();
	auto errorHandler = [&]()
	{
		m_spinlock.releaseSpinlock();
		if (lastErr == PHYMEM)
			return ALLOC_OUT_OF_PHYMEM;
		else
			return ALLOC_BOUNDS_ERROR;
	};
	size_t err = paging_allocate_at(&PML4_entry, &PDPT_entry, 39, attr, addr, pDirUser);
	if (err)
	{
		return errorHandler();
	}
	err = paging_allocate_at(&PDPT_entry, &PDIR_entry, 30, attr, addr, pDirUser);
	if (err)
	{
		return errorHandler();
	}
	err = paging_allocate_at(&PDIR_entry, &PTBL_entry, 21, attr, addr, pDirUser);
	if (err)
	{
		return errorHandler();
	}
	err = paging_allocate_at(&PTBL_entry, NULL, 12, attr, addr, pDirUser);
	if (err)
	{
		return errorHandler();
	}
	m_spinlock.releaseSpinlock();
	return allocLoc;
}

virtaddr CALLING_CONVENTION CX64DefaultVMemMngr::mapPhysicalAddressAt(virtaddr allocLoc, physaddr phAddr, size_t len, const PAGING_ATTRIBUTES& attrib)
{
	for (size_t n = 0; n < PAGE_NUM_ROUND_UP(len); n++)
	{
		virtaddr alloc = mapSinglePhysicalAddressAt((virtaddr)((size_t)allocLoc + n*PAGESIZE), PHYSADDR_ADD(phAddr, n*PAGESIZE), attrib);
		if (alloc != (virtaddr)((size_t)allocLoc + n*PAGESIZE))		//Any error code will satisfy
		{
			//Free what currently allocated
			free(allocLoc, n*PAGESIZE, false);
			return alloc;
		}
	}
	return allocLoc;
}

virtaddr CALLING_CONVENTION CX64DefaultVMemMngr::mapSinglePhysicalAddressAt(virtaddr allocLoc, physaddr phAddr, const PAGING_ATTRIBUTES& attr)
{
	virtaddr vaddr = allocateSingleAt(allocLoc, attr);
	//Now change physical
	if (((size_t)vaddr % PAGESIZE) != 0)		//All error codes must not be page-aligned
		return vaddr;
	if (MMU_PML4(vaddr)[MMU_PML4_INDEX(vaddr)] & PAGING_PSE)
	{
		freeSinglePage(vaddr);
		return MAP_PSE_ALLOC_ERROR;
	}
	if (MMU_PDPT(vaddr)[MMU_PDPT_INDEX(vaddr)] & PAGING_PSE)
	{
		freeSinglePage(vaddr);
		return MAP_PSE_ALLOC_ERROR;
	}
	if (MMU_PD(vaddr)[MMU_PD_INDEX(vaddr)] & PAGING_PSE)
	{
		freeSinglePage(vaddr);
		return MAP_PSE_ALLOC_ERROR;
	}
	else
	{
		m_spinlock.acquireSpinlock();
		physaddr physicalllyAllocated = (physaddr)((MMU_PT(vaddr)[MMU_PT_INDEX(vaddr)] & ~(0xFFF)));
		MMU_PT(vaddr)[MMU_PT_INDEX(vaddr)] &= 0xFFF;
		MMU_PT(vaddr)[MMU_PT_INDEX(vaddr)] |= (size_t)phAddr;
		INVLPG(vaddr);
		m_spinlock.releaseSpinlock();
		getMemoryManager()->getPMemMngr()->freeSinglePage(physicalllyAllocated);
		return vaddr;
	}
}

size_t CALLING_CONVENTION CX64DefaultVMemMngr::createNewAddressSpace()
{
	physaddr newpdir = getMemoryManager()->getPMemMngr()->allocateSinglePage();
	const size_t KRNL_MEMORY_BASE_NONCANON = CANONICAL_UNDO(KERNEL_MEMORY_BASE);
	if (newpdir == 0)
		return false;
	virtaddr mappeddir = mapSinglePhysicalPage(newpdir, kernelAttribs);
	if (((size_t)mappeddir % PAGESIZE) == 0)
	{
		getMemoryManager()->getPMemMngr()->freeSinglePage(newpdir);
		return false;
	}
	size_t* pdirarray = reinterpret_cast<size_t*>(mappeddir);
	for (int n = 0; n < (KRNL_MEMORY_BASE_NONCANON >> 39); n++)
	{
		pdirarray[n] = 0;
	}
	for (size_t n = (KRNL_MEMORY_BASE_NONCANON >> 39); n < PAGE_TABLE_ENTRIES; n++)
	{
		pdirarray[n] = MMU_PML4(0)[n];
	}
	unmapSinglePage(mappeddir);
	return (size_t)newpdir;
}

size_t CALLING_CONVENTION CX64DefaultVMemMngr::loadAddressSpace(size_t space)
{
	DISABLE_INTERRUPTS();
	m_spinlock.acquireSpinlock();
	size_t old = READ_CR3();
	WRITE_CR3(space);
	m_spinlock.releaseSpinlock();
	ENABLE_INTERRUPTS();
	return old;
}

CX64DefaultVMemMngr VMemMngr;

EXTERN CHAIOS_API_FUNC(CVMemMngr* CALLING_CONVENTION DefaultVMemMngrFactory())
{
	return &VMemMngr;
}