text:
<?php

class GETResourceVisibleHiddenPropertiesUnitTest extends ERestTestCase
{
	/**
	 * testGETResourcesVisibleProperties
	 *
     * tests that a GET request for a list of 'User' resources
     * With limited selected visible fields only
	 * returns the correct response
	 */
	public function testGETResourceVisibleProperties()
	{
        $request = new ERestTestRequestHelper();

        $request->addEvent('model.visible.properties', function() {
            return ['username', 'email'];
        });

        $request->addEvent('model.with.relations', function() {
            return [];
        });

		$request['config'] = [
			'url'			=> 'http://api/user/1',
			'type'		=> 'GET',
			'data'		=> null,
			'headers' => [
				'X_REST_USERNAME' => 'admin@restuser',
				'X_REST_PASSWORD' => 'admin@Access',
			],
		];

        $request_response = $request->send();
        $expected_response = '{"success":true,"message":"Record Found","data":{"totalCount":1,"user":{"username":"username1","email":"email@email1.com"}}}';
        $this->assertJsonStringEqualsJsonString($request_response, $expected_response);
	}

	/**
	 * testGETResourcesHiddenProperties
	 *
     * tests that a GET request for a list of 'User' resources
     * With exluded visible fields only
	 * returns the correct response
	 */
	public function testGETResourceHiddenProperties()
	{
        $request = new ERestTestRequestHelper();

        $request->addEvent('model.hidden.properties', function() {
            return ['password', 'id'];
        });

        $request->addEvent('model.with.relations', function() {
            return [];
        });

		$request['config'] = [
			'url'			=> 'http://api/user/1',
			'type'		=> 'GET',
			'data'		=> null,
			'headers' => [
				'X_REST_USERNAME' => 'admin@restuser',
				'X_REST_PASSWORD' => 'admin@Access',
			],
		];

        $request_response = $request->send();
        $expected_response = '{"success":true,"message":"Record Found","data":{"totalCount":1,"user":{"username":"username1","email":"email@email1.com"}}}';
        $this->assertJsonStringEqualsJsonString($request_response, $expected_response);
	}

    /**
	 * testGETResourcesVisibleRelatedProperties
	 *
     * tests that a GET request for a list of 'User' resources
     * With limited selected visible fields only
	 * returns the correct response
	 */
	public function testGETResourceVisibleRelatedProperties()
	{
        $request = new ERestTestRequestHelper();

        $request->addEvent('model.visible.properties', function() {
            return ['username', 'email', 'posts.id', '*.title', 'profile.website'];
        });

        $request->addEvent('model.with.relations', function() {
            return ['posts', 'profile'];
        });

		$request['config'] = [
			'url'			=> 'http://api/user/1',
			'type'		=> 'GET',
			'data'		=> null,
			'headers' => [
				'X_REST_USERNAME' => 'admin@restuser',
				'X_REST_PASSWORD' => 'admin@Access',
			],
		];

        $request_response = $request->send();
        $expected_response = '{"success":true,"message":"Record Found","data":{"totalCount":1,"user":{"username":"username1","email":"email@email1.com","posts":[{"id":"1","title":"title1"}],"profile":{"website":"mysite1.com"}}}}';
        $this->assertJsonStringEqualsJsonString($request_response, $expected_response);
    }

    /**
	 * testGETResourcesHiddenRelatedProperties
	 *
     * tests that a GET request for a list of 'User' resources
     * With exluded visible fields only
	 * returns the correct response
	 */
	public function testGETResourceHiddenRelatedProperties()
	{
        $request = new ERestTestRequestHelper();

        $request->addEvent('model.hidden.properties', function() {
            return ['password', 'id', '*.title', 'posts.id', '*.website'];
        });

        $request->addEvent('model.with.relations', function() {
            return ['posts', 'profile'];
        });

		$request['config'] = [
			'url'			=> 'http://api/user/1',
			'type'		=> 'GET',
			'data'		=> null,
			'headers' => [
				'X_REST_USERNAME' => 'admin@restuser',
				'X_REST_PASSWORD' => 'admin@Access',
			],
		];

        $request_response = $request->send();
        $expected_response = '{"success":true,"message":"Record Found","data":{"totalCount":1,"user":{"username":"username1","email":"email@email1.com","posts":[{"content":"content1","create_time":"2013-08-07 10:09:41","author_id":"1"}],"profile":{"id":"1","user_id":"1","photo":"1"}}}}';
        $this->assertJsonStringEqualsJsonString($request_response, $expected_response);
	}
}


text:
package org.jclouds.ultradns.ws;
import static com.google.common.base.Objects.equal;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;

import com.google.common.base.Objects;
import com.google.common.base.Optional;

public final class UltraDNSWSError {
   public static UltraDNSWSError fromCodeAndDescription(int code, Optional<String> description) {
      return new UltraDNSWSError(code, description);
   }

   private final int code;
   private final Optional<String> description;

   private UltraDNSWSError(int code, Optional<String> description) {
      this.code = code;
      this.description = checkNotNull(description, "description for code %s", code);
   }

   /**
    * The error code. ex {@code 1801}
    */
   public int getCode() {
      return code;
   }

   /**
    * The description of the error. ex {@code Zone does not exist in the system.}
    */
   public Optional<String> getDescription() {
      return description;
   }

   @Override
   public int hashCode() {
      return Objects.hashCode(code, description);
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null || getClass() != obj.getClass())
         return false;
      UltraDNSWSError that = UltraDNSWSError.class.cast(obj);
      return equal(this.code, that.code) && equal(this.description, that.description);
   }

   @Override
   public String toString() {
      return description.isPresent() ? format("Error %s: %s", code, description.get()) : format("Error %s", code);
   }
}

redpajama_set_name: RedPajamaGithub


text: package framework


text:
namespace SafetySharp.Runtime
{
	using System;
	using System.Threading;
	using Serialization;
	using Utilities;

	/// <summary>
	///   Stores the serialized states of a <see cref="RuntimeModel" />.
	/// </summary>
	/// <remarks>
	///   We store states in a contiguous array, indexed by the state's hash. The hashes are stored in a separate array,
	///   using open addressing, see Laarman, "Scalable Multi-Core Model Checking", Algorithm 2.3.
	/// </remarks>
	internal sealed unsafe class StateStorage : DisposableObject
	{
		/// <summary>
		///   The number of attempts that are made to find an empty bucket.
		/// </summary>
		private const int ProbeThreshold = 1000;

		/// <summary>
		///   The assumed size of a cache line in bytes.
		/// </summary>
		private const int CacheLineSize = 64;

		/// <summary>
		///   The number of buckets that can be stored in a cache line.
		/// </summary>
		private const int BucketsPerCacheLine = CacheLineSize / sizeof(int);

		/// <summary>
		///   The number of states that can be cached.
		/// </summary>
		private readonly int _capacity;

		/// <summary>
		///   The buffer that stores the hash table information.
		/// </summary>
		private readonly MemoryBuffer _hashBuffer = new MemoryBuffer();

		/// <summary>
		///   The memory where the hash table information is stored.
		/// </summary>
		private readonly int* _hashMemory;

		/// <summary>
		///   The buffer that stores the states.
		/// </summary>
		private readonly MemoryBuffer _stateBuffer = new MemoryBuffer();

		/// <summary>
		///   The pointer to the underlying state memory.
		/// </summary>
		private readonly byte* _stateMemory;

		/// <summary>
		///   The length in bytes of a state vector.
		/// </summary>
		private readonly int _stateVectorSize;

		/// <summary>
		///   Initializes a new instance.
		/// </summary>
		/// <param name="layout">The layout of the state vector..</param>
		/// <param name="capacity">The capacity of the cache, i.e., the number of states that can be stored in the cache.</param>
		public StateStorage(StateVectorLayout layout, int capacity)
		{
			Requires.NotNull(layout, nameof(layout));
			Requires.InRange(capacity, nameof(capacity), 1024, Int32.MaxValue);

			_stateVectorSize = layout.SizeInBytes;
			_capacity = capacity;

			_stateBuffer.Resize((long)_capacity * _stateVectorSize, zeroMemory: false);
			_stateMemory = _stateBuffer.Pointer;

			// We allocate enough space so that we can align the returned pointer such that index 0 is the start of a cache line
			_hashBuffer.Resize((long)_capacity * sizeof(int) + CacheLineSize, zeroMemory: true);
			_hashMemory = (int*)_hashBuffer.Pointer;

			if ((ulong)_hashMemory % CacheLineSize != 0)
				_hashMemory = (int*)(_hashBuffer.Pointer + (CacheLineSize - (ulong)_hashBuffer.Pointer % CacheLineSize));

			Assert.InRange((ulong)_hashMemory - (ulong)_hashBuffer.Pointer, 0ul, (ulong)CacheLineSize);
			Assert.That((ulong)_hashMemory % CacheLineSize == 0, "Invalid buffer alignment.");
		}

		/// <summary>
		///   Gets the state at the given zero-based <paramref name="index" />.
		/// </summary>
		/// <param name="index">The index of the state that should be returned.</param>
		public byte* this[int index] => _stateMemory + (long)index * _stateVectorSize;

		/// <summary>
		///   Adds the <paramref name="state" /> to the cache if it is not already known. Returns <c>true</c> to indicate that the state
		///   has been added. This method can be called simultaneously from multiple threads.
		/// </summary>
		/// <param name="state">The state that should be added.</param>
		/// <param name="index">Returns the unique index of the state.</param>
		public bool AddState(byte* state, out int index)
		{
			// We don't have to do any out of bounds checks here

			var hash = MemoryBuffer.Hash(state, _stateVectorSize, 0);
			for (var i = 1; i < ProbeThreshold; ++i)
			{
				// We store 30 bit hash values as 32 bit integers, with the most significant bit #31 being set
				// indicating the 'written' state and bit #30 indicating whether writing is not yet finished
				// 'empty' is represented by 0
				// We ignore two most significant bits of the original hash, which has no influence on the
				// correctness of the algorithm, but might result in more state comparisons
				var hashedIndex = MemoryBuffer.Hash((byte*)&hash, sizeof(int), i * 8345723) % _capacity;
				var memoizedHash = hashedIndex & 0x3FFFFFFF;
				var cacheLineStart = (hashedIndex / BucketsPerCacheLine) * BucketsPerCacheLine;

				for (var j = 0; j < BucketsPerCacheLine; ++j)
				{
					var offset = (int)(cacheLineStart + (hashedIndex + j) % BucketsPerCacheLine);
					var currentValue = Volatile.Read(ref _hashMemory[offset]);

					if (currentValue == 0 && Interlocked.CompareExchange(ref _hashMemory[offset], (int)memoizedHash | (1 << 30), 0) == 0)
					{
						MemoryBuffer.Copy(state, _stateMemory + (long)offset * _stateVectorSize, _stateVectorSize);
						Volatile.Write(ref _hashMemory[offset], (int)memoizedHash | (1 << 31));

						index = offset;
						return true;
					}

					// We have to read the hash value again as it might have been written now where it previously was not
					currentValue = Volatile.Read(ref _hashMemory[offset]);
					if ((currentValue & 0x3FFFFFFF) == memoizedHash)
					{
						while ((currentValue & 1 << 31) == 0)
							currentValue = Volatile.Read(ref _hashMemory[offset]);

						if (MemoryBuffer.AreEqual(state, _stateMemory + (long)offset * _stateVectorSize, _stateVectorSize))
						{
							index = offset;
							return false;
						}
					}
				}
			}

			throw new OutOfMemoryException(
				"Failed to find an empty hash table slot within a reasonable amount of time. Try increasing the state capacity.");
		}

		/// <summary>
		///   Disposes the object, releasing all managed and unmanaged resources.
		/// </summary>
		/// <param name="disposing">If true, indicates that the object is disposed; otherwise, the object is finalized.</param>
		protected override void OnDisposing(bool disposing)
		{
			if (disposing)
				_stateBuffer.SafeDispose();
		}
	}
}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mobihelp.customthemedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="22" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.Coolbluetheme" >
        <activity
            android:name="com.example.mobihelp.customthemedemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package su.ugatu.moodle.is.credit_calc;

import java.util.Date;

/**
 * Утилита, реализует методы работы с датами.
 *
 * @author rinat.enikeev@gmail.com
 * Date: 14.01.14
 * Time: 22:04
 */
public class CalendarUtil {

    public static final int NUMBER_OF_MONTHS = 12;

    /**
     * Calculate next month's date. Attention! Next month date for January 31
     * will be 28 or 29 February.
     *
     * @param date to which add month.
     * @return next month's date. If Day of @param date is greater than number
     *         of days in next month, then day is set to last day of next month.
     */
    public static Date nextMonthDate(Date date) {
        Date result = copyDate(date);
        int newMonth = result.getMonth() + 1;
        while (newMonth > 11) {
            newMonth -= 12;
            result.setYear(result.getYear() + 1);
        }
        result.setMonth(newMonth);
        if (result.getMonth() != newMonth) {
            /* If the date was January 31, for example, and
             * the month is set to February, then the new date will be treated as
             * if it were on March 3, because February has only 30 days. */
            result.setDate(date.getDate() - result.getDate());
            result.setMonth(newMonth);
            /* day was forcibly set to last day of month */
        }
        return result;
    }

    /**
     * Copies a date.
     *
     * @param date the date
     * @return the copy
     */
    public static Date copyDate(Date date) {
        if (date == null) {
            return null;
        }
        Date newDate = new Date();
        newDate.setTime(date.getTime());
        return newDate;
    }
}


text:
namespace MSINet.Interop
{
    public static class InstallPropertyNames
    {
        public static readonly string InstalledProductName = "InstalledProductName";
        public static readonly string VersionString = "VersionString";
        public static readonly string HelpLink = "HelpLink";
        public static readonly string HelpTelephone = "HelpTelephone";
        public static readonly string InstallLocation = "InstallLocation";
        public static readonly string InstallSource = "InstallSource";
        public static readonly string InstallDate = "InstallDate";
        public static readonly string Publisher = "Publisher";
        public static readonly string LocalPackage = "LocalPackage";
        public static readonly string URLInfoAbout = "URLInfoAbout";
        public static readonly string URLUpdateInfo = "URLUpdateInfo";
        public static readonly string VersionMinor = "VersionMinor";
        public static readonly string VersionMajor = "VersionMajor";
        public static readonly string ProductID = "ProductID";
        public static readonly string RegCompany = "RegCompany";
        public static readonly string RegOwner = "RegOwner";
        public static readonly string Uninstallable = "Uninstallable";
        public static readonly string State = "State";
        public static readonly string PatchType = "PatchType";
        public static readonly string LUAEnabled = "LUAEnabled";
        public static readonly string DisplayName = "DisplayName";
        public static readonly string MoreInfoURL = "MoreInfoURL";
        public static readonly string LastUsedSource = "LastUsedSource";
        public static readonly string LastUsedType = "LastUsedType";
        public static readonly string MediaPackagePath = "MediaPackagePath";
        public static readonly string DiskPrompt = "DiskPrompt";
    }
}


text:
/* DO NOT EDIT */
/* This file was generated from team_log_generated.stone */

package com.dropbox.core.v2.teamlog;

import com.dropbox.core.stone.StoneDeserializerLogger;
import com.dropbox.core.stone.StoneSerializers;
import com.dropbox.core.stone.StructSerializer;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

import java.io.IOException;
import java.util.Arrays;

/**
 * Group's logged information.
 */
public class GroupLogInfo {
    // struct team_log.GroupLogInfo (team_log_generated.stone)

    protected final String groupId;
    protected final String displayName;
    protected final String externalId;

    /**
     * Group's logged information.
     *
     * <p> Use {@link newBuilder} to create instances of this class without
     * specifying values for all optional fields. </p>
     *
     * @param displayName  The name of this group. Must not be {@code null}.
     * @param groupId  The unique id of this group.
     * @param externalId  External group ID.
     *
     * @throws IllegalArgumentException  If any argument does not meet its
     *     preconditions.
     */
    public GroupLogInfo(String displayName, String groupId, String externalId) {
        this.groupId = groupId;
        if (displayName == null) {
            throw new IllegalArgumentException("Required value for 'displayName' is null");
        }
        this.displayName = displayName;
        this.externalId = externalId;
    }

    /**
     * Group's logged information.
     *
     * <p> The default values for unset fields will be used. </p>
     *
     * @param displayName  The name of this group. Must not be {@code null}.
     *
     * @throws IllegalArgumentException  If any argument does not meet its
     *     preconditions.
     */
    public GroupLogInfo(String displayName) {
        this(displayName, null, null);
    }

    /**
     * The name of this group.
     *
     * @return value for this field, never {@code null}.
     */
    public String getDisplayName() {
        return displayName;
    }

    /**
     * The unique id of this group.
     *
     * @return value for this field, or {@code null} if not present.
     */
    public String getGroupId() {
        return groupId;
    }

    /**
     * External group ID.
     *
     * @return value for this field, or {@code null} if not present.
     */
    public String getExternalId() {
        return externalId;
    }

    /**
     * Returns a new builder for creating an instance of this class.
     *
     * @param displayName  The name of this group. Must not be {@code null}.
     *
     * @return builder for this class.
     *
     * @throws IllegalArgumentException  If any argument does not meet its
     *     preconditions.
     */
    public static Builder newBuilder(String displayName) {
        return new Builder(displayName);
    }

    /**
     * Builder for {@link GroupLogInfo}.
     */
    public static class Builder {
        protected final String displayName;

        protected String groupId;
        protected String externalId;

        protected Builder(String displayName) {
            if (displayName == null) {
                throw new IllegalArgumentException("Required value for 'displayName' is null");
            }
            this.displayName = displayName;
            this.groupId = null;
            this.externalId = null;
        }

        /**
         * Set value for optional field.
         *
         * @param groupId  The unique id of this group.
         *
         * @return this builder
         */
        public Builder withGroupId(String groupId) {
            this.groupId = groupId;
            return this;
        }

        /**
         * Set value for optional field.
         *
         * @param externalId  External group ID.
         *
         * @return this builder
         */
        public Builder withExternalId(String externalId) {
            this.externalId = externalId;
            return this;
        }

        /**
         * Builds an instance of {@link GroupLogInfo} configured with this
         * builder's values
         *
         * @return new instance of {@link GroupLogInfo}
         */
        public GroupLogInfo build() {
            return new GroupLogInfo(displayName, groupId, externalId);
        }
    }

    @Override
    public int hashCode() {
        int hash = Arrays.hashCode(new Object [] {
            groupId,
            displayName,
            externalId
        });
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        // be careful with inheritance
        else if (obj.getClass().equals(this.getClass())) {
            GroupLogInfo other = (GroupLogInfo) obj;
            return ((this.displayName == other.displayName) || (this.displayName.equals(other.displayName)))
                && ((this.groupId == other.groupId) || (this.groupId != null && this.groupId.equals(other.groupId)))
                && ((this.externalId == other.externalId) || (this.externalId != null && this.externalId.equals(other.externalId)))
                ;
        }
        else {
            return false;
        }
    }

    @Override
    public String toString() {
        return Serializer.INSTANCE.serialize(this, false);
    }

    /**
     * Returns a String representation of this object formatted for easier
     * readability.
     *
     * <p> The returned String may contain newlines. </p>
     *
     * @return Formatted, multiline String representation of this object
     */
    public String toStringMultiline() {
        return Serializer.INSTANCE.serialize(this, true);
    }

    /**
     * For internal use only.
     */
    static class Serializer extends StructSerializer<GroupLogInfo> {
        public static final Serializer INSTANCE = new Serializer();

        @Override
        public void serialize(GroupLogInfo value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException {
            if (!collapse) {
                g.writeStartObject();
            }
            g.writeFieldName("display_name");
            StoneSerializers.string().serialize(value.displayName, g);
            if (value.groupId != null) {
                g.writeFieldName("group_id");
                StoneSerializers.nullable(StoneSerializers.string()).serialize(value.groupId, g);
            }
            if (value.externalId != null) {
                g.writeFieldName("external_id");
                StoneSerializers.nullable(StoneSerializers.string()).serialize(value.externalId, g);
            }
            if (!collapse) {
                g.writeEndObject();
            }
        }

        @Override
        public GroupLogInfo deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException {
            GroupLogInfo value;
            String tag = null;
            if (!collapsed) {
                expectStartObject(p);
                tag = readTag(p);
            }
            if (tag == null) {
                String f_displayName = null;
                String f_groupId = null;
                String f_externalId = null;
                while (p.getCurrentToken() == JsonToken.FIELD_NAME) {
                    String field = p.getCurrentName();
                    p.nextToken();
                    if ("display_name".equals(field)) {
                        f_displayName = StoneSerializers.string().deserialize(p);
                    }
                    else if ("group_id".equals(field)) {
                        f_groupId = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p);
                    }
                    else if ("external_id".equals(field)) {
                        f_externalId = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p);
                    }
                    else {
                        skipValue(p);
                    }
                }
                if (f_displayName == null) {
                    throw new JsonParseException(p, "Required field \"display_name\" missing.");
                }
                value = new GroupLogInfo(f_displayName, f_groupId, f_externalId);
            }
            else {
                throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\"");
            }
            if (!collapsed) {
                expectEndObject(p);
            }
            StoneDeserializerLogger.log(value, value.toStringMultiline());
            return value;
        }
    }
}


text:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

  <import resource="service-beans.xml"/>
  <import resource="persistence-beans.xml"/>
  <import resource="aop-beans.xml"/>

</beans>


text:
package com.intellij.vcs.log.ui.render;

import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.ui.GraphicsUtil;
import com.intellij.util.ui.ImageUtil;
import com.intellij.util.ui.StartupUiUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.image.BufferedImage;
import java.util.List;

public class LabelIcon implements Icon {
  public static final float SIZE = 6.25f;
  private final int mySize;
  @NotNull private final List<? extends Color> myColors;
  @NotNull private final Color myBgColor;
  @NotNull private BufferedImage myImage;

  public LabelIcon(@NotNull JComponent component, int size, @NotNull Color bgColor, @NotNull List<? extends Color> colors) {
    mySize = size;
    myBgColor = bgColor;
    myColors = colors;
    myImage = createImage(component, null);
  }

  private BufferedImage createImage(Component c, Graphics2D g) {
    BufferedImage image = c != null ?
                          ImageUtil.createImage(c.getGraphicsConfiguration(), getIconWidth(), getIconHeight(), BufferedImage.TYPE_INT_ARGB)
                                    : ImageUtil.createImage(g, getIconWidth(), getIconHeight(), BufferedImage.TYPE_INT_ARGB);
    paintIcon(image.createGraphics());
    return image;
  }

  @Override
  public void paintIcon(Component c, Graphics g, int x, int y) {
    if (ImageUtil.getImageScale(myImage) != JBUIScale.sysScale((Graphics2D)g)) {
      myImage = createImage(null, (Graphics2D)g);
    }
    StartupUiUtil.drawImage(g, myImage, x, y, null);
  }

  private void paintIcon(@NotNull Graphics2D g2) {
    GraphicsConfig config = GraphicsUtil.setupAAPainting(g2);

    float scale = mySize / SIZE;

    for (int i = myColors.size() - 1; i >= 0; i--) {
      if (i != myColors.size() - 1) {
        g2.setColor(myBgColor);
        paintTag(g2, scale, scale * 2 * i + 1, 0);
      }
      g2.setColor(myColors.get(i));
      paintTag(g2, scale, scale * 2 * i, 0);
    }

    config.restore();
  }

  public void paintTag(Graphics2D g2, float scale, float x, float y) {
    Path2D.Float path = new Path2D.Float();
    x += scale * 0.25;
    y += scale;
    path.moveTo(x, y);
    path.lineTo(x + 2 * scale, y);
    path.lineTo(x + 5 * scale, y + 3 * scale);
    path.lineTo(x + 3 * scale, y + 5 * scale);
    path.lineTo(x, y + 2 * scale);
    path.lineTo(x, y);
    path.closePath();
    Ellipse2D hole = new Ellipse2D.Float(x + 1 * scale, y + 1 * scale, scale, scale);
    Area area = new Area(path);
    area.subtract(new Area(hole));
    g2.fill(area);
  }

  @Override
  public int getIconWidth() {
    return getWidth(myColors.size());
  }

  protected int getWidth(int labelsCount) {
    return getWidth(mySize, labelsCount);
  }

  public static int getWidth(int height, int labelsCount) {
    float scale = height / SIZE;
    return Math.round((SIZE + 2 * (labelsCount - 1)) * scale);
  }

  @Override
  public int getIconHeight() {
    return mySize;
  }
}


text:
package org.wso2.carbon.identity.sts.passive;

public class ResponseToken {

    // This required parameter specifies the result of the token issuance. This can take
    // the form of the <wsse:RequestSecurityTokenResponse> element, a SOAP
    // security token request response (that is, a <S:Envelope>) as detailed in WSTrust,
    // or a SOAP <S:Fault> element.
    private String results;

    // This optional parameter specifies the context information (if any) passed in with
    // the request. It should be noted that this parameter specifies the context
    // information (if any) passed in with the original request.
    private String context;

    // This parameter specifies a URL to which an HTTP GET can be issued. The result
    // is a document of type text/xml that contains the issuance result. This can either
    // be the <wsse:RequestSecurityTokenResopnse> element, a SOAP response, or a
    // SOAP <S:Fault> element.
    private String responsePointer;

    private String replyTo;

    private boolean authenticated;

    public String getReplyTo() {
        return replyTo;
    }

    public void setReplyTo(String replyTo) {
        this.replyTo = replyTo;
    }

    public boolean isAuthenticated() {
        return authenticated;
    }

    public void setAuthenticated(boolean authenticated) {
        this.authenticated = authenticated;
    }

    public String getResults() {
        return results;
    }

    public void setResults(String results) {
        this.results = results;
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }

    public String getResponsePointer() {
        return responsePointer;
    }

    public void setResponsePointer(String responsePointer) {
        this.responsePointer = responsePointer;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>fi.nls.oskari</groupId>
		<artifactId>oskari-parent</artifactId>
        <version>1.26</version>
	</parent>
	<groupId>fi.nls.oskari.service</groupId>
	<artifactId>oskari-search-nls</artifactId>
	<packaging>jar</packaging>
	<name>NLS Search Service</name>
	<dependencies>
		<dependency>
			<groupId>fi.nls.oskari.service</groupId>
			<artifactId>oskari-base</artifactId>
		</dependency>
		<dependency>
			<groupId>fi.nls.oskari.service</groupId>
			<artifactId>oskari-permissions</artifactId>
		</dependency>
		<dependency>
			<groupId>fi.nls.oskari.service</groupId>
			<artifactId>oskari-search</artifactId>
		</dependency>
		<dependency>
			<groupId>fi.nls.oskari.service</groupId>
			<artifactId>oskari-control-base</artifactId>
		</dependency>
       <dependency>
			<groupId>org.geotools</groupId>
			<artifactId>gt-epsg-hsql</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.xml</groupId>
			<artifactId>jsr173</artifactId>
		</dependency>

		<dependency>
			<groupId>java3d</groupId>
			<artifactId>vecmath</artifactId>
		</dependency>

		<dependency>
			<groupId>fi.mml</groupId>
			<artifactId>nameregister</artifactId>
		</dependency>

        <dependency>
            <groupId>org.deegree</groupId>
            <artifactId>deegree</artifactId>
        </dependency>

        <dependency>
            <groupId>fi.nls.oskari</groupId>
            <artifactId>shared-test-resources</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>xml-apis</groupId>
            <artifactId>xml-apis</artifactId>
            <version>1.4.01</version>
            <scope>test</scope>
        </dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.14</version>
		</dependency>

	</dependencies>
</project>


text:
// -*- C++ -*-

//==========================================================================
/**
 *  @file    Thread_Mutex.h
 *
 *  $Id: Thread_Mutex.h 92060 2010-09-27 18:08:48Z johnnyw $
 *
 *   Moved from Synch.h.
 *
 *  @author Douglas C. Schmidt <schmidt@cs.wustl.edu>
 */
//==========================================================================

#ifndef ACE_THREAD_MUTEX_H
#define ACE_THREAD_MUTEX_H
#include /**/ "ace/pre.h"

#include /**/ "ace/config-all.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#if !defined (ACE_HAS_THREADS)
#  include "ace/Null_Mutex.h"
#else /* ACE_HAS_THREADS */
// ACE platform supports some form of threading.

#include /**/ "ace/ACE_export.h"
#include "ace/OS_NS_Thread.h"

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

/**
 * @class ACE_Thread_Mutex
 *
 * @brief ACE_Thread_Mutex wrapper (only valid for threads in the same
 * process).
 *
 * This implementation is optimized for locking threads that are
 * in the same process.  It maps to <CRITICAL_SECTION>s on NT
 * and <ACE_mutex_t> with <type> set to <USYNC_THREAD> on UNIX.
 * ACE_Thread_Mutex is recursive on some platforms (like
 * Win32). However, on most platforms (like Solaris) it is not
 * recursive.  To be totally safe and portable, developers
 * should use ACE_Recursive_Thread_Mutex when they need a
 * recursive mutex.
 */
class ACE_Export ACE_Thread_Mutex
{
  friend class ACE_Condition_Thread_Mutex;
public:
  /// Constructor.
  ACE_Thread_Mutex (const ACE_TCHAR *name = 0,
                    ACE_mutexattr_t *attributes = 0);

  /// Implicitly destroy the mutex.
  ~ACE_Thread_Mutex (void);

  /**
   * Explicitly destroy the mutex.  Note that only one thread should
   * call this method since it doesn't protect against race
   * conditions.
   */
  int remove (void);

  /// Acquire lock ownership (wait on queue if necessary).
  int acquire (void);

  /**
   * Block the thread until we acquire the mutex or until @a tv times
   * out, in which case -1 is returned with @c errno == @c ETIME.  Note
   * that @a tv is assumed to be in "absolute" rather than "relative"
   * time.  The value of @a tv is updated upon return to show the
   * actual (absolute) acquisition time.
   */
  int acquire (ACE_Time_Value &tv);

  /**
   * If @a tv == 0 the call acquire() directly.  Otherwise, Block the
   * thread until we acquire the mutex or until @a tv times out, in
   * which case -1 is returned with @c errno == @c ETIME.  Note that
   * @a tv is assumed to be in "absolute" rather than "relative" time.
   * The value of @a tv is updated upon return to show the actual
   * (absolute) acquisition time.
   */
  int acquire (ACE_Time_Value *tv);

  /**
   * Conditionally acquire lock (i.e., don't wait on queue).  Returns
   * -1 on failure.  If we "failed" because someone else already had
   * the lock, @c errno is set to @c EBUSY.
   */
  int tryacquire (void);

  /// Release lock and unblock a thread at head of queue.
  int release (void);

  /**
   * Acquire mutex ownership.  This calls acquire() and is only here
   * to make the ACE_Thread_Mutex interface consistent with the
   * other synchronization APIs.
   */
  int acquire_read (void);

  /**
   * Acquire mutex ownership.  This calls acquire() and is only here
   * to make the ACE_Thread_Mutex interface consistent with the
   * other synchronization APIs.
   */
  int acquire_write (void);

  /**
   * Conditionally acquire mutex (i.e., won't block).  This calls
   * tryacquire() and is only here to make the ACE_Thread_Mutex
   * interface consistent with the other synchronization APIs.
   * Returns -1 on failure.  If we "failed" because someone else
   * already had the lock, @c errno is set to @c EBUSY.
   */
  int tryacquire_read (void);

  /**
   * Conditionally acquire mutex (i.e., won't block).  This calls
   * tryacquire() and is only here to make the ACE_Thread_Mutex
   * interface consistent with the other synchronization APIs.
   * Returns -1 on failure.  If we "failed" because someone else
   * already had the lock, @c errno is set to @c EBUSY.
   */
  int tryacquire_write (void);

  /**
   * This is only here to make the ACE_Thread_Mutex interface
   * consistent with the other synchronization APIs.  Assumes the
   * caller has already acquired the mutex using one of the above
   * calls, and returns 0 (success) always.
   */
  int tryacquire_write_upgrade (void);

  /// Return the underlying mutex.
  const ACE_thread_mutex_t &lock (void) const;
  ACE_thread_mutex_t &lock (void);

  /// Dump the state of an object.
  void dump (void) const;

  /// Declare the dynamic allocation hooks.
  ACE_ALLOC_HOOK_DECLARE;

protected:
  /// Mutex type that supports single-process locking efficiently.
  ACE_thread_mutex_t lock_;

  /// Keeps track of whether remove() has been called yet to avoid
  /// multiple <remove> calls, e.g., explicitly and implicitly in the
  /// destructor.  This flag isn't protected by a lock, so make sure
  /// that you don't have multiple threads simultaneously calling
  /// <remove> on the same object, which is a bad idea anyway...
  bool removed_;

private:
  // = Prevent assignment and initialization.
  void operator= (const ACE_Thread_Mutex &);
  ACE_Thread_Mutex (const ACE_Thread_Mutex &);
};

ACE_END_VERSIONED_NAMESPACE_DECL

#if defined (__ACE_INLINE__)
#include "ace/Thread_Mutex.inl"
#endif /* __ACE_INLINE__ */

#endif /* !ACE_HAS_THREADS */

#include /**/ "ace/post.h"
#endif /* ACE_THREAD_MUTEX_H */


text:
"""
References for BCD/EFI Boot Options
REPAIR BCD https://www.boyans.net/RepairWindows/RepairWindowsBCD.html

https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/bcd-system-store-settings-for-uefi
https://serverfault.com/questions/714337/changing-uefi-boot-order-from-windows

Get boot info via WMI
https://social.technet.microsoft.com/Forums/en-US/18094085-781f-4649-8ff8-331388097911/how-to-get-boot-configuration-data-bcd-information-out-of-wmi-with-powershell?forum=ITCG

Python - firmware_variables
https://github.com/netaneld122/firmware-variables

BCD Python Lib
https://github.com/trolldbois/bcdedit

Win32 example - bcd
https://github.com/sysprogs/BazisLib/blob/master/bzshlp/Win32/BCD.h

"""

import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import time
import datetime
import sys
import os
import logging
import random
from win32com.shell import shell, shellcon
import ntsecuritycon
import win32security
import win32api
import win32gui
import win32ui
import win32con
import win32gui_struct
import win32ts
import PIL
import pyscreenshot as ImageGrab

ROOT_FOLDER = os.path.join(shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, None, 0), "ope")
TMP_FOLDER = os.path.join(ROOT_FOLDER, "tmp")
LOG_FOLDER = os.path.join(TMP_FOLDER, "log")
SCREEN_SHOTS_FOLDER = os.path.join(TMP_FOLDER, "screen_shots")
BINARIES_FOLDER = os.path.join(ROOT_FOLDER, "ope_laptop_binaries")

EVERYONE, domain, type = win32security.LookupAccountName("", "Everyone")
ADMINISTRATORS, domain, type = win32security.LookupAccountName("", "Administrators")
# CURRENT_USER, domain, type = win32security.LookupAccountName("", win32api.GetUserName())
CURRENT_USER = None
try:
    CURRENT_USER, domain, type = win32security.LookupAccountName("", "huskers")
except:
    CURRENT_USER = None
if CURRENT_USER is None:
    try:
        CURRENT_USER, domain, type = win32security.LookupAccountName("", "ray")
    except:
        CURRENT_USER = None
SYSTEM_USER, domain, type = win32security.LookupAccountName("", "System")

# Setup loggin
logging.basicConfig(
    filename = os.path.join(LOG_FOLDER, 'ope-service-test.log'),
    level = logging.DEBUG,
    format = '[ope-service] %(levelname)-7.7s %(message)s'
)

def show_cacls(filename):
    print
    print
    for line in os.popen("cacls %s" % filename).read().splitlines():
        print line

def make_data_folder(folder):
    try:
        os.makedirs(folder)
    except:
        pass

    # Set permissions on this folder so that it isn't viewable by students
    sd = win32security.GetFileSecurity(folder, win32security.DACL_SECURITY_INFORMATION)

    # Create the blank DACL and add our ACE's
    dacl = win32security.ACL()
    #dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_GENERIC_READ, EVERYONE)
    #dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_WRITE, CURRENT_USER)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, ADMINISTRATORS)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, SYSTEM_USER)

    # Set our ACL
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(folder, win32security.DACL_SECURITY_INFORMATION, sd)

def grabScreenShot():
    # Grab the screen shot and save it to the logs folder
    # Get the hwnd for the current desktop window
    try:

        #hwnd = win32gui.GetDesktopWindow()
        hwnd = getDesktopWindow()
        l, t, r, b = win32gui.GetWindowRect(hwnd)
        w = r - l
        h = b - t
        logging.info("SC - HWND " + str(hwnd) + " " + str(w) + "/" + str(h))

        dc = win32gui.GetDC(win32con.HWND_DESKTOP)
        logging.info("DC " + str(dc))

        dcObj = win32ui.CreateDCFromHandle(dc)
        drawDC = dcObj.CreateCompatibleDC()
        logging.info("drawDC " + str(drawDC))

        #cDC = dcObj.CreateCompatibleDC() # Do we need this since it is the desktop dc?
        bm = win32ui.CreateBitmap()
        bm.CreateCompatibleBitmap(dcObj, w, h)
        drawDC.SelectObject(bm)
        drawDC.BitBlt((0, 0), (w, h), dcObj, (0, 0), win32con.SRCCOPY)

        bm.SaveBitmapFile(drawDC, os.path.join(SCREEN_SHOTS_FOLDER, "test.jpeg"))

        win32gui.DeleteObject(bm.GetHandle())
        drawDC.DeleteDC()
        dcObj.DeleteDC()
        win32gui.ReleaseDC(win32con.HWND_DESKTOP, dc)

        # dc = win32gui.GetWindowDC(hwnd)
        # logging.info("DC " + str(dc))
        # dcObj = win32ui.CreateDCFromHandle(dc)
        # logging.info("dcObj " + str(dcObj))
        # cDC = dcObj.CreateCompatibleDC()
        # logging.info("cDC " + str(cDC))
        # bm = win32ui.CreateBitmap()
        # logging.info("bm " + str(bm))
        # bm.CreateCompatibleBitmap(dcObj, w, h)
        # cDC.SelectObject(bm)
        # r = cDC.BitBlt((0,0), (w,h), dcObj, (0,0), win32con.SRCCOPY)
        # logging.info("bitblt " + str(r))
        # bm.SaveBitmapFile(cDC, os.path.join(SCREEN_SHOTS_FOLDER, "test.jpeg"))
        # dcObj.DeleteDC()
        # cDC.DeleteDC()
        # win32gui.ReleaseDC(hwnd, dc)
        #win32gui.DeleteObject(bm.GetHandle())
    except Exception as ex:
        logging.info("Error grabbing screenshot: " + str(ex))

    #m = ImageGrab.grab()

    # Save the file
    #p = os.path.join(SCREEN_SHOTS_FOLDER, str(datetime.datetime.now()) + ".png")
    #im.save(p, optimize=True)

def getDesktopWindow():
    console_id = win32ts.WTSGetActiveConsoleSessionId()
    if console_id == 0xffffffff:
        # User not logged in right now?
        logging.info("No console user")
        return None

    hwnd = None

    # Get processes running on this console
    svr = win32ts.WTSOpenServer(".")
    ps_list = win32ts.WTSEnumerateProcesses(svr, 1, 0)
    for ps in ps_list:
        logging.info("PS " + str(ps))
    win32ts.WTSCloseServer(svr)
    # sessions = win32ts.WTSEnumerateSessions(None, 1, 0)
    # for session in win32ts.WTSEnumerateSessions(win32ts.WTS_CURRENT_SERVER_HANDLE, 1, 0):
    #         print "SessionId: %s" % session['SessionId']
    #         print "\tWinStationName: %s" % session['WinStationName']
    #         print "\tState: %s" % session['State']
    #         print
    #         if session["WinStationName"] == "Console":
    #             cs = session

    #if cs is not None:
    #    # Get process list for this session
    return hwnd

#cs = getDesktopWindow()
#grabScreenShot()
#print cs

# Make the folders
#make_data_folder(LOG_FOLDER)
#make_data_folder(SCREEN_SHOTS_FOLDER)

# Clear current permissions, inheritance, and add system/admins back on

# Setup entries
# entries = [{'AccessMode': win32security.GRANT_ACCESS,
            # 'AccessPermissions': 0,
            # 'Inheritance': win32security.CONTAINER_INHERIT_ACE |
                           # win32security.OBJECT_INHERIT_ACE,
            # 'Trustee': {'TrusteeType': win32security.TRUSTEE_IS_USER,
                        # 'TrusteeForm': win32security.TRUSTEE_IS_NAME,
                        # 'Identifier': ''}}
            # for i in range(2)]

#Add our entries
# entries[0]['AccessPermissions'] = (ntsecuritycon.GENERIC_READ |
                                   # ntsecuritycon.GENERIC_WRITE)
# entries[0]['Trustee']['Identifier'] = USERX
# entries[1]['AccessPermissions'] = ntsecuritycon.GENERIC_ALL
# entries[1]['Trustee']['Identifier'] = "Administrators"

#HDC desktopDC = GetDC( HWND_DESKTOP ) ;

#// or
#HDC desktopDC2 = GetDC( NULL ) ;

#// or
#HDC desktopDC3 = GetDC( 0 ) ;

#// same diff

#// don't forget to
#ReleaseDC( HWND_DESKTOP, desktopDC ) ;
#// when you're done!

def set_ope_permissions():
    global ROOT_FOLDER, LOG_FOLDER, SCREEN_SHOTS_FOLDER, BINARIES_FOLDER, TMP_FOLDER

    # Make sure folders exits
    if not os.path.isdir(ROOT_FOLDER):
        os.makedirs(ROOT_FOLDER)
    if not os.path.isdir(TMP_FOLDER):
        os.makedirs(TMP_FOLDER)
    if not os.path.isdir(LOG_FOLDER):
        os.makedirs(LOG_FOLDER)
    if not os.path.isdir(SCREEN_SHOTS_FOLDER):
        os.makedirs(SCREEN_SHOTS_FOLDER)
    if not os.path.isdir(BINARIES_FOLDER):
        os.makedirs(BINARIES_FOLDER)

    # Make sure the ope-sshot.log file exists so we can set permissions on it later
    if not os.path.isfile(os.path.join(LOG_FOLDER, "ope-sshot.log")):
        f = open(os.path.join(LOG_FOLDER, "ope-sshot.log"), "w")
        f.close()

    # --- Set permissions on OPE folder - viewable by not writable
    # Set inheritance flags
    flags = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE
    sd = win32security.GetFileSecurity(ROOT_FOLDER, win32security.DACL_SECURITY_INFORMATION)
    # Create the blank DACL and add our ACE's
    dacl = win32security.ACL()
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, ADMINISTRATORS)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, SYSTEM_USER)
    if not CURRENT_USER is None:
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, CURRENT_USER)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags,
                               ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE,
                               EVERYONE)
    # Set our ACL
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(ROOT_FOLDER, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)

    # --- Set permissions on TMP folder - viewable by not writable
    # Set inheritance flags
    flags = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE
    sd = win32security.GetFileSecurity(TMP_FOLDER, win32security.DACL_SECURITY_INFORMATION)
    # Create the blank DACL and add our ACE's
    dacl = win32security.ACL()
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, ADMINISTRATORS)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, SYSTEM_USER)
    if not CURRENT_USER is None:
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, CURRENT_USER)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags,
                               ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE,
                               EVERYONE)
    # Set our ACL
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(TMP_FOLDER, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)

    # --- Set permissions on ope_laptop_binaries folder - viewable by not writable
    # Set inheritance flags
    flags = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE
    sd = win32security.GetFileSecurity(BINARIES_FOLDER, win32security.DACL_SECURITY_INFORMATION)
    # Create the blank DACL and add our ACE's
    dacl = win32security.ACL()
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, ADMINISTRATORS)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, SYSTEM_USER)
    if not CURRENT_USER is None:
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, CURRENT_USER)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags,
                               ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE,
                               EVERYONE)
    # Set our ACL
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    # Set on all folders
    win32security.SetFileSecurity(BINARIES_FOLDER, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)
    for root, dirs, files in os.walk(BINARIES_FOLDER, topdown=False):
        for f in files:
            try:
                win32security.SetFileSecurity(os.path.join(root, f), win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)
            except:
                logging.info("Error setting file permissions " + os.path.join(root, f))
        for d in dirs:
            try:
                win32security.SetFileSecurity(os.path.join(root, d), win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)
            except:
                logging.info("Error setting folder permissions " + os.path.join(root, d))

    # win32security.TreeSetNamedSecurityInfo(BINARIES_FOLDER, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, None, None, sd, None)

    # --- Set permissions on the log folder - create file or append only
    # Set inheritance flags
    flags = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE
    sd = win32security.GetFileSecurity(LOG_FOLDER, win32security.DACL_SECURITY_INFORMATION)
    # Create the blank DACL and add our ACE's
    dacl = win32security.ACL()
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, ADMINISTRATORS)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, SYSTEM_USER)
    if not CURRENT_USER is None:
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, CURRENT_USER)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, flags,
                             ntsecuritycon.FILE_ADD_FILE | ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE,
                             EVERYONE)
    # Set our ACL
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(LOG_FOLDER, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)

    # --- Set permissions on the log file for screen shots - append only
    # Set inheritance flags
    flags = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE
    sd = win32security.GetFileSecurity(os.path.join(LOG_FOLDER, "ope-sshot.log"), win32security.DACL_SECURITY_INFORMATION)
    # Create the blank DACL and add our ACE's
    dacl = win32security.ACL()
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, ADMINISTRATORS)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, SYSTEM_USER)
    if not CURRENT_USER is None:
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, CURRENT_USER)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, flags,
                             ntsecuritycon.FILE_APPEND_DATA | ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE,
                             EVERYONE)
    # Set our ACL
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(os.path.join(LOG_FOLDER, "ope-sshot.log"), win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)

    # --- Set permissions on the sshot folder - let students create but not modify/delete sshots
    # Set inheritance flags
    flags = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE
    sd = win32security.GetFileSecurity(SCREEN_SHOTS_FOLDER, win32security.DACL_SECURITY_INFORMATION)

    # Create the blank DACL and add our ACE's
    dacl = win32security.ACL()
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, ADMINISTRATORS)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, SYSTEM_USER)
    if not CURRENT_USER is None:
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, CURRENT_USER)
    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, flags,
                             ntsecuritycon.FILE_ADD_FILE  | ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE,
                             EVERYONE)
    # Set our ACL
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(SCREEN_SHOTS_FOLDER, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)

    # Possible to set whole tree?
    # win32security.TreeSetNamedSecurityInfo(folder, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, None, None, sd, None)

set_ope_permissions()