text:
use IO::Socket;

$ipaddr = $ARGV[0];
print "LocalHost Adresse: $ipaddr\n";

while(1)
{

	$socket = new IO::Socket::INET (
						LocalHost => $ipaddr,
						LocalPort => 5000,
						Proto => 'tcp',
						Listen => 5,
						Reuse => 1
					);

	die "Konnte keine Verbindung herstellen\n" unless $socket;

	print "TCP Server bereit und wartet auf einer verbingung beim Port 5000\n";

	$message_recieved='';
	$client_socket = '';
	$client_socket = $socket->accept();
	$peer_address = $client_socket->peerhost();
	$peer_port = $client_socket->peerport();
	print "Verbunden mit ( $peer_address , $peer_port )\n";

	$n=0;
	while (1)
	{
		$client_socket->recv($message_recieved,1024);
		$client_socket->send($message_recieved);
		if (($message_recieved eq '' and $n) or ($message_recieved eq 'q'))
		{
			print "Client hat ausgeschaltet!\n";
			close $socket;
			last;
		}
		print "Server hat folgendes Empfangen: $message_recieved\n";
		$n++;

	}
}


text:
The following instructions are provided for macOS and Ubuntu. Windows is not yet available.

**Note:** If you use IntelliJ or a similar IDE, you may want to follow the [MXNet-Scala on IntelliJ tutorial](../tutorials/scala/mxnet_scala_on_intellij.html) instead of these instructions.

## Maven

### Setup Instructions

**Step 1.** Install dependencies:

**macOS Steps**

```bash
brew update
brew tap caskroom/versions
brew cask install java8
brew install opencv
brew install maven
```

**Ubuntu Steps**

These scripts will install Maven and its dependencies.

```bash
wget https://raw.githubusercontent.com/apache/incubator-mxnet/master/ci/docker/install/ubuntu_core.sh
wget https://raw.githubusercontent.com/apache/incubator-mxnet/master/ci/docker/install/ubuntu_scala.sh
chmod +x ubuntu_core.sh
chmod +x ubuntu_scala.sh
sudo ./ubuntu_core.sh
sudo ./ubuntu_scala.sh
```

**Step 2.** Run the demo MXNet-Scala project.

Go to the [MXNet-Scala demo project's README](https://github.com/apache/incubator-mxnet/tree/master/scala-package/mxnet-demo) and follow the directions to test the MXNet-Scala package installation.

#### Maven Repository

Package information can be found in the Maven Repository:
https://mvnrepository.com/artifact/org.apache.mxnet

**Linux CPU**
```html
<!-- https://mvnrepository.com/artifact/org.apache.mxnet/mxnet-full_2.11-linux-x86_64-cpu -->
<dependency>
    <groupId>org.apache.mxnet</groupId>
    <artifactId>mxnet-full_2.11-linux-x86_64-cpu</artifactId>
</dependency>
```

**Linux GPU**
```html
<!-- https://mvnrepository.com/artifact/org.apache.mxnet/mxnet-full_2.11-linux-x86_64-gpu -->
<dependency>
    <groupId>org.apache.mxnet</groupId>
    <artifactId>mxnet-full_2.11-linux-x86_64-gpu</artifactId>
</dependency>
```

**macOS CPU**
```html
<!-- https://mvnrepository.com/artifact/org.apache.mxnet/mxnet-full_2.11-osx-x86_64-cpu -->
<dependency>
    <groupId>org.apache.mxnet</groupId>
    <artifactId>mxnet-full_2.11-osx-x86_64-cpu</artifactId>
</dependency>
```

**NOTE:** You may specify the version you wish to use by adding the version number to the `dependency` block. For example, to use v1.2.0 you would add `<version>1.2.0</version>`. Otherwise Maven will use the latest version available.

## Source

The previously mentioned setup with Maven is recommended. Otherwise, the following instructions for macOS, Ubuntu, and Windows are provided for reference only:

| OS | Step 1 | Step 2 |
|---|---|---|
|macOS | [Shared Library for macOS](http://mxnet.incubator.apache.org/install/osx_setup.html#build-the-shared-library) | [Scala Package for macOS](http://mxnet.incubator.apache.org/install/osx_setup.html#install-the-mxnet-package-for-scala) |
| Ubuntu | [Shared Library for Ubuntu](http://mxnet.incubator.apache.org/install/ubuntu_setup.html#installing-mxnet-on-ubuntu) | [Scala Package for Ubuntu](http://mxnet.incubator.apache.org/install/ubuntu_setup.html#install-the-mxnet-package-for-scala) |
| Windows | [Shared Library for Windows](http://mxnet.incubator.apache.org/install/windows_setup.html#build-the-shared-library) | Call for Contribution |

#### Build Scala from an Existing MXNet Installation
If you have already built MXNet **from source** and are looking to setup Scala from that point, you may simply run the following from the MXNet source root:

```
make scalapkg
make scalainstall
```

## Documentation

Scaladocs are generated as part of the docs build pipeline. You can find them published in the [Scala API](http://mxnet.incubator.apache.org/api/scala/index.html) section of the website or by going to the [scaladocs output](https://mxnet.incubator.apache.org/api/scala/docs/index.html#org.apache.mxnet.package) directly.

To build the docs yourself, follow the [developer build docs instructions](https://github.com/apache/incubator-mxnet/tree/master/docs/build_version_doc#developer-instructions).

## Resources

* [Scala API](http://mxnet.incubator.apache.org/api/scala/index.html)
* [scaladocs](https://mxnet.incubator.apache.org/api/scala/docs/index.html#org.apache.mxnet.package)
* [MXNet-Scala Tutorials](../tutorials/scala)

redpajama_set_name: RedPajamaGithub


text:
// *****************************************************************************
//
//  © Component Factory Pty Ltd 2012. All rights reserved.
//	The software and associated documentation supplied hereunder are the
//  proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy,
//  Seaford, Vic 3198, Australia and are supplied subject to licence terms.
//
//  Version 4.4.1.0 	www.ComponentFactory.com
// *****************************************************************************

using System;
using System.Text;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections.Generic;

namespace ComponentFactory.Krypton.Toolkit
{
	/// <summary>
	/// Storage for palette input control states.
	/// </summary>
    public class KryptonPaletteInputControl : Storage
    {
        #region Instance Fields
        internal PaletteTripleRedirect _stateCommon;
        internal PaletteTriple _stateDisabled;
        internal PaletteTriple _stateNormal;
        internal PaletteTriple _stateActive;
        #endregion

        #region Identity
        /// <summary>
        /// Initialize a new instance of the KryptonPaletteInputControl class.
		/// </summary>
        /// <param name="redirect">Redirector to inherit values from.</param>
        /// <param name="backStyle">Background style.</param>
        /// <param name="borderStyle">Border style.</param>
        /// <param name="contentStyle">Content style.</param>
        /// <param name="needPaint">Delegate for notifying paint requests.</param>
        public KryptonPaletteInputControl(PaletteRedirect redirect,
                                          PaletteBackStyle backStyle,
                                          PaletteBorderStyle borderStyle,
                                          PaletteContentStyle contentStyle,
                                          NeedPaintHandler needPaint)
		{
            // Create the storage objects
            _stateCommon = new PaletteTripleRedirect(redirect, backStyle, borderStyle, contentStyle, needPaint);
            _stateDisabled = new PaletteTriple(_stateCommon, needPaint);
            _stateNormal = new PaletteTriple(_stateCommon, needPaint);
            _stateActive = new PaletteTriple(_stateCommon, needPaint);
        }
        #endregion

        #region SetRedirector
        /// <summary>
        /// Update the redirector with new reference.
        /// </summary>
        /// <param name="redirect">Target redirector.</param>
        public void SetRedirector(PaletteRedirect redirect)
        {
            _stateCommon.SetRedirector(redirect);
        }
        #endregion

        #region IsDefault
        /// <summary>
        /// Gets a value indicating if all values are default.
        /// </summary>
        [Browsable(false)]
        public override bool IsDefault
        {
            get
            {
                return _stateCommon.IsDefault &&
                       _stateDisabled.IsDefault &&
                       _stateNormal.IsDefault &&
                       _stateActive.IsDefault;
            }
        }
        #endregion

        #region PopulateFromBase
        /// <summary>
        /// Populate values from the base palette.
        /// </summary>
        public void PopulateFromBase()
        {
            // Populate only the designated styles
            _stateDisabled.PopulateFromBase(PaletteState.Disabled);
            _stateNormal.PopulateFromBase(PaletteState.Normal);
            _stateActive.PopulateFromBase(PaletteState.Tracking);
        }
        #endregion

        #region StateCommon
        /// <summary>
        /// Gets access to the common input control appearance that other states can override.
        /// </summary>
        [KryptonPersist]
        [Category("Visuals")]
        [Description("Overrides for defining common input control appearance that other states can override.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public PaletteTripleRedirect StateCommon
        {
            get { return _stateCommon; }
        }

        private bool ShouldSerializeStateCommon()
        {
            return !_stateCommon.IsDefault;
        }
        #endregion

        #region StateDisabled
        /// <summary>
        /// Gets access to the disabled input control appearance entries.
        /// </summary>
        [KryptonPersist]
        [Category("Visuals")]
        [Description("Overrides for defining disabled input control appearance.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public PaletteTriple StateDisabled
        {
            get { return _stateDisabled; }
        }

        private bool ShouldSerializeStateDisabled()
        {
            return !_stateDisabled.IsDefault;
        }
        #endregion

        #region StateNormal
        /// <summary>
        /// Gets access to the normal input control appearance entries.
        /// </summary>
        [KryptonPersist]
        [Category("Visuals")]
        [Description("Overrides for defining normal input control appearance.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public PaletteTriple StateNormal
        {
            get { return _stateNormal; }
        }

        private bool ShouldSerializeStateNormal()
        {
            return !_stateNormal.IsDefault;
        }
        #endregion

        #region StateActive
        /// <summary>
        /// Gets access to the active input control appearance entries.
        /// </summary>
        [KryptonPersist]
        [Category("Visuals")]
        [Description("Overrides for defining active input control appearance.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public PaletteTriple StateActive
        {
            get { return _stateActive; }
        }

        private bool ShouldSerializeStateActive()
        {
            return !_stateActive.IsDefault;
        }
        #endregion
    }
}


text:
describe('deployment-info tests', function(){
    var should = require('should');

    it('should register the routes', function(){
        var p = require('../index.js'),
            r = [],
            plugin = {
              route: function(route) {
                  if(Array.isArray(route)){
                      route.forEach(function(ro){ r.push(ro); });
                  } else { r.push(route); }
              },
              log: function(){}
            };

        p.register(plugin, {}, function(){});
        r.length.should.eql(2);

        r[0].path.should.eql('/server');
        r[1].path.should.eql('/deployment-info');
    });
});


text:
package org.apache.camel.impl;

import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.spi.EndpointRegistry;
import org.apache.camel.util.CamelContextHelper;
import org.apache.camel.util.CompoundIterator;
import org.apache.camel.util.LRUCache;
import org.apache.camel.util.LRUCacheFactory;
import org.apache.camel.util.ServiceHelper;

/**
 * Default implementation of {@link org.apache.camel.spi.EndpointRegistry}
 */
public class DefaultEndpointRegistry extends AbstractMap<EndpointKey, Endpoint> implements EndpointRegistry<EndpointKey> {
    private static final long serialVersionUID = 1L;
    private Map<EndpointKey, Endpoint> dynamicMap;
    private Map<EndpointKey, Endpoint> staticMap;
    private final CamelContext context;
    private int maxCacheSize;

    public DefaultEndpointRegistry(CamelContext context) {
        this.maxCacheSize = CamelContextHelper.getMaximumEndpointCacheSize(context);
        // do not stop on eviction, as the validator may still be in use
        this.dynamicMap = LRUCacheFactory.newLRUCache(maxCacheSize, maxCacheSize, false);
        // static map to hold endpoints we do not want to be evicted
        this.staticMap = new ConcurrentHashMap<>();
        this.context = context;
    }

    public DefaultEndpointRegistry(CamelContext context, Map<EndpointKey, Endpoint> endpoints) {
        this(context);
        putAll(endpoints);
    }

    @Override
    public void start() throws Exception {
        if (dynamicMap instanceof LRUCache) {
            ((LRUCache) dynamicMap).resetStatistics();
        }
    }

    @Override
    public Endpoint get(Object o) {
        // try static map first
        Endpoint answer = staticMap.get(o);
        if (answer == null) {
            answer = dynamicMap.get(o);
            if (answer != null && (context.isSetupRoutes() || context.isStartingRoutes())) {
                dynamicMap.remove(o);
                staticMap.put((EndpointKey) o, answer);
            }
        }
        return answer;
    }

    @Override
    public Endpoint put(EndpointKey key, Endpoint endpoint) {
        // at first we must see if the key already exists and then replace it back, so it stays the same spot
        Endpoint answer = staticMap.remove(key);
        if (answer != null) {
            // replace existing
            staticMap.put(key, endpoint);
            return answer;
        }

        answer = dynamicMap.remove(key);
        if (answer != null) {
            // replace existing
            dynamicMap.put(key, endpoint);
            return answer;
        }

        // we want endpoints to be static if they are part of setting up or starting routes
        if (context.isSetupRoutes() || context.isStartingRoutes()) {
            answer = staticMap.put(key, endpoint);
        } else {
            answer = dynamicMap.put(key, endpoint);
        }

        return answer;
    }

    @Override
    public boolean containsKey(Object o) {
        return staticMap.containsKey(o) || dynamicMap.containsKey(o);
    }

    @Override
    public boolean containsValue(Object o) {
        return staticMap.containsValue(o) || dynamicMap.containsValue(o);
    }

    @Override
    public int size() {
        return staticMap.size() + dynamicMap.size();
    }

    public int staticSize() {
        return staticMap.size();
    }

    @Override
    public int dynamicSize() {
        return dynamicMap.size();
    }

    @Override
    public boolean isEmpty() {
        return staticMap.isEmpty() && dynamicMap.isEmpty();
    }

    @Override
    public Endpoint remove(Object o) {
        Endpoint answer = staticMap.remove(o);
        if (answer == null) {
            answer = dynamicMap.remove(o);
        }
        return answer;
    }

    @Override
    public void clear() {
        staticMap.clear();
        dynamicMap.clear();
    }

    @Override
    public Set<Entry<EndpointKey, Endpoint>> entrySet() {
        return new AbstractSet<Entry<EndpointKey, Endpoint>>() {
            @Override
            public Iterator<Entry<EndpointKey, Endpoint>> iterator() {
                return new CompoundIterator<>(Arrays.asList(
                        staticMap.entrySet().iterator(), dynamicMap.entrySet().iterator()
                ));
            }

            @Override
            public int size() {
                return staticMap.size() + dynamicMap.size();
            }
        };
    }

    @Override
    public int getMaximumCacheSize() {
        return maxCacheSize;
    }

    /**
     * Purges the cache
     */
    @Override
    public void purge() {
        // only purge the dynamic part
        dynamicMap.clear();
    }

    @Override
    public void cleanUp() {
        if (dynamicMap instanceof LRUCache) {
            ((LRUCache) dynamicMap).cleanUp();
        }
    }

    @Override
    public boolean isStatic(String key) {
        return staticMap.containsKey(new EndpointKey(key));
    }

    @Override
    public boolean isDynamic(String key) {
        return dynamicMap.containsKey(new EndpointKey(key));
    }

    @Override
    public void stop() throws Exception {
        ServiceHelper.stopServices(staticMap.values());
        ServiceHelper.stopServices(values());
        purge();
    }

    @Override
    public String toString() {
        return "EndpointRegistry for " + context.getName() + ", capacity: " + maxCacheSize;
    }
}


text:
package de.craftolution.craftoplugin.module.vote.reward;

import de.craftolution.craftoplugin.module.vote.record.VoteRecord;
import de.craftolution.craftoplugin.service.module.Component;
import org.bukkit.entity.Player;

import java.util.*;

public class UnrewardedVoteCache extends Component {

	Map<UUID, List<VoteRecord>> uuidMap = new HashMap<>();
	Map<String, List<VoteRecord>> nameMap = new HashMap<>();

	void insert(VoteRecord record) {
		if (record.getPlayer().isPresent()) {
			UUID uuid = record.getPlayer().get().getUniqueId();

			if (!uuidMap.containsKey(uuid)) {
				uuidMap.put(uuid, new ArrayList<>());
			}

			uuidMap.get(uuid).add(record);
		}
		else {
			String name = record.getUserName().toLowerCase();

			if (!nameMap.containsKey(name)) {
				nameMap.put(name, new ArrayList<>());
			}

			nameMap.get(name).add(record);
		}
	}

	List<VoteRecord> getUnrewardedVotes(Player player) {
		final UUID playerId = player.getUniqueId();
		final String name = player.getName().toLowerCase();

		if (!uuidMap.containsKey(playerId) && !nameMap.containsKey(name)) {
			return Collections.emptyList();
		}

		List<VoteRecord> list = new ArrayList<>();

		// Check uuid map
		List<VoteRecord> uuidVotes = uuidMap.get(playerId);
		if (uuidVotes != null && !uuidVotes.isEmpty()) {
			Iterator<VoteRecord> iterator = uuidVotes.iterator();

			while (iterator.hasNext()) {
				VoteRecord vote = iterator.next();
				if (vote.isRewarded()) { iterator.remove(); continue; } // Skip!

				list.add(vote);
			}
		}

		// Check name map
		List<VoteRecord> nameVotes = nameMap.get(name);
		if (nameVotes != null && !nameVotes.isEmpty()) {
			Iterator<VoteRecord> iterator = nameVotes.iterator();

			while (iterator.hasNext()) {
				VoteRecord vote = iterator.next();
				if (vote.isRewarded()) { iterator.remove(); continue; } // Skip!

				list.add(vote);
			}
		}

		// Remove from cache if list is empty
		if (uuidVotes != null && uuidVotes.isEmpty()) { uuidMap.remove(playerId); }
		if (nameVotes != null && nameVotes.isEmpty()) { nameMap.remove(name); }

		return list;
	}

	void remove(VoteRecord record) {
		if (record.getPlayer().isPresent()) {
			UUID uuid = record.getPlayer().get().getUniqueId();

			if (uuidMap.containsKey(uuid)) {
				uuidMap.get(uuid).remove(record);
			}
		}
		else {
			String name = record.getUserName().toLowerCase();

			if (nameMap.containsKey(name)) {
				nameMap.get(name).remove(record);
			}
		}
	}

	@Override
	protected void onDisable() {
		nameMap.clear();
		uuidMap.clear();
	}

}


text:
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.

using System;

namespace DotSpatial.Controls.Docking
{
    /// <summary>
    /// The active panel changed event args.
    /// </summary>
    public class DockablePanelEventArgs : EventArgs
    {
        #region  Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="DockablePanelEventArgs"/> class.
        /// </summary>
        /// <param name="activePanelKey">The active Panel Key.</param>
        public DockablePanelEventArgs(string activePanelKey)
        {
            ActivePanelKey = activePanelKey;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the active panel key.
        /// </summary>
        /// <value>The active panel key.</value>
        public string ActivePanelKey { get; set; }

        #endregion
    }
}


text:
package org.apache.bigtop.datagenerators.bigpetstore.generators.products.rules;

import org.apache.bigtop.datagenerators.bigpetstore.generators.products.rules.AlwaysTrueRule;
import org.apache.bigtop.datagenerators.bigpetstore.generators.products.rules.Rule;
import org.junit.Assert;
import org.junit.Test;

public class TestAlwaysTrueRule
{

	@Test
	public void testRuleMatches()
	{
		Rule rule = new AlwaysTrueRule();
		Assert.assertTrue(rule.ruleMatches(null));
	}
}


text:
@interface DVTTextStorage (PLYHighlightingHook)

- (NSColor *)ply_colorAtCharacterIndex:(unsigned long long)index
                        effectiveRange:(NSRangePointer)effectiveRange
                               context:(id)context;

@end


text:
layout: default
---

Acerca De

Este es el Portafolio del Equipo Número 2; para la asignatura de Sistemas Empotrados y Computación ubicua. En este portafolio, encontrará información acerca del equipo y de cada una de las actividades realizadas en esta asignatura.

Integrantes del Grupo:

Victor Suarez Garcia

Francisco Javier Rosales

Rocio Sanchez


text:
namespace ash {

// Do not add constant colors in this file. Get the colors from AshColorProvider
// instead.

// The size delta between the default font and the font size found in tray
// items like labels and buttons.
extern const int kTrayTextFontSizeIncrease;

ASH_EXPORT extern const int kTrayItemSize;

extern const float kTrayItemCornerRadius;

// Extra padding used beside a single icon in the tray area of the shelf.
constexpr int kTrayImageItemPadding = 3;

// The width of the tray menu.
constexpr int kTrayMenuWidth = 360;

extern const int kTrayPopupAutoCloseDelayInSeconds;
extern const int kTrayPopupAutoCloseDelayInSecondsWithSpokenFeedback;
extern const int kTrayPopupPaddingHorizontal;
extern const int kTrayPopupButtonEndMargin;

// The padding used on the left and right of labels. This applies to all labels
// in the system menu.
extern const int kTrayPopupLabelHorizontalPadding;

// The horizontal padding used to properly lay out a slider in a TriView
// container with a FillLayout (such as a volume notification bubble).
extern const int kTrayPopupSliderHorizontalPadding;

// The minimum/default height of the rows in the system tray menu.
extern const int kTrayPopupItemMinHeight;

// The width used for the first region of the row (which holds an image).
extern const int kTrayPopupItemMinStartWidth;

// The width used for the end region of the row (usually a more arrow).
extern const int kTrayPopupItemMinEndWidth;

// Padding used on right side of labels to keep minimum distance to the next
// item. This applies to all labels in the system menu.
extern const int kTrayPopupLabelRightPadding;

// The width of ToggleButton views including any border padding.
extern const int kTrayToggleButtonWidth;

// Constants for the title row.
constexpr int kTitleRowProgressBarHeight = 2;

// Width of lines used to separate menu items (e.g. input method menu).
constexpr int kMenuSeparatorWidth = 1;

// Width of lines used to separate sections of the system tray, for instance
// in tray detailed views.
constexpr int kTraySeparatorWidth = 0;

// The size of the icons appearing in the material design system tray.
constexpr int kTrayIconSize = 16;

// The padding on top of the time tray icon when vertically aligned.
constexpr int kTrayTimeIconTopPadding = 2;

// The padding around network tray icon in dip.
constexpr int kTrayNetworkIconPadding = 2;
constexpr int kUnifiedTrayNetworkIconPadding = 4;

// The size of the icons appearing in the material design system menu.
extern const int kMenuIconSize;
// The size of buttons in the system menu.
ASH_EXPORT extern const int kMenuButtonSize;
// The vertical padding for the system menu separator.
extern const int kMenuSeparatorVerticalPadding;
// The horizontal padding for the system menu separator.
extern const int kMenuExtraMarginFromLeftEdge;
// The visual padding to the left of icons in the system menu.
extern const int kMenuEdgeEffectivePadding;

// The inset applied to clickable surfaces in the system menu that do not have
// the ink drop filling the entire bounds.
extern const int kTrayPopupInkDropInset;

// The radius used to draw the corners of the rounded rect style ink drops.
extern const int kTrayPopupInkDropCornerRadius;

// Threshold to ignore update on the slider value.
constexpr float kAudioSliderIgnoreUpdateThreshold = 0.01;

// Duration for the collapse / expand animation in ms.
constexpr int kSystemMenuCollapseExpandAnimationDurationMs = 500;

constexpr gfx::Insets kUnifiedMenuItemPadding(0, 16, 16, 16);
constexpr gfx::Insets kUnifiedSystemInfoViewPadding(0, 16, 16, 16);
constexpr gfx::Insets kUnifiedManagedDeviceViewPadding(0, 16, 11, 16);
constexpr gfx::Insets kUnifiedSliderRowPadding(0, 12, 8, 16);
constexpr gfx::Insets kUnifiedSliderBubblePadding(12, 0, 4, 0);
constexpr gfx::Insets kUnifiedSliderPadding(0, 16);
constexpr gfx::Insets kMicGainSliderViewPadding(0, 52, 8, 0);
constexpr gfx::Insets kMicGainSliderPadding(0, 8, 0, 48);
constexpr int kMicGainSliderViewSpacing = 8;

constexpr int kTrayRadioButtonInterSpacing = 20;
constexpr gfx::Insets kTrayRadioButtonPadding(16, 20, 0, 0);
constexpr gfx::Insets kTraySubLabelPadding(4, 56, 16, 16);

constexpr int kMessageCenterCollapseThreshold = 175;
constexpr int kStackedNotificationBarHeight = 32;
constexpr int kStackedNotificationBarCollapsedHeight = 40;
constexpr int kNotificationIconStackThreshold = 28;
constexpr int kUnifiedSliderViewSpacing = 12;
constexpr int kUnifiedMessageCenterBubbleSpacing = 8;
constexpr int kUnifiedNotificationCenterSpacing = 16;
constexpr int kUnifiedTrayBatteryIconSize = 20;
constexpr int kUnifiedTrayIconSize = 18;
constexpr int kUnifiedTraySubIconSize = 15;
constexpr int kUnifiedTrayTextTopPadding = 1;
constexpr int kUnifiedTrayTextRightPadding = 1;
constexpr int kUnifiedTrayTimeLeftPadding = 1;
constexpr int kUnifiedTraySpacingBetweenIcons = 6;
constexpr int kUnifiedTrayBatteryWidth = 12;
constexpr int kUnifiedTrayBatteryBottomPadding = 1;
constexpr int kUnifiedTrayContentPadding = 12;
constexpr int kUnifiedTopShortcutSpacing = 16;
constexpr int kUnifiedNotificationHiddenLineHeight = 20;
constexpr int kUnifiedTopShortcutContainerTopPadding = 12;
constexpr int kUnifiedNotificationMinimumHeight = 40;
constexpr int kUnifiedBackButtonLeftPadding = 16;
constexpr gfx::Insets kUnifiedTopShortcutPadding(0, 16);
constexpr gfx::Insets kUnifiedNotificationHiddenPadding(6, 16);
constexpr gfx::Insets kUnifiedCircularButtonFocusPadding(4);
constexpr gfx::Insets kTrayBackgroundFocusPadding(1);

// Size of an icon drawn inside top shortcut buttons.
// A dark disc with |kTrayItemSize| diameter is drawn in the background.
constexpr int kTrayTopShortcutButtonIconSize = 20;

constexpr int kUnifiedManagedDeviceSpacing = 8;
constexpr int kUnifiedSystemInfoHeight = 16;
constexpr int kUnifiedSystemInfoSpacing = 8;
constexpr gfx::Insets kUnifiedSystemInfoDateViewPadding(3);

// Constants used in StackedNotificationBar located on top of the message
// center.
constexpr gfx::Insets kStackedNotificationIconsContainerPadding(1, 16, 0, 8);
constexpr int kStackedNotificationBarMaxIcons = 3;
constexpr int kStackedNotificationBarIconSpacing = 6;
constexpr int kStackedNotificationIconSize = 18;
constexpr int kNotificationIconAnimationLowPosition = 7;
constexpr int kNotificationIconAnimationHighPosition = -3;
constexpr double kNotificationIconAnimationScaleFactor = 0.77;
constexpr int kNotificationIconAnimationUpDurationMs = 50;
constexpr int kNotificationIconAnimationDownDurationMs = 17;
constexpr int kNotificationIconAnimationOutDurationMs = 67;
constexpr double kNotificationCenterDragExpandThreshold = 0.8;

// Constants used in FeaturePodsView of UnifiedSystemTray.
constexpr gfx::Size kUnifiedFeaturePodSize(112, 94);
constexpr gfx::Size kUnifiedFeaturePodCollapsedSize(46, 46);
constexpr gfx::Insets kUnifiedFeaturePodHoverPadding(2);
constexpr int kUnifiedFeaturePodVectorIconSize = 18;
constexpr int kUnifiedFeaturePodLabelWidth = 85;
constexpr int kUnifiedFeaturePodSpacing = 6;
constexpr int kUnifiedFeaturePodHoverCornerRadius = 4;
constexpr int kUnifiedFeaturePodVerticalPadding = 24;
constexpr int kUnifiedFeaturePodTopPadding = 20;
constexpr int kUnifiedFeaturePodBottomPadding = 0;
constexpr int kUnifiedFeaturePodHorizontalSidePadding = 12;
constexpr int kUnifiedFeaturePodHorizontalMiddlePadding = 0;
constexpr int kUnifiedFeaturePodCollapsedVerticalPadding = 12;
constexpr int kUnifiedFeaturePodCollapsedHorizontalPadding = 24;
constexpr int kUnifiedFeaturePodLabelLineHeight = 16;
constexpr int kUnifiedFeaturePodLabelMaxLines = 2;
constexpr int kUnifiedFeaturePodSubLabelLineHeight = 15;
constexpr int kUnifiedFeaturePodLabelFontSize = 13;
constexpr int kUnifiedFeaturePodSubLabelFontSize = 12;
constexpr int kUnifiedFeaturePodInterLabelPadding = 2;
constexpr int kUnifiedFeaturePodArrowSpacing = 4;
constexpr int kUnifiedFeaturePodMinimumHorizontalMargin = 4;
constexpr int kUnifiedFeaturePodItemsInRow = 3;
constexpr int kUnifiedFeaturePodMaxRows = 3;
constexpr int kUnifiedFeaturePodMinRows = 1;
constexpr int kUnifiedFeaturePodMaxItemsInCollapsed = 5;
constexpr int kUnifiedFeaturePodsPageSpacing = 48;
constexpr int kUnifiedNotificationSeparatorThickness = 1;
constexpr int kPageIndicatorViewMaxHeight = 20;

// Constants used in system tray page transition animations.
constexpr double kCollapseThreshold = 0.3;

// Separators between multiple users are shorter than the full width.
constexpr int kUnifiedUserChooserSeparatorSideMargin = 64;
// Additional gap above and below the longer separator between user list and
// "Sign in another user..." button.
constexpr int kUnifiedUserChooserLargeSeparatorVerticalSpacing = 8;

constexpr int kUnifiedUserChooserRowHeight = 64;

// Gap between the buttons on the top shortcut row, other than the
// expand/collapse button.
constexpr int kUnifiedTopShortcutButtonDefaultSpacing = 16;
constexpr int kUnifiedTopShortcutButtonMinSpacing = 4;

// Constants used in the detailed view in UnifiedSystemTray.
constexpr gfx::Insets kUnifiedDetailedViewPadding(0, 0, 8, 0);
constexpr gfx::Insets kUnifiedDetailedViewTitlePadding(0, 0, 0, 16);
constexpr int kUnifiedDetailedViewTitleRowHeight = 64;

// Constants used for the status area overflow button and state.
constexpr gfx::Size kStatusAreaOverflowButtonSize(28, 32);
constexpr int kStatusAreaLeftPaddingForOverflow = 100;
constexpr int kStatusAreaForceCollapseAvailableWidth = 200;
constexpr int kStatusAreaOverflowGradientSize = 24;

// Height compensations in tablet mode based on whether the hotseat is shown.
constexpr int kTrayBubbleInsetTabletModeCompensation = 8;
constexpr int kTrayBubbleInsetHotseatCompensation = 16;

// Constants used for the privacy screen toast.
constexpr int kPrivacyScreenToastMinWidth = 256;
constexpr int kPrivacyScreenToastMaxWidth = 512;
constexpr int kPrivacyScreenToastHeight = 64;
constexpr int kPrivacyScreenToastMainLabelFontSize = 14;
constexpr int kPrivacyScreenToastSubLabelFontSize = 13;
constexpr gfx::Insets kPrivacyScreenToastInsets(10, 16);
constexpr int kPrivacyScreenToastSpacing = 16;

// Constants used for media tray.
constexpr int kMediaTrayPadding = 8;

// There is no active user session during oobe, which means it doesn't support
// dark mode. Sets the icon color to be constant.
constexpr SkColor kIconColorInOobe = gfx::kGoogleGrey700;

}  // namespace ash

#endif  // ASH_SYSTEM_TRAY_TRAY_CONSTANTS_H_


text:
title: FAQs of sorts
date: '2015-01-11 00:00:00'
categories:
- blog
layout: post
slug: AMA
tags: []
draft: false

---
Well... that went well. The AMA's we put on [/r/IAmA](http://www.reddit.com/r/IAmA/comments/2rjy47/iama_new_business_opening_today_by_redditors_for/) and [/r/CasualIAMA](http://www.reddit.com/r/casualiama/comments/2rkwgq/we_are_a_business_opening_today_by_redditors_for/) both went well. Here's some of our favorite questions (and their answers) in order of date.

***

**So you make animations? Do I have to pay to get an animation? Or do you just make one?**

 -- [davidcarpenter122333](http://www.reddit.com/user/davidcarpenter122333)

> We are charging a flexible rate for each gif depending on complexity of the animation.

**Do you have any interesting stories you can tell us about getting this all put together?**

-- [sync95](http://www.reddit.com/user/Sync95)

> So we were together in a hotel once and everyone is bored. We decide to play a game called "What sounds most like it would be porn" with the TV guide. We find a good and turn it on. Turns out porn wasn't removed from the selections. Austin, instead of turning off that channel starts playing "smooth jazz" from his phone. Most awkward moment of my life.

**Do you have any examples of your work? Have any of your animations ever made the front page?**

-- [squeel](http://www.reddit.com/user/squeel)

> We haven't submitted any animations to reddit yet but examples can be seen at our [demo page](http://www.mixedmediastudios.org/demo.html)


text:
        Name
        Description
        Start Date
        End Date
        Project Assigned To

        {{project.name}}
        {{project.desc}}
        {{project.startdate}}
        {{project.enddate}}
        {{project.assignedto}}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "ncacn_http.h"

#include <winpr/crt.h>
#include <winpr/tchar.h>
#include <winpr/stream.h>
#include <winpr/dsparse.h>
#include <winpr/winhttp.h>

#include <openssl/rand.h>

#define TAG FREERDP_TAG("core.gateway.ntlm")

wStream* rpc_ntlm_http_request(rdpRpc* rpc, HttpContext* http, const char* method, int contentLength, SecBuffer* ntlmToken)
{
	wStream* s;
	HttpRequest* request;
	char* base64NtlmToken = NULL;

	request = http_request_new();

	if (ntlmToken)
		base64NtlmToken = crypto_base64_encode(ntlmToken->pvBuffer, ntlmToken->cbBuffer);

	http_request_set_method(request, method);

	request->ContentLength = contentLength;
	http_request_set_uri(request, http->URI);

	if (base64NtlmToken)
	{
		http_request_set_auth_scheme(request, "NTLM");
		http_request_set_auth_param(request, base64NtlmToken);
	}

	s = http_request_write(http, request);
	http_request_free(request);

	free(base64NtlmToken);

	return s;
}

int rpc_ncacn_http_send_in_channel_request(rdpRpc* rpc, RpcInChannel* inChannel)
{
	wStream* s;
	int status;
	int contentLength;
	BOOL continueNeeded;
	rdpNtlm* ntlm = inChannel->ntlm;
	HttpContext* http = inChannel->http;

	continueNeeded = ntlm_authenticate(ntlm);

	contentLength = (continueNeeded) ? 0 : 0x40000000;

	s = rpc_ntlm_http_request(rpc, http, "RPC_IN_DATA", contentLength, &ntlm->outputBuffer[0]);

	if (!s)
		return -1;

	status = rpc_in_channel_write(inChannel, Stream_Buffer(s), Stream_Length(s));

	Stream_Free(s, TRUE);

	return (status > 0) ? 1 : -1;
}

int rpc_ncacn_http_recv_in_channel_response(rdpRpc* rpc, RpcInChannel* inChannel, HttpResponse* response)
{
	char* token64 = NULL;
	int ntlmTokenLength = 0;
	BYTE* ntlmTokenData = NULL;
	rdpNtlm* ntlm = inChannel->ntlm;

	if (ListDictionary_Contains(response->Authenticates, "NTLM"))
	{
		token64 = ListDictionary_GetItemValue(response->Authenticates, "NTLM");

		if (!token64)
			return -1;

		crypto_base64_decode(token64, strlen(token64), &ntlmTokenData, &ntlmTokenLength);
	}

	if (ntlmTokenData && ntlmTokenLength)
	{
		ntlm->inputBuffer[0].pvBuffer = ntlmTokenData;
		ntlm->inputBuffer[0].cbBuffer = ntlmTokenLength;
	}

	return 1;
}

int rpc_ncacn_http_ntlm_init(rdpRpc* rpc, RpcChannel* channel)
{
	rdpTls* tls = channel->tls;
	rdpNtlm* ntlm = channel->ntlm;
	rdpContext* context = rpc->context;
	rdpSettings* settings = rpc->settings;
	freerdp* instance = context->instance;

	if (!settings->GatewayPassword || !settings->GatewayUsername ||
			!strlen(settings->GatewayPassword) || !strlen(settings->GatewayUsername))
	{
		if (instance->GatewayAuthenticate)
		{
			BOOL proceed = instance->GatewayAuthenticate(instance, &settings->GatewayUsername,
						&settings->GatewayPassword, &settings->GatewayDomain);

			if (!proceed)
			{
				freerdp_set_last_error(context, FREERDP_ERROR_CONNECT_CANCELLED);
				return 0;
			}

			if (settings->GatewayUseSameCredentials)
			{
				if (settings->GatewayUsername)
				{
					free(settings->Username);
					if (!(settings->Username = _strdup(settings->GatewayUsername)))
						return -1;
				}
				if (settings->GatewayDomain)
				{
					free(settings->Domain);
					if (!(settings->Domain = _strdup(settings->GatewayDomain)))
						return -1;
				}
				if (settings->GatewayPassword)
				{
					free(settings->Password);
					if (!(settings->Password = _strdup(settings->GatewayPassword)))
						return -1;
				}
			}
		}
	}

	if (!ntlm_client_init(ntlm, TRUE, settings->GatewayUsername,
			settings->GatewayDomain, settings->GatewayPassword, tls->Bindings))
	{
		return 0;
	}

	if (!ntlm_client_make_spn(ntlm, _T("HTTP"), settings->GatewayHostname))
	{
		return 0;
	}

	return 1;
}

void rpc_ncacn_http_ntlm_uninit(rdpRpc* rpc, RpcChannel* channel)
{
	ntlm_client_uninit(channel->ntlm);
	ntlm_free(channel->ntlm);
	channel->ntlm = NULL;
}

int rpc_ncacn_http_send_out_channel_request(rdpRpc* rpc, RpcOutChannel* outChannel, BOOL replacement)
{
	wStream* s;
	int status;
	int contentLength;
	BOOL continueNeeded;
	rdpNtlm* ntlm = outChannel->ntlm;
	HttpContext* http = outChannel->http;

	continueNeeded = ntlm_authenticate(ntlm);

	if (!replacement)
		contentLength = (continueNeeded) ? 0 : 76;
	else
		contentLength = (continueNeeded) ? 0 : 120;

	s = rpc_ntlm_http_request(rpc, http, "RPC_OUT_DATA", contentLength, &ntlm->outputBuffer[0]);

	if (!s)
		return -1;

	status = rpc_out_channel_write(outChannel, Stream_Buffer(s), Stream_Length(s));

	Stream_Free(s, TRUE);

	return (status > 0) ? 1 : -1;
}

int rpc_ncacn_http_recv_out_channel_response(rdpRpc* rpc, RpcOutChannel* outChannel, HttpResponse* response)
{
	char* token64 = NULL;
	int ntlmTokenLength = 0;
	BYTE* ntlmTokenData = NULL;
	rdpNtlm* ntlm = outChannel->ntlm;

	if (ListDictionary_Contains(response->Authenticates, "NTLM"))
	{
		token64 = ListDictionary_GetItemValue(response->Authenticates, "NTLM");

		if (!token64)
			return -1;

		crypto_base64_decode(token64, strlen(token64), &ntlmTokenData, &ntlmTokenLength);
	}

	if (ntlmTokenData && ntlmTokenLength)
	{
		ntlm->inputBuffer[0].pvBuffer = ntlmTokenData;
		ntlm->inputBuffer[0].cbBuffer = ntlmTokenLength;
	}

	return 1;
}


text:
import pytest

from pillowtalk import PillowtalkError

def test_exception(mybase):

    class Person(mybase):
        FIELDS = ["id", "name"]

    with pytest.raises(PillowtalkError):
        Person.load({"id": 5, "name": "Opps"})


text:
package io.github.tailhq.dynaml.analysis

import breeze.linalg.DenseVector
import io.github.tailhq.dynaml.pipes.{DataPipe, MetaPipe, MetaPipe21}

/**
  *
(B)ASIC SPLINES

  *
  * B-Spline generator as described in
  * B(asic)-Spline Basics by Carl de Boor.
  *
  * Bi,k(t) :=
  * ωi,k(t) Bi,k-1(t) + (1 - ωi+1,k(t)) Bi+1,k-1
  * @author mandar date 28/06/2017.
  * */
abstract class BSplineGenerator extends MetaPipe21[Int, Int, Double, Double] {

  /**
    * The knot sequence, strictly non-decreasing
    * */
  val knot: (Int) => Double

  /**
    * ωi,k(t) := 0, if ti = ti+k-1
    *                          otherwise, (t - ti)/(ti+k-1 - ti)
    * */
  def omega(i: Int, k: Int)(x: Double): Double = {
    val (t_i, t_ik) = (knot(i), knot(i+k-1))
    if(t_i != t_ik) (x-t_i)/(t_ik-t_i) else 0d
  }

  protected def bsplinerec(x: Double, k: Int, i: Int, acc: Seq[Double]): Double = acc match {
    case Seq() => 1d
    case Seq(a) => a
    case _ => bsplinerec(
      x, k+1, i, acc.sliding(2).toSeq.zipWithIndex.map(couple => {
        val (accum, index) = couple
        val (first, second) = (accum.head, accum.last)
        omega(index+i, k+1)(x)*first + (1d - omega(index+i+1, k+1)(x))*second
      }))
  }

  override def run(segment: Int, order: Int) = DataPipe(
    (t: Double) => bsplinerec(
      t, 1, segment,
      Seq.tabulate[Double](order)(l =>
        if(t >= knot(segment+l) && t < knot(segment+l+1)) 1d
        else 0d)
    )
  )
}

/**
  * The [[BSplineGenerator]] companion object has convenience methods for
  * creating arbitrary b-spline generators from knot sequences.
  * */
object BSplineGenerator {

  /**
    * Create a b-spline generator from a supplied sequence of knots.
    * @param ks A sequence of knots
    * @param isSorted Set to true if the sequence is already sorted (defaults to false).
    * @return a [[BSplineGenerator]] instance.
    * */
  def apply(ks: Seq[Double], isSorted: Boolean = false): BSplineGenerator = {
    val sorted_knots = if (isSorted) ks else ks.sorted

    new BSplineGenerator {
      override val knot = (i: Int) => {
        if(i >= 0 && i < sorted_knots.length) sorted_knots(i)
        else if(i < 0) sorted_knots.head
        else sorted_knots.last
      }
    }
  }

  /**
    * Create a b-spline generator from a
    * bi-infinite sequence of knots (specified as a [[DataPipe]])
    *
    * @param knotFunction A [[DataPipe]] from [[Int]] to [[Double]] which outputs
    *                     the knot for any index.
    * @return a [[BSplineGenerator]] instance.
    * */
  def apply(knotFunction: DataPipe[Int, Double]): BSplineGenerator = new BSplineGenerator {
    override val knot = knotFunction.run _
  }

}

/**
  * Cardinal B-Splines have knots as the sequence of integers.
  * */
object CardinalBSplineGenerator extends BSplineGenerator {
  override val knot = (i: Int) => i.toDouble
}

/**
  * Bernstein B-Splines have knots as (...000111...)
  * */
object BernsteinSplineGenerator extends BSplineGenerator {
  override val knot = (i: Int) => if(i <= 0) 0d else 1d
}

/**
  *
Generalised Piecewise Polynomial Splines

  *
  * Represents linear combinations of b-splines.
  *
  * */
abstract class SplineGenerator extends MetaPipe[Int, Double, Double] {

  /**
    * Specifies which knots have non-zero weights
    * */
  val knot_indices: Array[Int]

  /**
    * Weights each basic spline
    * */
  val coefficients: DenseVector[Double]

  /**
    * Used to calculate the basic splines
    * */
  val bSplineGenerator: BSplineGenerator

  override def run(order: Int) = DataPipe((x: Double) => {
    val splines = DenseVector(knot_indices.map(i => bSplineGenerator(i, order)(x)))
    coefficients dot splines
  })
}

object SplineGenerator {

  /**
    * Creates a spline generator.
    * */
  def apply(
    generator: BSplineGenerator)(
    indices: Seq[Int], coeff: DenseVector[Double]) =
    new SplineGenerator {

      override val bSplineGenerator = generator

      override val knot_indices = indices.toArray

      override val coefficients = coeff
    }

  def apply(knots: Seq[Double], coefficients: DenseVector[Double]): SplineGenerator =
    apply(BSplineGenerator(knots))(knots.indices, coefficients)

}


text:
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
    'Home\Module'                        => __DIR__ . '/Module.php',
    'Home\Controller\IndexController' => __DIR__ . '/src/Home/Controller/IndexController.php',
    'HomeTest\Framework\TestCase'        => __DIR__ . '/tests/Home/Framework/TestCase.php',
    'HomeTest\SampleTest'                => __DIR__ . '/tests/Home/SampleTest.php',
);


text:
William.Test
============

Test


text:
module Faraday
  class Request
    # TokenAuthentication is a middleware that adds a 'Token' header to a
    # Faraday request.
    class TokenAuthentication < load_middleware(:authorization)
      # Public
      def self.header(token, options = nil)
        options ||= {}
        options[:token] = token
        super(:Token, options)
      end

      def initialize(app, token, options = nil)
        super(app, token, options)
      end
    end
  end
end


text:
package nl.esciencecenter.e3dchem.knime.plants.configure;

import static org.junit.Assert.*;
import static org.junit.Assume.assumeFalse;

import org.junit.BeforeClass;
import org.junit.Test;

import nl.esciencecenter.e3dchem.knime.plants.configure.ConfigureDialog;
import nl.esciencecenter.e3dchem.knime.plants.configure.ConfigureFactory;

public class ConfigureDialogTest {

    @BeforeClass
    public static void setUp() {
        assumeFalse("Does not work on Windows", System.getProperty("os.name").contains("Windows"));
    }

    @Test
	public void test() {
		ConfigureFactory factory = new ConfigureFactory();
		ConfigureDialog dialog = (ConfigureDialog) factory.createNodeDialogPane();

		int result = dialog.getPanel().getComponentCount();
		assertEquals(2, result);
	}
}


text:
import { WorkItemTemplateReference } from "TFS/WorkItemTracking/Contracts";

import Templates from "./templates";

export default class Tags {
    public static getTagsFromTemplate(templateRef: WorkItemTemplateReference) : string[] {
        let tags: string[] = [];

        let regex = new RegExp("\\[(.*?)\\]", "g");
        let matches: RegExpExecArray = null;

        while (matches = regex.exec(templateRef.description)) {
            if (matches.length >= 2) {
                tags.push(matches[1]);
            }
        }
        return tags;
    }

    public static async getAllTagsFromTemplates(): Promise<string[]> {
        let templateTags: string[] = [];

        let taskTemplateRefs = await Templates.getTaskTemplateReferences();

        taskTemplateRefs.forEach(templateRef => {
            let tags = Tags.getTagsFromTemplate(templateRef);
            tags.filter(tag => templateTags.indexOf(tag) === -1).forEach(tag => {
                templateTags.push(tag);
            });
        });

        return templateTags.sort();
    }

    public static containsTag(templateRef: WorkItemTemplateReference, tag: string): boolean {
        let itemTags = Tags.getTagsFromTemplate(templateRef);
        return itemTags.indexOf(tag) >= 0;
    }
}


text:
class CreateMobileCodes < ActiveRecord::Migration[5.0]
  def change
    create_table :mobile_codes do |t|
      t.string :mobile
      t.string :code, limit: 20
      t.string :message_type, limit: 20
      t.integer :failed_attempts
      t.string :ip, limit: 50

      t.timestamps
    end

    add_index :mobile_codes, :mobile
    add_index :mobile_codes, :message_type
    add_index :mobile_codes, :ip
  end
end


text:
package org.springframework.boot.autoconfigure.jms;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Configuration properties for JMS.
 *
 * @author Greg Turnquist
 * @author Phillip Webb
 * @author Stephane Nicoll
 */
@ConfigurationProperties(prefix = "spring.jms")
public class JmsProperties {

	/**
	 * Specify if the default destination type is topic.
	 */
	private boolean pubSubDomain = false;

	/**
	 * Connection factory JNDI name. When set, takes precedence to others connection
	 * factory auto-configurations.
	 */
	private String jndiName;

	private final Listener listener = new Listener();

	public boolean isPubSubDomain() {
		return this.pubSubDomain;
	}

	public void setPubSubDomain(boolean pubSubDomain) {
		this.pubSubDomain = pubSubDomain;
	}

	public String getJndiName() {
		return this.jndiName;
	}

	public void setJndiName(String jndiName) {
		this.jndiName = jndiName;
	}

	public Listener getListener() {
		return this.listener;
	}

	public static class Listener {

		/**
		 * Start the container automatically on startup.
		 */
		private boolean autoStartup = true;

		/**
		 * Acknowledge mode of the container. By default, the listener is transacted with
		 * automatic acknowledgment.
		 */
		private AcknowledgeMode acknowledgeMode;

		/**
		 * Minimum number of concurrent consumers.
		 */
		private Integer concurrency;

		/**
		 * Maximum number of concurrent consumers.
		 */
		private Integer maxConcurrency;

		public boolean isAutoStartup() {
			return this.autoStartup;
		}

		public void setAutoStartup(boolean autoStartup) {
			this.autoStartup = autoStartup;
		}

		public AcknowledgeMode getAcknowledgeMode() {
			return this.acknowledgeMode;
		}

		public void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) {
			this.acknowledgeMode = acknowledgeMode;
		}

		public Integer getConcurrency() {
			return this.concurrency;
		}

		public void setConcurrency(Integer concurrency) {
			this.concurrency = concurrency;
		}

		public Integer getMaxConcurrency() {
			return this.maxConcurrency;
		}

		public void setMaxConcurrency(Integer maxConcurrency) {
			this.maxConcurrency = maxConcurrency;
		}

		public String formatConcurrency() {
			if (this.concurrency == null) {
				return (this.maxConcurrency != null ? "1-" + this.maxConcurrency : null);
			}
			return (this.maxConcurrency != null
					? this.concurrency + "-" + this.maxConcurrency
					: String.valueOf(this.concurrency));
		}
	}

	/**
	 * Translate the acknowledge modes defined on the {@link javax.jms.Session}.
	 *
	 * <p>
	 * {@link javax.jms.Session#SESSION_TRANSACTED} is not defined as we take care of this
	 * already via a call to {@code setSessionTransacted}.
	 */
	public enum AcknowledgeMode {

		/**
		 * Messages sent or received from the session are automatically acknowledged. This
		 * is the simplest mode and enables once-only message delivery guarantee.
		 */
		AUTO(1),

		/**
		 * Messages are acknowledged once the message listener implementation has called
		 * {@link javax.jms.Message#acknowledge()}. This mode gives the application
		 * (rather than the JMS provider) complete control over message acknowledgement.
		 */
		CLIENT(2),

		/**
		 * Similar to auto acknowledgment except that said acknowledgment is lazy. As a
		 * consequence, the messages might be delivered more than once. This mode enables
		 * at-least-once message delivery guarantee.
		 */
		DUPS_OK(3);

		private final int mode;

		AcknowledgeMode(int mode) {
			this.mode = mode;
		}

		public int getMode() {
			return this.mode;
		}
	}

}


text:
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System;

namespace UIWidgets
{
	public class TreeViewCustomEditor : Editor
	{
		protected Dictionary<string,SerializedProperty> SerializedProperties = new Dictionary<string,SerializedProperty>();

		protected List<string> Properties = new List<string>{
			"Multiple",

			"DefaultItem",
			"Container",
			"scrollRect",

			"defaultColor",
			"defaultBackgroundColor",

			"HighlightedColor",
			"HighlightedBackgroundColor",

			"selectedColor",
			"selectedBackgroundColor",

			"NodeToggle",
			"NodeSelected",
			"NodeDeselected",
		};

		protected virtual void OnEnable()
		{
			Properties.ForEach(x => {
				SerializedProperties.Add(x, serializedObject.FindProperty(x));
			});
		}

		public override void OnInspectorGUI()
		{
			serializedObject.Update();

			SerializedProperties.ForEach(x => EditorGUILayout.PropertyField(x.Value, true));

			serializedObject.ApplyModifiedProperties();
		}
	}
}


text:
class ResultsController < ApplicationController
  include TagsHelper
  before_filter :authorize_only_for_admin,
                except: [:codeviewer, :edit, :update_mark, :view_marks,
                         :create, :add_extra_mark, :next_grouping,
                         :update_overall_comment, :remove_extra_mark,
                         :update_marking_state, :download, :download_zip,
                         :note_message, :update_overall_remark_comment,
                         :update_remark_request, :cancel_remark_request]
  before_filter :authorize_for_ta_and_admin,
                only: [:edit, :update_mark, :create, :add_extra_mark,
                       :next_grouping, :update_overall_comment,
                       :remove_extra_mark, :update_marking_state, :note_message,
                       :update_overall_remark_comment]
  before_filter :authorize_for_user,
                only: [:codeviewer, :download, :download_zip]
  before_filter :authorize_for_student,
                only: [:view_marks, :update_remark_request,
                       :cancel_remark_request]
  after_filter  :update_remark_request_count,
                only: [:update_remark_request, :cancel_remark_request,
                       :set_released_to_students]

  def note_message
    @result = Result.find(params[:id])
    if params[:success]
      flash[:note_success] = I18n.t('notes.success')
    else
      flash[:fail_notice] = I18n.t('notes.error')
    end
  end

  def edit
    result_id = params[:id]
    @result = Result.find(result_id)
    @assignment = @result.submission.assignment
    @submission = @result.submission

    if @submission.remark_submitted?
      @old_result = Result.where(submission_id: @submission.id).first
    else
      @old_result = nil
    end

    @grouping = @result.submission.grouping
    @not_associated_tags = get_tags_not_associated_with_grouping(@grouping.id)
    @group = @grouping.group
    @files = @submission.submission_files.sort do |a, b|
      File.join(a.path, a.filename) <=> File.join(b.path, b.filename)
    end
    @test_result_files = @submission.test_results
    @first_file = @files.first
    @extra_marks_points = @result.extra_marks.points
    @extra_marks_percentage = @result.extra_marks.percentage
    @marks_map = Hash.new
    @old_marks_map = Hash.new
    @mark_criteria = @assignment.get_criteria
    @assignment.get_criteria.each do |criterion|
      mark = criterion.marks.find_or_create_by_result_id(@result.id)
      @marks_map[criterion.id] = mark

      # Loading up previous results for the case of a remark
      if @old_result
        oldmark = criterion.marks.find_or_create_by_result_id(@old_result.id)
        oldmark.save(validate: false)
        @old_marks_map[criterion.id] = oldmark
      end

      mark.save(validate: false)
      @result.update_total_mark
    end

    groupings = Grouping.get_groupings_for_assignment(@assignment,
                                                      current_user)
    # We sort by group name by default
    groupings = groupings.sort do |a, b|
      a.group.group_name <=> b.group.group_name
    end

    current_grouping_index = groupings.index(@grouping)
    if current_grouping_index.nil?
      @next_grouping = groupings.first
      @previous_grouping = groupings.last
    else
      unless groupings[current_grouping_index + 1].nil?
        @next_grouping = groupings[current_grouping_index + 1]
      end
      if (current_grouping_index - 1) >= 0
        @previous_grouping = groupings[current_grouping_index - 1]
      end
    end

    m_logger = MarkusLogger.instance
    m_logger.log("User '#{current_user.user_name}' viewed submission (id: #{@submission.id})" +
                 "of assignment '#{@assignment.short_identifier}' for group '" +
                 "#{@group.group_name}'")

    # Sets up the tags for the tag pane.
    # Creates a variable for all the tags not used
    # and all the tags that are used by the assignment.
    @all_tags = Tag.all
    @grouping_tags = get_tags_for_grouping(@grouping.id)
    @not_grouping_tags = get_tags_not_associated_with_grouping(@grouping.id)

    # Gets the top tags and their usage.
    @top_tags = get_top_tags
    @top_tags_num = Hash.new
    @top_tags.each do |current|
      @top_tags_num[current.id] = get_num_groupings_for_tag(current.id)
    end

    # Respond to AJAX request.
    respond_to do |format|
      format.html
      format.json do
        @request_type = params[:type]

        # Checks the operation requested.
        if @request_type.eql? 'add'
          create_grouping_tag_association_from_existing_tag(
              params[:grouping_id],
              params[:tag_id])
        else
          delete_grouping_tag_association(params[:tag_id],
                                          Grouping.find(params[:grouping_id]))
        end

        # Renders nothing.
        render nothing: true
      end
    end
  end

  ##  Tag Methods  ##

  def add_tag
    create_grouping_tag_association_from_existing_tag(params[:grouping_id],
                                                      params[:tag_id])
    respond_to do |format|
      format.html do
        redirect_to :back
      end
    end
  end

  def remove_tag
    delete_grouping_tag_association(params[:tag_id],
                                    Grouping.find(params[:grouping_id]))
    respond_to do |format|
      format.html do
        redirect_to :back
      end
    end
  end

  def next_grouping
    grouping = Grouping.find(params[:id])
    if grouping.has_submission? && grouping.is_collected?
        redirect_to action: 'edit',
                    id: grouping.current_submission_used.get_latest_result.id
    else
      redirect_to controller: 'submissions',
                  action: 'collect_and_begin_grading',
                  id: grouping.assignment.id,
                  grouping_id: grouping.id
    end
  end

  def set_released_to_students
    @result = Result.find(params[:id])
    released_to_students = (params[:value] == 'true')
    if params[:old_id]
      @old_result = Result.find(params[:old_id])
      @old_result.released_to_students = released_to_students
      @old_result.save
    end
    @result.released_to_students = released_to_students
    @result.save
    m_logger = MarkusLogger.instance
    assignment = @result.submission.assignment
    if params[:value] == 'true'
      m_logger.log("Marks released for assignment '#{assignment.short_identifier}', ID: '" +
                   "#{assignment.id}' (for 1 group).")
    else
      m_logger.log("Marks unreleased for assignment '#{assignment.short_identifier}', ID: '" +
                   "#{assignment.id}' (for 1 group).")
    end
  end

  #Updates the marking state
  def update_marking_state
    @result = Result.find(params[:id])
    @old_marking_state = @result.marking_state
    @result.marking_state = params[:value]
    if @result.save
      # If marking_state is complete, update the cached distribution
      if params[:value] == Result::MARKING_STATES[:complete]
        @result.submission.assignment.assignment_stat.refresh_grade_distribution
        @result.submission.assignment.update_results_stats
      end
      render template: 'results/update_marking_state'
    else # Failed to pass validations
      # Show error message
      render template: 'results/marker/show_result_error'
    end
  end

  def download
    if params[:download_zip_button]
      download_zip
      return
    end
    #Ensure student doesn't download a file not submitted by his own grouping
    unless authorized_to_download?(file_id: params[:select_file_id])
      render 'shared/http_status', formats: [:html],
             locals: { code: '404',
                          message: HttpStatusHelper::ERROR_CODE[
                              'message']['404'] }, status: 404,
             layout: false
      return
    end
    file = SubmissionFile.find(params[:select_file_id])
    begin
      if params[:include_annotations] == 'true' && !file.is_supported_image?
        file_contents = file.retrieve_file(true)
      else
        file_contents = file.retrieve_file
      end
    rescue Exception => e
      flash[:file_download_error] = e.message
      redirect_to action: 'edit',
                  assignment_id: params[:assignment_id],
                  submission_id: file.submission,
                  id: file.submission.get_latest_result.id
      return
    end
    filename = file.filename
    #Display the file in the page if it is an image/pdf, and download button
    #was not explicitly pressed
    if file.is_supported_image? && !params[:show_in_browser].nil?
      send_data file_contents, type: 'image', disposition: 'inline',
        filename: filename
    else
      send_data file_contents, filename: filename
    end
  end

  def download_zip

    #Ensure student doesn't download files not submitted by his own grouping
    unless authorized_to_download?(submission_id: params[:submission_id])
      render 'shared/http_status', formats: [:html],
             locals: { code: '404',
                          message: HttpStatusHelper::ERROR_CODE[
                              'message']['404'] }, status: 404,
             layout: false
      return
    end
    assignment = Assignment.find(params[:assignment_id])
    submission = Submission.find(params[:submission_id])
    grouping = Grouping.find(submission.grouping_id)

    revision_number = submission.revision_number
    repo_folder = assignment.repository_folder
    zip_name = "#{repo_folder}-#{grouping.group.repo_name}"

    if submission.blank?
      render text: t('student.submission.no_files_available')
      return
    end

    zip_path = if params[:include_annotations] == 'true'
                 "tmp/#{assignment.short_identifier}_" +
                     "#{grouping.group.group_name}_r#{revision_number}_ann.zip"
               else
                 "tmp/#{assignment.short_identifier}_" +
                     "#{grouping.group.group_name}_r#{revision_number}.zip"
               end

    files = submission.submission_files

    Zip::File.open(zip_path, Zip::File::CREATE) do |zip_file|
      files.each do |file|
        begin
          if params[:include_annotations] == 'true' && !file.is_supported_image?
            file_content = file.retrieve_file(true)
          else
            file_content = file.retrieve_file
          end
        rescue Exception => e
          render text: t('student.submission.missing_file',
                            file_name: file.filename, message: e.message)
          return
        end
        # Create the folder in the Zip file if it doesn't exist
        zip_file.mkdir(zip_name) unless zip_file.find_entry(zip_name)

        zip_file.get_output_stream(File.join(zip_name, file.filename)) do |f|
          f.puts file_content
        end
      end
    end
    # Send the Zip file
    send_file zip_path, disposition: 'inline',
              filename: zip_name + '.zip'
  end

  def codeviewer
    @assignment = Assignment.find(params[:assignment_id])
    @submission_file_id = params[:submission_file_id]
    @focus_line = params[:focus_line]

    @file = SubmissionFile.find(@submission_file_id)
    @result = @file.submission.get_latest_result
    # Is the current user a student?
    if current_user.student?
      # The Student does not have access to this file. Display an error.
      if @file.submission.grouping.membership_status(current_user).nil?
        render partial: 'shared/handle_error',
               formats:[:js],
               handlers: [:erb],
               locals: { error: t('submission_file.error.no_access',
                         submission_file_id: @submission_file_id) }
        return
      end
    end

    @annots = @file.annotations
    @all_annots = @file.submission.annotations

    begin
      @file_contents = @file.retrieve_file
    rescue Exception => e
      render partial: 'shared/handle_error',
             formats:[:js],
             handlers: [:erb],
             locals: { error: e.message }
      return
    end
    @code_type = @file.get_file_type

    # if dealing with a pdf file, get the number of images to display
    if @file.is_pdf?
      i = 1
      storage_path = File.join(MarkusConfigurator.markus_config_pdf_storage,
        @file.submission.grouping.group.repository_name,
        @file.path)
      filePathToCheck = File.join(storage_path, @file.filename.split('.')[0] + '_' + sprintf('%04d' % i.to_s()) + '.jpg')
      while File.exists?(filePathToCheck)
        i += 1
        filePathToCheck = File.join(storage_path, @file.filename.split('.')[0] + '_' + sprintf('%04d' % i.to_s()) + '.jpg')
      end
      i -= 1
      @nb_pdf_files_to_download = i
    end

    render template: 'results/common/codeviewer'
  end

  def update_mark
    result_mark = Mark.find(params[:mark_id])
    result_mark.mark = params[:mark]
    submission = result_mark.result.submission  # get submission for logging
    group = submission.grouping.group           # get group for logging
    assignment = submission.grouping.assignment # get assignment for logging
    m_logger = MarkusLogger.instance

    # FIXME checking both that result_mark is valid and correctly saved is
    # useless. The validation is done automatically before saving unless
    # specified otherwise.
    if result_mark.valid?
      unless result_mark.save
        m_logger.log("Error while trying to update mark of submission. User: '" +
                         "#{current_user.user_name}', Submission ID: '#{submission.id}'," +
                         " Assignment: '#{assignment.short_identifier}', Group: '#{group.group_name}'.",
                     MarkusLogger::ERROR)
        render partial: 'shared/handle_error',
               formats:[:js],
               handlers: [:erb],
               locals: { error: t('mark.error.save') + result_mark.errors.full_messages.join }
      else
        m_logger.log("User '#{current_user.user_name}' updated mark for submission (id: " +
                         "#{submission.id}) of assignment '#{assignment.short_identifier}' for group" +
                         " '#{group.group_name}'.", MarkusLogger::INFO)
        render partial: 'results/marker/update_mark',
               locals: { result_mark: result_mark, mark_value: result_mark.mark}
      end
    else
      render partial: 'results/marker/mark_verify_result',
             locals: {mark_id: result_mark.id,
                         mark_error: result_mark.errors.full_messages.join}
    end
  end

  def view_marks
    @assignment = Assignment.find(params[:assignment_id])
    @grouping = current_user.accepted_grouping_for(@assignment.id)

    if @grouping.nil?
      redirect_to controller: 'assignments',
                  action: 'student_interface',
                  id: params[:id]
      return
    end
    unless @grouping.has_submission?
      render 'results/student/no_submission'
      return
    end
    @submission = @grouping.current_submission_used
    unless @submission.has_result?
      render 'results/student/no_result'
      return
    end

    @result = @submission.get_original_result
    @old_result = nil
    if @submission.remark_submitted?
      @old_result = @result
      @result = @submission.get_remark_result
      # if remark result's marking state is 'unmarked' then the student has
      # saved a remark request but not submitted it yet, therefore, still editable
      if @result.marking_state != Result::MARKING_STATES[:unmarked] && !@result.released_to_students
        render 'results/student/no_remark_result'
        return
      end
    end

    unless @result.released_to_students
      render 'results/student/no_result'
      return
    end

    @annotation_categories = @assignment.annotation_categories
    @group = @grouping.group
    @files = @submission.submission_files.sort do |a, b|
      File.join(a.path, a.filename) <=> File.join(b.path, b.filename)
    end
    @test_result_files = @submission.test_results
    @first_file = @files.first
    @extra_marks_points = @result.extra_marks.points
    @extra_marks_percentage = @result.extra_marks.percentage
    @marks_map = Hash.new
    @old_marks_map = Hash.new
    @mark_criteria = @assignment.get_criteria
    @assignment.get_criteria.each do |criterion|
      mark = criterion.marks.find_or_create_by_result_id(@result.id)
      mark.save(validate: false)
      @marks_map[criterion.id] = mark

      if @old_result
        oldmark = criterion.marks.find_or_create_by_result_id(@old_result.id)
        oldmark.save(validate: false)
        @old_marks_map[criterion.id] = oldmark
      end
    end

    @host = Rails.application.config.action_controller.relative_url_root

    m_logger = MarkusLogger.instance
    m_logger.log("Student '#{current_user.user_name}' viewed results for assignment " +
                 "'#{@assignment.short_identifier}'.")
  end

  def add_extra_mark
    @result = Result.find(params[:id])
    if request.post?
      @extra_mark = ExtraMark.new
      @extra_mark.result = @result
      @extra_mark.unit = ExtraMark::POINTS
      if @extra_mark.update_attributes(extra_mark_params)
        # need to re-calculate total mark
        @result.update_total_mark
        render template: 'results/marker/insert_extra_mark'
      else
        render template: 'results/marker/add_extra_mark_error'
      end
      return
    end
    render template: 'results/marker/add_extra_mark'
  end

  #Deletes an extra mark from the database and removes it from the html
  def remove_extra_mark
    #find the extra mark and destroy it
    @extra_mark = ExtraMark.find(params[:id])
    @extra_mark.destroy
    #need to recalculate total mark
    @result = @extra_mark.result
    @result.update_total_mark
    render template: 'results/marker/remove_extra_mark'
  end

  def update_overall_comment
    @result = Result.find(params[:id])
    @result.overall_comment = params[:result][:overall_comment]
    @result.save
    render 'update_overall_comment', formats: [:js]
  end

  def update_overall_remark_comment
    @result = Result.find(params[:id])
    @result.overall_comment = params[:result][:overall_comment]
    @result.save
    render 'update_overall_remark_comment', formats: [:js]
  end

  def update_remark_request
    @assignment = Assignment.find(params[:assignment_id])
    unless @assignment.past_remark_due_date?
      @submission = Submission.find(params[:id])
      @submission.remark_request = params[:submission][:remark_request]
      @submission.remark_request_timestamp = Time.zone.now
      @submission.save
      if params[:real_commit] == 'Submit'
        @old_result = @submission.get_original_result
        unless @submission.get_remark_result
          @submission.create_remark_result
        end
        @result = @submission.get_remark_result
        @result.marking_state = Result::MARKING_STATES[:partial]
        @old_result.released_to_students = (params[:value] == 'false')
        @result.save
        @old_result.save
      end
    end
    render 'update_remark_request', formats: [:js]
  end

  def cancel_remark_request
    @submission = Submission.find(params[:submission_id])

    @remark_result = @submission.get_remark_result
    @remark_result.destroy

    @submission.remark_result_id = nil
    @submission.remark_request = nil
    @submission.save

    @result = @submission.get_original_result
    @result.released_to_students = true
    @result.save

    redirect_to controller: 'results',
                action: 'view_marks',
                id: params[:id]
  end

  def delete_grace_period_deduction
    @grouping = Grouping.find(params[:id])
    grace_deduction = GracePeriodDeduction.find(params[:deduction_id])
    grace_deduction.destroy
  end

  private

  #Return true if submission_id or file_id matches between accepted_student and
  #current_user. This is to prevent students from downloading files that they
  #or their group have not submitted. Return false otherwise.
  def authorized_to_download?(map)
    #If the user is a ta or admin, return true as they are authorized.
    if current_user.admin? || current_user.ta?
      return true
    end
    submission = if map[:file_id]
                   sub_file = SubmissionFile.find_by_id(map[:file_id])
                   sub_file.submission unless sub_file.nil?
                 elsif map[:submission_id]
                   Submission.find(map[:submission_id])
                 end
    if submission
      #Check that current_user is in fact in grouping that sub_file belongs to
      !submission.grouping.accepted_students.find { |user|
        user == current_user
      }.nil?
    else
      false
    end
  end

  def update_remark_request_count
    Assignment.find(params[:assignment_id]).update_remark_request_count
  end

  private

  def extra_mark_params
    params.require(:extra_mark).permit(:result,
                                       :description,
                                       :extra_mark)
  end
end


text:
function swap(arr, i, j) {
  if (i === j) {
    return;
  }
  const tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;
}

function checkArray(arr) {
  if (!Array.isArray(arr)) {
    throw new Error("Expect input to be an array.");
  }
}

/**
 * Selection sort, sorted by selecting min to max items for the start to the end position of the
 * array.
 *
 * Time complexity: O(N^2)
 * Space complexity: O(1)
 *
 * @param {Array} array
 * @return {Array}
 *
 */
export function selectionSort(array) {
  const arr = array.slice();
  checkArray(arr);
  if (arr.length < 2) return arr;

  for (let i = 0; i < arr.length - 1; i++) {
    let min = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[min] > arr[j]) {
        min = j;
      }
    }
    swap(arr, i, min);
  }
  return arr;
}

/**
 * Bubble sort, sorted by swapping item pairs(if needed) from the start postion to the end of the
 * array.
 * First round will have a largest item swapped to the array end, and second round will have the
 * second largest item swapped to array end - 1 position, and so on until all items are sorted.
 *
 * Time complexity: O(N^2)
 * Space complexity: O(1)
 *
 * @param {Array} array
 * @return {Array}
 *
 */
export function bubbleSort(array) {
  const arr = array.slice();
  checkArray(arr);
  if (arr.length < 2) return arr;

  for (let i = arr.length - 1; i > 0; i--) {
    let swapped = false;
    for (let j = 0; j < i; j++) {
      if (arr[j] > arr[j + 1]) {
        swap(arr, j, j + 1);
        swapped = true;
      }
    }
    if (!swapped) return arr;
  }
  return arr;
}

/**
 * Insertion sort, sorted by inserting each item into a proper position of the sorted part of the
 * array before it.
 * The second item is the first one to insert, this carries on until the last item is inserted into
 * the sorted part of the array before it.
 * Insertion sort is extra fast when the array to sort is `small`, or is `partially sorted`.
 *
 * Time complexity: O(N) ~ O(N^2)
 * Space complexity: O(1)
 *
 * @param {Array} array
 * @return {Array}
 *
 */
export function insertionSort(array) {
  const arr = array.slice();
  checkArray(arr);
  if (arr.length < 2) return arr;

  for (let i = 1; i < arr.length; i++) {
    let j = i;
    const toInsert = arr[j];
    while (j > 0 && arr[j - 1] > toInsert) {
      // compare all prev items with the one to insert until find the position to insert
      arr[j] = arr[j - 1];
      j -= 1;
    }
    arr[j] = toInsert;
  }
  return arr;
}

/**
 * Shell sort, a type of insertion sort, sorted by swapping each gapped array items. The gap reduces
 * after the gapped array items are sorted. This goes on until the array is sorted.
 * The gap number is determined by a base number, for example, if the base number is 2, then for an
 * array of 16 items, its gap range will be 7, 3, 1.
 *
 * Time complexity: O(NlogN)
 * Space complexity: O(1)
 *
 * @param {Array} array
 * @return {Array}
 *
 */
export function shellSort(array, base = 3) {
  const arr = array.slice();
  checkArray(arr);
  if (arr.length < 2) return arr;

  const len = arr.length;
  let gap = 1;

  while (gap < len / base) {
    gap = gap * base + 1;
  }
  while (gap > 0) {
    for (let init = gap; init < len; init++) {
      const tmp = arr[init];
      let pos = init;
      for (; pos >= gap && arr[pos - gap] > tmp; pos -= gap) {
        arr[pos] = arr[pos - gap];
      }
      arr[pos] = tmp;
    }
    gap = Math.floor(gap / base);
  }

  return arr;
}

/**
 * Quick sort, sorted by performing a "partition" process for a chosen pivot item, and the same is
 * done for the left/right partitioned parts, and so on.
 * The partition process will swap pairs of items until the left part are all smaller than pivot,
 * and right part are all larger.
 * This function implemented it by creating extra partitioned array upon each partition process.
 * It's concise and easy to read, but has extra space complexity.
 *
 * Time complexity: O(NlogN, N^2)
 * Space complexity: O(N)
 *
 * @param {Array} array
 * @return {Array}
 *
 */
export function quickSortWithArray(array) {
  const arr = array.slice();
  checkArray(arr);
  if (arr.length < 2) return arr;

  const [pivot, ...rest] = arr;
  const larger = rest.filter((item) => item > pivot);
  const smaller = rest.filter((item) => item <= pivot); // includes items equal to pivot

  return [...quickSortWithArray(smaller), pivot, ...quickSortWithArray(larger)];
}

/**
 * Quick sort, sorted by performing a "partition" process for a chosen pivot item, and the same is
 * done for the left/right partitioned parts, and so on.
 * The partition process will swap pairs of items until the left part are "all smaller than pivot",
 * and right part are "all larger".
 *
 * Time complexity: O(NlogN)
 * Space complexity: O(logN)
 *
 * @param {Array} array
 * @return {Array}
 *
 */
export function quickSort(array, lo = 0, hi = array.length) {
  checkArray(array);
  if (array.length < 2 || hi - 1 <= lo) return array;

  const partition = (arr, left, right) => {
    let i = left;
    let j = right;
    const pivot = arr[left];

    while (i < j) {
      while (arr[++i] <= pivot) if (i === right) break; // eslint-disable-line no-plusplus
      while (arr[--j] >= pivot) if (j === left) break; // eslint-disable-line no-plusplus
      if (i < j) swap(arr, i, j);
    }
    swap(arr, left, j);
    return j;
  };
  const pivotIndex = partition(array, lo, hi);
  quickSort(array, lo, pivotIndex);
  quickSort(array, pivotIndex + 1, hi);

  return array;
}

/**
 * Merge sort, sorted by recursively dividing the array into two sub-arrays and "merging"
 * corresponding sub-arrays back into a sorted array. The merge process ensures that the merged
 * array is sorted.
 *
 * Time complexity: O(NlogN)
 * Space complexity: O(N)
 *
 * @param {Array} array
 * @return {Array}
 *
 */
export function mergeSort(array) {
  const arr = array.slice();
  checkArray(arr);
  if (arr.length < 2) return arr;

  const merge = (left, right) => {
    const result = [];
    let i = 0;
    let j = 0;
    while (i < left.length && j < right.length) {
      if (left[i] <= right[j]) {
        result.push(left[i]);
        i += 1;
      }
      if (left[i] >= right[j]) {
        result.push(right[j]);
        j += 1;
      }
    }
    return result.concat(left.slice(i), right.slice(j));
  };

  const mid = Math.floor(arr.length / 2); // be aware that it's not `arr.length - 1`
  return merge(mergeSort(arr.slice(0, mid)), mergeSort(arr.slice(mid)));
}

/**
 * Heap sort, sorted by using the heapify process of the Heap data structure.
 * The Heap data structure looks like a binary tree, but there cannot be `null` gap within it.
 * A proper Heap should have the property that all parent nodes are larger than or equal to its
 * child nodes.
 * The heapify process can find the largest item of the array at a time, and then swap the largest
 * item to the end of the array. This process is repeated until all the array become sorted.
 *
 * Time complexity: O(NlogN)
 * Space complexity: O(1)
 *
 * @param {Array} array
 * @return {Array}
 *
 */
export function heapSort(array) {
  const arr = array.slice();
  checkArray(arr);
  if (arr.length < 2) return arr;

  const heapify = (list, index, end = list.length - 1) => {
    const parentIndex = Math.ceil(index / 2) - 1;
    if (index < 0 || parentIndex < 0) {
      return;
    }
    const isLeft = index % 2 === 1;
    const firstGenerationIndex = isLeft ? index + 1 : index - 1;

    let largest = parentIndex;
    if (list[index] > list[largest]) largest = index;
    if (firstGenerationIndex <= end && list[firstGenerationIndex] > list[largest]) {
      largest = firstGenerationIndex;
    }
    if (largest !== parentIndex) swap(list, largest, parentIndex);

    heapify(list, index - 2, end);
  };

  for (let last = arr.length - 1; last > 0; last -= 1) {
    heapify(arr, last, last);
    swap(arr, 0, last);
  }

  return arr;
}


text:
template <class> class RefPtr {};

template <typename T>
class HasRefPtr {
  typedef T TypedefOfT;
  RefPtr<TypedefOfT> refptr_member;
};


text:
package nl.knaw.huygens.timbuctoo.v5.graphql.security;

import com.google.common.collect.Sets;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLFieldsContainer;
import nl.knaw.huygens.timbuctoo.v5.dataset.DataSetRepository;
import nl.knaw.huygens.timbuctoo.v5.dataset.dto.BasicDataSetMetaData;
import nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet;
import nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSetMetaData;
import nl.knaw.huygens.timbuctoo.v5.security.dto.Permission;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

public class PermissionBasedFieldVisibilityTest {

  private UserPermissionCheck userPermissionCheck;

  @Before
  public void setUp() throws Exception {
    userPermissionCheck = mock(UserPermissionCheck.class);
  }

  @Test
  public void getFieldDefinitionsShowsOnlyDataSetsThatUserHasAccessTo() throws Exception {
    final DataSetRepository dataSetRepository = mock(DataSetRepository.class);
    DataSet dataSet = createDataSetWithUserPermissions(
      "user__dataSetUserHasAccessTo",
      Sets.newHashSet(Permission.READ)
    );
    DataSet dataSet2 = createDataSetWithUserPermissions(
      "user__dataSetUserDoesNotHasAccessTo",
      Sets.newHashSet()
    );
    Collection<DataSet> dataSetCollection = Sets.newHashSet(dataSet, dataSet2);
    given(dataSetRepository.getDataSets()).willReturn(dataSetCollection);
    final PermissionBasedFieldVisibility permissionBasedFieldVisibility =
      new PermissionBasedFieldVisibility(userPermissionCheck, dataSetRepository);
    final GraphQLFieldsContainer graphQlFieldsContainer = createGraphQlFieldsContainer(
      "user__dataSetUserHasAccessTo",
      "user__dataSetUserDoesNotHasAccessTo"
    );

    List<GraphQLFieldDefinition> retrievedGraphQlFieldDefinitions = permissionBasedFieldVisibility
      .getFieldDefinitions(graphQlFieldsContainer);

    assertThat(retrievedGraphQlFieldDefinitions, contains(hasProperty("name", is("user__dataSetUserHasAccessTo"))));
  }

  @Test
  public void getFieldDefinitionsShowsNonDataSetFields() throws Exception {
    final DataSetRepository dataSetRepository = mock(DataSetRepository.class);
    DataSet dataSet = createDataSetWithUserPermissions(
      "user__dataSetUserHasAccessTo",
      Sets.newHashSet(Permission.READ)
    );
    DataSet dataSet2 = createDataSetWithUserPermissions(
      "user__dataSetUserDoesNotHasAccessTo",
      Sets.newHashSet()
    );
    Collection<DataSet> dataSetCollection = Sets.newHashSet(dataSet, dataSet2);
    given(dataSetRepository.getDataSets()).willReturn(dataSetCollection);
    final PermissionBasedFieldVisibility permissionBasedFieldVisibility =
      new PermissionBasedFieldVisibility(userPermissionCheck, dataSetRepository);
    final GraphQLFieldsContainer graphQlFieldsContainer = createGraphQlFieldsContainer(
      "user__dataSetUserHasAccessTo",
      "user__dataSetUserDoesNotHasAccessTo", "nonDataSetField"
    );

    List<GraphQLFieldDefinition> retrievedGraphQlFieldDefinitions = permissionBasedFieldVisibility
      .getFieldDefinitions(graphQlFieldsContainer);

    assertThat(retrievedGraphQlFieldDefinitions,
      contains(hasProperty("name", is("user__dataSetUserHasAccessTo")),
        hasProperty("name",is("nonDataSetField"))));
  }

  private GraphQLFieldsContainer createGraphQlFieldsContainer(String... fieldNames) {
    List<GraphQLFieldDefinition> graphQlFieldDefinitions = new ArrayList<>();

    final GraphQLFieldsContainer graphQlFieldsContainer = mock(GraphQLFieldsContainer.class);

    for (String fieldName : fieldNames) {
      GraphQLFieldDefinition graphQlFieldDefinition = createGraphQlFieldDefinition(fieldName);
      graphQlFieldDefinitions.add(graphQlFieldDefinition);
      given(graphQlFieldsContainer.getFieldDefinition(fieldName)).willReturn(graphQlFieldDefinition);
    }

    given(graphQlFieldsContainer.getFieldDefinitions()).willReturn(graphQlFieldDefinitions);
    return graphQlFieldsContainer;
  }

  private GraphQLFieldDefinition createGraphQlFieldDefinition(String fieldName) {
    GraphQLFieldDefinition graphQlFieldDefinition = mock(GraphQLFieldDefinition.class);
    given(graphQlFieldDefinition.getName()).willReturn(fieldName);
    return graphQlFieldDefinition;
  }

  private DataSet createDataSetWithUserPermissions(String combinedId, Set<Permission> permissions) {
    DataSetMetaData dataSetMetaData = createDataSetMetadata(combinedId);
    for (Permission permission : permissions) {
      given(userPermissionCheck.hasPermission(dataSetMetaData, permission)).willReturn(true);
    }
    return createDataSet(dataSetMetaData);
  }

  private DataSet createDataSet(DataSetMetaData dataSetMetaData) {
    DataSet dataSet = mock(DataSet.class);
    given(dataSet.getMetadata()).willReturn(dataSetMetaData);
    return dataSet;
  }

  private DataSetMetaData createDataSetMetadata(String combinedId) {
    DataSetMetaData dataSetMetaData2 = mock(BasicDataSetMetaData.class);
    given(dataSetMetaData2.getCombinedId()).willReturn(combinedId);
    return dataSetMetaData2;
  }

  @Test
  public void getFieldDefinitionReturnsNullIfUserHasNoPermission() throws Exception {
    final DataSetRepository dataSetRepository = mock(DataSetRepository.class);
    DataSet dataSet = createDataSetWithUserPermissions(
      "user__dataSetUserHasAccessTo",
      Sets.newHashSet(Permission.READ)
    );
    DataSet dataSet2 = createDataSetWithUserPermissions(
      "user__dataSetUserDoesNotHasAccessTo",
      Sets.newHashSet()
    );
    Collection<DataSet> dataSetCollection = Sets.newHashSet(dataSet, dataSet2);
    given(dataSetRepository.getDataSets()).willReturn(dataSetCollection);
    final PermissionBasedFieldVisibility permissionBasedFieldVisibility =
      new PermissionBasedFieldVisibility(userPermissionCheck, dataSetRepository);

    final GraphQLFieldsContainer graphQlFieldsContainer = createGraphQlFieldsContainer(
      "user__dataSetUserHasAccessTo",
      "user__dataSetUserDoesNotHasAccessTo"
    );

    GraphQLFieldDefinition retrievedGraphQlFieldDefinition = permissionBasedFieldVisibility
      .getFieldDefinition(graphQlFieldsContainer,"user__dataSetUserDoesNotHasAccessTo");

    assertThat(retrievedGraphQlFieldDefinition,is(nullValue()));
  }

  @Test
  public void getFieldDefinitionReturnsFieldDefinitionIfUserHasPermission() throws Exception {
    final DataSetRepository dataSetRepository = mock(DataSetRepository.class);
    DataSet dataSet = createDataSetWithUserPermissions(
      "user__dataSetUserHasAccessTo",
      Sets.newHashSet(Permission.READ)
    );
    DataSet dataSet2 = createDataSetWithUserPermissions(
      "user__dataSetUserDoesNotHasAccessTo",
      Sets.newHashSet()
    );
    Collection<DataSet> dataSetCollection = Sets.newHashSet(dataSet, dataSet2);
    given(dataSetRepository.getDataSets()).willReturn(dataSetCollection);
    final PermissionBasedFieldVisibility permissionBasedFieldVisibility =
      new PermissionBasedFieldVisibility(userPermissionCheck, dataSetRepository);

    final GraphQLFieldsContainer graphQlFieldsContainer = createGraphQlFieldsContainer(
      "user__dataSetUserHasAccessTo",
      "user__dataSetUserDoesNotHasAccessTo"
    );

    GraphQLFieldDefinition retrievedGraphQlFieldDefinition = permissionBasedFieldVisibility
      .getFieldDefinition(graphQlFieldsContainer,"user__dataSetUserHasAccessTo");

    assertThat(retrievedGraphQlFieldDefinition,hasProperty("name", is("user__dataSetUserHasAccessTo")));
  }

  @Test
  public void getFieldDefinitionReturnsFieldDefinitionIfNotDataSetField() throws Exception {
    final DataSetRepository dataSetRepository = mock(DataSetRepository.class);
    DataSet dataSet = createDataSetWithUserPermissions(
      "user__dataSetUserHasAccessTo",
      Sets.newHashSet(Permission.READ)
    );
    DataSet dataSet2 = createDataSetWithUserPermissions(
      "user__dataSetUserDoesNotHasAccessTo",
      Sets.newHashSet()
    );
    Collection<DataSet> dataSetCollection = Sets.newHashSet(dataSet, dataSet2);
    given(dataSetRepository.getDataSets()).willReturn(dataSetCollection);
    final PermissionBasedFieldVisibility permissionBasedFieldVisibility =
      new PermissionBasedFieldVisibility(userPermissionCheck, dataSetRepository);

    final GraphQLFieldsContainer graphQlFieldsContainer = createGraphQlFieldsContainer(
      "user__dataSetUserHasAccessTo",
      "user__dataSetUserDoesNotHasAccessTo",
      "nonDataSetField"
    );

    GraphQLFieldDefinition retrievedGraphQlFieldDefinition = permissionBasedFieldVisibility
      .getFieldDefinition(graphQlFieldsContainer,new String("nonDataSetField")); //new String to make sure the
    //contents are compared not the instance.

    assertThat(retrievedGraphQlFieldDefinition,hasProperty("name", is("nonDataSetField")));
  }

}


text:
namespace Contrib.Regex
{
    /// <summary>
    /// Defines basic operations needed by <see cref="RegexQuery"/> for a regular expression implementation.
    /// </summary>
    /// <remarks>http://www.java2s.com/Open-Source/Java-Document/Net/lucene-connector/org/apache/lucene/search/regex/RegexCapabilities.java.htm</remarks>
    public interface IRegexCapabilities
    {
        /// <summary>
        /// Called by the constructor of <see cref="RegexTermEnum"/> allowing implementations to cache
        /// a compiled version of the regular expression pattern.
        /// </summary>
        /// <param name="pattern">regular expression pattern</param>
        void Compile(string pattern);

        /// <summary>
        /// True on match.
        /// </summary>
        /// <param name="s">text to match</param>
        /// <returns>true on match</returns>
        bool Match(string s);

        /// <summary>
        /// A wise prefix implementation can reduce the term enumeration (and thus performance)
        /// of RegexQuery dramatically.
        /// </summary>
        /// <returns>static non-regex prefix of the pattern last passed to <see cref="Compile"/>.
        ///   May return null</returns>
        string Prefix();
    }
}