text:
from __future__ import print_function

from helpers import unittest

from luigi.mock import MockTarget, MockFileSystem
from luigi import six

class MockFileTest(unittest.TestCase):

    def test_1(self):
        t = MockTarget('test')
        p = t.open('w')
        print('test', file=p)
        p.close()

        q = t.open('r')
        self.assertEqual(list(q), ['test\n'])
        q.close()

    def test_with(self):
        t = MockTarget("foo")
        with t.open('w') as b:
            b.write("bar")

        with t.open('r') as b:
            self.assertEqual(list(b), ['bar'])

    # That should work in python2 because of the autocast
    # That should work in python3 because the default format is Text
    def test_unicode(self):
        t = MockTarget("foo")
        with t.open('w') as b:
            b.write(u"bar")

        with t.open('r') as b:
            self.assertEqual(b.read(), u'bar')

class MockFileSystemTest(unittest.TestCase):
    fs = MockFileSystem()

    def _touch(self, path):
        t = MockTarget(path)
        with t.open('w'):
            pass

    def setUp(self):
        self.fs.clear()
        self.path = "/tmp/foo"
        self.path2 = "/tmp/bar"
        self.path3 = "/tmp/foobar"
        self._touch(self.path)
        self._touch(self.path2)

    def test_copy(self):
        self.fs.copy(self.path, self.path3)
        self.assertTrue(self.fs.exists(self.path))
        self.assertTrue(self.fs.exists(self.path3))

    def test_exists(self):
        self.assertTrue(self.fs.exists(self.path))

    def test_remove(self):
        self.fs.remove(self.path)
        self.assertFalse(self.fs.exists(self.path))

    def test_remove_recursive(self):
        self.fs.remove("/tmp", recursive=True)
        self.assertFalse(self.fs.exists(self.path))
        self.assertFalse(self.fs.exists(self.path2))

    def test_rename(self):
        self.fs.rename(self.path, self.path3)
        self.assertFalse(self.fs.exists(self.path))
        self.assertTrue(self.fs.exists(self.path3))

    def test_listdir(self):
        self.assertEqual(sorted([self.path, self.path2]), sorted(self.fs.listdir("/tmp")))

class TestImportMockFile(unittest.TestCase):

    def test_mockfile(self):
        from luigi.mock import MockFile
        if six.PY3:
            with self.assertWarnsRegex(DeprecationWarning, r'MockFile has been renamed MockTarget'):
                self.assertTrue(isinstance(MockFile('foo'), MockTarget))
        else:
            self.assertTrue(isinstance(MockFile('foo'), MockTarget))


text:
#include "cartographer/mapping/map_builder.h"

#include "absl/memory/memory.h"
#include "cartographer/common/time.h"
#include "cartographer/io/internal/mapping_state_serialization.h"
#include "cartographer/io/proto_stream.h"
#include "cartographer/io/proto_stream_deserializer.h"
#include "cartographer/io/serialization_format_migration.h"
#include "cartographer/mapping/internal/2d/local_trajectory_builder_2d.h"
#include "cartographer/mapping/internal/2d/pose_graph_2d.h"
#include "cartographer/mapping/internal/3d/local_trajectory_builder_3d.h"
#include "cartographer/mapping/internal/3d/pose_graph_3d.h"
#include "cartographer/mapping/internal/collated_trajectory_builder.h"
#include "cartographer/mapping/internal/global_trajectory_builder.h"
#include "cartographer/sensor/internal/collator.h"
#include "cartographer/sensor/internal/trajectory_collator.h"
#include "cartographer/sensor/internal/voxel_filter.h"
#include "cartographer/transform/rigid_transform.h"
#include "cartographer/transform/transform.h"

namespace cartographer {
namespace mapping {
namespace {

using mapping::proto::SerializedData;

std::vector<std::string> SelectRangeSensorIds(
    const std::set<MapBuilder::SensorId>& expected_sensor_ids) {
  std::vector<std::string> range_sensor_ids;
  for (const MapBuilder::SensorId& sensor_id : expected_sensor_ids) {
    if (sensor_id.type == MapBuilder::SensorId::SensorType::RANGE) {
      range_sensor_ids.push_back(sensor_id.id);
    }
  }
  return range_sensor_ids;
}

void MaybeAddPureLocalizationTrimmer(
    const int trajectory_id,
    const proto::TrajectoryBuilderOptions& trajectory_options,
    PoseGraph* pose_graph) {
  if (trajectory_options.pure_localization()) {
    LOG(WARNING)
        << "'TrajectoryBuilderOptions::pure_localization' field is deprecated. "
           "Use 'TrajectoryBuilderOptions::pure_localization_trimmer' instead.";
    pose_graph->AddTrimmer(absl::make_unique<PureLocalizationTrimmer>(
        trajectory_id, 3 /* max_submaps_to_keep */));
    return;
  }
  if (trajectory_options.has_pure_localization_trimmer()) {
    pose_graph->AddTrimmer(absl::make_unique<PureLocalizationTrimmer>(
        trajectory_id,
        trajectory_options.pure_localization_trimmer().max_submaps_to_keep()));
  }
}

}  // namespace

proto::MapBuilderOptions CreateMapBuilderOptions(
    common::LuaParameterDictionary* const parameter_dictionary) {
  proto::MapBuilderOptions options;
  options.set_use_trajectory_builder_2d(
      parameter_dictionary->GetBool("use_trajectory_builder_2d"));
  options.set_use_trajectory_builder_3d(
      parameter_dictionary->GetBool("use_trajectory_builder_3d"));
  options.set_num_background_threads(
      parameter_dictionary->GetNonNegativeInt("num_background_threads"));
  options.set_collate_by_trajectory(
      parameter_dictionary->GetBool("collate_by_trajectory"));
  *options.mutable_pose_graph_options() = CreatePoseGraphOptions(
      parameter_dictionary->GetDictionary("pose_graph").get());
  CHECK_NE(options.use_trajectory_builder_2d(),
           options.use_trajectory_builder_3d());
  return options;
}

MapBuilder::MapBuilder(const proto::MapBuilderOptions& options)
    : options_(options), thread_pool_(options.num_background_threads()) {
  CHECK(options.use_trajectory_builder_2d() ^
        options.use_trajectory_builder_3d());
  if (options.use_trajectory_builder_2d()) {
    pose_graph_ = absl::make_unique<PoseGraph2D>(
        options_.pose_graph_options(),
        absl::make_unique<optimization::OptimizationProblem2D>(
            options_.pose_graph_options().optimization_problem_options()),
        &thread_pool_);
  }
  if (options.use_trajectory_builder_3d()) {
    pose_graph_ = absl::make_unique<PoseGraph3D>(
        options_.pose_graph_options(),
        absl::make_unique<optimization::OptimizationProblem3D>(
            options_.pose_graph_options().optimization_problem_options()),
        &thread_pool_);
  }
  if (options.collate_by_trajectory()) {
    sensor_collator_ = absl::make_unique<sensor::TrajectoryCollator>();
  } else {
    sensor_collator_ = absl::make_unique<sensor::Collator>();
  }
}

int MapBuilder::AddTrajectoryBuilder(
    const std::set<SensorId>& expected_sensor_ids,
    const proto::TrajectoryBuilderOptions& trajectory_options,
    LocalSlamResultCallback local_slam_result_callback) {
  const int trajectory_id = trajectory_builders_.size();
  if (options_.use_trajectory_builder_3d()) {
    std::unique_ptr<LocalTrajectoryBuilder3D> local_trajectory_builder;
    if (trajectory_options.has_trajectory_builder_3d_options()) {
      local_trajectory_builder = absl::make_unique<LocalTrajectoryBuilder3D>(
          trajectory_options.trajectory_builder_3d_options(),
          SelectRangeSensorIds(expected_sensor_ids));
    }
    DCHECK(dynamic_cast<PoseGraph3D*>(pose_graph_.get()));
    trajectory_builders_.push_back(absl::make_unique<CollatedTrajectoryBuilder>(
        trajectory_options, sensor_collator_.get(), trajectory_id,
        expected_sensor_ids,
        CreateGlobalTrajectoryBuilder3D(
            std::move(local_trajectory_builder), trajectory_id,
            static_cast<PoseGraph3D*>(pose_graph_.get()),
            local_slam_result_callback)));
  } else {
    std::unique_ptr<LocalTrajectoryBuilder2D> local_trajectory_builder;
    if (trajectory_options.has_trajectory_builder_2d_options()) {
      local_trajectory_builder = absl::make_unique<LocalTrajectoryBuilder2D>(
          trajectory_options.trajectory_builder_2d_options(),
          SelectRangeSensorIds(expected_sensor_ids));
    }
    DCHECK(dynamic_cast<PoseGraph2D*>(pose_graph_.get()));
    trajectory_builders_.push_back(absl::make_unique<CollatedTrajectoryBuilder>(
        trajectory_options, sensor_collator_.get(), trajectory_id,
        expected_sensor_ids,
        CreateGlobalTrajectoryBuilder2D(
            std::move(local_trajectory_builder), trajectory_id,
            static_cast<PoseGraph2D*>(pose_graph_.get()),
            local_slam_result_callback)));
  }
  MaybeAddPureLocalizationTrimmer(trajectory_id, trajectory_options,
                                  pose_graph_.get());

  if (trajectory_options.has_initial_trajectory_pose()) {
    const auto& initial_trajectory_pose =
        trajectory_options.initial_trajectory_pose();
    pose_graph_->SetInitialTrajectoryPose(
        trajectory_id, initial_trajectory_pose.to_trajectory_id(),
        transform::ToRigid3(initial_trajectory_pose.relative_pose()),
        common::FromUniversal(initial_trajectory_pose.timestamp()));
  }
  proto::TrajectoryBuilderOptionsWithSensorIds options_with_sensor_ids_proto;
  for (const auto& sensor_id : expected_sensor_ids) {
    *options_with_sensor_ids_proto.add_sensor_id() = ToProto(sensor_id);
  }
  *options_with_sensor_ids_proto.mutable_trajectory_builder_options() =
      trajectory_options;
  all_trajectory_builder_options_.push_back(options_with_sensor_ids_proto);
  CHECK_EQ(trajectory_builders_.size(), all_trajectory_builder_options_.size());
  return trajectory_id;
}

int MapBuilder::AddTrajectoryForDeserialization(
    const proto::TrajectoryBuilderOptionsWithSensorIds&
        options_with_sensor_ids_proto) {
  const int trajectory_id = trajectory_builders_.size();
  trajectory_builders_.emplace_back();
  all_trajectory_builder_options_.push_back(options_with_sensor_ids_proto);
  CHECK_EQ(trajectory_builders_.size(), all_trajectory_builder_options_.size());
  return trajectory_id;
}

void MapBuilder::FinishTrajectory(const int trajectory_id) {
  sensor_collator_->FinishTrajectory(trajectory_id);
  pose_graph_->FinishTrajectory(trajectory_id);
}

std::string MapBuilder::SubmapToProto(
    const SubmapId& submap_id, proto::SubmapQuery::Response* const response) {
  if (submap_id.trajectory_id < 0 ||
      submap_id.trajectory_id >= num_trajectory_builders()) {
    return "Requested submap from trajectory " +
           std::to_string(submap_id.trajectory_id) + " but there are only " +
           std::to_string(num_trajectory_builders()) + " trajectories.";
  }

  const auto submap_data = pose_graph_->GetSubmapData(submap_id);
  if (submap_data.submap == nullptr) {
    return "Requested submap " + std::to_string(submap_id.submap_index) +
           " from trajectory " + std::to_string(submap_id.trajectory_id) +
           " but it does not exist: maybe it has been trimmed.";
  }
  submap_data.submap->ToResponseProto(submap_data.pose, response);
  return "";
}

void MapBuilder::SerializeState(bool include_unfinished_submaps,
                                io::ProtoStreamWriterInterface* const writer) {
  io::WritePbStream(*pose_graph_, all_trajectory_builder_options_, writer,
                    include_unfinished_submaps);
}

bool MapBuilder::SerializeStateToFile(bool include_unfinished_submaps,
                                      const std::string& filename) {
  io::ProtoStreamWriter writer(filename);
  io::WritePbStream(*pose_graph_, all_trajectory_builder_options_, &writer,
                    include_unfinished_submaps);
  return (writer.Close());
}

std::map<int, int> MapBuilder::LoadState(
    io::ProtoStreamReaderInterface* const reader, bool load_frozen_state) {
  io::ProtoStreamDeserializer deserializer(reader);

  // Create a copy of the pose_graph_proto, such that we can re-write the
  // trajectory ids.
  proto::PoseGraph pose_graph_proto = deserializer.pose_graph();
  const auto& all_builder_options_proto =
      deserializer.all_trajectory_builder_options();

  std::map<int, int> trajectory_remapping;
  for (int i = 0; i < pose_graph_proto.trajectory_size(); ++i) {
    auto& trajectory_proto = *pose_graph_proto.mutable_trajectory(i);
    const auto& options_with_sensor_ids_proto =
        all_builder_options_proto.options_with_sensor_ids(i);
    const int new_trajectory_id =
        AddTrajectoryForDeserialization(options_with_sensor_ids_proto);
    CHECK(trajectory_remapping
              .emplace(trajectory_proto.trajectory_id(), new_trajectory_id)
              .second)
        << "Duplicate trajectory ID: " << trajectory_proto.trajectory_id();
    trajectory_proto.set_trajectory_id(new_trajectory_id);
    if (load_frozen_state) {
      pose_graph_->FreezeTrajectory(new_trajectory_id);
    }
  }

  // Apply the calculated remapping to constraints in the pose graph proto.
  for (auto& constraint_proto : *pose_graph_proto.mutable_constraint()) {
    constraint_proto.mutable_submap_id()->set_trajectory_id(
        trajectory_remapping.at(constraint_proto.submap_id().trajectory_id()));
    constraint_proto.mutable_node_id()->set_trajectory_id(
        trajectory_remapping.at(constraint_proto.node_id().trajectory_id()));
  }

  MapById<SubmapId, transform::Rigid3d> submap_poses;
  for (const proto::Trajectory& trajectory_proto :
       pose_graph_proto.trajectory()) {
    for (const proto::Trajectory::Submap& submap_proto :
         trajectory_proto.submap()) {
      submap_poses.Insert(SubmapId{trajectory_proto.trajectory_id(),
                                   submap_proto.submap_index()},
                          transform::ToRigid3(submap_proto.pose()));
    }
  }

  MapById<NodeId, transform::Rigid3d> node_poses;
  for (const proto::Trajectory& trajectory_proto :
       pose_graph_proto.trajectory()) {
    for (const proto::Trajectory::Node& node_proto : trajectory_proto.node()) {
      node_poses.Insert(
          NodeId{trajectory_proto.trajectory_id(), node_proto.node_index()},
          transform::ToRigid3(node_proto.pose()));
    }
  }

  // Set global poses of landmarks.
  for (const auto& landmark : pose_graph_proto.landmark_poses()) {
    pose_graph_->SetLandmarkPose(landmark.landmark_id(),
                                 transform::ToRigid3(landmark.global_pose()),
                                 true);
  }

  if (options_.use_trajectory_builder_3d()) {
    CHECK_NE(deserializer.header().format_version(),
             io::kFormatVersionWithoutSubmapHistograms)
        << "The pbstream file contains submaps without rotational histograms. "
           "This can be converted with the 'pbstream migrate' tool, see the "
           "Cartographer documentation for details. ";
  }

  SerializedData proto;
  while (deserializer.ReadNextSerializedData(&proto)) {
    switch (proto.data_case()) {
      case SerializedData::kPoseGraph:
        LOG(ERROR) << "Found multiple serialized `PoseGraph`. Serialized "
                      "stream likely corrupt!.";
        break;
      case SerializedData::kAllTrajectoryBuilderOptions:
        LOG(ERROR) << "Found multiple serialized "
                      "`AllTrajectoryBuilderOptions`. Serialized stream likely "
                      "corrupt!.";
        break;
      case SerializedData::kSubmap: {
        proto.mutable_submap()->mutable_submap_id()->set_trajectory_id(
            trajectory_remapping.at(
                proto.submap().submap_id().trajectory_id()));
        const SubmapId submap_id(proto.submap().submap_id().trajectory_id(),
                                 proto.submap().submap_id().submap_index());
        pose_graph_->AddSubmapFromProto(submap_poses.at(submap_id),
                                        proto.submap());
        break;
      }
      case SerializedData::kNode: {
        proto.mutable_node()->mutable_node_id()->set_trajectory_id(
            trajectory_remapping.at(proto.node().node_id().trajectory_id()));
        const NodeId node_id(proto.node().node_id().trajectory_id(),
                             proto.node().node_id().node_index());
        const transform::Rigid3d& node_pose = node_poses.at(node_id);
        pose_graph_->AddNodeFromProto(node_pose, proto.node());
        break;
      }
      case SerializedData::kTrajectoryData: {
        proto.mutable_trajectory_data()->set_trajectory_id(
            trajectory_remapping.at(proto.trajectory_data().trajectory_id()));
        pose_graph_->SetTrajectoryDataFromProto(proto.trajectory_data());
        break;
      }
      case SerializedData::kImuData: {
        if (load_frozen_state) break;
        pose_graph_->AddImuData(
            trajectory_remapping.at(proto.imu_data().trajectory_id()),
            sensor::FromProto(proto.imu_data().imu_data()));
        break;
      }
      case SerializedData::kOdometryData: {
        if (load_frozen_state) break;
        pose_graph_->AddOdometryData(
            trajectory_remapping.at(proto.odometry_data().trajectory_id()),
            sensor::FromProto(proto.odometry_data().odometry_data()));
        break;
      }
      case SerializedData::kFixedFramePoseData: {
        if (load_frozen_state) break;
        pose_graph_->AddFixedFramePoseData(
            trajectory_remapping.at(
                proto.fixed_frame_pose_data().trajectory_id()),
            sensor::FromProto(
                proto.fixed_frame_pose_data().fixed_frame_pose_data()));
        break;
      }
      case SerializedData::kLandmarkData: {
        if (load_frozen_state) break;
        pose_graph_->AddLandmarkData(
            trajectory_remapping.at(proto.landmark_data().trajectory_id()),
            sensor::FromProto(proto.landmark_data().landmark_data()));
        break;
      }
      default:
        LOG(WARNING) << "Skipping unknown message type in stream: "
                     << proto.GetTypeName();
    }
  }

  if (load_frozen_state) {
    // Add information about which nodes belong to which submap.
    // Required for 3D pure localization.
    for (const proto::PoseGraph::Constraint& constraint_proto :
         pose_graph_proto.constraint()) {
      if (constraint_proto.tag() !=
          proto::PoseGraph::Constraint::INTRA_SUBMAP) {
        continue;
      }
      pose_graph_->AddNodeToSubmap(
          NodeId{constraint_proto.node_id().trajectory_id(),
                 constraint_proto.node_id().node_index()},
          SubmapId{constraint_proto.submap_id().trajectory_id(),
                   constraint_proto.submap_id().submap_index()});
    }
  } else {
    // When loading unfrozen trajectories, 'AddSerializedConstraints' will
    // take care of adding information about which nodes belong to which
    // submap.
    pose_graph_->AddSerializedConstraints(
        FromProto(pose_graph_proto.constraint()));
  }
  CHECK(reader->eof());
  return trajectory_remapping;
}

std::map<int, int> MapBuilder::LoadStateFromFile(
    const std::string& state_filename, const bool load_frozen_state) {
  const std::string suffix = ".pbstream";
  if (state_filename.substr(
          std::max<int>(state_filename.size() - suffix.size(), 0)) != suffix) {
    LOG(WARNING) << "The file containing the state should be a "
                    ".pbstream file.";
  }
  LOG(INFO) << "Loading saved state '" << state_filename << "'...";
  io::ProtoStreamReader stream(state_filename);
  return LoadState(&stream, load_frozen_state);
}

}  // namespace mapping
}  // namespace cartographer

redpajama_set_name: RedPajamaGithub


text:
package universalelectricity.prefab.vector;

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

import net.minecraft.entity.Entity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import universalelectricity.core.vector.Vector3;

/**
 * A cubical region class.
 *
 * @author Calclavia
 */
public class Region3
{
	public Vector3 min;
	public Vector3 max;

	public Region3()
	{
		this(new Vector3(), new Vector3());
	}

	public Region3(Vector3 min, Vector3 max)
	{
		this.min = min;
		this.max = max;
	}

	public Region3(AxisAlignedBB aabb)
	{
		this.min = new Vector3(aabb.minX, aabb.minY, aabb.minZ);
		this.max = new Vector3(aabb.maxX, aabb.maxY, aabb.maxZ);
	}

	public AxisAlignedBB toAABB()
	{
		return AxisAlignedBB.getBoundingBox(this.min.x, this.min.y, this.min.z, this.max.x, this.max.y, this.max.z);
	}

	public Region2 toRegion2()
	{
		return new Region2(this.min.toVector2(), this.max.toVector2());
	}

	/**
	 * Checks if a point is located inside a region
	 */
	public boolean isIn(Vector3 point)
	{
		return (point.x > this.min.x && point.x < this.max.x) && (point.y > this.min.y && point.y < this.max.y) && (point.z > this.min.z && point.z < this.max.z);
	}

	/**
	 * Returns whether the given region intersects with this one.
	 */
	public boolean isIn(Region3 region)
	{
		return region.max.x > this.min.x && region.min.x < this.max.x ? (region.max.y > this.min.y && region.min.y < this.max.y ? region.max.z > this.min.z && region.min.z < this.max.z : false) : false;
	}

	public void expand(Vector3 difference)
	{
		this.min.subtract(difference);
		this.max.add(difference);
	}

	/**
	 * @return List of vectors within this region.
	 */
	public List<Vector3> getVectors()
	{
		List<Vector3> vectors = new ArrayList<Vector3>();

		for (int x = this.min.intX(); x < this.max.intX(); x++)
		{
			for (int y = this.min.intY(); x < this.max.intY(); y++)
			{
				for (int z = this.min.intZ(); x < this.max.intZ(); z++)
				{
					vectors.add(new Vector3(x, y, z));
				}
			}
		}

		return vectors;
	}

	public List<Vector3> getVectors(Vector3 center, int radius)
	{
		List<Vector3> vectors = new ArrayList<Vector3>();

		for (int x = this.min.intX(); x < this.max.intX(); x++)
		{
			for (int y = this.min.intY(); x < this.max.intY(); y++)
			{
				for (int z = this.min.intZ(); x < this.max.intZ(); z++)
				{
					Vector3 vector3 = new Vector3(x, y, z);

					if (center.distanceTo(vector3) <= radius)
					{
						vectors.add(vector3);
					}
				}
			}
		}

		return vectors;
	}

	/**
	 * Returns all entities in this region.
	 */
	public List<Entity> getEntities(World world, Class<? extends Entity> entityClass)
	{
		return world.getEntitiesWithinAABB(entityClass, this.toAABB());
	}

	public List<Entity> getEntitiesExlude(World world, Entity entity)
	{
		return world.getEntitiesWithinAABBExcludingEntity(entity, this.toAABB());
	}

	public List<Entity> getEntities(World world)
	{
		return this.getEntities(world, Entity.class);
	}
}


text:
const {waitUntilReady, cleanup, PouchDB} = require('./utils');

describe('signatures', () => {
  before(waitUntilReady);
  afterEach(cleanup);

  it('seamless auth', () => {
    const promise = PouchDB.seamlessSession(() => {});
    promise.then.should.be.ok;
    promise.catch.should.be.ok;
    return promise;
  });
});


text:
package io.netty.resolver.dns;

import io.netty.channel.ChannelFactory;
import io.netty.channel.EventLoop;
import io.netty.channel.ReflectiveChannelFactory;
import io.netty.channel.socket.DatagramChannel;
import io.netty.resolver.AddressResolver;
import io.netty.resolver.AddressResolverGroup;
import io.netty.resolver.InetSocketAddressResolver;
import io.netty.resolver.NameResolver;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.UnstableApi;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.ConcurrentMap;

import static io.netty.util.internal.PlatformDependent.newConcurrentHashMap;

/**
 * A {@link AddressResolverGroup} of {@link DnsNameResolver}s.
 */
@UnstableApi
public class DnsAddressResolverGroup extends AddressResolverGroup<InetSocketAddress> {

    private final DnsNameResolverBuilder dnsResolverBuilder;

    private final ConcurrentMap<String, Promise<InetAddress>> resolvesInProgress = newConcurrentHashMap();
    private final ConcurrentMap<String, Promise<List<InetAddress>>> resolveAllsInProgress = newConcurrentHashMap();

    public DnsAddressResolverGroup(DnsNameResolverBuilder dnsResolverBuilder) {
        this.dnsResolverBuilder = dnsResolverBuilder.copy();
    }

    public DnsAddressResolverGroup(
            Class<? extends DatagramChannel> channelType,
            DnsServerAddressStreamProvider nameServerProvider) {
        this(new DnsNameResolverBuilder());
        dnsResolverBuilder.channelType(channelType).nameServerProvider(nameServerProvider);
    }

    public DnsAddressResolverGroup(
            ChannelFactory<? extends DatagramChannel> channelFactory,
            DnsServerAddressStreamProvider nameServerProvider) {
        this(new DnsNameResolverBuilder());
        dnsResolverBuilder.channelFactory(channelFactory).nameServerProvider(nameServerProvider);
    }

    @SuppressWarnings("deprecation")
    @Override
    protected final AddressResolver<InetSocketAddress> newResolver(EventExecutor executor) throws Exception {
        if (!(executor instanceof EventLoop)) {
            throw new IllegalStateException(
                    "unsupported executor type: " + StringUtil.simpleClassName(executor) +
                    " (expected: " + StringUtil.simpleClassName(EventLoop.class));
        }

        // we don't really need to pass channelFactory and nameServerProvider separately,
        // but still keep this to ensure backward compatibility with (potentially) override methods
        return newResolver((EventLoop) executor,
                dnsResolverBuilder.channelFactory(),
                dnsResolverBuilder.nameServerProvider());
    }

    /**
     * @deprecated Override {@link #newNameResolver(EventLoop, ChannelFactory, DnsServerAddressStreamProvider)}.
     */
    @Deprecated
    protected AddressResolver<InetSocketAddress> newResolver(
            EventLoop eventLoop, ChannelFactory<? extends DatagramChannel> channelFactory,
            DnsServerAddressStreamProvider nameServerProvider) throws Exception {

        final NameResolver<InetAddress> resolver = new InflightNameResolver<InetAddress>(
                eventLoop,
                newNameResolver(eventLoop, channelFactory, nameServerProvider),
                resolvesInProgress,
                resolveAllsInProgress);

        return newAddressResolver(eventLoop, resolver);
    }

    /**
     * Creates a new {@link NameResolver}. Override this method to create an alternative {@link NameResolver}
     * implementation or override the default configuration.
     */
    protected NameResolver<InetAddress> newNameResolver(EventLoop eventLoop,
                                                        ChannelFactory<? extends DatagramChannel> channelFactory,
                                                        DnsServerAddressStreamProvider nameServerProvider)
            throws Exception {
        // once again, channelFactory and nameServerProvider are most probably set in builder already,
        // but I do reassign them again to avoid corner cases with override methods
        return dnsResolverBuilder.eventLoop(eventLoop)
                .channelFactory(channelFactory)
                .nameServerProvider(nameServerProvider)
                .build();
    }

    /**
     * Creates a new {@link AddressResolver}. Override this method to create an alternative {@link AddressResolver}
     * implementation or override the default configuration.
     */
    protected AddressResolver<InetSocketAddress> newAddressResolver(EventLoop eventLoop,
                                                                    NameResolver<InetAddress> resolver)
            throws Exception {
        return new InetSocketAddressResolver(eventLoop, resolver);
    }
}


text:
#ifndef glm_core_func_packing
#define glm_core_func_packing

namespace glm
{
	namespace test{
		void main_core_func_packing();
	}//namespace test

	namespace core{
	namespace function{
	//! Define packing functions from section 8.4 floating-point pack and unpack functions of GLSL 4.00.8 specification
	namespace packing
	{
		/// \addtogroup core_funcs
		///@{

        //! First, converts each component of the normalized floating-point value v into 8- or 16-bit integer values.
        //! Then, the results are packed into the returned 32-bit unsigned integer.
        //!
        //! The conversion for component c of v to fixed point is done as follows:
        //! packUnorm2x16: round(clamp(c, 0, +1) * 65535.0)
        //!
        //! The first component of the vector will be written to the least significant bits of the output;
        //! the last component will be written to the most significant bits.
        //!
        //! \li GLSL packUnorm2x16 man page
        //! \li GLSL 4.00.08 specification, section 8.4
		detail::uint32 packUnorm2x16(detail::tvec2<detail::float32> const & v);

        //! First, converts each component of the normalized floating-point value v into 8- or 16-bit integer values.
        //! Then, the results are packed into the returned 32-bit unsigned integer.
        //!
        //! The conversion for component c of v to fixed point is done as follows:
        //! packUnorm4x8:	round(clamp(c, 0, +1) * 255.0)
        //!
        //! The first component of the vector will be written to the least significant bits of the output;
        //! the last component will be written to the most significant bits.
        //!
        //! \li GLSL packUnorm4x8 man page
        //! \li GLSL 4.00.08 specification, section 8.4
		detail::uint32 packUnorm4x8(detail::tvec4<detail::float32> const & v);

        //! First, converts each component of the normalized floating-point value v into 8- or 16-bit integer values.
        //! Then, the results are packed into the returned 32-bit unsigned integer.
        //!
        //! The conversion for component c of v to fixed point is done as follows:
        //! packSnorm4x8:	round(clamp(c, -1, +1) * 127.0)
        //!
        //! The first component of the vector will be written to the least significant bits of the output;
        //! the last component will be written to the most significant bits.
        //!
        //! \li GLSL packSnorm4x8 man page
        //! \li GLSL 4.00.08 specification, section 8.4
		detail::uint32 packSnorm4x8(detail::tvec4<detail::float32> const & v);

        //! First, unpacks a single 32-bit unsigned integer p into a pair of 16-bit unsigned integers, four 8-bit unsigned integers, or four 8-bit signed integers.
        //! Then, each component is converted to a normalized floating-point value to generate the returned two- or four-component vector.
        //!
        //! The conversion for unpacked fixed-point value f to floating point is done as follows:
        //! unpackUnorm2x16: f / 65535.0
        //!
        //! The first component of the returned vector will be extracted from the least significant bits of the input;
        //! the last component will be extracted from the most significant bits.
        //!
        //! \li GLSL unpackUnorm2x16 man page
        //! \li GLSL 4.00.08 specification, section 8.4
		detail::tvec2<detail::float32> unpackUnorm2x16(detail::uint32 const & p);

        //! First, unpacks a single 32-bit unsigned integer p into a pair of 16-bit unsigned integers, four 8-bit unsigned integers, or four 8-bit signed integers.
        //! Then, each component is converted to a normalized floating-point value to generate the returned two- or four-component vector.
        //!
        //! The conversion for unpacked fixed-point value f to floating point is done as follows:
        //! unpackUnorm4x8: f / 255.0
        //!
        //! The first component of the returned vector will be extracted from the least significant bits of the input;
        //! the last component will be extracted from the most significant bits.
        //!
        //! \li GLSL unpackUnorm4x8 man page
        //! \li GLSL 4.00.08 specification, section 8.4
        detail::tvec4<detail::float32> unpackUnorm4x8(detail::uint32 const & p);

        //! First, unpacks a single 32-bit unsigned integer p into a pair of 16-bit unsigned integers, four 8-bit unsigned integers, or four 8-bit signed integers.
        //! Then, each component is converted to a normalized floating-point value to generate the returned two- or four-component vector.
        //!
        //! The conversion for unpacked fixed-point value f to floating point is done as follows:
        //! unpackSnorm4x8: clamp(f / 127.0, -1, +1)
        //!
        //! The first component of the returned vector will be extracted from the least significant bits of the input;
        //! the last component will be extracted from the most significant bits.
        //!
        //! \li GLSL unpackSnorm4x8 man page
        //! \li GLSL 4.00.08 specification, section 8.4
		detail::tvec4<detail::float32> unpackSnorm4x8(detail::uint32 const & p);

        //! Returns a double-precision value obtained by packing the components of v into a 64-bit value.
        //! If an IEEE 754 Inf or NaN is created, it will not signal, and the resulting floating point value is unspecified.
        //! Otherwise, the bit- level representation of v is preserved.
        //! The first vector component specifies the 32 least significant bits;
        //! the second component specifies the 32 most significant bits.
        //!
        //! \li GLSL packDouble2x32 man page
        //! \li GLSL 4.00.08 specification, section 8.4
		double packDouble2x32(detail::tvec2<detail::uint32> const & v);

        //! Returns a two-component unsigned integer vector representation of v.
        //! The bit-level representation of v is preserved.
        //! The first component of the vector contains the 32 least significant bits of the double;
        //! the second component consists the 32 most significant bits.
        //!
        //! \li GLSL unpackDouble2x32 man page
        //! \li GLSL 4.00.08 specification, section 8.4
		detail::tvec2<detail::uint32> unpackDouble2x32(double const & v);

		///@}

	}//namespace packing
	}//namespace function
	}//namespace core

	using namespace core::function::packing;
}//namespace glm

#include "func_packing.inl"

#endif//glm_core_func_packing


text:
  <title>Search Console gebruiken</title>
  <meta name="project_path" value="/web/fundamentals/_project.yaml"/>
  <meta name="book_path" value="/web/fundamentals/_book.yaml"/>

Als u het eigendom van uw site al heeft geverifieerd, kunt u de eerste actie hieronder overslaan en meteen doorgaan met het controleren van uw sitegegevens in Search Console.

Wat u nodig heeft:

De mogelijkheid om het eigendom van uw site te verifiëren door bijvoorbeeld een bestand aan de root-directory toe te voegen, metatags goed te keuren, een Google Analytics-beheerdersaccount voor de site te hebben, enzovoort.

Wat u gaat doen:

In dit gedeelte gaat u de volgende acties uitvoeren:

Eigendom van uw site verifiëren in Search Console.

Controleren of de hacker het eigendom nog niet heeft geverifieerd in Search Console en ongewenste wijzigingen in de instellingen heeft aangebracht.

De aard van de aanval bepalen.

Eigendom van uw site verifiëren in Search Console

Open een browser en ga naar Webmaster Central op http://www.google.com/webmasters.

Klik op Search Console.

Log in bij Search Console met een Google-account.
    Als u geen Google-account heeft, klikt u op Een account maken. Een nieuw Google-account betekent niet dat u uw bestaande e-mailaccount bij een ander bedrijf verliest.
    (Meer informatie over accounts.)

Klik op Een site toevoegen. Geef de URL van uw site op in het vak en klik op Doorgaan.

Kies de voor u meest geschikte verificatiemethode. Op het tabblad Aanbevolen methode op de verificatiepagina wordt de methode getoond die volgens Google het beste werkt. Aanvullende methoden vindt u op het tabblad Alternatieve methoden.
    (Meer informatie over verificatie.)

Als u een verificatiemethode heeft gekozen waarvoor toegang tot uw site vereist is, zoals verificatie met een HTML-metatag of HTML-bestand, moet u uw site weer online zetten.

Klik op Verifiëren om het eigendomsrecht met de door u geselecteerde methode te verifiëren. Als de verificatie slaagt, wordt een scherm weergegeven met de melding dat u een geverifieerde eigenaar bent.
    U kunt uw site nu weer offline halen. Voor volgende stappen is echter vereist dat de site weer online komt.

Nadat u bent geverifieerd, controleert u of de hacker nog niet het eigendom heeft geverifieerd in Search Console en nog geen ongewenste wijzigingen in de instellingen heeft aangebracht.

Klik op het logo van Search Console om naar de homepage van Search Console te gaan.

Zoek uw site op en klik op Site beheren.

Klik op Gebruikers toevoegen of verwijderen.

Controleer of alle vermelde gebruikers en eigenaren geautoriseerd zijn.

Registreer de e-mailadressen van niet-geautoriseerde gebruikers (dit kan in de toekomst nuttig zijn) en verwijder deze gebruikers van uw site. Voor niet-geautoriseerde eigenaren moet u zowel de eigenaar als de eventuele verificatietokens verwijderen, zoals een metatag voor verificatie op uw homepage of een HTML-bestand op uw server. (Meer informatie.)

Ga na of in Search Console ongewenste wijzigingen zijn aangebracht in de instellingen. Klik op het pictogram Instellingen en vervolgens op Site-instellingen om te controleren op mogelijk ongewenste wijzigingen door de hacker, zoals een lagere crawlsnelheid (misschien met het doel om spiders van zoekmachines te hinderen). Controleer ook of er niets ongebruikelijks wordt vermeld in het gedeelte Google-index > URL's verwijderen of Instellingen > Adreswijziging.

De aard van de aanval bepalen

Aan de hand van de informatie in het Berichtencentrum en bij Beveiligingsproblemen in Search Console kunt u bepalen of uw site op een van de volgende manieren is gehackt:

Met content die spam bevat die de kwaliteit en relevantie van de zoekresultaten kan verminderen.

Voor phishing-doeleinden.

Voor het verspreiden van malware.

Voer de volgende stappen uit om met Search Console onderzoek te doen naar hackingacties of malware:

Klik op het logo van Search Console linksboven om naar de homepage van Search Console te gaan.

Klik op Berichten.

Controleer of er waarschuwingsberichten van Google zijn die aangeven of uw site is gebruikt voor 1) het versturen van pagina's, tekst of links die spam bevatten, 2) phishing, 3) het verspreiden van malware. Als u een phishing-melding heeft, verwijdert u dit bericht pas wanneer u het hele herstelproces heeft afgerond.

Ga naar Beveiligingsproblemen in Search Console.

Sites die zijn geïnfecteerd met malware, zijn voorzien van een kop 'Malware' en vervolgens een malwarecategorie, zoals 'Gewijzigde serverconfiguratie' of 'Invoeging van foutsjabloon'. In deze gevallen kan de hacker uw site gebruiken om uw bezoekers te infecteren met software waarmee vertrouwelijke informatie kan worden achterhaald of die schadelijk is voor hun computers. Ga door naar Schade door malware beoordelen voor informatie over hoe u dit kunt oplossen.

Sites die zijn gehackt om spam te versturen, kunnen als kop 'Gehackt' weergeven en vervolgens een categorie, zoals 'Invoeging van inhoud'. Waarschijnlijk heeft de hacker pagina's, tekst of links die spam bevatten, op uw site geplaatst. Ga door naar Schade door spam beoordelen voor informatie over hoe u dit kunt oplossen.

Bij Beveiligingsproblemen staat mogelijk niets vermeld over sites die een phishing-melding hebben in het Berichtencentrum van Search Console. Door phishing-pagina's op uw site te maken, gebruikt de hacker uw site om inloggegevens, wachtwoorden of financiële gegevens van uw gebruikers te verkrijgen, vaak door zich voor te doen als een betrouwbare site. Omdat het schoonmaken van phishing vergelijkbaar is met het schoonmaken van spam, kunt u gebruikmaken van de informatie onder Schade door spam beoordelen.

Volgende stap

De volgende stap in het proces is Schade door spam beoordelen (gehackt met spam) of Schade door malware beoordelen (gehackt met malware).


text:
'''Example shows the recommended way of how to run Kivy with a trio
event loop as just another async coroutine.
'''
import trio

from kivy.app import App
from kivy.lang.builder import Builder

kv = '''
BoxLayout:
    orientation: 'vertical'
    BoxLayout:
        ToggleButton:
            id: btn1
            group: 'a'
            text: 'Sleeping'
            allow_no_selection: False
            on_state: if self.state == 'down': label.status = self.text
        ToggleButton:
            id: btn2
            group: 'a'
            text: 'Swimming'
            allow_no_selection: False
            on_state: if self.state == 'down': label.status = self.text
        ToggleButton:
            id: btn3
            group: 'a'
            text: 'Reading'
            allow_no_selection: False
            state: 'down'
            on_state: if self.state == 'down': label.status = self.text
    Label:
        id: label
        status: 'Reading'
        text: 'Beach status is "{}"'.format(self.status)
'''

class AsyncApp(App):

    nursery = None

    def build(self):
        return Builder.load_string(kv)

    async def app_func(self):
        '''trio needs to run a function, so this is it. '''

        async with trio.open_nursery() as nursery:
            '''In trio you create a nursery, in which you schedule async
            functions to be run by the nursery simultaneously as tasks.

            This will run all two methods starting in random order
            asynchronously and then block until they are finished or canceled
            at the `with` level. '''
            self.nursery = nursery

            async def run_wrapper():
                # trio needs to be set so that it'll be used for the event loop
                await self.async_run(async_lib='trio')
                print('App done')
                nursery.cancel_scope.cancel()

            nursery.start_soon(run_wrapper)
            nursery.start_soon(self.waste_time_freely)

    async def waste_time_freely(self):
        '''This method is also run by trio and periodically prints something.
        '''
        try:
            i = 0
            while True:
                if self.root is not None:
                    status = self.root.ids.label.status
                    print('{} on the beach'.format(status))

                    # get some sleep
                    if self.root.ids.btn1.state != 'down' and i >= 2:
                        i = 0
                        print('Yawn, getting tired. Going to sleep')
                        self.root.ids.btn1.trigger_action()

                i += 1
                await trio.sleep(2)
        except trio.Cancelled as e:
            print('Wasting time was canceled', e)
        finally:
            # when canceled, print that it finished
            print('Done wasting time')

if __name__ == '__main__':
    trio.run(AsyncApp().app_func)


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
from scipy import stats
from tensorflow.contrib.distributions.python.ops import laplace as laplace_lib
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import nn_ops
from tensorflow.python.platform import test

class LaplaceTest(test.TestCase):

  def testLaplaceShape(self):
    with self.test_session():
      loc = constant_op.constant([3.0] * 5)
      scale = constant_op.constant(11.0)
      laplace = laplace_lib.Laplace(loc=loc, scale=scale)

      self.assertEqual(laplace.batch_shape_tensor().eval(), (5,))
      self.assertEqual(laplace.batch_shape, tensor_shape.TensorShape([5]))
      self.assertAllEqual(laplace.event_shape_tensor().eval(), [])
      self.assertEqual(laplace.event_shape, tensor_shape.TensorShape([]))

  def testLaplaceLogPDF(self):
    with self.test_session():
      batch_size = 6
      loc = constant_op.constant([2.0] * batch_size)
      scale = constant_op.constant([3.0] * batch_size)
      loc_v = 2.0
      scale_v = 3.0
      x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32)
      laplace = laplace_lib.Laplace(loc=loc, scale=scale)
      expected_log_pdf = stats.laplace.logpdf(x, loc_v, scale=scale_v)
      log_pdf = laplace.log_prob(x)
      self.assertEqual(log_pdf.get_shape(), (6,))
      self.assertAllClose(log_pdf.eval(), expected_log_pdf)

      pdf = laplace.prob(x)
      self.assertEqual(pdf.get_shape(), (6,))
      self.assertAllClose(pdf.eval(), np.exp(expected_log_pdf))

  def testLaplaceLogPDFMultidimensional(self):
    with self.test_session():
      batch_size = 6
      loc = constant_op.constant([[2.0, 4.0]] * batch_size)
      scale = constant_op.constant([[3.0, 4.0]] * batch_size)
      loc_v = np.array([2.0, 4.0])
      scale_v = np.array([3.0, 4.0])
      x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T
      laplace = laplace_lib.Laplace(loc=loc, scale=scale)
      expected_log_pdf = stats.laplace.logpdf(x, loc_v, scale=scale_v)
      log_pdf = laplace.log_prob(x)
      log_pdf_values = log_pdf.eval()
      self.assertEqual(log_pdf.get_shape(), (6, 2))
      self.assertAllClose(log_pdf_values, expected_log_pdf)

      pdf = laplace.prob(x)
      pdf_values = pdf.eval()
      self.assertEqual(pdf.get_shape(), (6, 2))
      self.assertAllClose(pdf_values, np.exp(expected_log_pdf))

  def testLaplaceLogPDFMultidimensionalBroadcasting(self):
    with self.test_session():
      batch_size = 6
      loc = constant_op.constant([[2.0, 4.0]] * batch_size)
      scale = constant_op.constant(3.0)
      loc_v = np.array([2.0, 4.0])
      scale_v = 3.0
      x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T
      laplace = laplace_lib.Laplace(loc=loc, scale=scale)
      expected_log_pdf = stats.laplace.logpdf(x, loc_v, scale=scale_v)
      log_pdf = laplace.log_prob(x)
      log_pdf_values = log_pdf.eval()
      self.assertEqual(log_pdf.get_shape(), (6, 2))
      self.assertAllClose(log_pdf_values, expected_log_pdf)

      pdf = laplace.prob(x)
      pdf_values = pdf.eval()
      self.assertEqual(pdf.get_shape(), (6, 2))
      self.assertAllClose(pdf_values, np.exp(expected_log_pdf))

  def testLaplaceCDF(self):
    with self.test_session():
      batch_size = 6
      loc = constant_op.constant([2.0] * batch_size)
      scale = constant_op.constant([3.0] * batch_size)
      loc_v = 2.0
      scale_v = 3.0
      x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32)

      laplace = laplace_lib.Laplace(loc=loc, scale=scale)
      expected_cdf = stats.laplace.cdf(x, loc_v, scale=scale_v)

      cdf = laplace.cdf(x)
      self.assertEqual(cdf.get_shape(), (6,))
      self.assertAllClose(cdf.eval(), expected_cdf)

  def testLaplaceLogCDF(self):
    with self.test_session():
      batch_size = 6
      loc = constant_op.constant([2.0] * batch_size)
      scale = constant_op.constant([3.0] * batch_size)
      loc_v = 2.0
      scale_v = 3.0
      x = np.array([-2.5, 2.5, -4.0, 0.1, 1.0, 2.0], dtype=np.float32)

      laplace = laplace_lib.Laplace(loc=loc, scale=scale)
      expected_cdf = stats.laplace.logcdf(x, loc_v, scale=scale_v)

      cdf = laplace.log_cdf(x)
      self.assertEqual(cdf.get_shape(), (6,))
      self.assertAllClose(cdf.eval(), expected_cdf)

  def testLaplaceLogSurvivalFunction(self):
    with self.test_session():
      batch_size = 6
      loc = constant_op.constant([2.0] * batch_size)
      scale = constant_op.constant([3.0] * batch_size)
      loc_v = 2.0
      scale_v = 3.0
      x = np.array([-2.5, 2.5, -4.0, 0.1, 1.0, 2.0], dtype=np.float32)

      laplace = laplace_lib.Laplace(loc=loc, scale=scale)
      expected_sf = stats.laplace.logsf(x, loc_v, scale=scale_v)

      sf = laplace.log_survival_function(x)
      self.assertEqual(sf.get_shape(), (6,))
      self.assertAllClose(sf.eval(), expected_sf)

  def testLaplaceMean(self):
    with self.test_session():
      loc_v = np.array([1.0, 3.0, 2.5])
      scale_v = np.array([1.0, 4.0, 5.0])
      laplace = laplace_lib.Laplace(loc=loc_v, scale=scale_v)
      expected_means = stats.laplace.mean(loc_v, scale=scale_v)
      self.assertEqual(laplace.mean().get_shape(), (3,))
      self.assertAllClose(laplace.mean().eval(), expected_means)

  def testLaplaceMode(self):
    with self.test_session():
      loc_v = np.array([0.5, 3.0, 2.5])
      scale_v = np.array([1.0, 4.0, 5.0])
      laplace = laplace_lib.Laplace(loc=loc_v, scale=scale_v)
      self.assertEqual(laplace.mode().get_shape(), (3,))
      self.assertAllClose(laplace.mode().eval(), loc_v)

  def testLaplaceVariance(self):
    with self.test_session():
      loc_v = np.array([1.0, 3.0, 2.5])
      scale_v = np.array([1.0, 4.0, 5.0])
      laplace = laplace_lib.Laplace(loc=loc_v, scale=scale_v)
      expected_variances = stats.laplace.var(loc_v, scale=scale_v)
      self.assertEqual(laplace.variance().get_shape(), (3,))
      self.assertAllClose(laplace.variance().eval(), expected_variances)

  def testLaplaceStd(self):
    with self.test_session():
      loc_v = np.array([1.0, 3.0, 2.5])
      scale_v = np.array([1.0, 4.0, 5.0])
      laplace = laplace_lib.Laplace(loc=loc_v, scale=scale_v)
      expected_stddev = stats.laplace.std(loc_v, scale=scale_v)
      self.assertEqual(laplace.stddev().get_shape(), (3,))
      self.assertAllClose(laplace.stddev().eval(), expected_stddev)

  def testLaplaceEntropy(self):
    with self.test_session():
      loc_v = np.array([1.0, 3.0, 2.5])
      scale_v = np.array([1.0, 4.0, 5.0])
      expected_entropy = stats.laplace.entropy(loc_v, scale=scale_v)
      laplace = laplace_lib.Laplace(loc=loc_v, scale=scale_v)
      self.assertEqual(laplace.entropy().get_shape(), (3,))
      self.assertAllClose(laplace.entropy().eval(), expected_entropy)

  def testLaplaceSample(self):
    with session.Session():
      loc_v = 4.0
      scale_v = 3.0
      loc = constant_op.constant(loc_v)
      scale = constant_op.constant(scale_v)
      n = 100000
      laplace = laplace_lib.Laplace(loc=loc, scale=scale)
      samples = laplace.sample(n, seed=137)
      sample_values = samples.eval()
      self.assertEqual(samples.get_shape(), (n,))
      self.assertEqual(sample_values.shape, (n,))
      self.assertAllClose(
          sample_values.mean(),
          stats.laplace.mean(
              loc_v, scale=scale_v),
          rtol=0.05,
          atol=0.)
      self.assertAllClose(
          sample_values.var(),
          stats.laplace.var(loc_v, scale=scale_v),
          rtol=0.05,
          atol=0.)
      self.assertTrue(self._kstest(loc_v, scale_v, sample_values))

  def testLaplaceSampleMultiDimensional(self):
    with session.Session():
      loc_v = np.array([np.arange(1, 101, dtype=np.float32)])  # 1 x 100
      scale_v = np.array([np.arange(1, 11, dtype=np.float32)]).T  # 10 x 1
      laplace = laplace_lib.Laplace(loc=loc_v, scale=scale_v)
      n = 10000
      samples = laplace.sample(n, seed=137)
      sample_values = samples.eval()
      self.assertEqual(samples.get_shape(), (n, 10, 100))
      self.assertEqual(sample_values.shape, (n, 10, 100))
      zeros = np.zeros_like(loc_v + scale_v)  # 10 x 100
      loc_bc = loc_v + zeros
      scale_bc = scale_v + zeros
      self.assertAllClose(
          sample_values.mean(axis=0),
          stats.laplace.mean(
              loc_bc, scale=scale_bc),
          rtol=0.35,
          atol=0.)
      self.assertAllClose(
          sample_values.var(axis=0),
          stats.laplace.var(loc_bc, scale=scale_bc),
          rtol=0.10,
          atol=0.)
      fails = 0
      trials = 0
      for ai, a in enumerate(np.reshape(loc_v, [-1])):
        for bi, b in enumerate(np.reshape(scale_v, [-1])):
          s = sample_values[:, bi, ai]
          trials += 1
          fails += 0 if self._kstest(a, b, s) else 1
      self.assertLess(fails, trials * 0.03)

  def _kstest(self, loc, scale, samples):
    # Uses the Kolmogorov-Smirnov test for goodness of fit.
    ks, _ = stats.kstest(samples, stats.laplace(loc, scale=scale).cdf)
    # Return True when the test passes.
    return ks < 0.02

  def testLaplacePdfOfSampleMultiDims(self):
    with session.Session() as sess:
      laplace = laplace_lib.Laplace(loc=[7., 11.], scale=[[5.], [6.]])
      num = 50000
      samples = laplace.sample(num, seed=137)
      pdfs = laplace.prob(samples)
      sample_vals, pdf_vals = sess.run([samples, pdfs])
      self.assertEqual(samples.get_shape(), (num, 2, 2))
      self.assertEqual(pdfs.get_shape(), (num, 2, 2))
      self.assertAllClose(
          stats.laplace.mean(
              [[7., 11.], [7., 11.]], scale=np.array([[5., 5.], [6., 6.]])),
          sample_vals.mean(axis=0),
          rtol=0.05,
          atol=0.)
      self.assertAllClose(
          stats.laplace.var([[7., 11.], [7., 11.]],
                            scale=np.array([[5., 5.], [6., 6.]])),
          sample_vals.var(axis=0),
          rtol=0.05,
          atol=0.)
      self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:, 0, 0], err=0.02)
      self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:, 0, 1], err=0.02)
      self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:, 1, 0], err=0.02)
      self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:, 1, 1], err=0.02)

  def _assertIntegral(self, sample_vals, pdf_vals, err=1e-3):
    s_p = zip(sample_vals, pdf_vals)
    prev = (0, 0)
    total = 0
    for k in sorted(s_p, key=lambda x: x[0]):
      pair_pdf = (k[1] + prev[1]) / 2
      total += (k[0] - prev[0]) * pair_pdf
      prev = k
    self.assertNear(1., total, err=err)

  def testLaplaceNonPositiveInitializationParamsRaises(self):
    with self.test_session():
      loc_v = constant_op.constant(0.0, name="loc")
      scale_v = constant_op.constant(-1.0, name="scale")
      laplace = laplace_lib.Laplace(
          loc=loc_v, scale=scale_v, validate_args=True)
      with self.assertRaisesOpError("scale"):
        laplace.mean().eval()
      loc_v = constant_op.constant(1.0, name="loc")
      scale_v = constant_op.constant(0.0, name="scale")
      laplace = laplace_lib.Laplace(
          loc=loc_v, scale=scale_v, validate_args=True)
      with self.assertRaisesOpError("scale"):
        laplace.mean().eval()

  def testLaplaceWithSoftplusScale(self):
    with self.test_session():
      loc_v = constant_op.constant([0.0, 1.0], name="loc")
      scale_v = constant_op.constant([-1.0, 2.0], name="scale")
      laplace = laplace_lib.LaplaceWithSoftplusScale(loc=loc_v, scale=scale_v)
      self.assertAllClose(nn_ops.softplus(scale_v).eval(), laplace.scale.eval())
      self.assertAllClose(loc_v.eval(), laplace.loc.eval())

if __name__ == "__main__":
  test.main()


text:
package org.unitime.timetable.onlinesectioning.model;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import org.cpsolver.studentsct.model.Course;
import org.infinispan.commons.marshall.Externalizer;
import org.infinispan.commons.marshall.SerializeWith;
import org.unitime.timetable.gwt.shared.SectioningException;
import org.unitime.timetable.model.CourseOffering;
import org.unitime.timetable.model.InstrOfferingConfig;
import org.unitime.timetable.onlinesectioning.AcademicSessionInfo;
import org.unitime.timetable.onlinesectioning.OnlineSectioningHelper;
import org.unitime.timetable.onlinesectioning.custom.CourseDetailsProvider;

/**
 * @author Tomas Muller
 */
@SerializeWith(XCourse.XCourseSerializer.class)
public class XCourse extends XCourseId {
	private static final long serialVersionUID = 1L;
    private String iSubjectArea = null;
    private String iCourseNumber = null;
    private String iDepartment = null;
    private String iConsentLabel = null, iConsentAbbv = null;
    private String iNote = null;
    private String iDetails = null;
    private int iLimit = 0;
    private int iProjected = 0;
    private Integer iWkEnroll = null, iWkChange = null, iWkDrop = null;
    private String iCreditAbbv = null, iCreditText = null;

    public XCourse() {
    	super();
    }

    public XCourse(ObjectInput in) throws IOException, ClassNotFoundException {
    	readExternal(in);
    }

    public XCourse(CourseOffering course, OnlineSectioningHelper helper) {
    	this(course);
    }

    public XCourse(CourseOffering course) {
    	super(course);
		iSubjectArea = course.getSubjectAreaAbbv().trim();
		iCourseNumber = course.getCourseNbr().trim();
		iNote = course.getScheduleBookNote();
		iDepartment = (course.getSubjectArea().getDepartment().getDeptCode() == null ? course.getSubjectArea().getDepartment().getAbbreviation() : course.getSubjectArea().getDepartment().getDeptCode());
        boolean unlimited = false;
        iLimit = 0;
        for (InstrOfferingConfig config: course.getInstructionalOffering().getInstrOfferingConfigs()) {
        	if (config.isUnlimitedEnrollment()) unlimited = true;
        	iLimit += config.getLimit();
        }
        if (course.getReservation() != null)
        	iLimit = course.getReservation();
        if (iLimit >= 9999) unlimited = true;
        if (unlimited) iLimit = -1;
        iProjected = (course.getProjectedDemand() != null ? course.getProjectedDemand().intValue() : course.getDemand() != null ? course.getDemand().intValue() : 0);
		iWkEnroll = course.getInstructionalOffering().getLastWeekToEnroll();
		iWkChange = course.getInstructionalOffering().getLastWeekToChange();
		iWkDrop = course.getInstructionalOffering().getLastWeekToDrop();
		if (course.getConsentType() != null) {
			iConsentLabel = course.getConsentType().getLabel();
			iConsentAbbv = course.getConsentType().getAbbv();
		}
        if (course.getCredit() != null) {
        	iCreditAbbv = course.getCredit().creditAbbv();
        	iCreditText = course.getCredit().creditText();
        }
    }

    public XCourse(Course course) {
    	super(course);
		iSubjectArea = course.getSubjectArea();
		iCourseNumber = course.getCourseNumber();
		iNote = course.getNote();
        iLimit = course.getLimit();
        iProjected = course.getProjected();
    }

    /** Subject area */
    public String getSubjectArea() {
        return iSubjectArea;
    }

    /** Course number */
    public String getCourseNumber() {
        return iCourseNumber;
    }

    /** Course offering limit */
    public int getLimit() {
        return iLimit;
    }

    public int getProjected() { return iProjected; }

	public Integer getLastWeekToEnroll() { return iWkEnroll; }
	public Integer getLastWeekToChange() { return iWkChange; }
	public Integer getLastWeekToDrop() { return iWkDrop; }
	public String getDepartment() { return iDepartment; }
	public String getConsentLabel() { return iConsentLabel; }
	public String getConsentAbbv() { return iConsentAbbv; }

    /** Course note */
    public String getNote() { return iNote; }

	public String getDetails(AcademicSessionInfo session, CourseDetailsProvider provider) throws SectioningException {
		if (iDetails == null && provider != null)
			iDetails = provider.getDetails(session, getSubjectArea(), getCourseNumber());
		return iDetails;
	}

    /**
     * Get credit (Online Student Scheduling only)
     */
    public String getCreditAbbv() { return iCreditAbbv; }
    public String getCreditText() { return iCreditText; }
    public String getCredit() { return getCreditAbbv() == null ? null : getCreditAbbv() + "|" + getCreditText(); }

	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		super.readExternal(in);
		iSubjectArea = (String)in.readObject();
		iCourseNumber = (String)in.readObject();
		iDepartment = (String)in.readObject();
		iConsentLabel = (String)in.readObject();
		iConsentAbbv = (String)in.readObject();
		iNote = (String)in.readObject();
		iDetails = (String)in.readObject();
		iLimit = in.readInt();
		iProjected = in.readInt();
		iWkEnroll = (in.readBoolean() ? in.readInt() : null);
		iWkChange = (in.readBoolean() ? in.readInt() : null);
		iWkDrop = (in.readBoolean() ? in.readInt() : null);
		iCreditAbbv = (String)in.readObject();
		iCreditText = (String)in.readObject();
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		super.writeExternal(out);
		out.writeObject(iSubjectArea);
		out.writeObject(iCourseNumber);
		out.writeObject(iDepartment);
		out.writeObject(iConsentLabel);
		out.writeObject(iConsentAbbv);
		out.writeObject(iNote);
		out.writeObject(iDetails);
		out.writeInt(iLimit);
		out.writeInt(iProjected);
		out.writeBoolean(iWkEnroll != null);
		if (iWkEnroll != null)
			out.writeInt(iWkEnroll);
		out.writeBoolean(iWkChange != null);
		if (iWkChange != null)
			out.writeInt(iWkChange);
		out.writeBoolean(iWkDrop != null);
		if (iWkDrop != null)
			out.writeInt(iWkDrop);
		out.writeObject(iCreditAbbv);
		out.writeObject(iCreditText);
	}

	public static class XCourseSerializer implements Externalizer<XCourse> {
		private static final long serialVersionUID = 1L;

		@Override
		public void writeObject(ObjectOutput output, XCourse object) throws IOException {
			object.writeExternal(output);
		}

		@Override
		public XCourse readObject(ObjectInput input) throws IOException, ClassNotFoundException {
			return new XCourse(input);
		}
	}
}


text:
'use strict';

var _Promise = require('babel-runtime/core-js/promise')['default'];

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

var _http = require('http');

var _http2 = _interopRequireDefault(_http);

var _querystring = require('querystring');

var _querystring2 = _interopRequireDefault(_querystring);

var _formData = require('form-data');

var _formData2 = _interopRequireDefault(_formData);

var _tapdance = require('tapdance');

var _helpers = require('../../helpers');

var _http3 = require('../http');

var _http4 = _interopRequireDefault(_http3);

var _libSerializerSerializersJson = require('../../../lib/serializer/serializers/json');

var _libSerializerSerializersJson2 = _interopRequireDefault(_libSerializerSerializersJson);

var _libSerializerSerializersForm = require('../../../lib/serializer/serializers/form');

var _test_instance = require('../test_instance');

var _test_instance2 = _interopRequireDefault(_test_instance);

var _lib = require('../../../lib');

var _lib2 = _interopRequireDefault(_lib);

var options = {
  serializers: [{ type: _libSerializerSerializersJson2['default'] }, { type: _libSerializerSerializersForm.formUrlEncoded }, { type: _libSerializerSerializersForm.formData }]
};

var test = _http4['default'].bind(null, options);

(0, _tapdance.run)(function () {
  (0, _tapdance.comment)('get anything should fail');
  return test('/', {
    headers: { 'Accept': 'application/x-www-form-urlencoded' }
  }, function (response) {
    (0, _helpers.equal)(response.status, 415, 'status is correct');
  });
});

(0, _tapdance.run)(function () {
  (0, _tapdance.comment)('create records using urlencoded data');
  return test('/animal', {
    method: 'post',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: _querystring2['default'].stringify({
      name: 'Ayy lmao',
      nicknames: ['ayy', 'lmao']
    })
  }, function (response) {
    (0, _helpers.equal)(response.status, 201, 'status is correct');
    (0, _helpers.ok)(~response.headers['content-type'].indexOf('application/json'), 'content type is correct');
    (0, _helpers.deepEqual)(response.body.map(function (record) {
      return record.name;
    }), ['Ayy lmao'], 'response body is correct');
  });
});

(0, _tapdance.run)(function () {
  (0, _tapdance.comment)('update records using urlencoded data');
  return test('/animal', {
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'X-HTTP-Method': 'PATCH'
    },
    body: _querystring2['default'].stringify({
      id: 1,
      name: 'Ayy lmao',
      nicknames: ['ayy', 'lmao']
    })
  }, function (response) {
    (0, _helpers.equal)(response.status, 200, 'status is correct');
    (0, _helpers.ok)(~response.headers['content-type'].indexOf('application/json'), 'content type is correct');
    (0, _helpers.deepEqual)(response.body.map(function (record) {
      return record.name;
    }), ['Ayy lmao'], 'response body is correct');
  });
});

(0, _tapdance.run)(function () {
  (0, _tapdance.comment)('create records using form data');

  var server = undefined;
  var store = undefined;
  var deadbeef = new Buffer('deadbeef', 'hex');
  var form = new _formData2['default']();
  form.append('name', 'Ayy lmao');
  form.append('picture', deadbeef, { filename: 'deadbeef.dump' });

  return (0, _test_instance2['default'])(options).then(function (s) {
    store = s;
    server = _http2['default'].createServer(_lib2['default'].net.http(store)).listen(1337);
  }).then(function () {
    return new _Promise(function (resolve, reject) {
      return form.submit('http://localhost:1337/animal', function (error, response) {
        return error ? reject(error) : resolve(response);
      });
    });
  }).then(function (response) {
    (0, _helpers.equal)(response.statusCode, 201, 'status is correct');
    (0, _helpers.ok)(~response.headers['content-type'].indexOf('application/json'), 'content type is correct');

    return new _Promise(function (resolve) {
      var chunks = [];
      response.on('data', function (chunk) {
        return chunks.push(chunk);
      });
      response.on('end', function () {
        return resolve(Buffer.concat(chunks));
      });
    });
  }).then(function (payload) {
    var body = JSON.parse(payload.toString());
    (0, _helpers.deepEqual)(body.map(function (record) {
      return record.name;
    }), ['Ayy lmao'], 'name is correct');
    (0, _helpers.deepEqual)(body.map(function (record) {
      return record.picture;
    }), [deadbeef.toString('base64')], 'picture is correct');
    store.disconnect();
    server.close();
  });
});

(0, _tapdance.run)(function () {
  (0, _tapdance.comment)('update records using form data');

  var server = undefined;
  var store = undefined;
  var deadbeef = new Buffer('deadbeef', 'hex');
  var form = new _formData2['default']();
  form.append('id', 1);
  form.append('name', 'Ayy lmao');
  form.append('picture', deadbeef, { filename: 'deadbeef.dump' });

  return (0, _test_instance2['default'])(options).then(function (s) {
    store = s;
    server = _http2['default'].createServer(_lib2['default'].net.http(store)).listen(1337);
  }).then(function () {
    return new _Promise(function (resolve, reject) {
      return form.submit({
        host: 'localhost',
        port: 1337,
        path: '/animal',
        headers: { 'X-HTTP-Method': 'PATCH' }
      }, function (error, response) {
        return error ? reject(error) : resolve(response);
      });
    });
  }).then(function (response) {
    (0, _helpers.equal)(response.statusCode, 200, 'status is correct');
    (0, _helpers.ok)(~response.headers['content-type'].indexOf('application/json'), 'content type is correct');

    return new _Promise(function (resolve) {
      var chunks = [];
      response.on('data', function (chunk) {
        return chunks.push(chunk);
      });
      response.on('end', function () {
        return resolve(Buffer.concat(chunks));
      });
    });
  }).then(function (payload) {
    var body = JSON.parse(payload.toString());
    (0, _helpers.deepEqual)(body.map(function (record) {
      return record.name;
    }), ['Ayy lmao'], 'name is correct');
    (0, _helpers.deepEqual)(body.map(function (record) {
      return record.picture;
    }), [deadbeef.toString('base64')], 'picture is correct');
    store.disconnect();
    server.close();
  });
});


text:
from apgl.io.GraphReader import GraphReader
from apgl.graph.VertexList import VertexList
from apgl.graph.SparseGraph import SparseGraph
import logging

class SimpleGraphReader(GraphReader):
        '''
        A class to read SimpleGraph files.
        '''
        def __init__(self):
            pass

        def readFromFile(self, fileName):
            """
            Read vertices and edges of the graph from the given file name. The file
            must have as its first line "Vertices" followed by a list of
            vertex indices (one per line). Then the lines following "Arcs" or "Edges"
            have a list of pairs of vertex indices represented directed or undirected
            edges.
            """
            infile = open(fileName, "r")
            line = infile.readline()
            line = infile.readline()
            ind = 0
            vertexIdDict = {}

            while infile and line != "Edges" and line != "Arcs":
                vertexIdDict[int(line)] = ind
                line = infile.readline().strip()
                ind += 1

            if line == "Edges":
                undirected = True
            elif line == "Arcs":
                undirected = False
            else:
                raise ValueError("Unknown edge types: " + line)

            numVertices = len(vertexIdDict)
            numFeatures = 0
            vList = VertexList(numVertices, numFeatures)
            sGraph = SparseGraph(vList, undirected)
            line = infile.readline()

            while line:
                s = line.split()
                try:
                    i = vertexIdDict[int(s[0].strip(',').strip())]
                    j = vertexIdDict[int(s[1].strip(',').strip())]
                    k = float(s[2].strip(',').strip())
                except KeyError:
                    print("Vertex not found in list of vertices.")
                    raise

                sGraph.addEdge(i, j, k)
                line = infile.readline()

            logging.info("Read graph with " + str(numVertices) + " vertices and " + str(sGraph.getNumEdges()) + " edges")

            return sGraph


text:
require_relative 'base'
require 'whois/scanners/whois.rnids.rs.rb'

module Whois
  class Parsers

    # Parser for the whois.rnids.rs server.
    #
    # @see Whois::Parsers::Example
    #   The Example parser for the list of all available methods.
    #
    class WhoisRnidsRs < Base
      include Scanners::Scannable

      self.scanner = Scanners::WhoisRnidsRs

      property_not_supported :disclaimer

      property_supported :domain do
        node("Domain name") { |str| str.chomp(".") }
      end

      property_not_supported :domain_id

      property_supported :status do
        case node("Domain status", &:downcase)
        when nil
          :available
        when 'active'
          :registered
        when 'locked'
          :registered
        when 'in transfer'
          :registered
        when 'expired'
          :expired
        else
          Whois::Parser.bug!(ParserError, "Unknown status `#{node('Domain status')}'.")
        end
      end

      property_supported :available? do
        !!node("status:available")
      end

      property_supported :registered? do
        !available?
      end

      property_supported :created_on do
        node("Registration date") { |value| parse_time(value) }
      end

      property_supported :updated_on do
        node("Modification date") { |value| parse_time(value) }
      end

      property_supported :expires_on do
        node("Expiration date") { |value| parse_time(value) }
      end

      property_supported :registrar do
        node("Registrar") do |str|
          Parser::Registrar.new(
            :id           => nil,
            :name         => node("Registrar")
          )
        end
      end

      property_supported :registrant_contacts do
        build_contact("Owner", Parser::Contact::TYPE_REGISTRANT)
      end

      property_supported :admin_contacts do
        build_contact("Administrative contact", Parser::Contact::TYPE_ADMINISTRATIVE)
      end

      property_supported :technical_contacts do
        build_contact("Technical contact", Parser::Contact::TYPE_TECHNICAL)
      end

      property_supported :nameservers do
        Array.wrap(node("DNS")).map do |line|
          name, ipv4 = line.split(/ - ?/).map(&:strip)
          name.chomp!(".")
          Parser::Nameserver.new(:name => name, :ipv4 => ipv4)
        end
      end

      private

      def build_contact(element, type)
        node(element) do |hash|
          Parser::Contact.new(
            :type         => type,
            :id           => nil,
            :name         => hash[element],
            :organization => nil,
            :address      => hash["Address"],
            :city         => nil,
            :zip          => nil,
            :state        => nil,
            :country      => nil,
            :country_code => nil,
            :phone        => nil,
            :fax          => nil,
            :email        => nil
          )
        end
      end

    end

  end
end


text:
package at.ac.tuwien.kr.alpha.grounder.transformation;

import at.ac.tuwien.kr.alpha.common.Predicate;
import at.ac.tuwien.kr.alpha.common.atoms.Atom;
import at.ac.tuwien.kr.alpha.common.atoms.BasicAtom;
import at.ac.tuwien.kr.alpha.common.atoms.Literal;
import at.ac.tuwien.kr.alpha.common.depgraph.ComponentGraph;
import at.ac.tuwien.kr.alpha.common.depgraph.ComponentGraph.SCComponent;
import at.ac.tuwien.kr.alpha.common.depgraph.Node;
import at.ac.tuwien.kr.alpha.common.depgraph.StratificationAlgorithm;
import at.ac.tuwien.kr.alpha.common.program.AnalyzedProgram;
import at.ac.tuwien.kr.alpha.common.program.InternalProgram;
import at.ac.tuwien.kr.alpha.common.rule.InternalRule;
import at.ac.tuwien.kr.alpha.grounder.IndexedInstanceStorage;
import at.ac.tuwien.kr.alpha.grounder.Instance;
import at.ac.tuwien.kr.alpha.grounder.RuleGroundingOrder;
import at.ac.tuwien.kr.alpha.grounder.RuleGroundingOrders;
import at.ac.tuwien.kr.alpha.grounder.Substitution;
import at.ac.tuwien.kr.alpha.grounder.WorkingMemory;
import at.ac.tuwien.kr.alpha.grounder.instantiation.AssignmentStatus;
import at.ac.tuwien.kr.alpha.grounder.instantiation.LiteralInstantiationResult;
import at.ac.tuwien.kr.alpha.grounder.instantiation.LiteralInstantiator;
import at.ac.tuwien.kr.alpha.grounder.instantiation.WorkingMemoryBasedInstantiationStrategy;
import org.apache.commons.collections4.SetUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

public class StratifiedEvaluation extends ProgramTransformation<AnalyzedProgram, InternalProgram> {

	private static final Logger LOGGER = LoggerFactory.getLogger(StratifiedEvaluation.class);

	private WorkingMemory workingMemory = new WorkingMemory();
	private Map<Predicate, LinkedHashSet<InternalRule>> predicateDefiningRules;

	private Map<Predicate, Set<Instance>> modifiedInLastEvaluationRun = new HashMap<>();

	private List<Atom> additionalFacts = new ArrayList<>(); // The additional facts derived by stratified evaluation. Note that it may contain duplicates.
	private Set<Integer> solvedRuleIds = new HashSet<>(); // Set of rules that have been completely evaluated.

	private LiteralInstantiator literalInstantiator;

	@Override
	// Note: ideally this returns a "PartiallyEvaluatedProgram" such that the grounder can directly use the working
	// memories created here rather than re-initialize everything.
	public InternalProgram apply(AnalyzedProgram inputProgram) {
		// Calculate a stratification and initialize the working memory.
		ComponentGraph componentGraph = inputProgram.getComponentGraph();
		List<SCComponent> strata = StratificationAlgorithm.calculateStratification(componentGraph);
		predicateDefiningRules = inputProgram.getPredicateDefiningRules();

		// Set up list of atoms which are known to be true - these will be expand by the evaluation.
		Map<Predicate, Set<Instance>> knownFacts = new LinkedHashMap<>(inputProgram.getFactsByPredicate());
		for (Map.Entry<Predicate, Set<Instance>> entry : knownFacts.entrySet()) {
			workingMemory.initialize(entry.getKey());
			workingMemory.addInstances(entry.getKey(), true, entry.getValue());
		}

		// Create working memories for all predicates occurring in each rule.
		for (InternalRule nonGroundRule : inputProgram.getRulesById().values()) {
			for (Predicate predicate : nonGroundRule.getOccurringPredicates()) {
				workingMemory.initialize(predicate);
			}
		}

		workingMemory.reset();

		// Set up literal instantiator.
		literalInstantiator = new LiteralInstantiator(new WorkingMemoryBasedInstantiationStrategy(workingMemory));

		// Evaluate the program part covered by the calculated stratification.
		for (SCComponent currComponent : strata) {
			evaluateComponent(currComponent);
		}

		// Build the program resulting from evaluating the stratified part.
		additionalFacts.addAll(inputProgram.getFacts()); // Add original input facts to newly derived ones.
		List<InternalRule> outputRules = new ArrayList<>();
		inputProgram.getRulesById().entrySet().stream().filter((entry) -> !solvedRuleIds.contains(entry.getKey()))
				.forEach((entry) -> outputRules.add(entry.getValue()));

		// NOTE: if InternalProgram requires solved rules, they should be added here.
		return new InternalProgram(outputRules, additionalFacts);
	}

	private void evaluateComponent(SCComponent comp) {
		LOGGER.debug("Evaluating component {}", comp);
		ComponentEvaluationInfo evaluationInfo = getRulesToEvaluate(comp);
		if (evaluationInfo.isEmpty()) {
			LOGGER.debug("No rules to evaluate for component {}", comp);
			return;
		}

		// Rules outside of dependency cycles only need to be evaluated once.
		if (!evaluationInfo.nonRecursiveRules.isEmpty()) {
			prepareInitialEvaluation(evaluationInfo.nonRecursiveRules);
			evaluateRules(evaluationInfo.nonRecursiveRules, true);
			for (IndexedInstanceStorage instanceStorage : workingMemory.modified()) {
				// Directly record all newly derived instances as additional facts.
				for (Instance recentlyAddedInstance : instanceStorage.getRecentlyAddedInstances()) {
					additionalFacts.add(new BasicAtom(instanceStorage.getPredicate(), recentlyAddedInstance.terms));
				}
				instanceStorage.markRecentlyAddedInstancesDone();
			}
		}
		boolean isInitialRun = true;
		if (!evaluationInfo.recursiveRules.isEmpty()) {
			do {
				// Now do the rules that cyclically depend on each other,
				// evaluate these until nothing new can be derived any more.
				if (isInitialRun) {
					prepareInitialEvaluation(evaluationInfo.recursiveRules);
				}
				evaluateRules(evaluationInfo.recursiveRules, isInitialRun);
				isInitialRun = false;
				modifiedInLastEvaluationRun = new HashMap<>();
				// Since we are stratified we never have to backtrack, therefore just collect the added instances.
				for (IndexedInstanceStorage instanceStorage : workingMemory.modified()) {
					// Directly record all newly derived instances as additional facts.
					for (Instance recentlyAddedInstance : instanceStorage.getRecentlyAddedInstances()) {
						additionalFacts.add(new BasicAtom(instanceStorage.getPredicate(), recentlyAddedInstance.terms));
					}
					modifiedInLastEvaluationRun.putIfAbsent(instanceStorage.getPredicate(), new LinkedHashSet<>());
					modifiedInLastEvaluationRun.get(instanceStorage.getPredicate()).addAll(instanceStorage.getRecentlyAddedInstances());
					instanceStorage.markRecentlyAddedInstancesDone();
				}
				// If the evaluation of rules did not modify the working memory we have a fixed-point.
			} while (!workingMemory.modified().isEmpty());
		}
		LOGGER.debug("Evaluation done - reached a fixed point on component {}", comp);
		SetUtils.union(evaluationInfo.nonRecursiveRules, evaluationInfo.recursiveRules)
				.forEach((rule) -> solvedRuleIds.add(rule.getRuleId()));
	}

	private void evaluateRules(Set<InternalRule> rules, boolean isInitialRun) {
		workingMemory.reset();
		LOGGER.debug("Starting component evaluation run...");
		for (InternalRule r : rules) {
			evaluateRule(r, !isInitialRun);
		}
	}

	/**
	 * To be called at the start of evaluateComponent. Adds all known instances of the predicates occurring in the given set
	 * of rules to the "modifiedInLastEvaluationRun" map in order to "bootstrap" incremental grounding, i.e. making sure
	 * that those instances are taken into account for ground substitutions by evaluateRule.
	 */
	private void prepareInitialEvaluation(Set<InternalRule> rulesToEvaluate) {
		modifiedInLastEvaluationRun = new HashMap<>();
		for (InternalRule rule : rulesToEvaluate) {
			// Register rule head instances.
			Predicate headPredicate = rule.getHeadAtom().getPredicate();
			IndexedInstanceStorage headInstances = workingMemory.get(headPredicate, true);
			modifiedInLastEvaluationRun.putIfAbsent(headPredicate, new LinkedHashSet<>());
			if (headInstances != null) {
				modifiedInLastEvaluationRun.get(headPredicate).addAll(headInstances.getAllInstances());
			}
			// Register positive body literal instances.
			for (Literal lit : rule.getPositiveBody()) {
				Predicate bodyPredicate = lit.getPredicate();
				IndexedInstanceStorage bodyInstances = workingMemory.get(bodyPredicate, true);
				modifiedInLastEvaluationRun.putIfAbsent(bodyPredicate, new LinkedHashSet<>());
				if (bodyInstances != null) {
					modifiedInLastEvaluationRun.get(bodyPredicate).addAll(bodyInstances.getAllInstances());
				}
			}
		}
	}

	private void evaluateRule(InternalRule rule, boolean checkAllStartingLiterals) {
		LOGGER.debug("Evaluating rule {}", rule);
		List<Substitution> satisfyingSubstitutions = calculateSatisfyingSubstitutionsForRule(rule, checkAllStartingLiterals);
		for (Substitution subst : satisfyingSubstitutions) {
			fireRule(rule, subst);
		}
	}

	private List<Substitution> calculateSatisfyingSubstitutionsForRule(InternalRule rule, boolean checkAllStartingLiterals) {
		LOGGER.debug("Grounding rule {}", rule);
		RuleGroundingOrders groundingOrders = rule.getGroundingOrders();

		// Treat rules with fixed instantiation first.
		LOGGER.debug("Is fixed rule? {}", rule.getGroundingOrders().fixedInstantiation());
		if (groundingOrders.fixedInstantiation()) {
			RuleGroundingOrder fixedGroundingOrder = groundingOrders.getFixedGroundingOrder();
			return calcSubstitutionsWithGroundingOrder(fixedGroundingOrder, Collections.singletonList(new Substitution()));
		}

		List<Literal> startingLiterals = groundingOrders.getStartingLiterals();
		// Check only one starting literal if indicated by the parameter.
		if (!checkAllStartingLiterals) {
			// If this is the first evaluation run, it suffices to start from the first starting literal only.
			Literal lit = startingLiterals.get(0);
			return calcSubstitutionsWithGroundingOrder(groundingOrders.orderStartingFrom(lit), substituteFromRecentlyAddedInstances(lit));
		}

		// Ground from all starting literals.
		List<Substitution> groundSubstitutions = new ArrayList<>(); // Collection of full ground substitutions for the given rule.
		for (Literal lit : startingLiterals) {
			List<Substitution> substitutionsForStartingLiteral = calcSubstitutionsWithGroundingOrder(groundingOrders.orderStartingFrom(lit),
					substituteFromRecentlyAddedInstances(lit));
			groundSubstitutions.addAll(substitutionsForStartingLiteral);
		}
		return groundSubstitutions;
	}

	/**
	 * Use this to find initial substitutions for a starting literal when grounding a rule.
	 * In order to avoid finding the same ground instantiations of rules again, only look at
	 * modifiedInLastEvaluationRun to obtain instances.
	 *
	 * @param lit the literal to substitute.
	 * @return valid ground substitutions for the literal based on the recently added instances (i.e. instances derived in
	 *         the last evaluation run).
	 */
	private List<Substitution> substituteFromRecentlyAddedInstances(Literal lit) {
		List<Substitution> retVal = new ArrayList<>();
		Set<Instance> instances = modifiedInLastEvaluationRun.get(lit.getPredicate());
		if (instances == null) {
			return Collections.emptyList();
		}
		for (Instance instance : instances) {
			Substitution unifyingSubstitution = Substitution.specializeSubstitution(lit, instance, Substitution.EMPTY_SUBSTITUTION);
			if (unifyingSubstitution != null) {
				retVal.add(unifyingSubstitution);
			}
		}
		return retVal;
	}

	private List<Substitution> calcSubstitutionsWithGroundingOrder(RuleGroundingOrder groundingOrder, List<Substitution> startingSubstitutions) {
		// Iterate through the grounding order and whenever instantiation of a Literal with a given substitution
		// causes a result with a type other than CONTINUE, discard that substitution.

		// Note that this function uses a stack of partial substitutions to simulate a recursive function.
		Stack<ArrayList<Substitution>> substitutionStack = new Stack<>(); // For speed, we really want ArrayLists on the stack.
		if (startingSubstitutions instanceof ArrayList) {
			substitutionStack.push((ArrayList<Substitution>) startingSubstitutions);
		} else {
			substitutionStack.push(new ArrayList<>(startingSubstitutions)); // Copy startingSubstitutions into ArrayList. Note: mostly happens for empty or
																			// singleton lists.
		}
		int currentOrderPosition = 0;
		List<Substitution> fullSubstitutions = new ArrayList<>();
		while (!substitutionStack.isEmpty()) {
			List<Substitution> currentSubstitutions = substitutionStack.peek();
			// If no more substitutions remain at current position, all have been processed, continue on next lower level.
			if (currentSubstitutions.isEmpty()) {
				substitutionStack.pop();
				currentOrderPosition--;
				continue;
			}
			// In case the full grounding order has been worked on, all current substitutions are full substitutions, add them to
			// result.
			Literal currentLiteral = groundingOrder.getLiteralAtOrderPosition(currentOrderPosition);
			if (currentLiteral == null) {
				fullSubstitutions.addAll(currentSubstitutions);
				currentSubstitutions.clear();
				// Continue on next lower level.
				substitutionStack.pop();
				currentOrderPosition--;
				continue;
			}
			// Take one substitution from the top-list of the stack and try extending it.
			Substitution currentSubstitution = currentSubstitutions.remove(currentSubstitutions.size() - 1); // Work on last element (removing last element is
																												// O(1) for ArrayList).
			LiteralInstantiationResult currentLiteralResult = literalInstantiator.instantiateLiteral(currentLiteral, currentSubstitution);
			if (currentLiteralResult.getType() == LiteralInstantiationResult.Type.CONTINUE) {
				// The currentSubstitution could be extended, push the extensions on the stack and continue working on them.
				ArrayList<Substitution> furtheredSubstitutions = new ArrayList<>();
				for (ImmutablePair<Substitution, AssignmentStatus> resultSubstitution : currentLiteralResult.getSubstitutions()) {
					furtheredSubstitutions.add(resultSubstitution.left);
				}
				substitutionStack.push(furtheredSubstitutions);
				// Continue work on the higher level.
				currentOrderPosition++;
			}
		}
		return fullSubstitutions;
	}

	private void fireRule(InternalRule rule, Substitution substitution) {
		Atom newAtom = rule.getHeadAtom().substitute(substitution);
		if (!newAtom.isGround()) {
			throw new IllegalStateException("Trying to fire rule " + rule.toString() + " with incompatible substitution " + substitution.toString());
		}
		LOGGER.debug("Firing rule - got head atom: {}", newAtom);
		workingMemory.addInstance(newAtom, true);
	}

	private ComponentEvaluationInfo getRulesToEvaluate(SCComponent comp) {
		Set<InternalRule> nonRecursiveRules = new HashSet<>();
		Set<InternalRule> recursiveRules = new HashSet<>();

		// Collect all predicates occurring in heads of rules of the given component.
		Set<Predicate> headPredicates = new HashSet<>();
		for (Node node : comp.getNodes()) {
			headPredicates.add(node.getPredicate());
		}
		// Check each predicate whether its defining rules depend on some of the head predicates, i.e., whether there is a
		// cycle.
		for (Predicate headPredicate : headPredicates) {
			HashSet<InternalRule> definingRules = predicateDefiningRules.get(headPredicate);
			if (definingRules == null) {
				// Predicate only occurs in facts, skip.
				continue;
			}
			// Note: here we assume that all rules defining a predicate belong to the same SC component.
			for (InternalRule rule : definingRules) {
				boolean isRuleRecursive = false;
				for (Literal lit : rule.getPositiveBody()) {
					if (headPredicates.contains(lit.getPredicate())) {
						// The rule body contains a predicate that is defined in the same
						// component, the rule is therefore part of a cyclic dependency within
						// this component.
						isRuleRecursive = true;
					}
				}
				if (isRuleRecursive) {
					recursiveRules.add(rule);
				} else {
					nonRecursiveRules.add(rule);
				}
			}
		}
		return new ComponentEvaluationInfo(nonRecursiveRules, recursiveRules);
	}

	/**
	 * Internal helper class to group rules within an {@SCComponent} into rules that are recursive, i.e. part of some cyclic
	 * dependency chain within that component, and non-recursive rules, i.e. rules where all body predicates occur in lower
	 * strata. The reason for this grouping is that, when evaluating rules within a component, non-recursive rules only need
	 * to be evaluated once, while recursive rules need to be evaluated until a fixed-point has been reached.
	 *
	 * Copyright (c) 2020, the Alpha Team.
	 */
	private class ComponentEvaluationInfo {
		final Set<InternalRule> nonRecursiveRules;
		final Set<InternalRule> recursiveRules;

		ComponentEvaluationInfo(Set<InternalRule> nonRecursive, Set<InternalRule> recursive) {
			nonRecursiveRules = Collections.unmodifiableSet(nonRecursive);
			recursiveRules = Collections.unmodifiableSet(recursive);
		}

		boolean isEmpty() {
			return nonRecursiveRules.isEmpty() && recursiveRules.isEmpty();
		}

	}

}


text:
package com.github.visgeek.utils.collections.test.testcase.collection.set.iset;

import java.util.Arrays;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import com.github.visgeek.utils.collections.EnumerableSet;

public class AddAll {
	@Rule
	public final ExpectedException expectedException = ExpectedException.none();

	@Test
	public void argIsNull() {
		this.expectedException.expect(NullPointerException.class);
		this.expectedException.expectMessage("collection");

		EnumerableSet<Integer> set = new EnumerableSet<>();
		set.addAll((Iterable<Integer>) null);
	}

	@Test
	public void argAsCollection() {
		Iterable<Integer> values = Arrays.asList(1, 2, 3, 2); // Collection

		EnumerableSet<Integer> set = new EnumerableSet<>();
		set.addAll(values);
		Assert.assertEquals(3, set.size());
	}

	@Test
	public void argAsIterable() {
		Iterable<Integer> values = () -> Arrays.asList(1, 2, 3, 2).iterator(); // Iterable

		EnumerableSet<Integer> set = new EnumerableSet<>();
		set.addAll(values);
		Assert.assertEquals(3, set.size());
	}
}


text:
using Sitemapify.Builders;
using Sitemapify.Models;
using Sitemapify.Providers;

namespace Sitemapify.Config
{
    public interface ISitemapifyConfigurer
    {
        /// <summary>
        /// The content provider is used to get a collection of <see cref="SitemapUrl"/>'s representing the sitemap xml document to generate
        /// </summary>
        /// <param name="contentProvider">The custom content provider</param>
        /// <returns></returns>
        ISitemapifyConfigurer UsingContentProvider(ISitemapContentProvider contentProvider);
        /// <summary>
        /// The cache provider is responsible for retaining the sitemap document once it is generated so as to avoid having to constantly generate it
        /// </summary>
        /// <remarks>The default cache provider uses an in-memory caching mechanism that expires the sitemap 1 hour after initial access</remarks>
        /// <param name="cacheProvider">The custom cache provider</param>
        /// <returns></returns>
        ISitemapifyConfigurer UsingCacheProvider(ISitemapCacheProvider cacheProvider);
        /// <summary>
        /// The document builder is responsible for taking the compiled sitemap urls and generating a valid sitemap schema compatible xml document
        /// </summary>
        /// <remarks>You really shouldn't need to alter this</remarks>
        /// <param name="documentBuilder">The custom document builder</param>
        /// <returns></returns>
        ISitemapifyConfigurer UsingDocumentBuilder(ISitemapDocumentBuilder documentBuilder);
    }
}