text:
require 'rails_helper'

describe CampaignsController, type: :request do
  describe '#index' do
    it 'renders a 200' do
      get '/campaigns'
      expect(response.status).to eq(200)
    end
  end

  describe '#create' do
    let(:user) { create(:user) }
    let(:admin) { create(:admin) }
    let(:title) { 'My New? Campaign 5!' }
    let(:expected_slug) { 'my_new_campaign_5' }
    let(:campaign_params) do
      { campaign: { title:,
                    default_passcode: 'custom',
                    custom_default_passcode: 'ohai' } }
    end

    context 'when user is an admin' do
      before do
        allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin)
      end

      it 'creates new campaigns with custom passcodes' do
        post '/campaigns', params: campaign_params
        new_campaign = Campaign.last
        expect(new_campaign.slug).to eq(expected_slug)
        expect(new_campaign.default_passcode).to eq('ohai')
      end

      it 'creates a campaign user for the current user' do
        post '/campaigns', params: campaign_params
        expect(CampaignsUsers.last.user_id).to eq(admin.id)
      end

      it 'does not create duplicate titles' do
        Campaign.create(title:, slug: 'foo')
        post '/campaigns', params: campaign_params
        expect(Campaign.last.slug).to eq('foo')
      end

      it 'does not create duplicate slugs' do
        Campaign.create(title: 'foo', slug: expected_slug)
        post '/campaigns', params: campaign_params
        expect(Campaign.last.title).to eq('foo')
      end
    end

    context 'when user is not an admin and feature flag is off' do
      before do
        allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
        allow(Features).to receive(:open_course_creation?).and_return(false)
      end

      it 'returns a 401 and does not create a campaign' do
        post '/campaigns', params: campaign_params
        expect(response.status).to eq(401)
        expect(Campaign.count).to eq(1)
      end
    end
  end

  describe '#update' do
    let(:user) { create(:user) }
    let(:admin) { create(:admin) }
    let(:campaign) { create(:campaign) }
    let(:description) { 'My new campaign is the best campaign ever!' }
    let(:campaign_params) { { slug: campaign.slug, description: } }
    let(:request_params) { { campaign: campaign_params, slug: campaign.slug } }

    it 'returns a 401 if the user is not an admin and not an organizer of the campaign' do
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      delete "/campaigns/#{campaign.slug}", params: request_params
      expect(response.status).to eq(401)
    end

    it 'updates the campaign if the user is an organizer of the campaign' do
      create(:campaigns_user, user_id: user.id, campaign_id: campaign.id,
                              role: CampaignsUsers::Roles::ORGANIZER_ROLE)
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      put "/campaigns/#{campaign.slug}", params: request_params
      expect(response.status).to eq(302) # redirect to /overview
      expect(campaign.reload.description).to eq(description)
    end

    it 'updates the campaign if the user is an admin' do
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin)
      put "/campaigns/#{campaign.slug}", params: request_params
      expect(response.status).to eq(302) # redirect to /overview
      expect(campaign.reload.description).to eq(description)
    end
  end

  describe '#destroy' do
    let(:user) { create(:user) }
    let(:admin) { create(:admin) }
    let(:campaign) { create(:campaign) }
    let(:request_params) { { slug: campaign.slug } }

    it 'returns a 401 if the user is not an admin and not an organizer of the campaign' do
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      delete "/campaigns/#{campaign.slug}", params: request_params
      expect(response.status).to eq(401)
      expect(Campaign.find_by(slug: campaign.slug)).not_to be_nil
    end

    it 'deletes the campaign if the user is a campaign organizer' do
      create(:campaigns_user, user_id: user.id, campaign_id: campaign.id,
                              role: CampaignsUsers::Roles::ORGANIZER_ROLE)
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      delete "/campaigns/#{campaign.slug}", params: request_params
      expect(response.status).to eq(302) # redirect to /campaigns
      expect(Campaign.find_by(slug: campaign.slug)).to be_nil
    end
  end

  describe '#add_organizer' do
    let(:user) { create(:user) }
    let(:admin) { create(:admin) }
    let(:campaign) { create(:campaign) }

    it 'returns a 401 if the user is not an admin and not an organizer of the campaign' do
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      request_params = { slug: campaign.slug, username: 'MusikAnimal' }
      put "/campaigns/#{campaign.slug}/add_organizer", params: request_params
      expect(response.status).to eq(401)
      expect(Campaign.find_by(slug: campaign.slug)).not_to be_nil
    end

    it 'adds the given user as an organizer of the campaign '\
       'if the current user is a campaign organizer' do
      create(:campaigns_user, user_id: user.id, campaign_id: campaign.id,
                              role: CampaignsUsers::Roles::ORGANIZER_ROLE)
      user2 = create(:user, username: 'MusikAnimal')
      request_params = { slug: campaign.slug, username: user2.username }
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      put "/campaigns/#{campaign.slug}/add_organizer", params: request_params
      expect(response.status).to eq(302) # redirect to /overview
      expect(CampaignsUsers.last.user_id).to eq(user2.id)
    end
  end

  describe '#remove_organizer' do
    let(:user) { create(:user) }
    let(:user2) { create(:user, username: 'user2') }
    let(:campaign) { create(:campaign) }
    let(:request_params) { { slug: campaign.slug, id: organizer.user_id } }
    let(:organizer) do
      create(:campaigns_user, user_id: user2.id, campaign_id: campaign.id,
                              role: CampaignsUsers::Roles::ORGANIZER_ROLE)
    end

    it 'returns a 401 if the user is not an admin and not an organizer of the campaign' do
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      put "/campaigns/#{campaign.slug}/remove_organizer", params: request_params
      expect(response.status).to eq(401)
      expect(CampaignsUsers.find_by(id: organizer.id)).not_to be_nil
    end

    it 'removes the given organizer from the campaign '\
       'if the current user is a campaign organizer' do
      create(:campaigns_user, user_id: user.id, campaign_id: campaign.id,
                              role: CampaignsUsers::Roles::ORGANIZER_ROLE)
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      put "/campaigns/#{campaign.slug}/remove_organizer", params: request_params
      expect(response.status).to eq(302) # redirect to /overview
      expect(CampaignsUsers.find_by(id: organizer.id)).to be_nil
    end
  end

  describe '#remove_course' do
    let(:user) { create(:user) }
    let(:campaign) { create(:campaign) }
    let(:course) { create(:course) }
    let(:request_params) { { slug: campaign.slug, course_id: course.id } }
    let!(:campaigns_course) do
      create(:campaigns_course, campaign_id: campaign.id,
                                course_id: course.id)
    end

    it 'returns a 401 if the user is not an admin and not an organizer of the campaign' do
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      put "/campaigns/#{campaign.slug}/remove_course", params: request_params
      expect(response.status).to eq(401)
      expect(CampaignsCourses.find_by(id: campaigns_course.id)).not_to be_nil
    end

    it 'removes the course from the campaign if the current user is a campaign organizer' do
      create(:campaigns_user, user_id: user.id, campaign_id: campaign.id,
                              role: CampaignsUsers::Roles::ORGANIZER_ROLE)
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      put "/campaigns/#{campaign.slug}/remove_course", params: request_params
      expect(response.status).to eq(302) # redirect to /overview
      expect(CampaignsCourses.find_by(id: campaigns_course.id)).to be_nil
    end
  end

  describe '#users.json' do
    let(:course) { create(:course) }
    let(:campaign) { create(:campaign) }
    let(:student) { create(:user) }
    let(:instructor) { create(:user, username: 'Dr. Instructor') }

    before do
      campaign.courses << course
      create(:courses_user, course_id: course.id, user_id: student.id,
                            role: CoursesUsers::Roles::STUDENT_ROLE)
      create(:courses_user, course_id: course.id, user_id: instructor.id,
                            role: CoursesUsers::Roles::INSTRUCTOR_ROLE)
    end

    it 'returns list of students and instructors' do
      get "/campaigns/#{campaign.slug}/users", params: { format: :json }
      expect(response.body).to include(student.username)
      expect(response.body).to include('Editor')
      expect(response.body).to include(instructor.username)
      expect(response.body).to include('Facilitator')
      expect(response.body).to include(course.slug)
      expect(response.body).to include(campaign.slug)
    end
  end

  describe '#assignments.json' do
    let(:course) { create(:course) }
    let(:campaign) { create(:campaign) }
    let(:student) { create(:user) }
    let(:article) { create(:article, title: 'Selfie') }

    before do
      campaign.courses << course
      create(:assignment, course:, user: student, article_title: 'Music',
             role: Assignment::Roles::ASSIGNED_ROLE)
      create(:assignment, course:, user: student, article_title: 'Selfie',
             article:, role: Assignment::Roles::REVIEWING_ROLE)
    end

    it 'returns list of students and instructors' do
      get "/campaigns/#{campaign.slug}/assignments", params: { format: :json }
      expect(response.body).to include(student.username)
      expect(response.body).to include('Editing')
      expect(response.body).to include('Reviewing')
      expect(response.body).to include(course.slug)
      expect(response.body).to include(campaign.slug)
      expect(response.body).to include(article.title)
      expect(response.body).to include('Music')
    end
  end

  describe '#students' do
    let(:course) { create(:course) }
    let(:campaign) { create(:campaign) }
    let(:student) { create(:user) }

    before do
      login_as build(:user)
      campaign.courses << course
      create(:courses_user, course_id: course.id, user_id: student.id,
                            role: CoursesUsers::Roles::STUDENT_ROLE)
    end

    after do
      FileUtils.remove_dir('public/system/analytics')
    end

    context 'without "course" option' do
      let(:request_params) { { slug: campaign.slug, format: :csv } }

      it 'returns a csv of student usernames' do
        expect(CsvCleanupWorker).to receive(:perform_at)
        get "/campaigns/#{campaign.slug}/students", params: request_params
        expect(response.body).to include('file is being generated')
        get "/campaigns/#{campaign.slug}/students", params: request_params
        follow_redirect!
        csv = response.body.force_encoding('utf-8')
        expect(csv).to include(student.username)
      end
    end

    context 'with "course" option' do
      let(:request_params) { { slug: campaign.slug, course: true, format: :csv } }

      it 'returns a csv of student usernames with course slugs' do
        expect(CsvCleanupWorker).to receive(:perform_at)
        get "/campaigns/#{campaign.slug}/students", params: request_params
        expect(response.body).to include('file is being generated')
        get "/campaigns/#{campaign.slug}/students", params: request_params
        follow_redirect!
        csv = response.body.force_encoding('utf-8')
        expect(csv).to include(student.username)
        expect(csv).to include(course.slug)
      end
    end
  end

  describe '#instructors' do
    let(:course) { create(:course) }
    let(:campaign) { create(:campaign) }
    let(:instructor) { create(:user) }

    before do
      login_as instructor
      campaign.courses << course
      create(:courses_user, course_id: course.id, user_id: instructor.id,
                            role: CoursesUsers::Roles::INSTRUCTOR_ROLE)
    end

    after do
      FileUtils.remove_dir('public/system/analytics')
    end

    context 'without "course" option' do
      let(:request_params) { { slug: campaign.slug, format: :csv } }

      it 'returns a csv of instructor usernames' do
        expect(CsvCleanupWorker).to receive(:perform_at)
        get "/campaigns/#{campaign.slug}/instructors", params: request_params
        expect(response.body).to include('file is being generated')
        get "/campaigns/#{campaign.slug}/instructors", params: request_params
        follow_redirect!
        expect(response.body).to include(instructor.username)
      end
    end

    context 'with "course" option' do
      let(:request_params) { { slug: campaign.slug, course: true, format: :csv } }

      it 'returns a csv of instructor usernames with course slugs' do
        expect(CsvCleanupWorker).to receive(:perform_at)
        get "/campaigns/#{campaign.slug}/instructors", params: request_params
        expect(response.body).to include('file is being generated')
        get "/campaigns/#{campaign.slug}/instructors", params: request_params
        follow_redirect!
        csv = response.body.force_encoding('utf-8')
        expect(csv).to include(instructor.username)
        expect(csv).to include(course.slug)
      end
    end
  end

  describe '#courses' do
    let(:course) { create(:course, user_count: 1) }
    let(:campaign) { create(:campaign) }
    let(:instructor) { create(:user) }
    let(:request_params) { { slug: campaign.slug, format: :csv } }

    before do
      login_as instructor
      campaign.courses << course
      create(:courses_user, course_id: course.id, user_id: instructor.id,
                            role: CoursesUsers::Roles::INSTRUCTOR_ROLE)
    end

    after do
      FileUtils.remove_dir('public/system/analytics')
    end

    it 'returns a csv of course data' do
      expect(CsvCleanupWorker).to receive(:perform_at)
      get "/campaigns/#{campaign.slug}/courses", params: request_params
      get "/campaigns/#{campaign.slug}/courses", params: request_params
      follow_redirect!
      csv = response.body.force_encoding('utf-8')
      expect(csv).to include(course.slug)
      expect(csv).to include(course.title)
      expect(csv).to include(course.school)
    end

    it 'cleans up the files afterwards' do
      # This normally happens long afterwards, but in test mode
      # sidekiq will execute all jobs immediately, so the file
      # will be created and immediately deleted.
      expect(CsvCleanupWorker).to receive(:perform_at).and_call_original
      get "/campaigns/#{campaign.slug}/courses", params: request_params
      expect(response.body).to include('file is being generated')
    end
  end

  describe 'CSV actions' do
    let(:wikidata) { Wiki.get_or_create(language: nil, project: 'wikidata') }
    let(:course) { create(:course) }
    let(:another_course) { create(:course, home_wiki: wikidata, slug: 'campaign/acourse') }
    let(:campaign) { create(:campaign) }
    let(:article) { create(:article) }
    let(:user) { create(:user) }
    let!(:revision) { create(:revision, article:, user:, date: course.start + 1.hour) }
    let!(:course_stats) do
      create(:course_stats, stats_hash: { 'www.wikidata.org' => {
               'claims created' => 12, 'other updates' => 1, 'unknown' => 1
             } },
             course:)
    end
    let(:request_params) { { slug: campaign.slug, format: :csv } }

    before do
      stub_wiki_validation
      login_as(user)
      campaign.courses.push course, another_course
      create(:courses_user, course:, user:)
    end

    after do
      FileUtils.remove_dir('public/system/analytics')
    end

    it 'return a csv of article data' do
      expect(CsvCleanupWorker).to receive(:perform_at)
      get "/campaigns/#{campaign.slug}/articles_csv", params: request_params
      get "/campaigns/#{campaign.slug}/articles_csv", params: request_params
      follow_redirect!
      csv = response.body.force_encoding('utf-8')
      expect(csv).to include(course.slug)
      expect(csv).to include(article.title)
    end

    it 'return a csv of revision data' do
      expect(CsvCleanupWorker).to receive(:perform_at)
      get "/campaigns/#{campaign.slug}/revisions_csv", params: request_params
      get "/campaigns/#{campaign.slug}/revisions_csv", params: request_params
      follow_redirect!
      csv = response.body.force_encoding('utf-8')
      expect(csv).to include(course.slug)
      expect(csv).to include(article.title)
      expect(csv).to include('references_added')
    end

    it 'returns a csv of wikidata' do
      expect(CsvCleanupWorker).to receive(:perform_at)
      get "/campaigns/#{campaign.slug}/wikidata.csv"
      get "/campaigns/#{campaign.slug}/wikidata.csv"
      follow_redirect!
      csv = response.body.force_encoding('utf-8')
      expect(csv).to include('course name,claims created')
    end
  end

  describe '#overview' do
    let(:user) { create(:user) }
    let(:campaign) { create(:campaign, description: 'New description') }

    before do
      create(:campaigns_user, user_id: user.id, campaign_id: campaign.id,
                              role: CampaignsUsers::Roles::ORGANIZER_ROLE)
      get "/campaigns/#{campaign.slug}/overview", params: { slug: campaign.slug }
    end

    it 'renders 200' do
      expect(response.status).to eq(200)
    end

    it 'shows the right campaign' do
      expect(response.body).to include(campaign.title)
    end

    it 'shows properties of the campaign' do
      expect(response.body).to include(campaign.description)
    end
  end

  describe '#programs' do
    let(:course) { create(:course) }
    let(:course2) { create(:course, title: 'course2', slug: 'foo/course2') }
    let(:campaign) { create(:campaign) }

    before do
      campaign.courses << course << course2
      get "/campaigns/#{campaign.slug}/programs", params: { slug: campaign.slug }
    end

    it 'renders 200' do
      expect(response.status).to eq(200)
    end

    it 'shows the right campaign' do
      expect(response.body).to include(campaign.title)
    end

    it 'lists the programs for the given campaign' do
      expect(response.body).to include(course.title)
      expect(response.body).to include(course2.title)
      expect(response.body).to include(course.school)
      expect(response.body).to include(course.term)
    end

    it 'shows a remove button for the programs if the user is an organizer or admin' do
      # don't show it if they are not an organizer or admin
      expect(response.body).not_to include(I18n.t('assignments.remove'))

      # when they are an organizer...
      user = create(:user)
      create(:campaigns_user, user_id: user.id, campaign_id: campaign.id,
                              role: CampaignsUsers::Roles::ORGANIZER_ROLE)
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
      get "/campaigns/#{campaign.slug}/programs", params: { slug: campaign.slug }
      expect(response.body).to include(I18n.t('assignments.remove'))

      # when they are an admin...
      admin = create(:admin)
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin)
      get "/campaigns/#{campaign.slug}/programs", params: { slug: campaign.slug }
      expect(response.body).to include(I18n.t('assignments.remove'))
    end

    it 'searches title, school, and term of campaign courses' do
      request_params = { slug: campaign.slug, courses_query: course.title }
      get "/campaigns/#{campaign.slug}/programs", params: request_params
      expect(response.body).to include(course.title)
    end
  end

  describe '#current_term' do
    it 'redirects to the corresponding subpage for the default term' do
      get '/current_term/articles'
      expect(response).to redirect_to '/campaigns/spring_2015/articles'
    end
  end
end


text:
package org.eclipse.cloudplatform.service.device.api;

import java.net.InetSocketAddress;
import java.util.*;

/**
 * Represents information about device registered in a cloud service.
 */
public class Device {

    private String id;

    private String deviceId;

    private String registrationId;

    private Date registrationDate;

    private Date lastUpdate;

    private String address;

    private int port;

    private InetSocketAddress registrationEndpointAddress;

    private long lifeTimeInSec;

    private List<LinkObject> objectLinks = new LinkedList<>();

    private Map<String, Object> properties = new HashMap<>();

    // Constructors

    public Device() {
    }

    public Device(String id, String deviceId, String registrationId, Date registrationDate, Date lastUpdate, String address, int port, InetSocketAddress registrationEndpointAddress, long lifeTimeInSec, List<LinkObject> objectLinks, Map<String, Object> properties) {
        this.id = id;
        this.deviceId = deviceId;
        this.registrationId = registrationId;
        this.registrationDate = registrationDate;
        this.lastUpdate = lastUpdate;
        this.address = address;
        this.port = port;
        this.registrationEndpointAddress = registrationEndpointAddress;
        this.lifeTimeInSec = lifeTimeInSec;
        this.objectLinks = objectLinks;
        this.properties = properties;
    }

    public static Device minimalDevice(String deviceId) {
        Device device = new Device();
        device.setDeviceId(deviceId);
        return device;
    }

    // Getters and setters

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }

    public String getRegistrationId() {
        return registrationId;
    }

    public void setRegistrationId(String registrationId) {
        this.registrationId = registrationId;
    }

    public Date getRegistrationDate() {
        return registrationDate;
    }

    public void setRegistrationDate(Date registrationDate) {
        this.registrationDate = registrationDate;
    }

    public Date getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(Date lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public InetSocketAddress getRegistrationEndpointAddress() {
        return registrationEndpointAddress;
    }

    public void setRegistrationEndpointAddress(InetSocketAddress registrationEndpointAddress) {
        this.registrationEndpointAddress = registrationEndpointAddress;
    }

    public long getLifeTimeInSec() {
        return lifeTimeInSec;
    }

    public void setLifeTimeInSec(long lifeTimeInSec) {
        this.lifeTimeInSec = lifeTimeInSec;
    }

    public List<LinkObject> getObjectLinks() {
        return objectLinks;
    }

    public void setObjectLinks(List<LinkObject> objectLinks) {
        this.objectLinks = objectLinks;
    }

    public Map<String, Object> getProperties() {
        return properties;
    }

    public void setProperties(Map<String, Object> properties) {
        this.properties = properties;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.github.andrewthehan.etude.theory;

import com.github.andrewthehan.etude.exception.EtudeException;
import com.github.andrewthehan.etude.util.Exceptional;

public enum Degree {
  TONIC, SUPERTONIC, MEDIANT, SUBDOMINANT, DOMINANT, SUBMEDIANT, LEADING_TONE;

  public static final int SIZE = Degree.values().length;

  public static final boolean isValid(int value) {
    return 1 <= value && value <= Degree.SIZE;
  }

  public static final Exceptional<Degree> fromValue(int value) {
    return Exceptional.of(value).filter(Degree::isValid, EtudeException.forInvalid(Degree.class, value, "out of range"))
        .map(i -> Degree.values()[i - 1]);
  }

  public final int getValue() {
    return ordinal() + 1;
  }
}


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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>rest-support</artifactId>
	<parent>
		<groupId>org.irods</groupId>
		<artifactId>base-service</artifactId>
		<version>4.2.1.0-SNAPSHOT</version>
	</parent>
	<packaging>jar</packaging>
	<name>Rest Support</name>
	<description>REST supporting libraries</description>
	<dependencies>
		<dependency>
			<groupId>org.irods.jargon</groupId>
			<artifactId>jargon-core</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
		</dependency>
	</dependencies>
</project>


text:
package com.example.tictactoe.baseboard

import com.example.tictactoe.InvalidPositionException
import com.example.tictactoe.player.PlayerMark
import com.example.tictactoe.baseboard.Board.Position

/**
 * @author s.a.ramamuniappa
 */
case class Square (val position: Position, marking: PlayerMark) {
  require(isValidPosition(position))
}


text:
{
    "title" : "How do I convert word document to a ISO 19005-1 (PDF/A) standard PDF file ? "
}

How do I convert word document to a ISO 19005-1 (PDF/A) standard PDF file ?
-

When converting a document to a pdf, by default Microsoft Word does not output a PDF/A (PDF Archive) file.  If you wish to use this format, you can specify the `--use-ISO190051` parameter and the pdf will be saved as PDF/A format and be self contained.  Please note however the file size may be larger.

This is the command line to use to output a pdf as iso 19005-1 format

Command Line
-

 ````
 docto -WD -f 'c:\path\' -o 'c:\output\' -t wdFormatPDF --use-ISO190051
 ````
 or easier to read
 ````
 docto  -WD
        -f 'c:\path\'
        -o 'c:\output\'
        -t wdFormatPDF
        --use-ISO190051
 ````

Command Line Explained
-

 - `{[$Params.appwd.cmd]}` :  {[$Params.appwd.desc]}
 - `{[$Params.dashf.cmd]}` :  {[$Params.dashf.desc]}
 - `{[$Params.dasho.cmd]}` :  {[$Params.dasho.desc]}
 - `{[$Params.dasht.cmd]}` :  {[$Params.dasht.desc]}
 - `{[$Params.dduseISO190051.cmd]}` :  {[$Params.dduseISO190051.desc]}

Some other interesting commands
-

You might find some of the following commands also interesting.

- [Convert all Word Document in a folder to a pdf file](ConvertDirDocToFilepdf.md);
{[foreach from=$Command.RelatedLinks key=LinkTitle item=L]}
 - [{[$LinkTitle]}]({[$L]})
{[/foreach]}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.apache.jmeter.testelement (Apache JMeter API)
</TITLE>

<META NAME="date" CONTENT="2014-11-05">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.jmeter.testelement

Interfaces

TestCloneable

TestElement

TestElementTraverser

TestIterationListener

TestListener

TestStateListener

ThreadListener

Classes

AbstractChart

AbstractScopedAssertion

AbstractScopedTestElement

AbstractTable

AbstractTestElement

AbstractTestElementBeanInfo

BarChart

JTLData

LineChart

OnErrorTestElement

ReportPage

ReportPlan

Table

TestPlan

VariablesCollection

WorkBench


text:
package org.bson;

import org.bson.codecs.BsonDocumentCodec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.json.JsonMode;
import org.bson.json.JsonReader;
import org.bson.json.JsonWriter;
import org.bson.json.JsonWriterSettings;
import org.junit.Test;

import java.io.StringWriter;
import java.util.Arrays;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

// Don't convert to Spock, as Groovy intercepts equals/hashCode methods that we are trying to test
public class BsonDocumentTest {
    private final BsonDocument emptyDocument = new BsonDocument();
    private final BsonDocument emptyRawDocument = new RawBsonDocument(emptyDocument, new BsonDocumentCodec());
    private final BsonDocument document = new BsonDocument()
                                    .append("a", new BsonInt32(1))
                                    .append("b", new BsonInt32(2))
                                    .append("c", new BsonDocument("x", BsonBoolean.TRUE))
                                    .append("d", new BsonArray(Arrays.asList(new BsonDocument("y",
                                                                                BsonBoolean.FALSE),
                                                                                new BsonInt32(1))));

    private final BsonDocument rawDocument = new RawBsonDocument(document, new BsonDocumentCodec());

    @Test
    public void shouldBeEqualToItself() {
        assertEquals(emptyDocument, emptyDocument);
        assertEquals(document, document);
    }

    @Test
    public void shouldBeEqualToEquivalentBsonDocument() {
        assertEquals(emptyDocument, emptyRawDocument);
        assertEquals(document, rawDocument);
        assertEquals(emptyRawDocument, emptyDocument);
        assertEquals(rawDocument, document);
    }

    @Test
    public void shouldNotBeEqualToDifferentBsonDocument() {
        // expect
        assertNotEquals(emptyDocument, document);
        assertNotEquals(document, emptyRawDocument);
        assertNotEquals(document, emptyRawDocument);
        assertNotEquals(emptyRawDocument, document);
        assertNotEquals(rawDocument, emptyDocument);
    }

    @Test
    public void shouldHaveSameHashCodeAsEquivalentBsonDocument() {
        assertEquals(emptyDocument.hashCode(), new BsonDocument().hashCode());
        assertEquals(emptyDocument.hashCode(), emptyRawDocument.hashCode());
        assertEquals(document.hashCode(), rawDocument.hashCode());
    }

    @Test
    public void toJsonShouldReturnEquivalent() {
        assertEquals(new BsonDocumentCodec().decode(new JsonReader(document.toJson()), DecoderContext.builder().build()),
                     document);
    }

    @Test
    public void toJsonShouldRespectDefaultJsonWriterSettings() {
        StringWriter writer = new StringWriter();
        new BsonDocumentCodec().encode(new JsonWriter(writer), document, EncoderContext.builder().build());
        assertEquals(writer.toString(), document.toJson());
    }

    @Test
    public void toJsonShouldRespectJsonWriterSettings() {
        StringWriter writer = new StringWriter();
        JsonWriterSettings settings = JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build();
        new BsonDocumentCodec().encode(new JsonWriter(writer, settings), document, EncoderContext.builder().build());
        assertEquals(writer.toString(), document.toJson(settings));
    }

    @Test
    public void toStringShouldEqualToJson() {
        assertEquals(document.toJson(), document.toString());
    }

    @Test
    public void shouldParseJson() {
        assertEquals(new BsonDocument("a", new BsonInt32(1)), BsonDocument.parse("{\"a\" : 1}"));
    }
}


text:
title: Hello world!
author: unfocused-admin
type: post
date: 2016-11-13T03:36:05+00:00
draft: true
url: /?p=5
categories:
  - Uncategorized

---
Welcome to WordPress. This is your first post. Edit or delete it, then start writing!


text:
<?php

namespace Symfony\Component\ExpressionLanguage\Tests\Fixtures;

use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\ExpressionLanguage\ExpressionPhpFunction;

class TestProvider implements ExpressionFunctionProviderInterface
{
    public function getFunctions()
    {
        return [
            new ExpressionFunction('identity', function ($input) {
                return $input;
            }, function (array $values, $input) {
                return $input;
            }),

            ExpressionFunction::fromPhp('strtoupper'),

            ExpressionFunction::fromPhp('\strtolower'),

            ExpressionFunction::fromPhp('Symfony\Component\ExpressionLanguage\Tests\Fixtures\fn_namespaced', 'fn_namespaced'),
        ];
    }
}

function fn_namespaced()
{
    return true;
}


text:
package lcow

// Maintainer: @jhowardmsft
// Graph-driver for Linux Containers On Windows (LCOW)

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/Microsoft/hcsshim"
	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/daemon/graphdriver"
	"github.com/docker/docker/pkg/archive"
	"github.com/docker/docker/pkg/idtools"
	"github.com/docker/docker/pkg/system"
	"github.com/jhowardmsft/opengcs/gogcs/client"
)

// init registers the LCOW driver to the register.
func init() {
	graphdriver.Register("lcow", InitLCOW)
}

const (
	// sandboxFilename is the name of the file containing a layers sandbox (read-write layer)
	sandboxFilename = "sandbox.vhdx"

	// svmScratchFilename is the name of the scratch-space used by an SVM to avoid running out of memory
	svmScratchFilename = "scratch.vhdx"
)

// cacheType is our internal structure representing an item in our local cache
// of things that have been mounted.
type cacheType struct {
	uvmPath   string // Path in utility VM
	hostPath  string // Path on host
	refCount  int    // How many times its been mounted
	isSandbox bool   // True if a sandbox
}

// Driver represents an LCOW graph driver.
type Driver struct {
	// homeDir is the hostpath where we're storing everything
	homeDir string
	// cachedSandboxFile is the location of the local default-sized cached sandbox
	cachedSandboxFile string
	// options are the graphdriver options we are initialised with
	options []string
	// config is the representation of the SVM.
	// @jhowardmsft LIFETIME TODO - For now, a global service utility-VM
	config client.Config
	// svmScratchSpaceFile is a host location for a dedicated scratch space
	// that the SVM utilities can use as a scratch-space to avoid OOMs
	// @jhowardmsft LIFETIME TODO - For now, a global service utility-VM
	svmScratchSpaceFile string

	// it is safe for windows to use a cache here because it does not support
	// restoring containers when the daemon dies.

	// cacheMu is the mutex protection add/update/deletes to our cache
	cacheMu sync.Mutex
	// cache is the cache of all the IDs we've mounted/unmounted.
	cache map[string]cacheType
}

// InitLCOW returns a new LCOW storage driver.
func InitLCOW(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
	title := "lcowdriver: init:"
	logrus.Debugf("%s %s", title, home)

	d := &Driver{
		homeDir:             home,
		options:             options,
		cachedSandboxFile:   filepath.Join(home, "cache", sandboxFilename),
		svmScratchSpaceFile: filepath.Join(home, "svmscratch", svmScratchFilename),
		cache:               make(map[string]cacheType),
	}

	if err := idtools.MkdirAllAs(home, 0700, 0, 0); err != nil {
		return nil, fmt.Errorf("%s failed to create '%s': %v", title, home, err)
	}

	// Cache directory for blank sandbox so don't have to pull it from the service VM each time
	if err := idtools.MkdirAllAs(filepath.Dir(d.cachedSandboxFile), 0700, 0, 0); err != nil {
		return nil, fmt.Errorf("%s failed to create '%s': %v", title, home, err)
	}

	// Location for the SVM scratch
	if err := idtools.MkdirAllAs(filepath.Dir(d.svmScratchSpaceFile), 0700, 0, 0); err != nil {
		return nil, fmt.Errorf("%s failed to create '%s': %v", title, home, err)
	}

	return d, nil
}

// startUvm starts the service utility VM if it isn't running.
// TODO @jhowardmsft. This will change before RS3 ships as we move to a model of one
// service VM globally to a service VM per container (or offline operation). However,
// for the initial bring-up of LCOW, this is acceptable.
func (d *Driver) startUvm(context string) error {
	const toolsScratchPath = "/mnt/gcs/LinuxServiceVM/scratch"

	// Nothing to do if it's already running
	if d.config.Uvm != nil {
		return nil
	}

	// So we need to start it. Generate a default configuration
	if err := d.config.GenerateDefault(d.options); err != nil {
		return fmt.Errorf("failed to generate default gogcs configuration (%s): %s", context, err)
	}

	scratchAttached := false
	if _, err := os.Stat(d.svmScratchSpaceFile); err == nil {
		// We have a scratch space already, so just attach it as a mapped virtual disk
		logrus.Debugf("lcowdriver: startuvm: (%s) attaching pre-existing scratch", context)
		mvd := hcsshim.MappedVirtualDisk{
			HostPath:          d.svmScratchSpaceFile,
			ContainerPath:     toolsScratchPath,
			CreateInUtilityVM: true,
		}
		d.config.MappedVirtualDisks = append(d.config.MappedVirtualDisks, mvd)
		scratchAttached = true
	}

	d.config.Name = "LinuxServiceVM" // TODO @jhowardmsft - This requires an in-flight platform change. Can't hard code it to this longer term
	if err := d.config.Create(); err != nil {
		return fmt.Errorf("failed to start utility VM (%s): %s", context, err)
	}

	// Hot-add the scratch-space if not already attached
	if !scratchAttached {
		logrus.Debugf("lcowdriver: startuvm: (%s) creating an SVM scratch", context)
		if err := d.config.CreateSandbox(d.svmScratchSpaceFile, client.DefaultSandboxSizeMB, d.cachedSandboxFile); err != nil {
			return fmt.Errorf("failed to create SVM scratch VHDX (%s): %s", context, err)
		}
		logrus.Debugf("lcowdriver: startuvm: (%s) hot-adding an SVM scratch", context)
		if err := d.config.HotAddVhd(d.svmScratchSpaceFile, toolsScratchPath); err != nil {
			return fmt.Errorf("failed to hot-add %s failed: %s", d.svmScratchSpaceFile, err)
		}
	}
	logrus.Debugf("lcowdriver: startuvm: (%s) successful", context)
	return nil
}

// terminateUvm terminates the service utility VM if its running.
func (d *Driver) terminateUvm(context string) error {
	// Nothing to do if it's not running
	if d.config.Uvm == nil {
		return nil
	}

	// FIXME: @jhowardmsft
	// This isn't thread-safe yet, but will change anyway with the lifetime
	// changes and multiple instances. Deferring that work for now.
	uvm := d.config.Uvm
	d.config.Uvm = nil

	if err := uvm.Terminate(); err != nil {
		return fmt.Errorf("failed to terminate utility VM (%s): %s", context, err)
	}

	if err := uvm.WaitTimeout(time.Duration(d.config.UvmTimeoutSeconds) * time.Second); err != nil {
		return fmt.Errorf("failed waiting for utility VM to terminate (%s): %s", context, err)
	}

	return nil
}

// String returns the string representation of a driver. This should match
// the name the graph driver has been registered with.
func (d *Driver) String() string {
	return "lcow"
}

// Status returns the status of the driver.
func (d *Driver) Status() [][2]string {
	return [][2]string{
		{"LCOW", ""},
	}
}

// Exists returns true if the given id is registered with this driver.
func (d *Driver) Exists(id string) bool {
	_, err := os.Lstat(d.dir(id))
	logrus.Debugf("lcowdriver: exists: id %s %t", id, err == nil)
	return err == nil
}

// CreateReadWrite creates a layer that is writable for use as a container
// file system. That equates to creating a sandbox VHDx.
func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
	logrus.Debugf("lcowdriver: createreadwrite: id %s", id)

	if err := d.startUvm("createreadwrite"); err != nil {
		return err
	}

	if err := d.Create(id, parent, opts); err != nil {
		return err
	}

	return d.config.CreateSandbox(filepath.Join(d.dir(id), sandboxFilename), client.DefaultSandboxSizeMB, d.cachedSandboxFile)
}

// Create creates a new read-only layer with the given id.
func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
	logrus.Debugf("lcowdriver: create: id %s parent: %s", id, parent)

	parentChain, err := d.getLayerChain(parent)
	if err != nil {
		return err
	}

	var layerChain []string
	if parent != "" {
		if !d.Exists(parent) {
			return fmt.Errorf("lcowdriver: cannot create read-only layer with missing parent %s", parent)
		}
		layerChain = []string{d.dir(parent)}
	}
	layerChain = append(layerChain, parentChain...)

	// Make sure layers are created with the correct ACL so that VMs can access them.
	layerPath := d.dir(id)
	logrus.Debugf("lcowdriver: create: id %s: creating layerPath %s", id, layerPath)
	if err := system.MkdirAllWithACL(layerPath, 755, system.SddlNtvmAdministratorsLocalSystem); err != nil {
		return err
	}

	if err := d.setLayerChain(id, layerChain); err != nil {
		if err2 := os.RemoveAll(layerPath); err2 != nil {
			logrus.Warnf("Failed to remove layer %s: %s", layerPath, err2)
		}
		return err
	}
	logrus.Debugf("lcowdriver: createreadwrite: id %s: success", id)

	return nil
}

// Remove unmounts and removes the dir information.
func (d *Driver) Remove(id string) error {
	logrus.Debugf("lcowdriver: remove: id %s", id)
	tmpID := fmt.Sprintf("%s-removing", id)
	tmpLayerPath := d.dir(tmpID)
	layerPath := d.dir(id)

	logrus.Debugf("lcowdriver: remove: id %s: layerPath %s", id, layerPath)
	if err := os.Rename(layerPath, tmpLayerPath); err != nil && !os.IsNotExist(err) {
		return err
	}

	if err := os.RemoveAll(tmpLayerPath); err != nil {
		return err
	}

	logrus.Debugf("lcowdriver: remove: id %s: layerPath %s succeeded", id, layerPath)
	return nil
}

// Get returns the rootfs path for the id. It is reference counted and
// effectively can be thought of as a "mount the layer into the utility
// vm if it isn't already"
func (d *Driver) Get(id, mountLabel string) (string, error) {
	dir, _, _, err := d.getEx(id)
	return dir, err
}

// getEx is Get, but also returns the cache-entry and the size of the VHD
func (d *Driver) getEx(id string) (string, cacheType, int64, error) {
	title := "lcowdriver: getEx"
	logrus.Debugf("%s %s", title, id)

	if err := d.startUvm(fmt.Sprintf("getex %s", id)); err != nil {
		logrus.Debugf("%s failed to start utility vm: %s", title, err)
		return "", cacheType{}, 0, err
	}

	// Work out what we are working on
	vhdFilename, vhdSize, isSandbox, err := client.LayerVhdDetails(d.dir(id))
	if err != nil {
		logrus.Debugf("%s failed to get LayerVhdDetails from %s: %s", title, d.dir(id), err)
		return "", cacheType{}, 0, fmt.Errorf("%s failed to open layer or sandbox VHD to open in %s: %s", title, d.dir(id), err)
	}
	logrus.Debugf("%s %s, size %d, isSandbox %t", title, vhdFilename, vhdSize, isSandbox)

	hotAddRequired := false
	d.cacheMu.Lock()
	var cacheEntry cacheType
	if _, ok := d.cache[id]; !ok {
		// The item is not currently in the cache.
		//
		// Sandboxes need hot-adding in the case that there is a single global utility VM
		// This will change for multiple instances with the lifetime changes.
		if isSandbox {
			hotAddRequired = true
		}
		d.cache[id] = cacheType{
			uvmPath:   fmt.Sprintf("/mnt/%s", id),
			refCount:  1,
			isSandbox: isSandbox,
			hostPath:  vhdFilename,
		}
	} else {
		// Increment the reference counter in the cache.
		cacheEntry = d.cache[id]
		cacheEntry.refCount++
		d.cache[id] = cacheEntry
	}

	cacheEntry = d.cache[id]
	logrus.Debugf("%s %s: isSandbox %t, refCount %d", title, id, cacheEntry.isSandbox, cacheEntry.refCount)
	d.cacheMu.Unlock()

	if hotAddRequired {
		logrus.Debugf("%s %s: Hot-Adding %s", title, id, vhdFilename)
		if err := d.config.HotAddVhd(vhdFilename, cacheEntry.uvmPath); err != nil {
			return "", cacheType{}, 0, fmt.Errorf("%s hot add %s failed: %s", title, vhdFilename, err)
		}
	}

	logrus.Debugf("%s %s success. %s: %+v: size %d", title, id, d.dir(id), cacheEntry, vhdSize)
	return d.dir(id), cacheEntry, vhdSize, nil
}

// Put does the reverse of get. If there are no more references to
// the layer, it unmounts it from the utility VM.
func (d *Driver) Put(id string) error {
	title := "lcowdriver: put"
	logrus.Debugf("%s %s", title, id)

	if err := d.startUvm(fmt.Sprintf("put %s", id)); err != nil {
		return err
	}

	d.cacheMu.Lock()
	// Bad-news if unmounting something that isn't in the cache.
	entry, ok := d.cache[id]
	if !ok {
		d.cacheMu.Unlock()
		return fmt.Errorf("%s possible ref-count error, or invalid id was passed to the graphdriver. Cannot handle id %s as it's not in the cache", title, id)
	}

	// Are we just decrementing the reference count
	if entry.refCount > 1 {
		entry.refCount--
		d.cache[id] = entry
		logrus.Debugf("%s %s: refCount decremented to %d", title, id, entry.refCount)
		d.cacheMu.Unlock()
		return nil
	}

	// No more references, so tear it down if previously hot-added
	if entry.isSandbox {
		logrus.Debugf("%s %s: Hot-Removing %s", title, id, entry.hostPath)
		if err := d.config.HotRemoveVhd(entry.hostPath); err != nil {
			d.cacheMu.Unlock()
			return fmt.Errorf("%s failed to hot-remove %s from service utility VM: %s", title, entry.hostPath, err)
		}
	}

	// @jhowardmsft TEMPORARY FIX WHILE WAITING FOR HOT-REMOVE TO BE FIXED IN PLATFORM
	//d.terminateUvm(fmt.Sprintf("put %s", id))

	// Remove from the cache map.
	delete(d.cache, id)
	d.cacheMu.Unlock()

	logrus.Debugf("%s %s: refCount 0. %s (%s) completed successfully", title, id, entry.hostPath, entry.uvmPath)
	return nil
}

// Cleanup ensures the information the driver stores is properly removed.
// We use this opportunity to cleanup any -removing folders which may be
// still left if the daemon was killed while it was removing a layer.
func (d *Driver) Cleanup() error {
	title := "lcowdriver: cleanup"
	logrus.Debugf(title)

	d.cacheMu.Lock()
	for k, v := range d.cache {
		logrus.Debugf("%s cache entry: %s: %+v", title, k, v)
		if v.refCount > 0 {
			logrus.Warnf("%s leaked %s: %+v", title, k, v)
		}
	}
	d.cacheMu.Unlock()

	items, err := ioutil.ReadDir(d.homeDir)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}

	// Note we don't return an error below - it's possible the files
	// are locked. However, next time around after the daemon exits,
	// we likely will be able to to cleanup successfully. Instead we log
	// warnings if there are errors.
	for _, item := range items {
		if item.IsDir() && strings.HasSuffix(item.Name(), "-removing") {
			if err := os.RemoveAll(filepath.Join(d.homeDir, item.Name())); err != nil {
				logrus.Warnf("%s failed to cleanup %s: %s", title, item.Name(), err)
			} else {
				logrus.Infof("%s cleaned up %s", title, item.Name())
			}
		}
	}
	return nil
}

// Diff takes a layer (and it's parent layer which may be null, but
// is ignored by this implementation below) and returns a reader for
// a tarstream representing the layers contents. The id could be
// a read-only "layer.vhd" or a read-write "sandbox.vhdx". The semantics
// of this function dictate that the layer is already mounted.
func (d *Driver) Diff(id, parent string) (io.ReadCloser, error) {
	title := "lcowdriver: diff:"
	logrus.Debugf("%s id %s", title, id)

	if err := d.startUvm(fmt.Sprintf("diff %s", id)); err != nil {
		return nil, err
	}

	d.cacheMu.Lock()
	if _, ok := d.cache[id]; !ok {
		d.cacheMu.Unlock()
		return nil, fmt.Errorf("%s fail as %s is not in the cache", title, id)
	}
	cacheEntry := d.cache[id]
	d.cacheMu.Unlock()

	// Stat to get size
	fileInfo, err := os.Stat(cacheEntry.hostPath)
	if err != nil {
		return nil, fmt.Errorf("%s failed to stat %s: %s", title, cacheEntry.hostPath, err)
	}

	// Then obtain the tar stream for it
	logrus.Debugf("%s %s, size %d, isSandbox %t", title, cacheEntry.hostPath, fileInfo.Size(), cacheEntry.isSandbox)
	tarReadCloser, err := d.config.VhdToTar(cacheEntry.hostPath, cacheEntry.uvmPath, cacheEntry.isSandbox, fileInfo.Size())
	if err != nil {
		return nil, fmt.Errorf("%s failed to export layer to tar stream for id: %s, parent: %s : %s", title, id, parent, err)
	}
	logrus.Debugf("%s id %s parent %s completed successfully", title, id, parent)
	return tarReadCloser, nil
}

// ApplyDiff extracts the changeset from the given diff into the
// layer with the specified id and parent, returning the size of the
// new layer in bytes. The layer should not be mounted when calling
// this function. Another way of describing this is that ApplyDiff writes
// to a new layer (a VHD in LCOW) the contents of a tarstream it's given.
func (d *Driver) ApplyDiff(id, parent string, diff io.Reader) (int64, error) {
	logrus.Debugf("lcowdriver: applydiff: id %s", id)

	if err := d.startUvm(fmt.Sprintf("applydiff %s", id)); err != nil {
		return 0, err
	}

	return d.config.TarToVhd(filepath.Join(d.homeDir, id, "layer.vhd"), diff)
}

// Changes produces a list of changes between the specified layer
// and its parent layer. If parent is "", then all changes will be ADD changes.
// The layer should not be mounted when calling this function.
func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
	logrus.Debugf("lcowdriver: changes: id %s parent %s", id, parent)
	// TODO @gupta-ak. Needs implementation with assistance from service VM
	return nil, nil
}

// DiffSize calculates the changes between the specified layer
// and its parent and returns the size in bytes of the changes
// relative to its base filesystem directory.
func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
	logrus.Debugf("lcowdriver: diffsize: id %s", id)
	// TODO @gupta-ak. Needs implementation with assistance from service VM
	return 0, nil
}

// GetMetadata returns custom driver information.
func (d *Driver) GetMetadata(id string) (map[string]string, error) {
	logrus.Debugf("lcowdriver: getmetadata: id %s", id)
	m := make(map[string]string)
	m["dir"] = d.dir(id)
	return m, nil
}

// dir returns the absolute path to the layer.
func (d *Driver) dir(id string) string {
	return filepath.Join(d.homeDir, filepath.Base(id))
}

// getLayerChain returns the layer chain information.
func (d *Driver) getLayerChain(id string) ([]string, error) {
	jPath := filepath.Join(d.dir(id), "layerchain.json")
	logrus.Debugf("lcowdriver: getlayerchain: id %s json %s", id, jPath)
	content, err := ioutil.ReadFile(jPath)
	if os.IsNotExist(err) {
		return nil, nil
	} else if err != nil {
		return nil, fmt.Errorf("lcowdriver: getlayerchain: %s unable to read layerchain file %s: %s", id, jPath, err)
	}

	var layerChain []string
	err = json.Unmarshal(content, &layerChain)
	if err != nil {
		return nil, fmt.Errorf("lcowdriver: getlayerchain: %s failed to unmarshall layerchain file %s: %s", id, jPath, err)
	}
	return layerChain, nil
}

// setLayerChain stores the layer chain information on disk.
func (d *Driver) setLayerChain(id string, chain []string) error {
	content, err := json.Marshal(&chain)
	if err != nil {
		return fmt.Errorf("lcowdriver: setlayerchain: %s failed to marshall layerchain json: %s", id, err)
	}

	jPath := filepath.Join(d.dir(id), "layerchain.json")
	logrus.Debugf("lcowdriver: setlayerchain: id %s json %s", id, jPath)
	err = ioutil.WriteFile(jPath, content, 0600)
	if err != nil {
		return fmt.Errorf("lcowdriver: setlayerchain: %s failed to write layerchain file: %s", id, err)
	}
	return nil
}


text:
package org.smartdeveloperhub.curator.connector.util;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
	ResourceUtilTest.class,
	CloseablesTest.class,
})
public class UtilTestsSuite {

}


text:
import sys, os
from time import gmtime, strftime

_H2O_IP_                      = "127.0.0.1"
_H2O_PORT_                    = 54321
_H2O_EXTRA_CONNECT_ARGS_      = dict()
_ON_HADOOP_                   = False
_HADOOP_NAMENODE_             = None
_IS_IPYNB_                    = False
_IS_PYDEMO_                   = False
_IS_PYUNIT_                   = False
_IS_PYBOOKLET_                = False
_RESULTS_DIR_                 = False
_TEST_NAME_                   = ""
_FORCE_CONNECT_               = False
_LDAP_USER_NAME_              = None
_LDAP_PASSWORD_               = None
_KERB_PRINCIPAL_              = None

def parse_args(args):
    global _H2O_IP_
    global _H2O_PORT_
    global _H2O_EXTRA_CONNECT_ARGS_
    global _ON_HADOOP_
    global _HADOOP_NAMENODE_
    global _IS_IPYNB_
    global _IS_PYDEMO_
    global _IS_PYUNIT_
    global _IS_PYBOOKLET_
    global _RESULTS_DIR_
    global _TEST_NAME_
    global _FORCE_CONNECT_
    global _LDAP_USER_NAME_
    global _LDAP_PASSWORD_
    global _KERB_PRINCIPAL_

    i = 1
    while (i < len(args)):
        s = args[i]
        if ( s == "--usecloud" or s == "--uc" ):
            i = i + 1
            if (i > len(args)): usage()
            param = args[i]
            if param.lower().startswith("https://"):
                _H2O_EXTRA_CONNECT_ARGS_ = {'https': True, 'verify_ssl_certificates': False}
                param = param[8:]
            argsplit = param.split(":")
            _H2O_IP_   = argsplit[0]
            _H2O_PORT_ = int(argsplit[1])
        elif (s == "--hadoopNamenode"):
            i = i + 1
            if (i > len(args)): usage()
            _HADOOP_NAMENODE_ = args[i]
        elif (s == "--onHadoop"):
            _ON_HADOOP_ = True
        elif (s == "--ipynb"):
            _IS_IPYNB_ = True
        elif (s == "--pyDemo"):
            _IS_PYDEMO_ = True
        elif (s == "--pyUnit"):
            _IS_PYUNIT_ = True
        elif (s == "--pyBooklet"):
            _IS_PYBOOKLET_ = True
        elif (s == "--resultsDir"):
            i = i + 1
            if (i > len(args)): usage()
            _RESULTS_DIR_ = args[i]
        elif (s == "--testName"):
            i = i + 1
            if (i > len(args)): usage()
            _TEST_NAME_ = args[i]
        elif (s == "--ldapUsername"):
            i = i + 1
            if (i > len(args)): usage()
            _LDAP_USER_NAME_ = args[i]
        elif (s == "--ldapPassword"):
            i = i + 1
            if (i > len(args)): usage()
            _LDAP_PASSWORD_ = args[i]
        elif (s == "--kerbPrincipal"):
            i = i + 1
            if (i > len(args)): usage()
            _KERB_PRINCIPAL_ = args[i]
        elif (s == "--forceConnect"):
            _FORCE_CONNECT_ = True
        else:
            unknownArg(s)
        i = i + 1

def usage():
    print("")
    print("Usage for:  python pyunit.py [...options...]")
    print("")
    print("    --usecloud        connect to h2o on specified ip and port, where ip and port are specified as follows:")
    print("                      IP:PORT")
    print("")
    print("    --onHadoop        Indication that tests will be run on h2o multinode hadoop clusters.")
    print("                      `locate` and `sandbox` pyunit test utilities use this indication in order to")
    print("                      behave properly. --hadoopNamenode must be specified if --onHadoop option is used.")
    print("    --hadoopNamenode  Specifies that the pyunit tests have access to this hadoop namenode.")
    print("                      `hadoop_namenode` pyunit test utility returns this value.")
    print("")
    print("    --ipynb           test is ipython notebook")
    print("")
    print("    --pyDemo          test is python demo")
    print("")
    print("    --pyUnit          test is python unit test")
    print("")
    print("    --pyBooklet       test is python booklet")
    print("")
    print("    --resultsDir      the results directory.")
    print("")
    print("    --testName        name of the pydemo, pyunit, or pybooklet.")
    print("")
    print("    --ldapUsername    LDAP username.")
    print("")
    print("    --ldapPassword    LDAP password.")
    print("")
    print("    --kerbPrincipal   Kerberos service principal.")
    print("")
    print("    --forceConnect    h2o will attempt to connect to cluster regardless of cluster's health.")
    print("")
    sys.exit(1) #exit with nonzero exit code

def unknownArg(arg):
    print("")
    print("ERROR: Unknown argument: " + arg)
    print("")
    usage()

def h2o_test_setup(sys_args):
    h2o_py_dir = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)),".."))
    h2o_docs_dir = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","..","h2o-docs"))

    parse_args(sys_args)

    sys.path.insert(1, h2o_py_dir)
    import h2o
    from tests import pyunit_utils, pydemo_utils, pybooklet_utils

    for pkg in (pyunit_utils, pybooklet_utils):
        setattr(pkg, '__on_hadoop__', _ON_HADOOP_)
        setattr(pkg, '__hadoop_namenode__', _HADOOP_NAMENODE_)
        setattr(pkg, '__test_name__', _TEST_NAME_)
        setattr(pkg, '__results_dir__', _RESULTS_DIR_)

    if _IS_PYUNIT_ or _IS_IPYNB_ or _IS_PYBOOKLET_ or _IS_PYDEMO_:
        pass
    else:
        raise(EnvironmentError, "Unrecognized test type. Must be of type ipynb, pydemo, pyunit, or pybooklet, but got: "
                                "{0}".format(_TEST_NAME_))

    print("[{0}] {1}\n".format(strftime("%Y-%m-%d %H:%M:%S", gmtime()), "Connect to h2o on IP: {0} PORT: {1}".format(_H2O_IP_, _H2O_PORT_)))
    auth = None
    if _LDAP_USER_NAME_ is not None and _LDAP_PASSWORD_ is not None:
        print("Using basic auth with %s user name" % _LDAP_USER_NAME_)
        auth = (_LDAP_USER_NAME_, _LDAP_PASSWORD_)
    elif _KERB_PRINCIPAL_ is not None:
        print("Using SPNEGO auth with %s principal" % _KERB_PRINCIPAL_)
        from h2o.auth import SpnegoAuth
        auth = SpnegoAuth(service_principal=_KERB_PRINCIPAL_)
    else:
        print("Not using any auth")
    h2o.connect(ip=_H2O_IP_, port=_H2O_PORT_, verbose=False, auth=auth, **_H2O_EXTRA_CONNECT_ARGS_)
    h2o.utils.config.H2OConfigReader.get_config()["general.allow_breaking_changes"] = True

    #rest_log = os.path.join(_RESULTS_DIR_, "rest.log")
    #h2o.start_logging(rest_log)
    #print "[{0}] {1}\n".format(strftime("%Y-%m-%d %H:%M:%S", gmtime()), "Started rest logging in: {0}".format(rest_log))

    h2o.log_and_echo("------------------------------------------------------------")
    h2o.log_and_echo("")
    h2o.log_and_echo("STARTING TEST: " + _TEST_NAME_)
    h2o.log_and_echo("")
    h2o.log_and_echo("------------------------------------------------------------")

    h2o.remove_all()

    if _IS_IPYNB_:       pydemo_utils.ipy_notebook_exec(_TEST_NAME_)
    elif _IS_PYUNIT_:    pyunit_utils.pyunit_exec(_TEST_NAME_)
    elif _IS_PYBOOKLET_: pybooklet_utils.pybooklet_exec(_TEST_NAME_)
    elif _IS_PYDEMO_:    pydemo_utils.pydemo_exec(_TEST_NAME_)

if __name__ == "__main__":
    h2o_test_setup(sys.argv)


text:
from html.parser import HTMLParser
import glob

class ListParser(HTMLParser):
    nais = False # next data is title
    kode = 0
    finn = {}
    def handle_starttag(self, tag, attrs):
        dattr = dict(attrs)
        if tag == 'div' and 'data-favorite-ad' in dattr:
            self.kode = int(dattr['data-favorite-ad'])
            self.finn[self.kode] = {}
        if tag == 'h2' and 'class' in dattr and dattr['class'] == 't3 truncate pvt man':
            self.nais = True
    def handle_data(self, data):
        dast = data.strip()
        if self.nais:# and dast not in ['Velkommen til m.finn.no', '']:
            self.finn[self.kode]['title'] = dast
            self.nais = False
    def handle_endtag(self, tag):
        self.nais = False
    def __iter__(self):
        return iter(self.finn.items())

NXT_IS_KEY = 1
NXT_IS_VAL = 2
class AdParser(HTMLParser):
    lstkey = ''
    values = {}
    nxt_is = 0 # next is ?
    def handle_starttag(self, tag, attrs):
        dattr = dict(attrs)
        if tag == 'dt' and 'data-automation-id' in dattr and dattr['data-automation-id'] == 'key':
            self.nxt_is = NXT_IS_KEY
        if tag == 'dd' and 'data-automation-id' in dattr and dattr['data-automation-id'] == 'value':
            self.nxt_is = NXT_IS_VAL

    def handle_data(self, data):
        if self.nxt_is == NXT_IS_KEY:
            self.values[data] = ''
            self.lstkey = data.strip().lower()
        elif self.nxt_is == NXT_IS_VAL:
            self.values[self.lstkey] = data.strip()

    def handle_endtag(self, tag):
        self.nxt_is = 0
    def clean(self):
        self.values = dict((k, v) for k, v in self.values.items() if v)
    def __repr__(self):
        return str(self.values)

    def __iter__(self):
        return iter(self.values)

    def __getitem__(self, item):
        return self.values[item]

if __name__ == '__main__':
    parser = ListParser()
    for fname in glob.glob('favorites/*.html'):
        for chunk in open(fname):
            parser.feed(chunk)

    print('\n'.join(map(str, parser)))

    f = open('parsed.txt', 'w')
    parser = AdParser()
    for chunk in open('ads/71231332.html'):
        parser.feed(chunk)
    parser.clean()

    print(parser)


text:
<?php

namespace BearCMS;

/**
 *
 * @property-read \BearCMS\Data\BlogPosts $blogPosts
 * @property-read \BearCMS\Data\Pages $pages
 * @property-read \BearCMS\Data\Settings $settings
 * @property-read \BearCMS\Data\Users $users
 */
class Data
{

    use \IvoPetkov\DataObjectTrait;

    function __construct()
    {
        $this
            ->defineProperty('blogPosts', [
                'init' => function () {
                    return new \BearCMS\Data\BlogPosts();
                },
                'readonly' => true
            ])
            ->defineProperty('pages', [
                'init' => function () {
                    return new \BearCMS\Data\Pages();
                },
                'readonly' => true
            ])
            ->defineProperty('settings', [
                'init' => function () {
                    return new \BearCMS\Data\Settings();
                },
                'readonly' => true
            ])
            ->defineProperty('users', [
                'init' => function () {
                    return new \BearCMS\Data\Users();
                },
                'readonly' => true
            ]);
    }

    /**
     *
     * @return int
     */
    public function getUploadsSize(): int
    {
        return Internal\Data\UploadsSize::getSize();
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gameshop.advance.exceptions.sales;

/**
 *
 * @author Lorenzo Di Giuseppe <lorenzo.digiuseppe88@gmail.com>
 */
public class ClientNotFoundException extends Exception {

    private int codiceTessera;

    public ClientNotFoundException(int codiceTessera) {
        this.codiceTessera = codiceTessera;
    }

    public int getCodiceTessera() {
        return codiceTessera;
    }

    public void setCodiceTessera(int codiceTessera) {
        this.codiceTessera = codiceTessera;
    }

}


text:
var fs = require('fs');
var file = process.argv[2];

var callback = function(err, fileContents) {
  var lines = fileContents.toString().split("\n");
  console.log(lines.length -1);
}

fs.readFile(file, callback);


text:
* Using firebase command line tool to deploy:
  * `brew install firebase-cli` - install firebase CLI
  * `firebase deploy` - deploy to firebase

# Features

* Application can be run in a local http server, or emulated/released to Android/iOS
* Application can be run in a local http server, or emulated/released to Android/iOS
  * `gulp cordova:run:android` - run application on Android's devise
  * Run `gulp help` or see `gulp/tasks.coffee` for more information about all tasks
* Useful hooks and tweaks, which allow you to deploy your cordova app out-of-the-box
* SASS + CoffeeScript + Jade combo
* Support for multiple environments, like *development, staging, production* (configuration available in `gulpfile.coffee`)
* Tests configured and working: unit (karma + mocha) and end to end (protractor)
* Rollbar support (configured, working in angular functions and support for uploading the sourcemaps to Rollbar server)

# Requirements

* NodeJS
* Cordova 4.2+
* Android or iOS SDK installed and [configured](http://docs.phonegap.com/en/4.0.0/guide_platforms_index.md.html#Platform%20Guides) (required only if you want to deploy the app to native mobile platforms - you can run `gulp` server without that)

# How to install

```
git clone wandp/song-a-day-ionic
cd song-a-day-ionic
git submodule update --init --recursive

# install dependencies
npm install
npm install -g gulp
bower install
brew install imagemagick # or `apt-get install imagemagick`, if you're on linux

gulp # build www/ directory and run http server on 4440 port
```

If you get "too many files" error, try: `ulimit -n 10000`. You may want to add this line to your .bashrc / .zshrc / config.fish.

## What does the `gulp build` do?

More or less:

* All .scss, .coffee, .jade files from `app/` will be compiled and copied to `www/`
* All `.ejs` files from `assets/` will be compiled to `www/`.
* All other files from `assets/` will be copied to `www/`.

For detailed description, see `gulpfile.coffee`.

P.S. `www/` is like `dist/` directory for Cordova. That's why it's not included in this repository, as it's fully generated with `gulp`.

## Testing

Requirements: installed PhantomJS and configured [selenium standalone webdriver](https://github.com/angular/protractor/blob/master/docs/getting-started.md#setup-and-config).

#### Unit tests (karma & PhantomJS/Chrome)

```
gulp test:unit # using PhantomJS
gulp test:unit --browsers Chrome # or using Google Chrome
```

#### e2e tests (protractor & selenium)

```
gulp # your www/ directory should be built and served at :4400 port
node_modules/.bin/webdriver-manager start & # run selenium server in the background

gulp test:e2e # finally, run e2e tests
```

# How to run on mobile?

I recommend [tmux](http://tmux.sourceforge.net/) for handling multiple terminal tabs/windows ;)

1. Copy `.envrc.android-sample` or `.envrc.ios-sample` to `.envrc` and configure it.

  * Ofcourse, if you're a Mac user and you can compile both Android and iOS on the same machine, you can include all the variables from both of these files in only one `.envrc` .

  * Also, make sure you have all the keys and certificates needed stored in `keys/android/` and `keys/ios/`:

    * `keys/android/songaday.keystore`
    * `keys/ios/songaday_staging.mobileprovision`
    * `keys/ios/songaday_production.mobileprovision`

2. Ensure, you have [configured ios/android platform with Cordova](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html), f.e. by running `gulp cordova:platform-add:[ios|android]`.

3. Run `gulp cordova:emulate:[ios|android]` or `gulp cordova:run:[ios|android]`.

# Releasing to appstores

First, generate the certificate keys:

#### Android

1. [Generate .keystore file](http://developer.android.com/tools/publishing/app-signing.html):
`keytool -genkey -v -keystore keys/android/$ANDROID_KEYSTORE_NAME.keystore -alias $ANDROID_ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000`

#### iPhone

1. Create a certificate and a provisioning profile, as it's described [here](http://docs.build.phonegap.com/en_US/3.3.0/signing_signing-ios.md.html#iOS%20Signing).

2. Download the provisioning profile and copy it into `keys/ios/`, so it will match the `IOS_PROVISIONING_PROFILE` file set up in the `gulpfile.coffee`.

Then, generate the application and deploy it to the webserver with:

```
gulp release:[ios|android] --env=[staging|production]
```


text:
import os
import sys

from BTL.platform import bttime
from BTL.DictWithLists import DictWithLists
from BTL.obsoletepythonsupport import set
from BTL.sparse_set import SparseSet
from BTL.Lists import collapse

import wx

if os.name == 'nt':
    import win32gui
    import win32con

def _ScaleBlit(bmp, dc, dst_rect):
    sX = float(dst_rect.width) / float(bmp.GetWidth())
    sY = float(dst_rect.height) / float(bmp.GetHeight())

    dc.SetUserScale(sX, sY)

    old_mode = None
    if os.name == 'nt':
        h_dst = dc.GetHDC()
        try:
            old_mode = win32gui.SetStretchBltMode(h_dst, win32con.HALFTONE)
        except:
            pass

    if sX == 0:
        x = 0
    else:
        x = dst_rect.x/sX

    if sY == 0:
        y = 0
    else:
        y = dst_rect.y/sY

    if sys.platform == "darwin":
        # magic!
        y = round(y)
        x += 0.2
        dc.SetDeviceOrigin(x, y)
        dc.DrawBitmap(bmp, 0, 0, True)
        dc.SetDeviceOrigin(0, 0)
    else:
        dc.DrawBitmap(bmp, x, y, True)

    if os.name == 'nt':
        try:
            win32gui.SetStretchBltMode(h_dst, old_mode)
        except:
            pass

    dc.SetUserScale(1, 1)

class DoubleBufferedMixin(object):

    def __init__(self):
        self.bind_events()
        self.buffer_size = wx.Size(-1, -1)
        self.last_size = self._calc_size()
        self.init_buffer()

    def _calc_size(self):
        return self.GetClientSize()

    def init_buffer(self):
        size = self._calc_size()
        if ((self.buffer_size.width < size.width) or
            (self.buffer_size.height < size.height)):
            self.buffer = wx.EmptyBitmap(size.width, size.height)
            dc = wx.MemoryDC()
            dc.SelectObject(self.buffer)
            dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
            dc.Clear()
            dc.SelectObject(wx.NullBitmap)
            self.buffer_size = size
            return True
        return False

    def bind_events(self):
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e : None)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

    def redraw(self):
        dc = wx.MemoryDC()
        dc.SelectObject(self.buffer)
        size = self._calc_size()
        self.last_size = size
        self.draw(dc, size=size)
        dc.SelectObject(wx.NullBitmap)
        self.Refresh()

    def OnSize(self, event):
        reallocated = self.init_buffer()
        if reallocated or self.last_size != self._calc_size():
            self.redraw()
        else:
            self.Refresh()

    def OnPaint(self, event):
        dc = wx.BufferedPaintDC(self, self.buffer)

class ScaledBufferMixin(DoubleBufferedMixin):

    def __init__(self, w_step=200, h_step=15):
        self.w_step = w_step
        self.h_step = h_step
        # don't go crazy
        self.w_max = 1000
        self.h_max = 100
        DoubleBufferedMixin.__init__(self)

    def _round(self, d, step):
        return max(int(d / step), 1) * step

    def _calc_size(self):
        size = self.GetClientSize()
        # * 2 for the high quality
        w = self._round(size.width*2, self.w_step)
        h = self._round(size.height, self.h_step)
        w = max(w, self.buffer_size.width)
        w = min(w, self.w_max)
        h = max(h, self.buffer_size.height)
        h = min(h, self.h_max)
        return wx.Size(w, h)

    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        _ScaleBlit(self.buffer, dc, self.GetClientRect(), strip_border=1)

class ListCtrlPassThrough(object):
    def __init__(self, listctrl):
        # I'll be nice and ignore you.
        if not isinstance(listctrl, wx.ListCtrl):
            return
        self.listctrl = listctrl
        self.Bind(wx.EVT_LEFT_DOWN, self.LeftDown)
        self.Bind(wx.EVT_LEFT_DCLICK, self.LeftDClick)
        self.Bind(wx.EVT_CONTEXT_MENU, self.ContextMenu)

    def _resolve_position(self):
        p = self.GetPosition()
        p -= self.listctrl._get_origin_offset()
        return p

    def _resolve_index(self):
        p = self._resolve_position()
        try:
            i, flags = self.listctrl.HitTest(p)
        except TypeError:
            # unpack non-sequence
            return
        return i

    def ContextMenu(self, event):
        self.listctrl.DoPopup(self._resolve_position())

    def LeftDClick(self, event):
        i = self._resolve_index()
        if i is None:
            return

        e = wx.ListEvent(wx.wxEVT_COMMAND_LIST_ITEM_ACTIVATED)
        e.m_itemIndex = i
        self.listctrl.ProcessEvent(e)

    def LeftDown(self, event):
        i = self._resolve_index()
        if i is None:
            return

        if not event.ControlDown():
            if event.ShiftDown():
                if '__WXMSW__' in wx.PlatformInfo:
                    self.listctrl.DeselectAll()
                f = self.listctrl.GetFocusedItem()
                if f > -1:
                    for j in xrange(min(i,f), max(i,f)):
                        self.listctrl.Select(j)
                    self.listctrl.Select(f)
            else:
                self.listctrl.DeselectAll()

        self.listctrl.Select(i)
        self.listctrl.SetFocus()
        self.listctrl.Focus(i)

class NullGauge(object):
    def NullMethod(*a):
        pass
    __init__ = NullMethod
    def __getattr__(self, attr):
        return self.NullMethod

class SimpleDownloadGauge(ListCtrlPassThrough, ScaledBufferMixin, wx.Window):

    def __init__(self, parent,
                 completed_color=None,
                 remaining_color=None,
                 border_color=None,
                 border=True,
                 size=(0,0),
                 top_line=True,
                 **k):
        original = {
            "smooth": True,
            "border color": wx.NamedColour("light gray"),
            "completed color": wx.Colour(0, 230, 50),
            "line color"     : wx.Colour(0, 178, 39),
            "remaining color": wx.NamedColour("white"),
            "transferring color": wx.NamedColour("yellow"),
            "missing color": wx.NamedColour("red"),
            "rare colors": [wx.Colour(235, 235, 255),
                            wx.Colour(215, 215, 255),
                            wx.Colour(195, 195, 255),
                            wx.Colour(175, 175, 255),
                            wx.Colour(155, 155, 255),
                            wx.Colour(135, 135, 255),
                            wx.Colour(115, 115, 255),
                            wx.Colour(95, 95, 255),
                            wx.Colour(75, 75, 255),
                            wx.Colour(55, 55, 255),
                            wx.Colour(50, 50, 255)]
            }

        new_green = {
            "smooth": True,
            "border color": wx.Colour(111, 111, 111),
            "completed color": wx.Colour(14, 183, 19),
            "line color"     : wx.Colour(255, 255, 0),
            "remaining color": wx.NamedColour("white"),
            "transferring color": wx.Colour(94, 243, 99),
            "missing color": wx.Colour(255, 0, 0),
            "rare colors": [wx.Colour(185, 185, 185),
                            wx.Colour(195, 195, 195),
                            wx.Colour(205, 205, 205),
                            wx.Colour(215, 215, 215),
                            wx.Colour(225, 225, 225),
                            wx.Colour(235, 235, 235),
                            wx.Colour(245, 245, 245),
                            wx.Colour(255, 255, 255)]
            }

        new_blue = {
            "smooth": True,
            "border color": wx.NamedColour("light gray"),
            "completed color": wx.NamedColour("blue"),
            "line color"     : wx.NamedColour("blue"),
            "remaining color": wx.NamedColour("white"),
            "transferring color": wx.NamedColour("yellow"),
            "missing color": wx.Colour(255, 0, 0),
            "rare colors": [wx.Colour(185, 185, 185),
                            wx.Colour(195, 195, 195),
                            wx.Colour(205, 205, 205),
                            wx.Colour(215, 215, 215),
                            wx.Colour(225, 225, 225),
                            wx.Colour(235, 235, 235),
                            wx.Colour(245, 245, 245),
                            wx.Colour(255, 255, 255)]
            }

        self.gauge_theme = new_green

        wx.Window.__init__(self, parent, size=size, **k)
        #wx.Gauge.__init__(self, parent, 0, 10000, style=wx.GA_SMOOTH)
        ListCtrlPassThrough.__init__(self, parent)
        if border_color == None:
            border_color = self.gauge_theme["border color"]
        if completed_color == None:
            completed_color = self.gauge_theme["completed color"]
        if remaining_color == None:
            remaining_color = self.gauge_theme["remaining color"]
        self.completed_color = completed_color
        self.remaining_color = remaining_color
        self.border_color = border_color
        self.border = border
        self.line_color = self.gauge_theme["line color"]
        self.top_line = top_line
        self.smoother = wx.BitmapFromImage(
            wx.GetApp().theme_library.get(("progressbar",)))
        self.percent = None
        ScaledBufferMixin.__init__(self)

    def invalidate(self):
        pass

    def SetValue(self, value, state=None, data=None, redraw=True):
        #wx.Gauge.SetValue(self, value * 10000)
        if value != self.percent:
            self.percent = value
            self.redraw()

    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        rect = self.GetClientRect()

        if self.border:
            dc.SetPen(wx.Pen(self.border_color))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.DrawRectangle(0, 0, rect.width, rect.height)
            rect = wx.Rect(rect.x + 1, rect.y + 1,
                           rect.width - 2, rect.height - 2)

        _ScaleBlit(self.buffer, dc, rect)

    def draw(self, dc, size):
        srect = wx.Rect(0, 0, size.width, size.height)
        self.draw_bar(dc, srect)

        # dear god, I hope it's smooth
        if self.gauge_theme["smooth"]:
            dc.SetClippingRegion(srect.x, srect.y, srect.width, srect.height)
            _ScaleBlit(self.smoother, dc,
                       wx.Rect(0, 0, srect.width, srect.height))

        # top-line
        if self.top_line and self.percent is not None:
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.SetPen(wx.Pen(self.line_color))
            line_width = 1
            # top:
            line_position = 0
            # middle:
            #line_position = (srect.height) // 2
            # bottom:
            #line_position = srect.height - line_width
            dc.DrawRectangle(srect.x, line_position,
                             srect.width * self.percent, line_width)
            dc.SetPen(wx.Pen(self.border_color))
            dc.DrawRectangle(srect.x + srect.width * self.percent, line_position,
                             srect.width, line_width)

    def draw_bar(self, dc, rect):
        if self.percent == None:
            return 0
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(wx.Brush(self.remaining_color))
        dc.DrawRectangle(rect.x, rect.y,
                         rect.width, rect.height)
        dc.SetBrush(wx.Brush(self.completed_color))
        dc.DrawRectangle(rect.x, rect.y,
                         rect.width * self.percent, rect.height)
        return 0

REFRESH_MAX_SEC = 3

class FancyDownloadGauge(SimpleDownloadGauge):

    def __init__(self, *args, **kwargs):
        self.resolution = 1000
        self.grouped = DictWithLists()
        self.missing_known = False
        self.last_time = bttime()
        self.last_update = -1
        SimpleDownloadGauge.__init__(self, *args, **kwargs)
        self.transfering_color = self.gauge_theme["transferring color"]
        self.missing_color = self.gauge_theme["missing color"]
        self.SetValue(None, redraw=False)

    def gradient(self, v):
        if v == 0:
            if self.missing_known:
                c = self.missing_color
            else:
                c = self.gauge_theme["rare colors"][0]
        else:
            v = min(v, len(self.gauge_theme["rare colors"]))
            c = self.gauge_theme["rare colors"][v - 1]
        return c

    def invalidate(self):
        self.last_time = 0

    def SetValue(self, percent, state = None, data = None, redraw=True):
        # only draw if progress moved .01% or it's been REFRESH_MAX_SEC seconds
        if self.percent != None:
            if (percent < (self.percent + 0.0001) and
                bttime() < (self.last_time + REFRESH_MAX_SEC)):
                return
        self.last_time = bttime()

        if not redraw:
            return

        p_dirty = False
        if self.percent != percent:
            p_dirty = True
        self.percent = percent

        missing_known = state == "running"
        if self.missing_known != missing_known:
            p_dirty = True
        self.missing_known = missing_known

        if not data:
            # no data. allow future SetValues to continue passing
            # until we get something
            self.last_time = 0 - REFRESH_MAX_SEC
            # draw an empty bar
            data = (0, -1, {})

        length, update, piece_states = data

        self.resolution = length

        if p_dirty or update != self.last_update:
            self.grouped = piece_states
            self.redraw()
        self.last_update = update

    def draw_bar(self, dc, rect):
        # size events can catch this
        if self.percent is None:
            return

        y1 = rect.y
        w = rect.width
        h = rect.height

        if self.resolution <= 0:
            return

        # sort, so we get 0...N, h, t
        keys = self.grouped.keys()
        keys.sort()
        for k in keys:
            v = self.grouped[k]

            if k == 'h':
                c = self.completed_color
            elif k == 't':
                c = self.transfering_color
            else:
                c = self.gradient(k)

            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.SetBrush(wx.Brush(c))

            def draw(b, e):
                b = float(b)
                e = float(e)
                r = float(self.resolution)
                x1 = (b / r) * w
                x2 = (e / r) * w
                # stupid floats
                x1 = int(rect.x + x1)
                x2 = int(rect.x + x2)
                dc.DrawRectangle(x1, y1,
                                 x2 - x1, h)

            if isinstance(v, SparseSet):
                for (b, e) in v.iterrange():
                    draw(b, e)
            elif isinstance(v, dict):
                for b in v.iterkeys():
                    draw(b, b + 1)
            elif isinstance(v, set):
                #for b in v:
                #   draw(b, b + 1)
                # maybe this is better? (fewer rectangles)
                l = list(v)
                l.sort()
                for (b, e) in collapse(l):
                    draw(b, e)
            else:
                # assumes sorted!
                for (b, e) in collapse(v):
                    draw(b, e)

class ModerateDownloadGauge(FancyDownloadGauge):

    def __init__(self, parent,
                 completed_color=None,
                 remaining_color=None,
                 border_color=None,
                 border=True,
                 size=(0,0),
                 top_line=False,
                 *args, **kwargs):
        FancyDownloadGauge.__init__(self, parent,
                                    completed_color=completed_color,
                                    remaining_color=remaining_color,
                                    border_color=border_color,
                                    border=border,
                                    size=size,
                                    top_line=top_line,
                                    *args, **kwargs)
        self.resolution = 1000

    def sort(a,b):
        if   isinstance(a, str) and isinstance(b, str) : return cmp(a,b)
        elif isinstance(a, int) and isinstance(b, int) : return cmp(b,a)
        elif isinstance(a, str): return -1
        elif isinstance(b, str): return  1

    sort = staticmethod(sort)

    def SetValue(self, value, state=None, data=None, redraw=True):
        if data is not None:
            sorted_data = {}
            length, update, piece_states = data
            self.resolution = length
            keys = piece_states.keys()
            keys.sort(self.sort)
            pos = 0
            h = piece_states.get('h', SparseSet())
            t = piece_states.get('t', set())
            t = list(t)
            t.sort()
            have_trans_sparse_set = h + t
            for k in keys:
                p = piece_states[k]
                if k in ('h', 't'):
                    count = len(p)
                else:
                    count = 0
                    # OW
                    for i in p:
                        if i not in have_trans_sparse_set:
                            count += 1
                if not count:
                    continue
                newpos = pos+count
                s = SparseSet()
                s.add(pos, newpos)
                sorted_data[k] = s
                pos = newpos
            data = (length, update, sorted_data)
        FancyDownloadGauge.SetValue(self, value, state, data, redraw)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.axwave.ak.test</groupId>
  <artifactId>audio-parent</artifactId>
  <version>1.0.0-SNAPSHOT</version>

  <packaging>pom</packaging>

  <modules>
    <module>./transport</module>
    <module>./client</module>
    <module>./server</module>
  </modules>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <maven.compiler.plugin.version>3.3</maven.compiler.plugin.version>
    <java.version>1.8</java.version>

    <findbugs.version>3.0.1</findbugs.version>
    <findbugs.plugin.version>3.0.3</findbugs.plugin.version>
    <pmd.plugin.version>3.5</pmd.plugin.version>
    <pmd.version>3.5</pmd.version>

    <hessian.version>4.0.38</hessian.version>
    <lombok.version>1.16.10</lombok.version>
    <log4j.version>1.2.17</log4j.version>
    <transport.version>1.0.0-SNAPSHOT</transport.version>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven.compiler.plugin.version}</version>
        <configuration>
          <source>${java.version}</source>
          <target>${java.version}</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-pmd-plugin</artifactId>
        <version>${pmd.version}</version>
        <configuration>
          <linkXRef>true</linkXRef>
          <skip>${skipCodeChecks}</skip>
          <targetJdk>${java.version}</targetJdk>
          <failOnViolation>true</failOnViolation>
          <failurePriority>4</failurePriority>
          <verbose>true</verbose>
          <aggregate>true</aggregate>
        </configuration>

        <executions>
          <execution>
            <phase>compile</phase>
            <goals>
              <goal>check</goal>
              <goal>cpd-check</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>${findbugs.plugin.version}</version>
        <configuration>
          <skip>${skipCodeChecks}</skip>
          <effort>Max</effort>
          <threshold>Low</threshold>
          <xmlOutput>true</xmlOutput>
          <failOnError>true</failOnError>
        </configuration>
        <executions>
          <execution>
            <phase>process-classes</phase>
            <goals>
              <goal>
                check
              </goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>

    <dependency>
      <groupId>com.caucho</groupId>
      <artifactId>hessian</artifactId>
      <version>${hessian.version}</version>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>findbugs-maven-plugin</artifactId>
      <version>${findbugs.version}</version>
      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-jdk14</artifactId>
        </exclusion>
        <exclusion>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>

  <repositories>
    <repository>
      <id>central</id>
      <name>Maven Repository Switchboard</name>
      <layout>default</layout>
      <url>http://repo1.maven.org/maven2</url>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>

    <repository>
      <id>spring-snapshots</id>
      <name>Spring Snapshots</name>
      <url>https://repo.spring.io/snapshot</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>

    <repository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/milestone</url>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>central</id>
      <name>Maven Plugin Repository</name>
      <url>http://repo1.maven.org/maven2</url>
      <layout>default</layout>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
    </pluginRepository>

    <pluginRepository>
      <id>spring-snapshots</id>
      <name>Spring Snapshots</name>
      <url>https://repo.spring.io/snapshot</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </pluginRepository>

    <pluginRepository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/milestone</url>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </pluginRepository>
  </pluginRepositories>

</project>