text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEditor.Experimental.VFX;
using UnityEngine.Experimental.VFX;

namespace UnityEditor.VFX
{
    interface ILayoutProvider
    {
        void GenerateAttributeLayout(uint capacity, Dictionary<VFXAttribute, int> storedAttribute);
        string GetCodeOffset(VFXAttribute attrib, string index);
        uint GetBufferSize(uint capacity);

        VFXGPUBufferDesc GetBufferDesc(uint capacity);
    }

    class StructureOfArrayProvider : ILayoutProvider
    {
        private struct AttributeLayout
        {
            public int bucket;
            public int offset;

            public AttributeLayout(int bucket, int offset)
            {
                this.bucket = bucket;
                this.offset = offset;
            }
        }

        // return size
        private int GenerateBucketLayout(List<VFXAttribute> attributes, int bucketId)
        {
            var sortedAttrib = attributes.OrderByDescending(a => VFXValue.TypeToSize(a.type));

            var attribBlocks = new List<List<VFXAttribute>>();
            foreach (var value in sortedAttrib)
            {
                var block = attribBlocks.FirstOrDefault(b => b.Sum(a => VFXValue.TypeToSize(a.type)) + VFXValue.TypeToSize(value.type) <= 4);
                if (block != null)
                    block.Add(value);
                else
                    attribBlocks.Add(new List<VFXAttribute>() { value });
            }

            int currentOffset = 0;
            int minAlignment = 0;
            foreach (var block in attribBlocks)
            {
                foreach (var attrib in block)
                {
                    int size = VFXValue.TypeToSize(attrib.type);
                    int alignment = size > 2 ? 4 : size;
                    minAlignment = Math.Max(alignment, minAlignment);
                    // align offset
                    currentOffset = (currentOffset + alignment - 1) & ~(alignment - 1);
                    m_AttributeLayout.Add(attrib, new AttributeLayout(bucketId, currentOffset));
                    currentOffset += size;
                }
            }

            return (currentOffset + minAlignment - 1) & ~(minAlignment - 1);
        }

        public void GenerateAttributeLayout(uint capacity, Dictionary<VFXAttribute, int> storedAttribute)
        {
            m_BucketSizes.Clear();
            m_AttributeLayout.Clear();
            m_BucketOffsets.Clear();

            var attributeBuckets = new Dictionary<int, List<VFXAttribute>>();
            foreach (var kvp in storedAttribute)
            {
                List<VFXAttribute> attributes;
                if (!attributeBuckets.ContainsKey(kvp.Value))
                {
                    attributes = new List<VFXAttribute>();
                    attributeBuckets[kvp.Value] = attributes;
                }
                else
                    attributes = attributeBuckets[kvp.Value];

                attributes.Add(kvp.Key);
            }

            int bucketId = 0;
            foreach (var bucket in attributeBuckets)
            {
                int bucketOffset = bucketId == 0 ? 0 : m_BucketOffsets[bucketId - 1] + (int)capacity * m_BucketSizes[bucketId - 1];
                m_BucketOffsets.Add((bucketOffset + 3) & ~3); // align on dword;
                m_BucketSizes.Add(GenerateBucketLayout(bucket.Value, bucketId));
                ++bucketId;
            }

            // Debug log
            if (VFXViewPreference.advancedLogs)
            {
                var builder = new StringBuilder();
                builder.AppendLine("ATTRIBUTE LAYOUT");
                builder.Append(string.Format("NbBuckets:{0} ( ", m_BucketSizes.Count));
                foreach (int size in m_BucketSizes)
                    builder.Append(size + " ");
                builder.AppendLine(")");
                foreach (var kvp in m_AttributeLayout)
                    builder.AppendLine(string.Format("Attrib:{0} type:{1} bucket:{2} offset:{3}", kvp.Key.name, kvp.Key.type, kvp.Value.bucket, kvp.Value.offset));
                Debug.Log(builder.ToString());
            }
        }

        public string GetCodeOffset(VFXAttribute attrib, string index)
        {
            AttributeLayout layout;
            if (!m_AttributeLayout.TryGetValue(attrib, out layout))
            {
                throw new InvalidOperationException(string.Format("Cannot find attribute {0}", attrib.name));
            }
            return string.Format("({2} * 0x{0:X} + 0x{1:X}) << 2", m_BucketSizes[layout.bucket], m_BucketOffsets[layout.bucket] + layout.offset, index);
        }

        public uint GetBufferSize(uint capacity)
        {
            return (uint)m_BucketOffsets.LastOrDefault() + capacity * (uint)m_BucketSizes.LastOrDefault();
        }

        public VFXGPUBufferDesc GetBufferDesc(uint capacity)
        {
            var layout = m_AttributeLayout.Select(o => new VFXLayoutElementDesc()
            {
                name = o.Key.name,
                type = o.Key.type,
                offset = new VFXLayoutOffset()
                {
                    structure = (uint)m_BucketSizes[o.Value.bucket],
                    bucket = (uint)m_BucketOffsets[o.Value.bucket],
                    element = (uint)o.Value.offset
                }
            });
            return new VFXGPUBufferDesc()
            {
                type = ComputeBufferType.Raw,
                size = GetBufferSize(capacity),
                stride = 4,
                capacity = capacity,
                layout = layout.ToArray()
            };
        }

        public struct BucketInfo
        {
            public int size;
            public int usedSize;
            public VFXAttribute[] attributes;
            public int[] channels;
        }

        public BucketInfo[] GetBucketLayoutInfo()
        {
            int count = m_BucketSizes.Count;
            BucketInfo[] buckets = new BucketInfo[count];
            for (int i = 0; i < count; i++)
            {
                int size = m_BucketSizes[i];
                buckets[i].size = size;
                buckets[i].usedSize = 0;
                buckets[i].attributes = new VFXAttribute[size];
                buckets[i].channels = new int[size];
            }

            foreach (var kvp in m_AttributeLayout)
            {
                var attrib = kvp.Key;
                int size = VFXValue.TypeToSize(attrib.type);
                int offset = kvp.Value.offset;
                for (int i = 0; i < size; i++)
                {
                    buckets[kvp.Value.bucket].attributes[i + offset] = attrib;
                    buckets[kvp.Value.bucket].channels[i + offset] = i;
                    buckets[kvp.Value.bucket].usedSize = Math.Max(buckets[kvp.Value.bucket].usedSize, i + offset + 1);
                }
            }

            return buckets;
        }

        private Dictionary<VFXAttribute, AttributeLayout> m_AttributeLayout = new Dictionary<VFXAttribute, AttributeLayout>();
        private List<int> m_BucketSizes = new List<int>();
        private List<int> m_BucketOffsets = new List<int>();
    }

    class VFXDataParticle : VFXData, ISpaceable
    {
        public override VFXDataType type { get { return VFXDataType.kParticle; } }

        public uint capacity
        {
            get { return m_Capacity; }
            set { m_Capacity = value; }
        }

        private uint alignedCapacity
        {
            get
            {
                uint capacity = m_Capacity;
                const uint kThreadPerGroup = 64;
                if (capacity > kThreadPerGroup)
                    capacity = (uint)((capacity + kThreadPerGroup - 1) & ~(kThreadPerGroup - 1)); // multiple of kThreadPerGroup
                return (capacity + 3u) & ~3u; // Align on 4 boundary
            }
        }

        public override uint sourceCount
        {
            get
            {
                var init = owners.FirstOrDefault(o => o.contextType == VFXContextType.kInit);

                if (init == null)
                    return 0u;

                var cpuCount = init.inputContexts.Where(o => o.contextType == VFXContextType.kSpawner).Count();
                var gpuCount = init.inputContexts.Where(o => o.contextType == VFXContextType.kSpawnerGPU).Count();

                if (cpuCount != 0 && gpuCount != 0)
                {
                    throw new InvalidOperationException("Cannot mix GPU & CPU spawners in init");
                }

                if (cpuCount > 0)
                {
                    return (uint)cpuCount;
                }
                else if (gpuCount > 0)
                {
                    if (gpuCount > 1)
                    {
                        throw new InvalidOperationException("Don't support multiple GPU event (for now)");
                    }
                    var parent = m_DependenciesIn.OfType<VFXDataParticle>().FirstOrDefault();
                    return parent != null ? parent.m_Capacity : 0u;
                }
                return init != null ? (uint)init.inputContexts.Where(o => o.contextType == VFXContextType.kSpawner /* Explicitly ignore spawner gpu */).Count() : 0u;
            }
        }

        public uint attributeBufferSize
        {
            get
            {
                return m_layoutAttributeCurrent.GetBufferSize(alignedCapacity);
            }
        }

        public VFXGPUBufferDesc attributeBufferDesc
        {
            get
            {
                return m_layoutAttributeCurrent.GetBufferDesc(capacity);
            }
        }

        public VFXCoordinateSpace space
        {
            get { return m_Space; }
            set { m_Space = value; Modified(); }
        }

        public override bool CanBeCompiled()
        {
            // Has enough contexts and capacity
            if (m_Owners.Count < 1 || m_Capacity <= 0)
                return false;

            // Has a initialize
            if (m_Owners[0].contextType != VFXContextType.kInit)
                return false;

            // Has a spawner
            if (m_Owners[0].inputContexts.FirstOrDefault() == null)
                return false;

            // Has an output
            if (m_Owners.Last().contextType == VFXContextType.kOutput)
                return true;

            // Has a least one dependent compilable system
            if (m_Owners.SelectMany(c => c.allLinkedOutputSlot)
                .Select(s => ((VFXModel)s.owner).GetFirstOfType<VFXContext>())
                .Any(c => c.CanBeCompiled()))
                return true;

            return false;
        }

        public override VFXDeviceTarget GetCompilationTarget(VFXContext context)
        {
            return VFXDeviceTarget.GPU;
        }

        public override void GenerateAttributeLayout()
        {
            m_layoutAttributeCurrent.GenerateAttributeLayout(alignedCapacity, m_StoredCurrentAttributes);
            var parent = m_DependenciesIn.OfType<VFXDataParticle>().FirstOrDefault();
            if (parent != null)
            {
                m_layoutAttributeSource.GenerateAttributeLayout(parent.alignedCapacity, parent.m_StoredCurrentAttributes);
                m_ownAttributeSourceBuffer = false;
            }
            else
            {
                var readSourceAttribute = m_ReadSourceAttributes.ToDictionary(o => o, _ => (int)VFXAttributeMode.ReadSource);
                m_layoutAttributeSource.GenerateAttributeLayout(sourceCount, readSourceAttribute);
                m_ownAttributeSourceBuffer = true;
            }
        }

        public override string GetAttributeDataDeclaration(VFXAttributeMode mode)
        {
            if (m_StoredCurrentAttributes.Count == 0)
                return string.Empty;
            else if ((mode & VFXAttributeMode.Write) != 0)
                return "RWByteAddressBuffer attributeData;";
            else
                return "ByteAddressBuffer attributeData;";
        }

        private string GetCastAttributePrefix(VFXAttribute attrib)
        {
            if (VFXExpression.IsFloatValueType(attrib.type))
                return "asfloat";
            return "";
        }

        private string GetByteAddressBufferMethodSuffix(VFXAttribute attrib)
        {
            int size = VFXExpression.TypeToSize(attrib.type);
            if (size == 1)
                return string.Empty;
            else if (size <= 4)
                return size.ToString();
            else
                throw new ArgumentException(string.Format("Attribute {0} of type {1} cannot be handled in ByteAddressBuffer due to its size of {2}", attrib.name, attrib.type, size));
        }

        public override string GetLoadAttributeCode(VFXAttribute attrib, VFXAttributeLocation location)
        {
            var attributeStore = location == VFXAttributeLocation.Current ? m_layoutAttributeCurrent : m_layoutAttributeSource;
            var attributeBuffer = location == VFXAttributeLocation.Current ? "attributeBuffer" : "sourceAttributeBuffer";
            var index = location == VFXAttributeLocation.Current ? "index" : "sourceIndex";

            if (location == VFXAttributeLocation.Current && !m_StoredCurrentAttributes.ContainsKey(attrib))
                throw new ArgumentException(string.Format("Attribute {0} does not exist in data layout", attrib.name));

            if (location == VFXAttributeLocation.Source && !m_ReadSourceAttributes.Any(a => a.name == attrib.name))
                throw new ArgumentException(string.Format("Attribute {0} does not exist in data layout", attrib.name));

            return string.Format("{0}({3}.Load{1}({2}))", GetCastAttributePrefix(attrib), GetByteAddressBufferMethodSuffix(attrib), attributeStore.GetCodeOffset(attrib, index), attributeBuffer);
        }

        public override string GetStoreAttributeCode(VFXAttribute attrib, string value)
        {
            if (!m_StoredCurrentAttributes.ContainsKey(attrib))
                throw new ArgumentException(string.Format("Attribute {0} does not exist in data layout", attrib.name));

            return string.Format("attributeBuffer.Store{0}({1},{3}({2}))", GetByteAddressBufferMethodSuffix(attrib), m_layoutAttributeCurrent.GetCodeOffset(attrib, "index"), value, attrib.type == VFXValueType.Boolean ? "uint" : "asuint");
        }

        public override IEnumerable<VFXContext> InitImplicitContexts()
        {
            if (!NeedsSort())
            {
                m_Contexts = m_Owners;
                return Enumerable.Empty<VFXContext>();
            }

            m_Contexts = new List<VFXContext>(m_Owners.Count + 1);
            int index = 0;

            // First add init and updates
            for (index = 0; index < m_Owners.Count; ++index)
            {
                if ((m_Owners[index].contextType == VFXContextType.kOutput))
                    break;
                m_Contexts.Add(m_Owners[index]);
            }

            // Then the camera sort
            var cameraSort = VFXContext.CreateImplicitContext<VFXCameraSort>(this);
            m_Contexts.Add(cameraSort);

            // And finally output
            for (; index < m_Owners.Count; ++index)
                m_Contexts.Add(m_Owners[index]);

            return new VFXContext[] { cameraSort };
        }

        public bool NeedsIndirectBuffer()
        {
            return owners.OfType<VFXAbstractParticleOutput>().Any(o => o.HasIndirectDraw());
        }

        public bool NeedsSort()
        {
            return owners.OfType<VFXAbstractParticleOutput>().Any(o => o.HasSorting());
        }

        public override void FillDescs(
            List<VFXGPUBufferDesc> outBufferDescs,
            List<VFXEditorSystemDesc> outSystemDescs,
            VFXExpressionGraph expressionGraph,
            Dictionary<VFXContext, VFXContextCompiledData> contextToCompiledData,
            Dictionary<VFXContext, int> contextSpawnToBufferIndex,
            Dictionary<VFXData, int> attributeBuffer,
            Dictionary<VFXData, int> eventBuffer)
        {
            bool hasKill = IsAttributeStored(VFXAttribute.Alive);

            var deadListBufferIndex = -1;
            var deadListCountIndex = -1;

            var systemBufferMappings = new List<VFXMapping>();
            var systemValueMappings = new List<VFXMapping>();

            var attributeBufferIndex = attributeBuffer[this];

            int attributeSourceBufferIndex = -1;
            int eventGPUFrom = -1;
            if (m_DependenciesIn.Any())
            {
                if (m_DependenciesIn.Count != 1)
                {
                    throw new InvalidOperationException("Unexpected multiple input dependency for GPU event");
                }
                attributeSourceBufferIndex = attributeBuffer[m_DependenciesIn.FirstOrDefault()];
                eventGPUFrom = eventBuffer[this];
            }

            if (attributeBufferIndex != -1)
            {
                outBufferDescs.Add(m_layoutAttributeCurrent.GetBufferDesc(alignedCapacity));
                systemBufferMappings.Add(new VFXMapping("attributeBuffer", attributeBufferIndex));
            }

            if (m_ownAttributeSourceBuffer && m_layoutAttributeSource.GetBufferSize(sourceCount) > 0u)
            {
                if (attributeSourceBufferIndex != -1)
                {
                    throw new InvalidOperationException("Unexpected source while filling description of data particle");
                }

                attributeSourceBufferIndex = outBufferDescs.Count;
                outBufferDescs.Add(m_layoutAttributeSource.GetBufferDesc(sourceCount));
            }

            if (attributeSourceBufferIndex != -1)
            {
                systemBufferMappings.Add(new VFXMapping("sourceAttributeBuffer", attributeSourceBufferIndex));
            }

            var systemFlag = VFXSystemFlag.SystemDefault;
            if (eventGPUFrom != -1)
            {
                systemFlag |= VFXSystemFlag.SystemReceivedEventGPU;
                systemBufferMappings.Add(new VFXMapping("eventList", eventGPUFrom));
            }

            if (hasKill)
            {
                systemFlag |= VFXSystemFlag.SystemHasKill;

                deadListBufferIndex = outBufferDescs.Count;
                outBufferDescs.Add(new VFXGPUBufferDesc() { type = ComputeBufferType.Counter, size = capacity, stride = 4 });
                systemBufferMappings.Add(new VFXMapping("deadList", deadListBufferIndex));

                deadListCountIndex = outBufferDescs.Count;
                outBufferDescs.Add(new VFXGPUBufferDesc() { type = ComputeBufferType.Raw, size = 1, stride = 4 });
                systemBufferMappings.Add(new VFXMapping("deadListCount", deadListCountIndex));
            }

            var initContext = m_Contexts.FirstOrDefault(o => o.contextType == VFXContextType.kInit);
            if (initContext != null)
                systemBufferMappings.AddRange(initContext.inputContexts.Where(o => o.contextType == VFXContextType.kSpawner).Select(o => new VFXMapping("spawner_input", contextSpawnToBufferIndex[o])));
            if (m_Contexts.Count() > 0 && m_Contexts.First().contextType == VFXContextType.kInit) // TODO This test can be removed once we ensure priorly the system is valid
            {
                var mapper = contextToCompiledData[m_Contexts.First()].cpuMapper;

                var boundsCenterExp = mapper.FromNameAndId("bounds_center", -1);
                var boundsSizeExp = mapper.FromNameAndId("bounds_size", -1);

                int boundsCenterIndex = boundsCenterExp != null ? expressionGraph.GetFlattenedIndex(boundsCenterExp) : -1;
                int boundsSizeIndex = boundsSizeExp != null ? expressionGraph.GetFlattenedIndex(boundsSizeExp) : -1;

                if (boundsCenterIndex != -1 && boundsSizeIndex != -1)
                {
                    systemValueMappings.Add(new VFXMapping("bounds_center", boundsCenterIndex));
                    systemValueMappings.Add(new VFXMapping("bounds_size", boundsSizeIndex));
                }
            }

            int indirectBufferIndex = -1;
            bool needsIndirectBuffer = NeedsIndirectBuffer();
            if (needsIndirectBuffer)
            {
                systemFlag |= VFXSystemFlag.SystemHasIndirectBuffer;
                indirectBufferIndex = outBufferDescs.Count;
                outBufferDescs.Add(new VFXGPUBufferDesc() { type = ComputeBufferType.Counter, size = capacity, stride = 4 });
                systemBufferMappings.Add(new VFXMapping("indirectBuffer", indirectBufferIndex));
            }

            // sort buffers
            int sortBufferAIndex = -1;
            int sortBufferBIndex = -1;
            bool needsSort = NeedsSort();
            if (needsSort)
            {
                sortBufferAIndex = outBufferDescs.Count;
                sortBufferBIndex = sortBufferAIndex + 1;

                outBufferDescs.Add(new VFXGPUBufferDesc() { type = ComputeBufferType.Default, size = capacity, stride = 8 });
                systemBufferMappings.Add(new VFXMapping("sortBufferA", sortBufferAIndex));

                outBufferDescs.Add(new VFXGPUBufferDesc() { type = ComputeBufferType.Default, size = capacity, stride = 8 });
                systemBufferMappings.Add(new VFXMapping("sortBufferB", sortBufferBIndex));
            }

            var taskDescs = new List<VFXEditorTaskDesc>();
            var bufferMappings = new List<VFXMapping>();
            var uniformMappings = new List<VFXMapping>();

            for (int i = 0; i < m_Contexts.Count; ++i)
            {
                var context = m_Contexts[i];
                var contextData = contextToCompiledData[context];

                var taskDesc = new VFXEditorTaskDesc();
                taskDesc.type = context.taskType;

                bufferMappings.Clear();

                if (attributeBufferIndex != -1)
                    bufferMappings.Add(new VFXMapping("attributeBuffer", attributeBufferIndex));

                if (eventGPUFrom != -1 && context.contextType == VFXContextType.kInit)
                    bufferMappings.Add(new VFXMapping("eventList", eventGPUFrom));

                if (deadListBufferIndex != -1 && context.contextType != VFXContextType.kOutput && context.taskType != VFXTaskType.CameraSort)
                    bufferMappings.Add(new VFXMapping(context.contextType == VFXContextType.kUpdate ? "deadListOut" : "deadListIn", deadListBufferIndex));

                if (deadListCountIndex != -1 && context.contextType == VFXContextType.kInit)
                    bufferMappings.Add(new VFXMapping("deadListCount", deadListCountIndex));

                if (attributeSourceBufferIndex != -1 && context.contextType == VFXContextType.kInit)
                    bufferMappings.Add(new VFXMapping("sourceAttributeBuffer", attributeSourceBufferIndex));

                if (indirectBufferIndex != -1 &&
                    (context.contextType == VFXContextType.kUpdate ||
                     (context.contextType == VFXContextType.kOutput && (context as VFXAbstractParticleOutput).HasIndirectDraw())))
                {
                    bufferMappings.Add(new VFXMapping(context.taskType == VFXTaskType.CameraSort ? "inputBuffer" : "indirectBuffer", indirectBufferIndex));
                }

                if (deadListBufferIndex != -1 && context.contextType == VFXContextType.kOutput && (context as VFXAbstractParticleOutput).NeedsDeadListCount())
                    bufferMappings.Add(new VFXMapping("deadListCount", deadListCountIndex));

                if (context.taskType == VFXTaskType.CameraSort)
                {
                    bufferMappings.Add(new VFXMapping("outputBuffer", sortBufferAIndex));
                    if (deadListCountIndex != -1)
                        bufferMappings.Add(new VFXMapping("deadListCount", deadListCountIndex));
                }

                var gpuTarget = context.allLinkedOutputSlot.SelectMany(o => (o.owner as VFXContext).outputContexts)
                    .Where(c => c.CanBeCompiled())
                    .Select(o => eventBuffer[o.GetData()])
                    .ToArray();
                for (uint indexTarget = 0; indexTarget < (uint)gpuTarget.Length; ++indexTarget)
                {
                    var prefix = VFXCodeGeneratorHelper.GeneratePrefix(indexTarget);
                    bufferMappings.Add(new VFXMapping(string.Format("eventListOut_{0}", prefix), gpuTarget[indexTarget]));
                }

                uniformMappings.Clear();
                foreach (var uniform in contextData.uniformMapper.uniforms.Concat(contextData.uniformMapper.textures))
                    uniformMappings.Add(new VFXMapping(contextData.uniformMapper.GetName(uniform), expressionGraph.GetFlattenedIndex(uniform)));

                // Retrieve all cpu mappings at context level (-1)
                var cpuMappings = contextData.cpuMapper.CollectExpression(-1).Select(exp => new VFXMapping(exp.name, expressionGraph.GetFlattenedIndex(exp.exp))).ToArray();

                //Check potential issue with invalid operation on CPU
                foreach (var mapping in cpuMappings)
                {
                    if (mapping.index < 0)
                    {
                        throw new InvalidOperationException("Unable to compute CPU expression for mapping : " + mapping.name);
                    }
                }

                taskDesc.buffers = bufferMappings.ToArray();
                taskDesc.values = uniformMappings.ToArray();
                taskDesc.parameters = cpuMappings.Concat(contextData.parameters).ToArray();
                taskDesc.shaderSourceIndex = contextToCompiledData[context].indexInShaderSource;

                taskDescs.Add(taskDesc);
            }

            outSystemDescs.Add(new VFXEditorSystemDesc()
            {
                flags = systemFlag,
                tasks = taskDescs.ToArray(),
                capacity = capacity,
                buffers = systemBufferMappings.ToArray(),
                values = systemValueMappings.ToArray(),
                type = VFXSystemType.Particle,
                layer = m_Layer
            });
        }

        public override void CopySettings<T>(T dst)
        {
            var instance = dst as VFXDataParticle;
            instance.m_Capacity = m_Capacity;
            instance.m_Space = m_Space;
        }

        public StructureOfArrayProvider.BucketInfo[] GetCurrentAttributeLayout()
        {
            return m_layoutAttributeCurrent.GetBucketLayoutInfo();
        }

        public StructureOfArrayProvider.BucketInfo[] GetSourceAttributeLayout()
        {
            return m_layoutAttributeSource.GetBucketLayoutInfo();
        }

        [SerializeField]
        private uint m_Capacity = 65536;
        [SerializeField]
        private VFXCoordinateSpace m_Space;
        [NonSerialized]
        private StructureOfArrayProvider m_layoutAttributeCurrent = new StructureOfArrayProvider();
        [NonSerialized]
        private StructureOfArrayProvider m_layoutAttributeSource = new StructureOfArrayProvider();
        [NonSerialized]
        private bool m_ownAttributeSourceBuffer;
    }
}


The portion of Quebec's religious neutrality law that dictates when Quebecers must leave their faces uncovered in order to receive public services has been suspended for a second time, only days before it was slated to go into effect.
Blanchard said Section 10, which pertains to face coverings, appears to be "a violation" of the Canadian and Quebec charters, which "provide for freedom of conscience and religion."
The judge concluded that "irreparable harm will be caused to Muslim women" if the relevant section of the law had gone into effect on July 1.
"We're very happy with the decision," said Catherine McKenzie, who was part of the legal team that challenged the law's constitutionality on behalf of Warda Naili, a Quebec woman who wears a niqab.
"This law has an important impact on women who cover their faces for religious reasons. Women were going to be potentially cut off from very basic services so it was important for us to ask for the law to be stayed again."
A spokesperson for Justice Minister Stéphanie Vallée, who has been the point person on the law, said the government is analyzing the judgment and that it is still within the 30-day appeal period.
In his ruling, Blanchard also noted there is still "confusion and uncertainty" about how the process will work.
The guidelines, released in May, state that exemptions to the law, previously known as Bill 62, can only be granted to individuals on religious grounds if the demand is serious, doesn't violate the rights of others and doesn't impose "undue hardships."
"It would be determined on a case by case [basis], following a request. Is this someone who has a sincere belief who is wearing this piece of clothing regularly, in their daily life, or if the request is being put forward with the aim of getting an advantage."


text:
ND VB Twitter
ND VB Instagram
ND VB Facebook
2020 History and Record Supplement
volleyball camps
Irish Honored With AVCA Team Academic Award
NOTRE DAME, Ind. – The American Volleyball Coaches Association (AVCA) announced recently that a record 354 teams earned the AVCA Team Academic Award for the 2007-2008 season. The number smashes the previous high mark of 308 schools set a year ago.
The award, which was initiated in the 1992-93 academic year, honors collegiate and high school volleyball teams that displayed excellence in the classroom during the school year by maintaining at least a 3.30 cumulative team grade-point-average on a 4.0 scale or a 4.10 cumulative team grade-point-average on a 5.0 scale.
"I'm proud of the success that the team had in the classroom throughout the year," said Irish head coach Debbie Brown. "We have an incredibly hard working group both on and off the court, and the dedication they have shown toward their studies is truly amazing."
The 2008 spring semester saw the Irish volleyball team earn a 3.453 grade-point-average following a fall term in which the team posted a 3.350 grade-point-average. The Irish sported a 3.440 cumulative grade-point-average upon the completion of the school year.
Overall, NCAA Division I broke its own record for number of collegiate schools at any division receiving the award, as 71 institutions were honored this year, surpassing the mark of 56 set a year ago. NCAA Division III also surpassed the previous collegiate record, as well as its own division-high, as 62 of those schools attained the mark.
In total, 213 collegiate programs met the requirements for the award in 2007-08. In addition to the NCAA Division I & Division III recipients, a total of 39 NCAA Division II schools bested its previous high mark of 31.
Notre Dame opens the 2008 season on Aug. 29 (Friday) against IPFW at the Joyce Center.
Volleyball Irish Volleyball Inks Two In Early Signing Period
Volleyball No. 5 Irish Top BC in Four Sets
Volleyball @NDvolleyball | Highlights vs. Boston College (10.23.20)

redpajama_set_name: RedPajamaCommonCrawl


text:
Tag: Nations
LOCAL Top Story
US applauds Sri Lanka Government for its efforts to promote reconciliation
Written by:Dilshan WijegunasekeraPosted on: 16th March 2017 16th March 2017
(WASHINGTON, LANKAPUVATH) – The United States (US) is pleased that Sri Lanka has agreed once again to co-sponsor the resolution, and invites like-minded United Nations (UN) members to demonstrate support for reconciliation and peace in Sri Lanka by adding their names to the list of cosponsors. The United States further applauds the administration of President Maithripala Sirisena for its continuing efforts to promote reconciliation.
"US applauds Sri Lanka Government for its efforts to promote reconciliation"
MORE NEWS WORLD
Let us make a world of peace for our future generations
Written by:Dilshan WijegunasekeraPosted on: 15th March 2017
(SEOUL, LANKAPUVATH) – Faced with the reality of uncertainty in global cooperation triggered by a chain of political upheavals from the Brexit to elections in the United States (US) and European states, a new approach to pursue an international peaceful order is discussed.
"Let us make a world of peace for our future generations"
UN says world faces largest humanitarian crisis since 1945
(AFRICA, LANKAPUVATH) – The world is facing its largest humanitarian crisis since 1945, the United Nations (UN) says, issuing a plea for help to avoid "A catastrophe."
"UN says world faces largest humanitarian crisis since 1945"
Two more years to implement Sri Lanka co-sponsored UN resolution
Written by:Dilshan WijegunasekeraPosted on: 9th March 2017 9th March 2017
(COLOMBO, LANKAPUVATH) – Sri Lanka has been given 2 more years to implement Sri Lanka co-sponsored 30/1 Geneva resolution 2015 without any amendment or new suggestions by the United Nations Human Rights Council (UNHRC), said the Acting Foreign Minister Dr. Harsha De Silva.
"Two more years to implement Sri Lanka co-sponsored UN resolution"
Vaiko writes to Premier Modi on Lanka issue
(TAMIL NADU, LANKAPUVATH) – Marumalarchi Dravida Munnetra Kazhagam (MDMK) General Secretary Vaiko on Monday (06) urged the Indian Government to change its position in the United Nations Human Rights Council (UNHRC) in favour of an independent international investigation into the alleged human rights violations by the Sri Lankan armed forces in 2009, The Hindu reported.
"Vaiko writes to Premier Modi on Lanka issue"
HIGHLIGHTED LOCAL
Sri Lanka joins South Asian partners to safeguard children's rights
Written by:Dilshan WijegunasekeraPosted on: 6th March 2017
(COLOMBO, LANKAPUVATH) – Sri Lankan legislators have joined fellow lawmakers from across South Asia to prioritize and safeguard children's rights in the region, the United Nations International Children's Emergency Fund (UNICEF) said on Monday (06).
"Sri Lanka joins South Asian partners to safeguard children's rights"
North Korea fires 4 ballistic missiles into sea
(NORTH KOREA, LANKAPUVATH) – North Korea has launched 4 ballistic missiles towards the Sea of Japan. 3 Of them fell into Japan's Exclusive Economic Zone (EEZ) after flying some 1,000 Km (620 miles), in what Prime Minister Shinzo Abe called a "New stage of threat."
"North Korea fires 4 ballistic missiles into sea"
Tamil Nadu protesters seek trial of Sri Lankan Army
(TAMIL NADU, LANKAPUVATH) – A large number of people participated in a protest staged on Sunday (05) demanding that the Indian Government pass a resolution seeking to try the Sri Lankan Army in the International Criminal Court (ICC) for war crimes against Sri Lankan Tamils, The Hindu reported.
"Tamil Nadu protesters seek trial of Sri Lankan Army"
Somalia says 110 dead in last 48-hours due to drought
(MOGADISHU, LANKAPUVATH) – Some 110 people have died in Southern Somalia in the last 2-days from famine and diarrhea resulting from a drought, the Prime Minister said on Saturday (04), as the area braces itself for widespread shortages of food.
"Somalia says 110 dead in last 48-hours due to drought"
"Need Centre's help in Sri Lanka issue," says Anbumani Ramadoss
(CHENNAI, LANKAPUVATH) – Citing the report of United Nations Human Rights Commissioner Zeid Raad Al Hussein accusing Sri Lanka of failing to comply with the Commission's resolutions for hybrid mechanism to probe the war crimes and return of Army occupied lands to Tamils, Pattali Makkal Katchi (PMK) Youth Wing Leader Anbumani Ramadoss on Saturday (04) asked the Union Government to take the issue to the United Nations Security Council (UNSC) to ensure justice for Tamils.
""Need Centre's help in Sri Lanka issue," says Anbumani Ramadoss"


text:
events twitter insta facebook music about contact shop
Homostash is a multi platform project created and run by London based DJ and promoter Tafkanik & art director Rodrigo Branco. It features and brings together alternative culture and moustache lovers across the globe. The community can interact via Facebook, Instagram and Twitter by submitting pictures, liking or sharing the online content in those virtual spaces. That way either proud moustache owners or simply facial hair enthusiasts can meet and follow daily news surrounding the theme.
Since its creation in 2014, Homostash has also been a London based party that delivers an open-minded, welcoming and fun atmosphere. The party's main home is Dalston Superstore, an iconic LGBT club which has been awarded the top spot at Time Out London's best London LGBT clubs list. Additionally, Homostash has a residency at one of the biggest London clubs, EGG London (among Top100 best clubs in the world according to DJ MAG) as part of the Berlin Berlin events. Furthermore, Homostash was awarded the honour of running the official event for LGBT History month UK at Five Miles in 2018.
The party is home to local and international DJs, as well as visual artists who showcase their work in forms of exhibitions
or audiovisual materials that match the vibe of the party.
Not only does it have great music, focusing mainly on techno and tech house, but also an inspirational setting for anyone looking for fun and creative people. The party is also popular among celebrities and has been attended by several stars including: Skin (Skunk Anansie), Jake Shears (Scissor Sisters) and Hammed Sinno (Mashrou Leila).
Homostash has also worked closely with and supported several charities, such as the Movember Foundation, Long Time No Syphilis, Positive East and Prepster.
— Photos by Lucas Fonseca, Michele Baron & Hawt! Photo
Homostash©


text:
2017 Was the Safest-Ever Year to Fly
Health & Wellness Jan 3, 2018
It's the rare year during which no one dies in a commercial jet airline crash. For whatever reasons, 2017 was such a year.
That made 2017 the safest year ever for commercial aviation, both in terms of accidents and fatalities.
There were aviation-related fatalities during the year, however, when incidents involving cargo and propeller-driven aircraft are considered.
According to the Aviation Safety Network, there were 10 fatal airliner accidents during 2017, resulting in 44 pilot and passenger deaths. Five of the accidents involved cargo planes, five were small passenger planes.
It's Not Just You – Air Travel Really Has Gotten Worse
There was a notable pattern to the accidents: four of the 10 crashes, accounting for 25 of the 44 fatalities, involved some variant of the Cessna 208 single-engine turboprop planes; and two of the 10 downed planes, accounting for eight deaths, were Let L-410UVP-E20s, the twin-engine turboprop produced by Czech company LET Kunovice.
The worst of the year's accidents was the NatureAir crash on Punta Islita, Costa Rica, resulting in 12 fatalities. That, ironically, was on December 31, New Year's eve.
How concerned are you about air safety when you fly?
New Disney Policy Puts Security Over Privacy
EU Court Calls Uber a Taxi Company. Will Rates Rise?
These Are the 10 Busiest North American Air Routes
Don't Miss a Trip, Tip, or Deal!
Let us do the legwork! Sign up for our free newsletter now.


This brother sister duo was as adorable and fun as can be....they were naturals at being 'natural' and made my job easy. It was great to get to know them and reconnect with their mom who was a high school friend of mine! Allison, thank you so much for reaching out....it was so great to see you after all of these years!
I just love these pics! You really captured their personalities. Thank you, Jaime! It was great to see you too.


text:
Home Sport News Draymond Green wants to win Defensive Player of the Year: 'I need...
Draymond Green wants to win Defensive Player of the Year: 'I need that bad'
Draymond Green is still bitter about making second team all-defense last year and is making it a point to ensure that doesn't happen again.
The 28-year-old forward said Wednesday that it's a big goal of his to win the Defensive Player of the Year award this season and that he thinks about it when he wakes up each morning.
"I need that," Green told reporters. "I need that bad. Real bad. I made second team All-Defense last year. I'm pissed about that still. I'll be pissed until I right that, so that's a serious goal of mine this year. And I'm on it every night."
He added: "I'm pissed. Second-team All-Defense, that's disrespectful."
Green missed several weeks of training camp due to a sore knee but he appears to have returned to form, scoring 16 points with 14 rebounds and eight assists Wednesday in a victory over the Pelicans.
Even though Green battled an injury, his teammates never doubted whether he would make an impact.
"He didn't change his name, and he's still Draymond Green, No. 23 for the Warriors," Stephen Curry said in Wednesday's postgame press conference. "You never worry about him finding a way to impact the game. [Whether] he's making or missing shots, whatever, he always gets timely stops.
"He's talking, an emotional leader, so just like it was with Klay [Thompson] shooting a basketball, you never worry about Draymond getting implemented into an all-around game that helps us get wins. It's great to see him with a little pep in his step, a little juice and excitement out there. He's playing well."
Green has averaged 8.9 points with 7.2 rebounds and 8.1 assists through nine games this season.
Previous articleFanboy Luka Doncic gets game-worn LeBron James jersey after first meeting
Next articleLOOK: JuJu Smith-Schuster went trick-or-treating in full Steelers uniform


text:
Tagged: juvenile idiopathic arthritis
Jon Packham
Honorary Senior Lecturer in Rheumatology, Keele University, Stoke on Trent, UK; Consultant Rheumatologist, Haywood Hospital, Staffordshire and Stoke on Trent Partnership (SSoTP) NHS Trust,
Brit-PACT
spondyloarthropathy
Dr Jon Packham BM, FRCP, DM is currently honorary Senior Lecturer in Rheumatology at Keele University, Stoke on Trent UK and Consultant Rheumatologist at the Haywood Hospital for the Staffordshire and Stoke on Trent Partnership (SSoTP) NHS Trust, with specialist interests in spondyloarthropathy and juvenile idiopathic arthritis.
Previous and current appointments include: member of the Heberden Committee at the British Society for Rheumatology (BSR), member of BSR Council, West Midlands regional BSR chair, vice chair for the BSR biologics registries subcommittee, member of the National Integrated Care working group, medical advisor for JIA to National Rheumatoid Arthritis Society, member of NICE guideline development groups 'Spondyloarthropathies' and 'Depression in chronic disease', BSR national gout audit co-lead, secretary for the British Society for Paediatric and Adolescent Rheumatology (BSPAR) and rheumatology regional specialist advisor for the Royal College of Physicians.
Dr Packham is a member of Arthritis Research UK Spondyloarthropathy clinical studies group and founder member of BRIT-PACT. He is associate medical director of research for SSoTP NHS trust and an active member of the Keele Haywood Rheumatology Academic Group, working closely with the Arthritis Research UK Primary Care Centre at Keele University. Current and past research: psychological outcomes in inflammatory arthritis, quality of life and fatigue in spondyloarthropathy, long term outcomes in juvenile arthritis, treatment paradigms for psoriatic arthritis and spondyloarthropathy, biomarkers for disease outcome in inflammatory arthritis and community based studies of psoriasis and psoriatic arthritis.


North & South is happy to provide roadside assistance and off-road recovery throughout Cleveland, Tennessee, and the surrounding area. Our fleet is on call 24/7 to assist clients throughout the county, and will provide you with an accurate estimated time of arrival.
From jumpstarts and lockouts for any vehicle to load shifts and transfers for trailers, we serve all kinds of drivers. Our powerful winch can even provide off-road recovery for both light and heavy-duty vehicles. We also have wreckers for low clearance areas as well as Landoll trailers and lowboys to haul equipment like bulldozers, excavators, or tour buses. Prices vary depending on your needs, so get in touch with us for details.


The Resource Shadow shows -- Juvenile literature.
2 Items that share the Concept Shadow shows -- Juvenile literature.
Context of Shadow shows -- Juvenile literature.
Data Citation of the Concept Shadow shows -- Juvenile literature.


text:
Sprengbojen sind minenähnliche Schwimmkörper mit einer kleinen Sprengladung, die in Feldern von Ankertauminen zwischen diesen ausgelegt werden, um Minenräumversuche des Gegners zu erschweren. Ihr Zweck ist es, das gegnerische Räumgeschirr durch Sprengung zu zerstören. Sie gehören mit Reißbojen zu den sogenannten Sperrschutzmitteln bzw. Minenfeldschutzmitteln.

Die deutsche Kriegsmarine setzte im Zweiten Weltkrieg vornehmlich die beiden Typen "Sprengboje C" (SprBC) und "Sprengboje D" (SprBD) ein, die sich nur unwesentlich voneinander unterschieden. Es handelte sich dabei um eine aus 2 mm dickem Stahlblech gefertigte, etwa 25 kg schwere und 90 cm hohe Spitzboje (konisches Oberteil, Halbkugel-Unterteil) mit maximal 34 cm Durchmesser. Das obere Drittel ragte aus dem Wasser, wenn das maximal 100 m lange Ankertau nicht auf die entsprechende Wassertiefe eingestellt war. An der Spitze der Boje befand sich ein Griffring zum Verladen und Verstauen der Boje. In einer Schraube darunter endete der durch die gesamte Boje reichende Sicherungsstab des unten an der Sprengladung befindlichen Schlagbolzenanzünders. Im unteren Drittel der Boje, in der Halbkugel, befand sich die Sprengladung von 800 g in einer Schubhülse, einem Hohlzylinder, der nur durch einen sehr dünnen Scherstift festgehalten wurde. Wenn beim Räumversuch die Räumtrosse am Ankertau der Sprengboje nach oben glitt, drückte sie schließlich von unten gegen die Schubhülse, wobei der Scherstift abgebrochen wurde. Die Bewegung der dadurch freigewordenen Schubhülse löste den Schlagbolzenanzünder aus, der die Sprengladung zum Detonieren brachte und dabei mit der Boje auch die Räumleine zerstörte.

Literatur
  Military Arms Research Service: German Underwater Ordnance: Mines. Bureau of Ordnance Publication OP 1673A, Navy Department, Washington, DC, 24 June 1946, S. 100–102; (auch bei: )
 Karl von Kutzleben, Wilhelm Schroeder, Jochen Brennecke: Minenschiffe 1939–1945. Die geheimnisumwitterten Einsätze des "Mitternachtsgeschwaders". Köhler, Herford 1974, ISBN 3-7822-0098-5, S. 25–27
 Technische Dienstvorschrift TDv 1351/001-15.- Mine, Unterwasser, DM 21 (Sprengboje), Technische Dienstvorschriften und Handbücher der Bundeswehr

Weblinks
 Sprengboje D

Minenkriegsführung (See)
Seemine

redpajama_set_name: RedPajamaWikipedia


text:
var spawn = require('child_process').spawn;
var duplexer = require('duplexer2');

module.exports = function (counter) {
    var ps = spawn(cmd, args);
    return duplexer(ps.stdin, ps.stdout);
};

// TODO
// Fix solution with duplexer. Maybe wrong version based on the github issues comment
// https://github.com/substack/stream-adventure/issues/155
// TAP version 13
// # (anonymous)
// ok 1 stream-adventure verify YOURFILE.js
// ok 2 solution exports a function
// not ok 3 should be equal
//   ---
//     operator: equal
//     expected:
//       'bake\nbequeath\nbiscuit\nbat\nbat\nboolean\nballoon\nbiscuit\nbite\nbite\nbeetle\nballoon\nbat\nbeet'
//     actual:
//       'bake\nbequeath'
//     at: ConcatStream.<anonymous> (/Users/jose/.nvm/versions/v4.0.0/lib/node_modules/stream-adventure/node_modules/concat-stream/index.js:36:43)
//   ...

// 1..3
// # tests 3
// # pass  2
// # fail  1

// #########################################
// ###   YOUR SOLUTION IS NOT CORRECT!   ###
// #########################################

redpajama_set_name: RedPajamaGithub


Get hold of the very best Spacial coupon codes plus promotions. Snap up our Spacial deals before they expire. Benefit from our in depth Spacial discount voucher collection.
Enter your email below and we will send you the latest and greatest Spacial discounts.
Just click on the button underneath the offer that you want to use. You are going to then be directed to the Spacial web site, and a new window will open showing the discount code. To see the discount coupon code, simply look at the new window. Here it's possible to copy the promo code to enable you to return to the Spacial web-site and paste the promo code into the applicable box during the check-out process. Then it's just a case of simply clicking on a button to apply the discount and you should immediately discover the markdown given to the transaction. That is certainly all there is to it!
Please be sure to paste all Coupons exactly as they appear considering that extra spaces & capital letters could cause the Coupon Codes to not fuction.
Software copyright infringement is against the law. SoftwareCoupons.com will not distribute Spacial key, Spacial crack, serial number generators, hacked downloads or Spacial cracked versions. Our site will only offer Spacial promotional codes that are genuine and authorised by Spacial.
SoftwareCoupons.com is definitely the most important provider of software discounts & deals. Make sure you take a second to signup for our free software news letter and get instant access to free software, priority software coupon codes and special deals.


text:
Q: How to install UpSetPlot on google colab I am using google colab for python programming.
however, the package UpSetPlot was not installed. I tried using the command:
!pip install UpSetPlot

but the following error appears:
Collecting UpSetPlot
  Using cached https://files.pythonhosted.org/packages/a7/11/5cc8a0ebaf4f3a9a8e02cd3a9a13806eaebfc1d2ffb4a40031bdc83ad1be/UpSetPlot-0.5.0.tar.gz
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

A: There seems to be a problem in versions after 0.4.1 of upsetplot which may be related to the version of Python that is used in Colab.
Try this in a Colab cell.
!pip install upsetplot==0.4.1

redpajama_set_name: RedPajamaStackExchange


Members of the Odisha Union of Journalists (OUJ) from Balangir, Subarnapur nd Kalahandi and others districts led by its president Prasanna Mohanty, National Union of Journalist(NUJ) vice president Shankar Prasad Mishra and others on Thursday staged dharna before the collectorate here demanding fulfillment of a 12 -point charter of demands.
The demands include enactment of Journalist Protection Act, completion of identification of scribe within a stipulated time, insurance cover for scribe, medi claim, hike in corpus fund announced by the CM, pension facility after retirement, residential facility, decentralisation of accreditation process, formation of an Accreditation and Welfare Committee, Press Academy and travel facility for journalist.
The scribes were supported by local trade unions and citizens of Balangir. Later, they submitted a memorandum to CM Naveen Patnaik through the district administration.


Don't miss a single meeting, message, or contact. Now, with push-based email, appointments, and contacts from Outlook.com, and Hotmail, you're alerted to real-time information the moment it arrives.
Using the navigation bar speeds up communication. Open your email, calendar, contacts, and tasks fast. Everything you need is there.
Get the very latest updates automatically from people in the social networks you rely on most—LinkedIn, Facebook, and others. When something's posted, you'll know.
Check your schedule, an appointment, a task, or details about someone you're emailing—without having to rearrange windows or lose your train of thought.
Sort multiple contacts into a single view with all their contact information, including social network updates. You'll see social context quickly and remove needless duplication.
When others can see your calendar, scheduling meetings and responding to meeting invitations are easier and more convenient for everyone.
Improved search lets you find email messages, attachments, calendar appointments, and contacts even faster. So you can communicate with the right people, right now.
Discover how filters and context commands speed things up. With a single click, instantly see what's on your calendar today, next week, or next month. And you have several intuitive ways to filter, arrange, and work with your email.
Check the forecast on the Weather Bar and let the coming weather inform how you plan your day's schedule or your next trip.