// Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.googlesource.gerrit.plugins.webhooks;

import com.google.gerrit.common.EventListener;
import com.google.gerrit.extensions.config.FactoryModule;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.inject.Scopes;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.http.impl.client.CloseableHttpClient;

public class Module extends FactoryModule {

  @Override
  protected void configure() {
    bind(ScheduledExecutorService.class)
        .annotatedWith(WebHooksExecutor.class)
        .toProvider(ExecutorProvider.class);
    bind(Configuration.class).in(Scopes.SINGLETON);
    bind(CloseableHttpClient.class).toProvider(HttpClientProvider.class).in(Scopes.SINGLETON);
    factory(PostTask.Factory.class);
    DynamicSet.bind(binder(), EventListener.class).to(EventHandler.class);
  }
}

// Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.googlesource.gerrit.plugins.webhooks;

import com.google.gerrit.common.EventListener;
import com.google.gerrit.extensions.config.FactoryModule;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.inject.Scopes;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.http.impl.client.CloseableHttpClient;

public class Module extends FactoryModule {

  @Override
  protected void configure() {
    bind(ScheduledExecutorService.class)
        .annotatedWith(WebHooksExecutor.class)
        .toProvider(ExecutorProvider.class);
    bind(CloseableHttpClient.class).toProvider(HttpClientProvider.class).in(Scopes.SINGLETON);
    factory(PostTask.Factory.class);
    DynamicSet.bind(binder(), EventListener.class).to(EventHandler.class);
  }
}

Remove binding to singleton as Configuration has already Singleton scope

Change-Id: Ia43162be3ea477e10401c914f424949de4e18d6e
Signed-off-by: Jacek Centkowski <ce4a73803a80af51ece4477dad59cc7b1801c73e@collab.net>


package se.ericthelin.fractions;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class GreatestCommonDivisorTest {

	@Test
	public void returnsFirstWhenSecondIsZero() {
		assertThat(GreatestCommonDivisor.of(6, 0), is(6));
	}

	@Test
	public void returnsSecondWhenFirstIsZero() {
		assertThat(GreatestCommonDivisor.of(0, 4), is(4));
	}

	@Test
	public void returnsGreatestCommonDivisorOfFirstAndSecond() {
		assertThat(GreatestCommonDivisor.of(6, 4), is(2));
	}
}

package se.ericthelin.fractions;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class GreatestCommonDivisorTest {

	@Test
	public void returnsFirstWhenSecondIsZero() {
		assertThat(GreatestCommonDivisor.of(6, 0), is(6));
	}

	@Test
	public void returnsSecondWhenFirstIsZero() {
		assertThat(GreatestCommonDivisor.of(0, 4), is(4));
	}

	@Test
	public void returnsGreatestCommonDivisorOfFirstAndSecond() {
		assertThat(GreatestCommonDivisor.of(6, 4), is(2));
	}

	@Test
	public void acceptsArgumentsInReverseOrder() {
		assertThat(GreatestCommonDivisor.of(4, 6), is(2));
	}
}

Check that GreatestCommonDivisor accepts arguments in reverse order


package com.btk5h.skriptmirror;

import ch.njol.skript.Skript;
import ch.njol.skript.lang.SyntaxElement;
import ch.njol.skript.lang.SyntaxElementInfo;

import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;

public class ParseOrderWorkarounds {
  private static String[] PARSE_ORDER = {
      "com.btk5h.skriptmirror.skript.CondExpressionStatement",
      "com.w00tmast3r.skquery.elements.conditions.CondBoolean",
      "com.pie.tlatoani.Miscellaneous.CondBoolean"
  };

  public static void reorderSyntax() {
    Arrays.stream(PARSE_ORDER)
        .forEach(c -> {
          ensureLast(Skript.getStatements(), c);
          ensureLast(Skript.getConditions(), c);
        });
  }

  private static <E extends SyntaxElement> void ensureLast(Collection<SyntaxElementInfo<? extends E>> elements,
                                                           String element) {
    Optional<SyntaxElementInfo<? extends E>> optionalElementInfo = elements.stream()
        .filter(info -> info.c.getName().equals(element))
        .findFirst();

    optionalElementInfo.ifPresent(elementInfo -> {
      elements.remove(elementInfo);
      elements.add(elementInfo);
    });
  }
}

package com.btk5h.skriptmirror;

import ch.njol.skript.Skript;
import ch.njol.skript.lang.SyntaxElement;
import ch.njol.skript.lang.SyntaxElementInfo;

import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;

public class ParseOrderWorkarounds {
  private static String[] PARSE_ORDER = {
      "com.btk5h.skriptmirror.skript.CondExpressionStatement",
      "com.btk5h.skriptmirror.skript.custom.effect.CustomEffect",
      "com.btk5h.skriptmirror.skript.custom.condition.CustomCondition",
      "com.w00tmast3r.skquery.elements.conditions.CondBoolean",
      "com.pie.tlatoani.Miscellaneous.CondBoolean"
  };

  public static void reorderSyntax() {
    Arrays.stream(PARSE_ORDER)
        .forEach(c -> {
          ensureLast(Skript.getStatements(), c);
          ensureLast(Skript.getConditions(), c);
          ensureLast(Skript.getEffects(), c);
        });
  }

  private static <E extends SyntaxElement> void ensureLast(Collection<SyntaxElementInfo<? extends E>> elements,
                                                           String element) {
    Optional<SyntaxElementInfo<? extends E>> optionalElementInfo = elements.stream()
        .filter(info -> info.c.getName().equals(element))
        .findFirst();

    optionalElementInfo.ifPresent(elementInfo -> {
      elements.remove(elementInfo);
      elements.add(elementInfo);
    });
  }
}

Reorder custom effects and conditions

Reorder custom effects and conditions


package beaform.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class Formula {

	@Id @GeneratedValue(generator = "uuid")
	@GenericGenerator(name="uuid", strategy="uuid2")

	private String id;
	private String name;
	private String description;

	public String getId() {
		return this.id;
	}

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

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return this.description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}

package beaform.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class Formula {

	@Id @GeneratedValue(generator = "uuid")
	@GenericGenerator(name="uuid", strategy="uuid2")

	private String id;
	private String name;
	private String description;

	public String getId() {
		return this.id;
	}

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

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return this.description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append(this.id);
		builder.append(" | ");
		builder.append(this.name);
		builder.append(" | ");
		builder.append(this.description);

		return builder.toString();

	}

}

Add a more useful toString method for a formula


package com.devinci.lib.util;

import android.os.Build;

/**
 * Utility methods to check Android version.
 */
public enum Versions {
  ;

  /**
   * Checks if the device is at least Marshmallow 6.0 API23.
   *
   * @return true if the device is API >= 23, false otherwise
   */
  public static boolean isMarshmallow() {
    //TODO t.rozbicki 31.08.15 replace with Marshmallow version code
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
  }

  /**
   * Checks if the device is at least Lollipop 5.1 API22.
   *
   * @return true if the device is API >= 22, false otherwise
   */
  public static boolean isLollipopMR1() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
  }

  /**
   * Checks if the device is at least Lollipop 5.0 API21.
   *
   * @return true if the device is API >= 21, false otherwise
   */
  public static boolean isLollipop() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
  }
}

package com.devinci.lib.util;

import android.os.Build;

/**
 * Utility methods to check Android version.
 */
public class Versions {

  private Versions() {
  }

  /**
   * Checks if the device is at least Marshmallow 6.0 API23.
   *
   * @return true if the device is API >= 23, false otherwise
   */
  public static boolean isMarshmallow() {
    //TODO t.rozbicki 31.08.15 replace with Marshmallow version code
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
  }

  /**
   * Checks if the device is at least Lollipop 5.1 API22.
   *
   * @return true if the device is API >= 22, false otherwise
   */
  public static boolean isLollipopMR1() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
  }

  /**
   * Checks if the device is at least Lollipop 5.0 API21.
   *
   * @return true if the device is API >= 21, false otherwise
   */
  public static boolean isLollipop() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
  }
}

Use private constructor instead of enum to prevent instances


package io.quarkus.it.main;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;

import io.quarkus.it.arc.UnusedBean;
import io.quarkus.test.junit.QuarkusTest;

@QuarkusTest
public class DynamicTestsTestCase {

    @Inject
    UnusedBean bean;

    @Test
    public void testInjection() {
        assertNotNull(bean);
    }

    @TestFactory
    public List<?> dynamicTests() {
        return Arrays.asList(
                DynamicTest.dynamicTest("test 1", () -> {
                    assertNotNull(bean);
                }),
                DynamicTest.dynamicTest("test 2", () -> {
                    assertEquals(1, 1);
                }));
    }
}

package io.quarkus.it.main;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;

import io.quarkus.it.arc.UnusedBean;
import io.quarkus.test.junit.QuarkusTest;

@QuarkusTest
public class DynamicTestsTestCase {

    @Inject
    UnusedBean bean;

    @Test
    public void testInjection() {
        assertNotNull(bean);
    }

    @TestFactory
    public List<DynamicTest> dynamicTests() {
        return Arrays.asList(
                DynamicTest.dynamicTest("test 1", () -> {
                    assertNotNull(bean);
                }),
                DynamicTest.dynamicTest("test 2", () -> {
                    assertEquals(1, 1);
                }));
    }
}

Use the actual DynamicTest type

Use the actual DynamicTest type

? was only used with the previous solution,
with the new solution, code can refer to the type
without any problem


package com.github.arteam.jdbi3.strategies;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.annotation.Timed;
import org.jdbi.v3.core.extension.ExtensionMethod;
import org.jdbi.v3.core.statement.StatementContext;

import java.lang.reflect.Method;

/**
 * Takes into account the {@link Timed} annotation on extension methods
 */
public class TimedAnnotationNameStrategy implements StatementNameStrategy {

    @Override
    public String getStatementName(StatementContext statementContext) {
        ExtensionMethod extensionMethod = statementContext.getExtensionMethod();
        if (extensionMethod != null) {
            final Class<?> clazz = extensionMethod.getType();
            final Method method = extensionMethod.getMethod();
            final Timed timed = method.getAnnotation(Timed.class);
            if (timed != null) {
                return timed.absolute() ? timed.name() : MetricRegistry.name(clazz, timed.name());
            }
        }
        return null;
    }
}

package com.github.arteam.jdbi3.strategies;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.annotation.Timed;
import org.jdbi.v3.core.extension.ExtensionMethod;
import org.jdbi.v3.core.statement.StatementContext;

import java.lang.reflect.Method;

/**
 * Takes into account the {@link Timed} annotation on extension methods
 */
public class TimedAnnotationNameStrategy implements StatementNameStrategy {

    @Override
    public String getStatementName(StatementContext statementContext) {
        ExtensionMethod extensionMethod = statementContext.getExtensionMethod();
        if (extensionMethod != null) {
            final Class<?> clazz = extensionMethod.getType();
            final Timed classTimed = clazz.getAnnotation(Timed.class);
            final Method method = extensionMethod.getMethod();
            final Timed methodTimed = method.getAnnotation(Timed.class);
            // If the method is metered, figure out the name
            if (methodTimed != null) {
                if (methodTimed.absolute()) {
                    return methodTimed.name();
                } else {
                    // We need to check if the class has a custom timer name
                    return classTimed == null ? MetricRegistry.name(clazz, methodTimed.name()) :
                            MetricRegistry.name(classTimed.name(), methodTimed.name());
                }
            }
            // Maybe the class is metered?
            if (classTimed != null) {
                return MetricRegistry.name(classTimed.name(), method.getName());
            }
        }
        return null;
    }
}

Add support for annotating the class as `@Timed`


package com.stephentuso.welcome.ui;

import android.view.View;

/**
 * Created by stephentuso on 11/15/15.
 */
public class SkipButton extends WelcomeScreenViewWrapper {

    private boolean enabled = true;

    public SkipButton(View button, boolean enabled) {
        super(button);
        this.enabled = enabled;
        if (!enabled)
            button.setVisibility(View.GONE);
    }

    @Override
    public void onPageSelected(int pageIndex, int lastPageIndex) {
        setVisibility(enabled && pageIndex != lastPageIndex);
    }

}

package com.stephentuso.welcome.ui;

import android.view.View;

/**
 * Created by stephentuso on 11/15/15.
 */
public class SkipButton extends WelcomeScreenViewWrapper {

    private boolean enabled = true;

    public SkipButton(View button, boolean enabled) {
        super(button);
        this.enabled = enabled;
        if (!enabled)
            button.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onPageSelected(int pageIndex, int lastPageIndex) {
        setVisibility(enabled && pageIndex != lastPageIndex);
    }

}

Fix layout issue when skipping is disabled


/*
 * The MIT License
 *
 * Copyright (c) 2010 The Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package net.sf.picard.cmdline;

public class CreateHtmlDocForStandardOptions {
    public static void main(final String[] args) throws Exception {
        CommandLineParser clp = new CommandLineParser(new DummyProgram());
        clp.htmlPrintOptions(System.out, true);
    }

    static class DummyProgram extends CommandLineProgram {
        @Override
        protected int doWork() {
            return 0;
        }
    }
}

/*
 * The MIT License
 *
 * Copyright (c) 2010 The Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package net.sf.picard.cmdline;

public class CreateHtmlDocForStandardOptions {
    public static void main(final String[] args) throws Exception {
        System.setProperty("java.io.tmpdir", "<System temp directory>");
        System.setProperty("user.name", "<current user name>");
        CommandLineParser clp = new CommandLineParser(new DummyProgram());
        clp.htmlPrintOptions(System.out, true);
    }

    static class DummyProgram extends CommandLineProgram {
        @Override
        protected int doWork() {
            return 0;
        }
    }
}

Fix HTML help generation for TMP_DIR so it has a more generic default value.


package recursion.cons.ismember;

import plm.universe.bat.BatTest;
import plm.universe.cons.ConsEntity;
import plm.universe.cons.RecList;

public class IsMemberEntity extends ConsEntity {

	@Override
	public void run(BatTest t) {
		RecList parameter = RecList.fromArray( (int[]) t.getParameter(0) );
		t.setResult( isMember( parameter, (int)t.getParameter(1) ) );
	}

	/* BEGIN TEMPLATE */
	Boolean isMember(RecList seq, int val) {
		/* BEGIN SOLUTION */
		if (seq == null)
			return false;
		if (seq.head == val)
			return true;
		return isMember(seq.tail,val);
		/* END SOLUTION */
	}
	/* END TEMPLATE */
}

package recursion.cons.ismember;

import plm.universe.bat.BatTest;
import plm.universe.cons.ConsEntity;
import plm.universe.cons.RecList;

public class IsMemberEntity extends ConsEntity {

	@Override
	public void run(BatTest t) {
		RecList parameter = RecList.fromArray( (int[]) t.getParameter(0) );
		t.setResult( isMember( parameter, (int)t.getParameter(1) ) );
	}

	/* BEGIN TEMPLATE */
	boolean isMember(RecList seq, int val) {
		/* BEGIN SOLUTION */
		if (seq == null)
			return false;
		if (seq.head == val)
			return true;
		return isMember(seq.tail,val);
		/* END SOLUTION */
	}
	/* END TEMPLATE */
}

Fix Java entity of exercise 'IsMember'

Fix Java entity of exercise 'IsMember'


package com.fsck.k9.view;

import android.content.Context;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class K9PullToRefreshListView extends PullToRefreshListView {

    public K9PullToRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected ListView createListView(Context context, AttributeSet attrs) {
        return new ListView(context, attrs) {
            @Override
            public void onRestoreInstanceState(Parcelable state) {
                super.onRestoreInstanceState(state);

                /*
                 * Force the list view to apply the restored state instantly instead of
                 * asynchronously, so potential data changes (which in turn cause an internal
                 * position save/restore) don't overwrite our saved position.
                 */
                layoutChildren();
            }
        };
    }
}

package com.fsck.k9.view;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class K9PullToRefreshListView extends PullToRefreshListView {

    public K9PullToRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected ListView createListView(Context context, AttributeSet attrs) {
        return new ListView(context, attrs) {
            @Override
            public void onRestoreInstanceState(Parcelable state) {
                super.onRestoreInstanceState(state);

                /*
                 * Force the list view to apply the restored state instantly instead of
                 * asynchronously, so potential data changes (which in turn cause an internal
                 * position save/restore) don't overwrite our saved position.
                 */
                layoutChildren();
            }

            @Override
            protected void dispatchDraw(Canvas canvas) {
                if (getAdapter() != null) {
                    int count = getChildCount();
                    int itemCount = getAdapter().getCount();

                    /*
                     * 2013-03-18 - cketti
                     *
                     * Work around a bug in ListView (?) that leads to a crash deep inside the
                     * framework code.
                     * I didn't track down the exact cause of this. My best guess is that we change
                     * the data (remove items) while the ListView isn't visible. Probably because
                     * the view is hidden, layoutChildren() is never called and when this method
                     * runs the layout contains more item views than the adapter contains elements
                     * and bad things(tm) happen.
                     */
                    if (itemCount < count) {
                        layoutChildren();
                    }
                }

                super.dispatchDraw(canvas);
            }
        };
    }
}

Work around a bug in ListView

Work around a bug in ListView


package com.lhkbob.entreri.task;

import com.lhkbob.entreri.EntitySystem;

public final class Timers {

    public static Task fixedDelta(double dt) {
        return new FixedDeltaTask(dt);
    }

    public static Task measuredDelta() {
        return new MeasuredDeltaTask();
    }

    private static class FixedDeltaTask implements Task {
        private final ElapsedTimeResult delta;

        public FixedDeltaTask(double dt) {
            delta = new ElapsedTimeResult(dt);
        }

        @Override
        public Task process(EntitySystem system, Job job) {
            job.report(delta);
            return null;
        }

        @Override
        public void reset(EntitySystem system) {
            // do nothing
        }
    }

    private static class MeasuredDeltaTask implements Task {
        private long lastStart = -1L;

        @Override
        public Task process(EntitySystem system, Job job) {
            long now = System.nanoTime();
            if (lastStart <= 0) {
                job.report(new ElapsedTimeResult(0));
            } else {
                job.report(new ElapsedTimeResult((now - lastStart) / 1e9));
            }
            lastStart = now;

            return null;
        }

        @Override
        public void reset(EntitySystem system) {
            // do nothing
        }
    }
}

package com.lhkbob.entreri.task;

import java.util.Collections;
import java.util.Set;

import com.lhkbob.entreri.ComponentData;
import com.lhkbob.entreri.EntitySystem;

public final class Timers {

    public static Task fixedDelta(double dt) {
        return new FixedDeltaTask(dt);
    }

    public static Task measuredDelta() {
        return new MeasuredDeltaTask();
    }

    private static class FixedDeltaTask implements Task, ParallelAware {
        private final ElapsedTimeResult delta;

        public FixedDeltaTask(double dt) {
            delta = new ElapsedTimeResult(dt);
        }

        @Override
        public Task process(EntitySystem system, Job job) {
            job.report(delta);
            return null;
        }

        @Override
        public void reset(EntitySystem system) {
            // do nothing
        }

        @Override
        public Set<Class<? extends ComponentData<?>>> getAccessedComponents() {
            return Collections.emptySet();
        }

        @Override
        public boolean isEntitySetModified() {
            return false;
        }
    }

    private static class MeasuredDeltaTask implements Task, ParallelAware {
        private long lastStart = -1L;

        @Override
        public Task process(EntitySystem system, Job job) {
            long now = System.nanoTime();
            if (lastStart <= 0) {
                job.report(new ElapsedTimeResult(0));
            } else {
                job.report(new ElapsedTimeResult((now - lastStart) / 1e9));
            }
            lastStart = now;

            return null;
        }

        @Override
        public void reset(EntitySystem system) {
            // do nothing
        }

        @Override
        public Set<Class<? extends ComponentData<?>>> getAccessedComponents() {
            return Collections.emptySet();
        }

        @Override
        public boolean isEntitySetModified() {
            return false;
        }
    }
}

Make the timing tasks parallel aware.

Make the timing tasks parallel aware.


package assettocorsa.servermanager.services;

import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by pete on 3/04/2015.
 */
public interface IAppSettingsService {
    public void loadAppSettings() throws IOException, IOException;
    public void storeAppSettings() throws IOException;

    public String getAssettoCorsaDirectory();
    public void setAssettoCorsaDirectorty(String dir);

    public String getExportDirectory();
    public void setExportDirectorty(String dir);

}

package assettocorsa.servermanager.services;

import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by pete on 3/04/2015.
 */
public interface IAppSettingsService {
    public void loadAppSettings() throws IOException;
    public void storeAppSettings() throws IOException;

    public String getAssettoCorsaDirectory();
    public void setAssettoCorsaDirectorty(String dir);

    public String getExportDirectory();
    public void setExportDirectorty(String dir);

}

Remove double up on exception list for load settings


import backend.Core;
import java.io.IOException;
import parse.GreetParser;
import parse.StepParser;

public class App {
  public String getGreeting() {
    return "Hello world.";
  }

  /**
   * Main entry point to G2Tutorial.
   *
   * @param  args commandline arguments
   */
  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Available commands:\n\tgreet");
      System.exit(1);
    }

    if (args[0].equals("greet")) {
      // Greet just exists as a template for parsing
      GreetParser p = new GreetParser(args);
      p.parse();
    } else if (args[0].equals("init")) {
      // Initializes an empty git repo
      try {
        Core.initCore();
      } catch (IOException e) {
        System.err.println("Could not init g2t");
        e.printStackTrace();
      }
      System.exit(0);
    } else if (args[0].equals("step")) {
      // Commits the current changes as a step and starts a new step
      Core c = null;
      try {
        c = new Core();
      } catch (IOException e) {
        System.err.println("g2t is not initialized");
        e.printStackTrace();
      }
      StepParser p = new StepParser(args, c);
      p.parse();
    } else {
      System.out.println("Available commands:\n"
          + "\tgreet, init");
      System.exit(1);
    }
  }
}

import backend.Core;
import java.io.IOException;
import parse.GreetParser;
import parse.StepParser;

public class App {
  public String getGreeting() {
    return "Hello world.";
  }

  /**
   * Main entry point to G2Tutorial.
   *
   * @param  args commandline arguments
   */
  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Available commands:\n\tgreet");
      System.exit(1);
    }

    if (args[0].equals("greet")) {
      // Greet just exists as a template for parsing
      GreetParser p = new GreetParser(args);
      p.parse();
    } else if (args[0].equals("init")) {
      // Initializes an empty git repo
      try {
        Core.initCore();
      } catch (IOException e) {
        System.err.println("Could not init g2t");
        e.printStackTrace();
      }
      System.exit(0);
    } else if (args[0].equals("step")) {
      // Commits the current changes as a step and starts a new step
      Core c = null;
      try {
        c = new Core();
      } catch (IOException e) {
        System.err.println("g2t is not initialized");
        e.printStackTrace();
      }
      StepParser p = new StepParser(args, c);
      p.parse();
    } else {
      System.out.println("Available commands:\n"
          + "\tgreet, init, step");
      System.exit(1);
    }
  }
}

Add step command to help

Add step command to help


package com.vaadin.components.grid;

import com.google.gwt.core.client.EntryPoint;

/**
 * Exports vaadin grid.
 */
public class GridEntryPoint implements EntryPoint {

    @Override
    public void onModuleLoad() {
    }
}

package com.vaadin.components.grid;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.user.client.ui.RootPanel;
import com.vaadin.client.BrowserInfo;

/**
 * Exports vaadin grid.
 */
public class GridEntryPoint implements EntryPoint {

    @Override
    public void onModuleLoad() {
        Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
            @Override
            public void execute() {
                RootPanel.get().removeStyleName(BrowserInfo.get().getCSSClass());
            }
        });
    }
}

Remove browser specific selectors from the body element

Change-Id: I2f38067cc33fc2c2c8e0e2a311a43213f73ad3c8


package com.thebuerkle.mcclient.request;
import org.apache.mina.core.buffer.IoBuffer;

public class HandshakeRequest extends Request {

    public final String username;
    public final String host;
    public final int port;

    public HandshakeRequest(String username, String host, int port) {
        super(0x02);

        this.username = username;
        this.host = host;
        this.port = port;
    }

    @Override()
    public int getSize() {
        return 1 + (2 + this.username.length()*2) + (2+ this.host.length()*2) + 4;
    }

    @Override()
    public void write(IoBuffer out) {
        mc_byte(out, 47); // 1.4 protocol version
        mc_string(out, username);
        mc_string(out, host);
        mc_int(out, port);
    }
}

package com.thebuerkle.mcclient.request;
import org.apache.mina.core.buffer.IoBuffer;

public class HandshakeRequest extends Request {

    public final String username;
    public final String host;
    public final int port;

    public HandshakeRequest(String username, String host, int port) {
        super(0x02);

        this.username = username;
        this.host = host;
        this.port = port;
    }

    @Override()
    public int getSize() {
        return 1 + (2 + this.username.length()*2) + (2+ this.host.length()*2) + 4;
    }

    @Override()
    public void write(IoBuffer out) {
        mc_byte(out, 49); // 1.4.4 protocol version
        mc_string(out, username);
        mc_string(out, host);
        mc_int(out, port);
    }
}

Update protocol version to 49

Update protocol version to 49


package valandur.webapi.servlet.registry;

import org.eclipse.jetty.http.HttpMethod;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.Sponge;
import valandur.webapi.api.annotation.WebAPIEndpoint;
import valandur.webapi.api.annotation.WebAPIServlet;
import valandur.webapi.api.servlet.WebAPIBaseServlet;
import valandur.webapi.servlet.ServletData;

import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

@WebAPIServlet(basePath = "registry")
public class RegistryServlet extends WebAPIBaseServlet {

    @WebAPIEndpoint(method = HttpMethod.GET, path = "/:class", perm = "one")
    public void getRegistry(ServletData data, String className) {
        try {
            Class type = Class.forName(className);
            if (!CatalogType.class.isAssignableFrom(type)) {
                data.sendError(HttpServletResponse.SC_BAD_REQUEST, "Class must be a CatalogType");
                return;
            }

            Collection<CatalogType> types = Sponge.getRegistry().getAllOf(type);
            data.addJson("types", types, false);
        } catch (ClassNotFoundException e) {
            data.sendError(HttpServletResponse.SC_NOT_FOUND, "Class " + className + " could not be found");
        }
    }
}

package valandur.webapi.servlet.registry;

import org.eclipse.jetty.http.HttpMethod;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.Sponge;
import valandur.webapi.api.annotation.WebAPIEndpoint;
import valandur.webapi.api.annotation.WebAPIServlet;
import valandur.webapi.api.servlet.WebAPIBaseServlet;
import valandur.webapi.servlet.ServletData;

import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

@WebAPIServlet(basePath = "registry")
public class RegistryServlet extends WebAPIBaseServlet {

    @WebAPIEndpoint(method = HttpMethod.GET, path = "/:class", perm = "one")
    public void getRegistry(ServletData data, String className) {
        try {
            Class type = Class.forName(className);
            if (!CatalogType.class.isAssignableFrom(type)) {
                data.sendError(HttpServletResponse.SC_BAD_REQUEST, "Class must be a CatalogType");
                return;
            }

            Collection<CatalogType> types = Sponge.getRegistry().getAllOf(type);
            data.addJson("ok", true, false);
            data.addJson("types", types, false);
        } catch (ClassNotFoundException e) {
            data.sendError(HttpServletResponse.SC_NOT_FOUND, "Class " + className + " could not be found");
        }
    }
}

Return "ok" field in json response

fix(registry): Return "ok" field in json response


package managers.nodes;

import com.fasterxml.jackson.databind.JsonNode;
import play.libs.F.Promise;

public class UserManager extends LabeledNodeWithPropertiesManager {

    public UserManager() {
        this.label = "User";
    }

    @Override
    protected Promise<Boolean> create(JsonNode properties, String location) {
        return super.create(properties, location, "username");
    }

}

package managers.nodes;

import com.fasterxml.jackson.databind.JsonNode;
import play.libs.F.Promise;

public class UserManager extends LabeledNodeWithPropertiesManager {

    public UserManager() {
        this.label = "User";
    }

    // CREATE

    @Override
    protected Promise<Boolean> create(JsonNode properties, String location) {
        return super.create(properties, location, "username");
    }

}

WIP: Enable operations that write to the DB to be rolled back on error
by wrapping them in transactions.

Add comments to indicate purpose of groups of related `UserManager`
methods.


package com.githang.statusbar;

import android.annotation.TargetApi;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

/**
 * 兼容M版本
 *
 * @author 黄浩杭 (huanghaohang@parkingwang.com)
 * @version 2016-06-20
 * @since 2016-06-20
 */

class StatusBarCompatM {
    @TargetApi(Build.VERSION_CODES.M)
    static void setStatusBarColor(Window window, int color, boolean lightStatusBar) {
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        window.setStatusBarColor(color);
        View decor = window.getDecorView();
        int ui = decor.getSystemUiVisibility();
        if (lightStatusBar) {
            ui |=View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        } else {
            ui &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        }
        decor.setSystemUiVisibility(ui);
    }

}

package com.githang.statusbar;

import android.annotation.TargetApi;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

/**
 * 兼容M版本
 *
 * @author 黄浩杭 (huanghaohang@parkingwang.com)
 * @version 2016-06-20
 * @since 2016-06-20
 */

class StatusBarCompatM {
    @TargetApi(Build.VERSION_CODES.M)
    static void setStatusBarColor(Window window, int color, boolean lightStatusBar) {
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        window.setStatusBarColor(color);

        // 设置浅色状态栏时的界面显示
        View decor = window.getDecorView();
        int ui = decor.getSystemUiVisibility();
        if (lightStatusBar) {
            ui |=View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        } else {
            ui &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        }
        decor.setSystemUiVisibility(ui);

        // 去掉系统状态栏下的windowContentOverlay
        View v = window.findViewById(android.R.id.content);
        if (v != null) {
            v.setForeground(null);
        }
    }

}

Remove the shadow below status bar that occurs in version greater than M.


package pw.scho.battleship.model;

import java.util.Random;

public class BoardRandomizer {

    private final Random random = new Random();
    private Board board;

    public Board randomizeWithStandardShips() {
        return randomize(new int[]{2, 2, 2, 2, 3, 3, 3, 4, 4, 5});
    }

    public Board randomize(int[] shipSizes) {
        board = new Board();

        for (int size : shipSizes) {
            placeShip(size);
        }

        return board;
    }

    private void placeShip(int size) {
        while (true) {
            Ship ship = createRandomShip(size);

            if (board.shipIsPlaceable(ship)) {
                board.placeShip(ship);
                break;
            }
        }
    }

    private Ship createRandomShip(int size) {
        int x = random.nextInt(Board.WIDTH - 1);
        int y = random.nextInt(Board.HEIGHT - 1);

        Position position = new Position(x, y);

        if (random.nextBoolean()) {
            return Ship.createHorizontal(position, size);
        } else {
            return Ship.createVertical(position, size);
        }
    }
}

package pw.scho.battleship.model;

import java.util.Random;

public class BoardRandomizer {

    private final Random random = new Random();
    private Board board;

    public Board randomizeWithStandardShips() {
        return randomize(new int[]{2, 2, 3, 3, 4, 5});
    }

    public Board randomize(int[] shipSizes) {
        board = new Board();

        for (int size : shipSizes) {
            placeShip(size);
        }

        return board;
    }

    private void placeShip(int size) {
        while (true) {
            Ship ship = createRandomShip(size);

            if (board.shipIsPlaceable(ship)) {
                board.placeShip(ship);
                break;
            }
        }
    }

    private Ship createRandomShip(int size) {
        int x = random.nextInt(Board.WIDTH - 1);
        int y = random.nextInt(Board.HEIGHT - 1);

        Position position = new Position(x, y);

        if (random.nextBoolean()) {
            return Ship.createHorizontal(position, size);
        } else {
            return Ship.createVertical(position, size);
        }
    }
}

Reduce number of placed ships

Reduce number of placed ships


/*
 * 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 org.opensim.threejs;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.eclipse.jetty.JettyMain;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
import org.opensim.swingui.SwingWorker;
import org.opensim.utils.BrowserLauncher;
import org.opensim.view.pub.OpenSimDB;
import org.opensim.view.pub.ViewDB;

@ActionID(
        category = "Edit",
        id = "org.opensim.threejs.VisualizerWindow"
)
@ActionRegistration(
        displayName = "#CTL_VisualizerWindow"
)
@ActionReference(path = "Menu/Window", position = 3333)
@Messages("CTL_VisualizerWindow=Visualizer")
public final class VisualizerWindowAction implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // launch server and open page in fixed location to be used as a view
        openVisualizerWindow();
    }

    public static void openVisualizerWindow() {
        ViewDB.getInstance().startVisualizationServer();
        BrowserLauncher.openURL("http://localhost:"+JettyMain.getServerPort()+JettyMain.getPathToStartPage()+"index.html");
    }

}

/*
 * 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 org.opensim.threejs;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.eclipse.jetty.JettyMain;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
import org.opensim.swingui.SwingWorker;
import org.opensim.utils.BrowserLauncher;
import org.opensim.view.pub.OpenSimDB;
import org.opensim.view.pub.ViewDB;

@ActionID(
        category = "Edit",
        id = "org.opensim.threejs.VisualizerWindow"
)
@ActionRegistration(
        displayName = "#CTL_VisualizerWindow"
)
@ActionReference(path = "Menu/Window", position = 3333)
@Messages("CTL_VisualizerWindow=Vis Browser")
public final class VisualizerWindowAction implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // launch server and open page in fixed location to be used as a view
        openVisualizerWindow();
    }

    public static void openVisualizerWindow() {
        ViewDB.getInstance().startVisualizationServer();
        BrowserLauncher.openURL("http://localhost:"+JettyMain.getServerPort()+JettyMain.getPathToStartPage()+"index.html");
    }

}

Rename menu pick that opens into Browser as VisBrowser. Changing JxBrowser menu pick to Visualizer to follow.


package io.cattle.platform.core.constants;

public class ProjectConstants {

    public static final String TYPE = "project";
    public static final String PROJECT_DEFAULT_NAME = " Default";

    public static final String RANCHER_ID = "rancher_id";

    public static final String OWNER = "owner";
    public static final String MEMBER = "member";

    public static final String AUTH_HEADER = "Authorization";
    public static final String OAUTH_BASIC = "X-API-BEARER=";
    public static final String AUTH_TYPE = "bearer ";
    public static final String PROJECT_HEADER = "X-API-Project-Id";

}

package io.cattle.platform.core.constants;

public class ProjectConstants {

    public static final String TYPE = "project";
    public static final String PROJECT_DEFAULT_NAME = " Default";

    public static final String RANCHER_ID = "rancher_id";

    public static final String OWNER = "owner";
    public static final String MEMBER = "member";

    public static final String AUTH_HEADER = "Authorization";
    public static final String OAUTH_BASIC = "X-API-BEARER";
    public static final String AUTH_TYPE = "bearer ";
    public static final String PROJECT_HEADER = "X-API-Project-Id";

}

Remove = requirement from the x-api-bearer.


/* (C) 2012 Pragmatic Software
   This Source Code Form is subject to the terms of the Mozilla Public
   License, v. 2.0. If a copy of the MPL was not distributed with this
   file, You can obtain one at http://mozilla.org/MPL/2.0/
   */

package com.googlecode.networklog;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;

import android.support.v4.app.DialogFragment;

public class DatePickerFragment extends DialogFragment {
  int year;
  int month;
  int day;
  DatePickerDialog.OnDateSetListener listener;

  public DatePickerFragment() {
  }

  public DatePickerFragment(int year, int month, int day, DatePickerDialog.OnDateSetListener listener) {
    this(year, month, day);
    this.listener = listener;
  }

  public DatePickerFragment(int year, int month, int day) {
    this.year = year;
    this.month = month;
    this.day = day;
  }

  public void setListener(DatePickerDialog.OnDateSetListener listener) {
    this.listener = listener;
  }

  @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
      return new DatePickerDialog(getActivity(), this.listener, this.year, this.month, this.day);
    }
}

/* (C) 2012 Pragmatic Software
   This Source Code Form is subject to the terms of the Mozilla Public
   License, v. 2.0. If a copy of the MPL was not distributed with this
   file, You can obtain one at http://mozilla.org/MPL/2.0/
   */

package com.googlecode.networklog;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;

import java.util.Calendar;

import android.support.v4.app.DialogFragment;

public class DatePickerFragment extends DialogFragment {
  int year;
  int month;
  int day;
  DatePickerDialog.OnDateSetListener listener;

  public DatePickerFragment() {
    Calendar cal = Calendar.getInstance();
    this.year = cal.get(Calendar.YEAR);
    this.month = cal.get(Calendar.MONTH);
    this.day = cal.get(Calendar.DAY_OF_MONTH);
  }

  public DatePickerFragment(int year, int month, int day, DatePickerDialog.OnDateSetListener listener) {
    this(year, month, day);
    this.listener = listener;
  }

  public DatePickerFragment(int year, int month, int day) {
    this.year = year;
    this.month = month;
    this.day = day;
  }

  public void setListener(DatePickerDialog.OnDateSetListener listener) {
    this.listener = listener;
  }

  @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
      return new DatePickerDialog(getActivity(), this.listener, this.year, this.month, this.day);
    }
}

Fix issue with DatePicker rotation in FROYO/GINGERBREAD


/*
 * Copyright 2006-2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.openspaces.pu.container.support;

import org.openspaces.pu.container.CannotCloseContainerException;
import org.openspaces.pu.container.ProcessingUnitContainer;

/**
 * Compound processing unit container wraps several processing unit containers and
 * allows to close them.
 *
 * @author kimchy
 */
public class CompoundProcessingUnitContainer implements ProcessingUnitContainer {

    private ProcessingUnitContainer[] containers;

    public CompoundProcessingUnitContainer(ProcessingUnitContainer[] containers) {
        this.containers = containers;
    }

    public void close() throws CannotCloseContainerException {
        for (ProcessingUnitContainer container : containers) {
            container.close();
        }
    }
}

/*
 * Copyright 2006-2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.openspaces.pu.container.support;

import org.openspaces.pu.container.CannotCloseContainerException;
import org.openspaces.pu.container.ProcessingUnitContainer;

/**
 * Compound processing unit container wraps several processing unit containers and
 * allows to close them.
 *
 * @author kimchy
 */
public class CompoundProcessingUnitContainer implements ProcessingUnitContainer {

    private final ProcessingUnitContainer[] containers;

    public CompoundProcessingUnitContainer(ProcessingUnitContainer[] containers) {
        this.containers = containers;
    }

    /**
     * @return the underlying processing unit containers.
     * @since 8.0.3
     */
    public ProcessingUnitContainer[] getProcessingUnitContainers() {
        return containers;
    }

    public void close() throws CannotCloseContainerException {
        for (ProcessingUnitContainer container : containers) {
            container.close();
        }
    }
}

GS-8956: Allow extracting Processing Unit Containers from a Compound Processing Unit Container

svn path=/trunk/openspaces/; revision=89106

Former-commit-id: acf333707ebb008757b03896f93f1d252dca2b62


package com.structurizr.example.structurizr;

import com.structurizr.Workspace;
import com.structurizr.api.StructurizrClient;

public class UploadToStructurizr extends AbstractStructurizrWorkspace {

    public static void main(String[] args) throws Exception {
        new UploadToStructurizr().run();
    }

    void run() throws Exception {
        Workspace workspace = readFromFile();
        StructurizrClient structurizrClient = new StructurizrClient();
        structurizrClient.mergeWorkspace(121, workspace);
    }

}

package com.structurizr.example.structurizr;

import com.structurizr.Workspace;
import com.structurizr.api.StructurizrClient;

import java.io.File;

public class UploadToStructurizr extends AbstractStructurizrWorkspace {

    public static void main(String[] args) throws Exception {
        new UploadToStructurizr().run();
    }

    void run() throws Exception {
        Workspace workspace = readFromFile();
        StructurizrClient structurizrClient = new StructurizrClient();
        structurizrClient.setWorkspaceArchiveLocation(new File(System.getProperty("user.home"), "structurizr-workspaces"));
        structurizrClient.mergeWorkspace(121, workspace);
    }

}

Save Structurizr workspaces to a persistent directory.


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.vfs2.example;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.VFS;

/**
 * Simply changed the last modification time of the given file
 */
public class ChangeLastModificationTime
{
    public static void main(String[] args) throws Exception
    {
        if (args.length == 0)
        {
            System.err.println("Please pass the name of a file as parameter.");
            return;
        }

        FileObject fo = VFS.getManager().resolveFile(args[0]);
        long setTo = System.currentTimeMillis();
        System.err.println("set to: " + setTo);
        fo.getContent().setLastModifiedTime(setTo);
        System.err.println("after set: " + fo.getContent().getLastModifiedTime());
    }
}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.vfs2.example;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.VFS;

/**
 * Simply changed the last modification time of the given file.
 */
public class ChangeLastModificationTime
{
    public static void main(String[] args) throws Exception
    {
        if (args.length == 0)
        {
            System.err.println("Please pass the name of a file as parameter.");
            return;
        }

        FileObject fo = VFS.getManager().resolveFile(args[0]);
        long setTo = System.currentTimeMillis();
        System.err.println("set to: " + setTo);
        fo.getContent().setLastModifiedTime(setTo);
        System.err.println("after set: " + fo.getContent().getLastModifiedTime());
    }
}

Fix Checkstyle issues: First sentence should end with a period.

git-svn-id: c455d203a03ec41bf444183aad31e7cce55db786@1352225 13f79535-47bb-0310-9956-ffa450edef68


package net.morimekta.providence.tools.common;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * General utility methods.
 */
public class Utils {
    public static String getVersionString() throws IOException {
        Properties properties = new Properties();
        try (InputStream in = Utils.class.getResourceAsStream("/version.properties")) {
            properties.load(in);
        }
        return "v" + properties.getProperty("build.version");
    }
}

package net.morimekta.providence.tools.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.Properties;

/**
 * General utility methods.
 */
public class Utils {
    private transient volatile static String versionString = null;

    public static String getVersionString() {
        if (versionString == null) {
            try {
                Properties properties = new Properties();
                try (InputStream in = Utils.class.getResourceAsStream("/version.properties")) {
                    properties.load(in);
                }
                versionString = "v" + properties.getProperty("build.version");
            } catch (IOException e) {
                throw new UncheckedIOException(e.getMessage(), e);
            }
        }
        return versionString;
    }
}

Read version string only once.

Read version string only once.


/*
Copyright (c) 2016 Sebastian Schmidt

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 */
package de.swm.nis.logicaldecoding.application;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import de.swm.nis.logicaldecoding.RefreshCacheApplication;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = RefreshCacheApplication.class)
public class RefreshCacheApplicationTests {

	@Test
	public void contextLoads() {
	}

}

/*
Copyright (c) 2016 Sebastian Schmidt

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 */
package de.swm.nis.logicaldecoding.application;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import de.swm.nis.logicaldecoding.RefreshCacheApplication;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = RefreshCacheApplication.class)
public class RefreshCacheApplicationTests {

	@Test
	public void contextLoads() {
	}

}

Migrate to Spring Boot 1.4.0

Migrate to Spring Boot 1.4.0


package com.example.e4.rcp.todo.events;

/**
 * @noimplement only used for constant definition
 */

public interface MyEventConstants {

	// this key can only used for event registration, you cannot
	// send out generic events
	String TOPIC_TODO_ALLTOPICS = "TOPIC_TODOS/*";

	// events to be send out
	String TOPIC_TODOS_CHANGED = "TOPIC_TODOS/CHANGED";

	String TOPIC_TODO_NEW = "TOPIC_TODOS/TODO/NEW";

	String TOPIC_TODO_DELETE = "TOPIC_TODOS/TODO/DELETED";

	String TOPIC_TODO_UPDATE = "TOPIC_TODOS/TODO/UPDATED";
}

package com.example.e4.rcp.todo.events;

/**
 * @noimplement This interface is not intended to be implemented by clients.
 *
 * Only used for constant interfaces
 */

public interface MyEventConstants {

	// this key can only used for event registration, you cannot
	// send out generic events
	String TOPIC_TODO_ALLTOPICS = "TOPIC_TODOS/*";

	// events to be send out
	String TOPIC_TODOS_CHANGED = "TOPIC_TODOS/CHANGED";

	String TOPIC_TODO_NEW = "TOPIC_TODOS/TODO/NEW";

	String TOPIC_TODO_DELETE = "TOPIC_TODOS/TODO/DELETED";

	String TOPIC_TODO_UPDATE = "TOPIC_TODOS/TODO/UPDATED";
}

Update of Javadoc for event constants

Update of Javadoc for event constants


/*
 * 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 edu.harvard.iq.dataverse;

import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author xyang
 */
@Stateless
@Named
public class DataverseUserServiceBean {

    @PersistenceContext(unitName = "VDCNet-ejbPU")
    private EntityManager em;

    public String encryptPassword(String plainText) {
        return PasswordEncryption.getInstance().encrypt(plainText);
    }

    public DataverseUser save(DataverseUser dataverseUser) {
         return em.merge(dataverseUser);
    }
}

/*
 * 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 edu.harvard.iq.dataverse;

import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author xyang
 */
@Stateless
@Named
public class DataverseUserServiceBean {

    @PersistenceContext(unitName = "VDCNet-ejbPU")
    private EntityManager em;

    public String encryptPassword(String plainText) {
        return PasswordEncryption.getInstance().encrypt(plainText);
    }

    public DataverseUser save(DataverseUser dataverseUser) {
         return em.merge(dataverseUser);
    }

    /*
    public List<DataverseUser> findByUserName(String userName) {
        Query query = em.createQuery("select object(o) from DataverseUser as o where o.userName =:userName");
        query.setParameter("userName", userName);
        return query.getResultList();
    }
    */

    public DataverseUser findByUserName(String userName) {
        String query = "SELECT u from DataverseUser u where u.userName = :userName ";
        DataverseUser user = null;
        try {
            user = (DataverseUser) em.createQuery(query).setParameter("userName", userName).getSingleResult();
        } catch (javax.persistence.NoResultException e) {
        }
        return user;
    }
}

Check if a username exists.

Check if a username exists.


/**
 * Yobi, Project Hosting SW
 *
 * Copyright 2013 NAVER Corp.
 * http://yobi.io
 *
 * @Author kjkmadness
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package playRepository.hooks;

import java.util.Collection;
import java.util.Date;

import models.Project;

import org.eclipse.jgit.transport.PostReceiveHook;
import org.eclipse.jgit.transport.ReceiveCommand;
import org.eclipse.jgit.transport.ReceivePack;

/**
 * project 가 마지막 업데이트된 시점 저장
 */
public class UpdateLastPushedDate implements PostReceiveHook {
    private Project project;

    public UpdateLastPushedDate(Project project) {
        this.project = project;
    }

    @Override
    public void onPostReceive(ReceivePack receivePack, Collection<ReceiveCommand> commands) {
        project.lastPushedDate = new Date();
        project.save();
    }
}

/**
 * Yobi, Project Hosting SW
 *
 * Copyright 2013 NAVER Corp.
 * http://yobi.io
 *
 * @Author kjkmadness
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package playRepository.hooks;

import java.util.Collection;
import java.util.Date;

import models.Project;

import org.eclipse.jgit.transport.PostReceiveHook;
import org.eclipse.jgit.transport.ReceiveCommand;
import org.eclipse.jgit.transport.ReceivePack;

/**
 * project 가 마지막 업데이트된 시점 저장
 */
public class UpdateLastPushedDate implements PostReceiveHook {
    private Project project;

    public UpdateLastPushedDate(Project project) {
        this.project = project;
    }

    @Override
    public void onPostReceive(ReceivePack receivePack, Collection<ReceiveCommand> commands) {
        synchronized(project) {
            project.refresh();
            project.lastPushedDate = new Date();
            project.save();
        }
    }
}

git: Fix blocking if users push simultaneously

If many git clients push commits into same repository simultaneously,
many of them are blocked because of project table's
OptimisticLockException.

Solution:
* Refresh the project before update it.
* Use synchronized block.


/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id$
 */
package com.seaglass.state;

import java.awt.Component;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;

/**
 */
public class ToolBarWindowIsActiveState extends State {
    public ToolBarWindowIsActiveState() {
        super("WindowIsActive");
    }

    protected boolean isInState(JComponent c) {
        Component parent = c;
        while (parent.getParent() != null) {
            if (parent instanceof JInternalFrame || parent instanceof JFrame) {
                break;
            }
            parent = parent.getParent();
        }
        if (parent instanceof JInternalFrame) {
            return ((JInternalFrame) parent).isSelected();
        } else if (parent instanceof JFrame) {
            return ((JFrame) parent).isActive();
        }
        // Default to true.
        return true;
    }
}

/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id$
 */
package com.seaglass.state;

import java.awt.Component;
import java.awt.Window;

import javax.swing.JComponent;
import javax.swing.JInternalFrame;

/**
 */
public class ToolBarWindowIsActiveState extends State {
    public ToolBarWindowIsActiveState() {
        super("WindowIsActive");
    }

    protected boolean isInState(JComponent c) {
        Component parent = c;
        while (parent.getParent() != null) {
            if (parent instanceof JInternalFrame || parent instanceof Window) {
                break;
            }
            parent = parent.getParent();
        }
        if (parent instanceof JInternalFrame) {
            return ((JInternalFrame) parent).isSelected();
        } else if (parent instanceof Window) {
            return ((Window) parent).isFocused();
        }
        // Default to true.
        return true;
    }
}

Use Window instead of JFrame to find top-level parent.


package com.github.fluxw42.thistothat;

import com.github.fluxw42.thistothat.conf.ConfigurationImpl;

import java.io.File;

/**
 * Date: 2/2/16 - 11:51 PM
 *
 * @author Jeroen Meulemeester
 */
public class Main {

    public static void main(final String[] args) throws Exception {
        final File configFile = args == null || args.length == 0 || args[0] == null || args[0].trim().isEmpty() ?
                new File("this-to-that.properties") : new File(args[0].trim());

        final ConfigurationImpl config = new ConfigurationImpl(configFile);
        final ThisToThat thisToThat = new ThisToThat(config);
        thisToThat.start();
    }

}

package com.github.fluxw42.thistothat;

import com.github.fluxw42.thistothat.conf.ConfigurationImpl;

import java.io.File;

/**
 * Date: 2/2/16 - 11:51 PM
 *
 * @author Jeroen Meulemeester
 */
public class Main {

    /**
     * The default config file
     */
    private static final File DEFAULT_CONFIG = new File("conf", "this-to-that.properties");

    public static void main(final String[] args) throws Exception {
        final File configFile = args == null || args.length == 0 || args[0] == null || args[0].trim().isEmpty() ?
                DEFAULT_CONFIG : new File(args[0].trim());

        final ConfigurationImpl config = new ConfigurationImpl(configFile);
        final ThisToThat thisToThat = new ThisToThat(config);
        thisToThat.start();
    }

}

Use the new location of the default config file


package dk.aau.kah.bits.helpers;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

import com.google.gson.Gson;

import dk.aau.kah.bits.database.DatabaseConfig;

public class ConfigurationLoader {

	public static DatabaseConfig load(String JSONFile) throws FileNotFoundException {
		String path = "src/main/resources/databaseConfigurations/";
		BufferedReader configuration = new BufferedReader(new FileReader(path+JSONFile));
		Gson gson = new Gson();
		DatabaseConfig config = gson.fromJson(configuration, DatabaseConfig.class);
		config.setTDBFileName(JSONFile);
		config.setTDBFilePath(path+JSONFile);
		return config;

	}
}

package dk.aau.kah.bits.helpers;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

import com.google.gson.Gson;

import dk.aau.kah.bits.database.DatabaseConfig;

public class ConfigurationLoader {

	public static DatabaseConfig load(String JSONFile) throws FileNotFoundException {
		String path = "src/main/resources/databaseConfigurations/";
		BufferedReader configuration = new BufferedReader(new FileReader(path+JSONFile));
		Gson gson = new Gson();
		DatabaseConfig config = gson.fromJson(configuration, DatabaseConfig.class);
		config.setConfigFileName(JSONFile);
		config.setTDBDatasetPath("src/main/resources/tdb/"+JSONFile.substring(0, JSONFile.length()-5)+"/");
		return config;

	}
}

Update the name of some functions

Update the name of some functions


/*
 * DomUI Java User Interface library
 * Copyright (c) 2010 by Frits Jalvingh, Itris B.V.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * See the "sponsors" file for a list of supporters.
 *
 * The latest version of DomUI and related code, support and documentation
 * can be found at http://www.domui.org/
 * The contact for the project is Frits Jalvingh <jal@etc.to>.
 */
package to.etc.domui.trouble;

import to.etc.domui.util.*;

public class MultipleParameterException extends UIException {
	public MultipleParameterException(String name) {
		super(Msgs.BUNDLE, Msgs.X_MULTIPLE_PARAMETER, name);
	}
}

/*
 * DomUI Java User Interface library
 * Copyright (c) 2010 by Frits Jalvingh, Itris B.V.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * See the "sponsors" file for a list of supporters.
 *
 * The latest version of DomUI and related code, support and documentation
 * can be found at http://www.domui.org/
 * The contact for the project is Frits Jalvingh <jal@etc.to>.
 */
package to.etc.domui.trouble;

import to.etc.domui.util.*;
import to.etc.webapp.nls.*;

public class MultipleParameterException extends CodeException {
	public MultipleParameterException(String name) {
		super(Msgs.BUNDLE, Msgs.X_MULTIPLE_PARAMETER, name);
	}
}

Rebase exception: this is not an UI exception


package com.todoist.markup;

import java.util.regex.Pattern;

class Patterns {
    public static final Pattern HEADER = Pattern.compile("^\\*\\s+");
    public static final Pattern BOLD = Pattern.compile("!!\\s*((?!!!).+?)\\s*!!");
    public static final Pattern ITALIC = Pattern.compile("_\\s*((?!_).+?)\\s*_");
    public static final Pattern INLINE_CODE = Pattern.compile("`\\s*((?!`).+?)\\s*`");
    public static final Pattern CODE_BLOCK = Pattern.compile("```\\s*((?!```).+?)\\s*```", Pattern.DOTALL);
    public static final Pattern LINK = Pattern.compile("((?:[a-zA-Z]+)://[^\\s]+)(?:\\s+\\(([^)]+)\\))?");
    public static final Pattern GMAIL = Pattern.compile("\\[\\[gmail=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
    public static final Pattern OUTLOOK = Pattern.compile("\\[\\[outlook=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
    public static final Pattern THUNDERBIRD =
            Pattern.compile("\\[\\[thunderbird\\n?\\s*([^\\n]+)\\s+([^\\n]+)\\s+\\]\\]");
}

package com.todoist.markup;

import java.util.regex.Pattern;

class Patterns {
    private static final String PATTERN_BASE = "%s\\s*((?!%s).+?)\\s*%s";

    public static final Pattern HEADER = Pattern.compile("^\\*\\s+");
    public static final Pattern BOLD = Pattern.compile(PATTERN_BASE.replaceAll("%s", "(?:__|\\\\*\\\\*)"));
    public static final Pattern ITALIC = Pattern.compile(PATTERN_BASE.replaceAll("%s", "[_\\*]"));
    public static final Pattern INLINE_CODE = Pattern.compile(PATTERN_BASE.replaceAll("%s", "`"));
    public static final Pattern CODE_BLOCK = Pattern.compile(PATTERN_BASE.replaceAll("%s", "`{3}"), Pattern.DOTALL);
    public static final Pattern LINK = Pattern.compile("((?:[a-zA-Z]+)://[^\\s]+)(?:\\s+\\(([^)]+)\\))?");
    public static final Pattern GMAIL = Pattern.compile("\\[\\[gmail=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
    public static final Pattern OUTLOOK = Pattern.compile("\\[\\[outlook=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
    public static final Pattern THUNDERBIRD =
            Pattern.compile("\\[\\[thunderbird\\n?\\s*([^\\n]+)\\s+([^\\n]+)\\s+\\]\\]");
}

Extend bold and italic pattern

Extend bold and italic pattern


package starpunk;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.tools.imagepacker.TexturePacker;

public class Main
{
  public static void main( final String[] args )
  {
    final TexturePacker.Settings settings = new TexturePacker.Settings();
    settings.maxWidth = 1024;
    settings.maxHeight = 1024;
    TexturePacker.process( settings, "src/main/resources", "target/assets", "game" );

    final LwjglApplicationConfiguration configuration = new LwjglApplicationConfiguration();
    configuration.fullscreen = false;
    configuration.width = StarPunkGame.WIDTH;
    configuration.height = StarPunkGame.HEIGHT;
		configuration.useGL20 = true;
		configuration.vSyncEnabled = true;
    configuration.title = "Star Punk";
    new LwjglApplication( new StarPunkGame(), configuration );
  }
}

package starpunk;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.tools.imagepacker.TexturePacker2;

public class Main
{
  public static void main( final String[] args )
  {
    final TexturePacker2.Settings settings = new TexturePacker2.Settings();
    settings.maxWidth = 1024;
    settings.maxHeight = 1024;
    TexturePacker2.process( settings, "src/main/resources", "target/assets", "game.atlas" );

    final LwjglApplicationConfiguration configuration = new LwjglApplicationConfiguration();
    configuration.fullscreen = false;
    configuration.width = StarPunkGame.WIDTH;
    configuration.height = StarPunkGame.HEIGHT;
		configuration.useGL20 = true;
		configuration.vSyncEnabled = true;
    configuration.title = "Star Punk";
    new LwjglApplication( new StarPunkGame(), configuration );
  }
}

Upgrade to on-deprecated texture packer

Upgrade to on-deprecated texture packer


package tests;

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

@RunWith(Suite.class)
@SuiteClasses({
	EmailBuilderTests.class,
	EmailTests.class })

public class AllTests {
}

package tests;

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

@RunWith(Suite.class)
@SuiteClasses({
	EmailBuilderTests.class,
	EmailTests.class,
	EmailSortingTests.class })

public class AllTests {
}

Add the sorting test class to the test suite.


package me.ryanw.overcast.impl;

import me.ryanw.overcast.api.OvercastFriend;
import me.ryanw.overcast.api.OvercastPlayer;
import me.ryanw.overcast.impl.object.ParsedPlayer;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OvercastAPI {

    public static OvercastPlayer getPlayer(String username) throws IOException {
        Connection.Response response = Jsoup.connect("https://oc.tc/users/" + username).method(Connection.Method.GET).execute();
        if (response.statusCode() != 200) return null;
        return new ParsedPlayer(response.parse());
    }

    public static List<OvercastPlayer> getPlayers(List<String> usernames) throws IOException {
        List<OvercastPlayer> playerList = new ArrayList<OvercastPlayer>();
        for (String username : usernames) {
            Connection.Response response = Jsoup.connect("https://oc.tc/users/" + username).method(Connection.Method.GET).execute();
            if (response.statusCode() != 200) break;
            playerList.add(new ParsedPlayer(response.parse()));
        }
        return playerList;
    }
}

package me.ryanw.overcast.impl;

import me.ryanw.overcast.api.OvercastFriend;
import me.ryanw.overcast.api.OvercastPlayer;
import me.ryanw.overcast.impl.object.ParsedPlayer;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OvercastAPI {

    private static String userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
    private static int connectionTimeout = 3000;

    public static OvercastPlayer getPlayer(String username) throws IOException {
        Connection.Response response = Jsoup.connect("https://oc.tc/users/" + username)
                .method(Connection.Method.GET).userAgent(userAgent).timeout(connectionTimeout).execute();
        if (response.statusCode() != 200) return null;
        return new ParsedPlayer(response.parse());
    }

    public static List<OvercastPlayer> getPlayers(List<String> usernames) throws IOException {
        List<OvercastPlayer> playerList = new ArrayList<OvercastPlayer>();
        for (String username : usernames) {
            Connection.Response response = Jsoup.connect("https://oc.tc/users/" + username)
                    .method(Connection.Method.GET).userAgent(userAgent).timeout(connectionTimeout).execute();
            if (response.statusCode() != 200) break;
            playerList.add(new ParsedPlayer(response.parse()));
        }
        return playerList;
    }
}

Add connection timeout & user agent

Add connection timeout & user agent


package co.paystack.android.api.service;

import java.util.HashMap;

import co.paystack.android.api.model.TokenApiResponse;
import retrofit2.Call;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

/**
 * ApiService
 */
public interface ApiService {

  /**
   * call for creating token
   *
   * @param fields - the fields of postData to send
   * @return Call - a call that can be executed directly `call.execute()` (synchronous implementation)
   *            or enqueued `call.enqueue(params)` (asynchronous implementation)
   * @see retrofit2.Call
   */
  @FormUrlEncoded
  @POST("/bosco/createmobiletoken")
  Call<TokenApiResponse> createToken(@FieldMap HashMap<String, String> fields);

}

package co.paystack.android.api.service;

import java.util.HashMap;

import co.paystack.android.api.model.ChargeApiResponse;
import co.paystack.android.api.model.TokenApiResponse;
import co.paystack.android.api.model.ValidateApiResponse;
import retrofit2.Call;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

/**
 * ApiService
 */
public interface ApiService {

  /**
   * call for creating token
   *
   * @param fields - the fields of postData to send
   * @return Call - a call that can be executed directly `call.execute()` (synchronous implementation)
   *            or enqueued `call.enqueue(params)` (asynchronous implementation)
   * @see retrofit2.Call
   */
  @FormUrlEncoded
  @POST("/bosco/createmobiletoken")
  Call<TokenApiResponse> createToken(@FieldMap HashMap<String, String> fields);

    @FormUrlEncoded
    @POST("/charge/mobile_charge")
    Call<ChargeApiResponse> charge(@FieldMap HashMap<String, String> fields);

    @FormUrlEncoded
    @POST("/charge/validate")
    Call<ValidateApiResponse> validateCharge(@FieldMap HashMap<String, String> fields);

}

Add Charge and Validate Endpoints

Add Charge and Validate Endpoints


package is.ru.sparkit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class ChuckJokeTest {

    final ChuckJoke chuck = new ChuckJoke();

    @Test
    public void chuckNorrisNameInRandomJoke(){
        String name = "Chuck Norris";
        assertTrue(chuck.getRandom().contains(name));
    }

    @Test
    public void specificJokeById(){
        String chuckJoke = chuck.getSpecific(15);
        String joke = "When Chuck Norris goes to donate blood, he declines the syringe, and instead requests a hand gun and a bucket.";
        assertEquals(chuckJoke, joke);
    }
}

package is.ru.sparkit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class ChuckJokeTest {

    final ChuckJoke chuck = new ChuckJoke();

    @Test
    public void chuckNorrisNameInRandomJoke(){
        String name = "Chuck Norris";
        assertTrue(chuck.getRandom().contains(name));
    }

    @Test
    public void specificJokeById(){
        String chuckJoke = chuck.getSpecific(5);
        String joke = "Chuck Norris lost his virginity before his dad did.";
        assertEquals(chuckJoke, joke);
    }
}

Use a shorter joke for test

Use a shorter joke for test


package com.mick88.dittimetable;

import android.content.Context;

import com.michaldabski.msqlite.MSQLiteOpenHelper;
import com.mick88.dittimetable.timetable.Timetable;

public class DatabaseHelper extends MSQLiteOpenHelper
{
	private static final String name = "timetables.db";
	private static final int version = 1;

	public DatabaseHelper(Context context, Class<?>[] trackedClasses) {
		super(context, name, null, version, new Class<?>[]{
				Timetable.class,
		});
	}

}

package com.mick88.dittimetable;

import java.util.List;

import android.content.Context;

import com.michaldabski.msqlite.MSQLiteOpenHelper;
import com.mick88.dittimetable.timetable.Timetable;

public class DatabaseHelper extends MSQLiteOpenHelper
{
	private static final String name = "timetables.db";
	private static final int version = 1;

	public DatabaseHelper(Context context) {
		super(context, name, null, version, new Class<?>[]{
				Timetable.class,
		});
	}

	public Timetable getTimetable(String course, int year, String weeks)
	{
		List<Timetable> timetables = select(Timetable.class, "course=? AND year=? and weekRange=?",
				new String[]{course, String.valueOf(year), weeks},
				null, "1");
		if (timetables.isEmpty()) return null;
		return timetables.get(0);
	}

	public void saveTimetable(Timetable timetable)
	{
		replace(timetable);
	}
}

Add methods to save and load timetable

Add methods to save and load timetable


package com.devcru.journowatch.api.services;

import org.springframework.beans.factory.annotation.Autowired;

import com.devcru.journowatch.api.daoimpl.VenueDaoImpl;
import com.devcru.journowatch.api.objects.Venue;

public class VenueService {

	@Autowired
	VenueDaoImpl vd;

	public boolean createVenue(Venue venue) {
		boolean isSuccess = vd.createVenue(venue);
		return isSuccess;
	}

	public Venue getVenue(Venue venue) {
		venue = vd.getVenue(venue);
		return venue;
	}

	public boolean updateVenue(Venue venue) {
		boolean isSuccess = vd.updateVenue(venue);
		return isSuccess;
	}

	public boolean deleteVenue(Venue venue) {
		boolean isSuccess = vd.deleteVenue(venue);
		return isSuccess;
	}

}

package com.devcru.journowatch.api.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.devcru.journowatch.api.daoimpl.VenueDaoImpl;
import com.devcru.journowatch.api.objects.Venue;

@Service
public class VenueService {

	@Autowired
	private VenueDaoImpl vd;

	public boolean createVenue(Venue venue) {
		boolean isSuccess = vd.createVenue(venue);
		return isSuccess;
	}

	public Venue getVenue(Venue venue) {
		venue = vd.getVenue(venue);
		return venue;
	}

	public boolean updateVenue(Venue venue) {
		boolean isSuccess = vd.updateVenue(venue);
		return isSuccess;
	}

	public boolean deleteVenue(Venue venue) {
		boolean isSuccess = vd.deleteVenue(venue);
		return isSuccess;
	}

}

Add other DaoImpl beans in rest-dispatcher-servlet.xml 4


import java.util.*;

public class Table {

    public class Entry {
        public Integer iface;
        public IPAddress destinationIP;
        public IPAddress nextHop;

        public Entry(String d, String n, Integer i) {
            iface = i;
            destinationIP = new IPAddress(d);
            nextHop = new IPAddress(n);
        }
    }

    HashMap<IPAddress, Entry> table;

    public Table() {
        table = new HashMap<IPAddress, Entry>();
    }

    public void add(String destinationIP, String nextHop, Integer iface) {
        table.put(new IPAddress(destinationIP), new Entry(destinationIP, nextHop, iface));
    }

    public boolean isEmpty() {
        return table.size() == 0;
    }

    public void print() {
        System.out.println("-------------------------------------------------");
        System.out.println("|   Destination   |     Next Hop    | Interface |");
        System.out.println("-------------------------------------------------");

        for (Map.Entry<IPAddress, Entry> item : table.entrySet()) {
            Entry e = item.getValue();
            System.out.printf("| %15s | %15s | %5d     |\n", e.destinationIP, e.nextHop, e.iface);
        }

        System.out.println("-------------------------------------------------\n");
    }

    public Entry findDestinationIP(IPAddress ip) {
        if (table.containsKey(ip)) {
            return table.get(ip);
        }
    }
}

import java.util.*;

public class Table {

    public static class Entry {
        public Integer iface;
        public IPAddress destinationIP;
        public IPAddress nextHop;

        public Entry(String d, String n, Integer i) {
            iface = i;
            destinationIP = new IPAddress(d);
            nextHop = new IPAddress(n);
        }
    }

    HashMap<IPAddress, Entry> table;

    public Table() {
        table = new HashMap<IPAddress, Entry>();
    }

    public void add(String destinationIP, String nextHop, Integer iface) {
        table.put(new IPAddress(destinationIP), new Entry(destinationIP, nextHop, iface));
    }

    public boolean isEmpty() {
        return table.size() == 0;
    }

    public void print() {
        System.out.println("-------------------------------------------------");
        System.out.println("|   Destination   |     Next Hop    | Interface |");
        System.out.println("-------------------------------------------------");

        for (Map.Entry<IPAddress, Entry> item : table.entrySet()) {
            Entry e = item.getValue();
            System.out.printf("| %15s | %15s | %5d     |\n", e.destinationIP, e.nextHop, e.iface);
        }

        System.out.println("-------------------------------------------------\n");
    }

    public Entry findDestinationIP(IPAddress ip) {
        if (table.containsKey(ip)) {
            return table.get(ip);
        }
    }
}

Make the Entry class static

Make the Entry class static

So we don't to instantiate it. Was getting weird errors :/

Found on SO somewhere.


package org.jreform.types;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.jreform.InputDataType;

public final class DateType implements InputDataType<Date>
{
    private DateFormat dateFormat;

    private DateType(String dateFormatPattern)
    {
        dateFormat = new SimpleDateFormat(dateFormatPattern);
    }

    // TODO: test the parseValue method - dateFormat sometimes doesn't
    //       fail if the input string is "invalid"
    public Date parseValue(String value)
    {
        try
        {
            return dateFormat.parse(value);
        }
        catch(ParseException ex)
        {
            return null;
        }
    }

    public Class<Date> getType()
    {
        return Date.class;
    }

    public static InputDataType<Date> dateType(String dateFormatPattern)
    {
        return new DateType(dateFormatPattern);
    }

}

package org.jreform.types;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.jreform.InputDataType;

public final class DateType implements InputDataType<Date>
{
    private DateFormat dateFormat;

    private DateType(String dateFormatPattern)
    {
        dateFormat = new SimpleDateFormat(dateFormatPattern);
        dateFormat.setLenient(false);
    }

    public Date parseValue(String value)
    {
        try
        {
            return dateFormat.parse(value);
        }
        catch(ParseException ex)
        {
            return null;
        }
    }

    public Class<Date> getType()
    {
        return Date.class;
    }

    public static InputDataType<Date> dateType(String dateFormatPattern)
    {
        return new DateType(dateFormatPattern);
    }

}

Set date format leniency to false.

Set date format leniency to false.


package ie.omk.smpp.event;

public class QueueFullException extends RuntimeException {
    static final long serialVersionUID = 1L;
}

package ie.omk.smpp.event;

public class QueueFullException extends RuntimeException {
    static final long serialVersionUID = 1L;

    public QueueFullException() {
        super();
    }

    public QueueFullException(String message, Throwable cause) {
        super(message, cause);
    }

    public QueueFullException(String message) {
        super(message);
    }

    public QueueFullException(Throwable cause) {
        super(cause);
    }
}

Add standard constructors from parent class.


package problems;

import java.util.HashMap;

public class LongestSubstringWORepeating {
    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        int l = 0, r = 0;
        int max = 0; // max length
        HashMap<Character, Character> hs = new HashMap<Character, Character>();

        char c = 0, d = 0;
        for (r = 0; r < len; r++) {
            c = s.charAt(r);
            if (!hs.containsKey(c)) { // no such char in substring yet
                hs.put(c, c);
            } else { // char repeat
                if (r - l > max)
                    max = r - l;
                while ((d = s.charAt(l)) != c) { // search the repeat one
                    hs.remove(d);
                    l++;
                }
                l++; // go to the first non-repeat one
            }
        }
        if (r - l > max)
            max = r - l;

        return max;
    }

    public static void main(String[] args) {
        LongestSubstringWORepeating ls = new LongestSubstringWORepeating();

        String s = "abcabcdbb";
        int a = ls.lengthOfLongestSubstring(s);
        System.out.println(a);
    }
}

package problems;

import java.util.HashSet;

public class LongestSubstringWORepeating {
    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        int l = 0, r = 0;
        int max = 0; // max length
        HashSet<Character> hs = new HashSet<Character>();

        for (r = 0; r < len; r++) {
            char c = s.charAt(r);
            if (!hs.contains(c)) // no such char in substring yet
                hs.add(c);
            else { // char repeat
                max = Math.max(r - l, max);
                while (s.charAt(l) != c) // search the repeat one
                    hs.remove(s.charAt(l++));
                l++; // go to the first non-repeat one
            }
        }
        return Math.max(r - l, max);
    }

    public static void main(String[] args) {
        LongestSubstringWORepeating ls = new LongestSubstringWORepeating();

        String s = "abcabcdbb";
        int a = ls.lengthOfLongestSubstring(s);
        System.out.println(a);
    }
}

Update Longest Substring Without Repeating