package com.uwetrottmann.trakt.v2.services;

import com.uwetrottmann.trakt.v2.BaseTestCase;
import com.uwetrottmann.trakt.v2.exceptions.OAuthUnauthorizedException;
import com.uwetrottmann.trakt.v2.entities.Movie;
import com.uwetrottmann.trakt.v2.entities.Show;
import com.uwetrottmann.trakt.v2.enums.Extended;
import org.junit.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class RecommendationsTest extends BaseTestCase {

    @Test
    public void test_movies() throws OAuthUnauthorizedException {
        List<Movie> movies = getTrakt().recommendations().movies(Extended.DEFAULT_MIN);
        assertThat(movies).isNotEmpty();
    }

    @Test
    public void test_shows() throws OAuthUnauthorizedException {
        List<Show> shows = getTrakt().recommendations().shows(Extended.DEFAULT_MIN);
        assertThat(shows).isNotEmpty();
    }

}

package com.uwetrottmann.trakt.v2.services;

import com.uwetrottmann.trakt.v2.BaseTestCase;
import com.uwetrottmann.trakt.v2.TestData;
import com.uwetrottmann.trakt.v2.exceptions.OAuthUnauthorizedException;
import com.uwetrottmann.trakt.v2.entities.Movie;
import com.uwetrottmann.trakt.v2.entities.Show;
import com.uwetrottmann.trakt.v2.enums.Extended;
import org.junit.Test;
import retrofit.client.Response;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class RecommendationsTest extends BaseTestCase {

    @Test
    public void test_movies() throws OAuthUnauthorizedException {
        List<Movie> movies = getTrakt().recommendations().movies(Extended.DEFAULT_MIN);
        assertThat(movies).isNotEmpty();
    }

    @Test
    public void test_dismissMovie() throws OAuthUnauthorizedException {
        Response response = getTrakt().recommendations().dismissMovie(String.valueOf(TestData.MOVIE_TRAKT_ID));
        assertThat(response).isNotNull();
    }

    @Test
    public void test_shows() throws OAuthUnauthorizedException {
        List<Show> shows = getTrakt().recommendations().shows(Extended.DEFAULT_MIN);
        assertThat(shows).isNotEmpty();
    }

    @Test
    public void test_dismissShow() throws OAuthUnauthorizedException {
        Response response = getTrakt().recommendations().dismissShow(String.valueOf(TestData.SHOW_TRAKT_ID));
        assertThat(response).isNotNull();
    }

}

Add tests for hide recommendation endpoints.


package net.ripe.db.whois.common.domain;

import com.google.common.collect.Sets;
import net.ripe.db.whois.common.etree.Interval;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class IpRanges {
    private static final Logger LOGGER = LoggerFactory.getLogger(IpRanges.class);

    private Set<Interval> ripeRanges;

    @Value("${ipranges.trusted}")
    public void setRipeRanges(final String... ripeRanges) {
        final Set<Interval> ipResources = Sets.newLinkedHashSetWithExpectedSize(ripeRanges.length);
        for (final String ripeRange : ripeRanges) {
            ipResources.add(IpInterval.parse(ripeRange));
        }

        this.ripeRanges = ipResources;
        LOGGER.info("Using ripe ranges: {}", ripeRanges);
    }

    public boolean isInRipeRange(final Interval ipResource) {
        for (final Interval resource : ripeRanges) {
            if (resource.getClass().equals(ipResource.getClass()) && resource.contains(ipResource)) {
                return true;
            }
        }

        return false;
    }
}

package net.ripe.db.whois.common.domain;

import com.google.common.collect.Sets;
import net.ripe.db.whois.common.etree.Interval;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class IpRanges {
    private static final Logger LOGGER = LoggerFactory.getLogger(IpRanges.class);

    private Set<Interval> ripeRanges;

    @Value("${ipranges.trusted}")
    public void setRipeRanges(final String... ripeRanges) {
        final Set<Interval> ipResources = Sets.newLinkedHashSetWithExpectedSize(ripeRanges.length);
        for (final String ripeRange : ripeRanges) {
            ipResources.add(IpInterval.parse(ripeRange));
        }

        this.ripeRanges = ipResources;
        LOGGER.info("Using ripe ranges: {}", ripeRanges);
    }

    public boolean isInRipeRange(final Interval ipResource) {
        for (final Interval resource : ripeRanges) {
            if (resource.getClass().equals(ipResource.getClass()) && resource.contains(ipResource)) {
                return true;
            }
        }

        LOGGER.info("{} is not in RIPE range", ipResource.toString());

        return false;
    }
}

Check integration test source address.


package de.uni_stuttgart.vis.vowl.owl2vowl.constants;

public class Node_Types {
	public static final String TYPE_CLASS = "owl:Class";
	public static final String TYPE_RDFSCLASS = "rdfs:Class";
	public static final String TYPE_EQUIVALENT = "owl:equivalentClass";
	public static final String TYPE_EXTERNALCLASS = "externalclass";
	public static final String TYPE_DEPRECTAEDCLASS = "owl:DeprecatedClass";
	public static final String TYPE_THING = "owl:Thing";
	public static final String TYPE_NOTHING = "owl:Nothing";
	public static final String TYPE_RDFSRESOURCE = "rdfs:Resource";
	public static final String TYPE_UNION = "owl:unionOf";
	public static final String TYPE_INTERSECTION = "owl:intersectionOf";
	public static final String TYPE_COMPLEMENT = "owl:complementOf";
	public static final String TYPE_DATATYPE = "rdfs:Datatype";
	public static final String TYPE_LITERAL = "rdfs:Literal";
}

package de.uni_stuttgart.vis.vowl.owl2vowl.constants;

public class Node_Types {
	public static final String TYPE_CLASS = "owl:Class";
	public static final String TYPE_RDFSCLASS = "rdfs:Class";
	public static final String TYPE_EQUIVALENT = "owl:equivalentClass";
	public static final String TYPE_EXTERNALCLASS = "externalclass";
	public static final String TYPE_DEPRECTAEDCLASS = "owl:DeprecatedClass";
	public static final String TYPE_THING = "owl:Thing";
	public static final String TYPE_NOTHING = "owl:Nothing";
	public static final String TYPE_RDFSRESOURCE = "rdfs:Resource";
	public static final String TYPE_UNION = "owl:unionOf";
	public static final String TYPE_INTERSECTION = "owl:intersectionOf";
	public static final String TYPE_COMPLEMENT = "owl:complementOf";
	public static final String TYPE_DATATYPE = "rdfs:Datatype";
	public static final String TYPE_LITERAL = "rdfs:Literal";
	public static final String KEY_TYPE_DATA_ONE_OF = "DATA_ONE_OF";
}

Add type constant for data one of.


package info.u_team.u_team_test.screen;

import info.u_team.u_team_core.gui.elements.EnergyStorageWidget;
import info.u_team.u_team_core.screen.UBasicContainerScreen;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.BasicEnergyCreatorContainer;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.energy.CapabilityEnergy;

@OnlyIn(Dist.CLIENT)
public class BasicEnergyCreatorScreen extends UBasicContainerScreen<BasicEnergyCreatorContainer> {

	public BasicEnergyCreatorScreen(BasicEnergyCreatorContainer container, PlayerInventory playerInventory, ITextComponent title) {
		super(container, playerInventory, title, new ResourceLocation(TestMod.MODID, "textures/gui/energy_creator.png"), 176, 173);
	}

	@Override
	protected void func_231160_c_() {
		super.func_231160_c_();
		func_230480_a_(new EnergyStorageWidget(guiLeft + 9, guiTop + 20, 54, container.getTileEntity().getCapability(CapabilityEnergy.ENERGY)));
	}
}

package info.u_team.u_team_test.screen;

import info.u_team.u_team_core.gui.elements.EnergyStorageWidget;
import info.u_team.u_team_core.screen.UBasicContainerScreen;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.BasicEnergyCreatorContainer;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.energy.CapabilityEnergy;

@OnlyIn(Dist.CLIENT)
public class BasicEnergyCreatorScreen extends UBasicContainerScreen<BasicEnergyCreatorContainer> {

	private static final ResourceLocation BACKGROUND = new ResourceLocation(TestMod.MODID, "textures/gui/energy_creator.png");

	public BasicEnergyCreatorScreen(BasicEnergyCreatorContainer container, PlayerInventory playerInventory, ITextComponent title) {
		super(container, playerInventory, title, BACKGROUND, 176, 173);
	}

	@Override
	protected void func_231160_c_() {
		super.func_231160_c_();
		func_230480_a_(new EnergyStorageWidget(guiLeft + 9, guiTop + 20, 54, container.getTileEntity().getCapability(CapabilityEnergy.ENERGY)));
	}
}

Add static field for texture in basic energy creator


package org.libvirt.jna;

import com.sun.jna.Structure;

/**
 * JNA mapping for the virSchedParameterValue structure
 */
public class virSchedParameterValue extends Structure {
    public int i; /* data for integer case */
    public int ui; /* data for unsigned integer case */
    public long l; /* data for long long integer case */
    public long ul; /* data for unsigned long long integer case */
    public double d; /* data for double case */
    public byte b; /* data for char case */
}

package org.libvirt.jna;

import com.sun.jna.Union;

/**
 * JNA mapping for the virSchedParameterValue structure
 */
public class virSchedParameterValue extends Union {
    public int i; /* data for integer case */
    public int ui; /* data for unsigned integer case */
    public long l; /* data for long long integer case */
    public long ul; /* data for unsigned long long integer case */
    public double d; /* data for double case */
    public byte b; /* data for char case */
}

Make the parameters a Union based on the comments from Frederic Ddangtran


/*******************************************************************************
 * Copyright 2016, 2017 vanilladb.org contributors
 *
 * 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.vanilladb.core.server.task;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.vanilladb.core.util.CoreProperties;

/**
 * The task manager of VanillaCore. This manager is responsible for maintaining
 * the thread pool of worker thread.
 */
public class TaskMgr {

	public final static int THREAD_POOL_SIZE;

	static {
		THREAD_POOL_SIZE = CoreProperties.getLoader().getPropertyAsInteger(
				TaskMgr.class.getName() + ".THREAD_POOL_SIZE", 150);
	}

	private ExecutorService executor;

	public TaskMgr() {
		executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
	}

	public void runTask(Task task) {
		executor.execute(task);
	}
}

/*******************************************************************************
 * Copyright 2016, 2017 vanilladb.org contributors
 *
 * 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.vanilladb.core.server.task;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import org.vanilladb.core.util.CoreProperties;

/**
 * The task manager of VanillaCore. This manager is responsible for maintaining
 * the thread pool of worker thread.
 */
public class TaskMgr {

	public final static int THREAD_POOL_SIZE;

	static {
		THREAD_POOL_SIZE = CoreProperties.getLoader().getPropertyAsInteger(
				TaskMgr.class.getName() + ".THREAD_POOL_SIZE", 150);
	}

	private ThreadPoolExecutor executor;

	public TaskMgr() {
		executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(THREAD_POOL_SIZE);
	}

	public void runTask(Task task) {
		executor.execute(task);
	}

	public int getActiveCount() {
		return executor.getActiveCount();
	}
}

Return active thread count from the threadpool


package net.folab.fo.runtime;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.lang.reflect.Field;

import net.folab.fo.runtime._fo._lang.Boolean;
import net.folab.fo.runtime._fo._lang.Integer;

import org.junit.Test;
import org.junit.Before;

public class GeneratedCodeTest {

    private Class<?> genClass;

    @Before
    public void setUp() throws ClassNotFoundException {
        genClass = Class.forName("net.folab.fo.runtime._");
    }

    @Test
    public void test() throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {

        test("_a", Integer.valueOf(1));
        test("_b", Integer.valueOf(2));
        test("_c", Integer.valueOf(3));
        test("_d", Integer.valueOf(4));
        test("_e", Integer.valueOf(5));
        test("_f", Boolean.FALSE);
        test("_t", Boolean.TRUE);
        test("_nt", Boolean.FALSE);

    }

    public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected)
            throws NoSuchFieldException, IllegalAccessException {
        Field field = genClass.getField(name);
        @SuppressWarnings("unchecked")
        Evaluable<T> value = (Evaluable<T>) field.get(null);
        assertThat(value.evaluate(), is(expected));
    }

}

package net.folab.fo.runtime;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.lang.reflect.Field;

import net.folab.fo.runtime._fo._lang.Boolean;
import net.folab.fo.runtime._fo._lang.Integer;

import org.junit.Test;

public class GeneratedCodeTest {

    private Class<?> genClass;

    public void setup(String className) throws ClassNotFoundException {
        ClassLoader classLoader = new ClassLoader(getClass().getClassLoader()) {
        };
        genClass = classLoader.loadClass(className);
    }

    @Test
    public void test__() throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
        setup("net.folab.fo.runtime._");
        test();
    }

    public void test() throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {

        test("_a", Integer.valueOf(1));
        test("_b", Integer.valueOf(2));
        test("_c", Integer.valueOf(3));
        test("_d", Integer.valueOf(4));
        test("_e", Integer.valueOf(5));
        test("_f", Boolean.FALSE);
        test("_t", Boolean.TRUE);
        test("_nt", Boolean.FALSE);

    }

    public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected)
            throws NoSuchFieldException, IllegalAccessException {
        Field field = genClass.getField(name);
        @SuppressWarnings("unchecked")
        Evaluable<T> value = (Evaluable<T>) field.get(null);
        assertThat(value.evaluate(), is(expected));
    }

}

Split class loading code to compare static class & generated class


/*
 * Copyright 2018 Red Hat, Inc.
 *
 * 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 io.quarkus.deployment.steps;

import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.HotDeploymentConfigFileBuildItem;

class DevModeBuildStep {

    @BuildStep
    HotDeploymentConfigFileBuildItem config() {
        return new HotDeploymentConfigFileBuildItem("META-INF/microprofile-config.properties");
    }
}

/*
 * Copyright 2018 Red Hat, Inc.
 *
 * 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 io.quarkus.deployment.steps;

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

import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.HotDeploymentConfigFileBuildItem;

class DevModeBuildStep {

    @BuildStep
    List<HotDeploymentConfigFileBuildItem> config() {
        return Arrays.asList(new HotDeploymentConfigFileBuildItem("META-INF/microprofile-config.properties"),
                new HotDeploymentConfigFileBuildItem("application.properties"));
    }
}

Add application.properties to hot reload


package com.annimon.jecp;

/**
 *
 * @author aNNiMON
 */
public interface ApplicationListener {

    public void onCreate();

    public void onPause();

    public void onExit();
}

package com.annimon.jecp;

/**
 *
 * @author aNNiMON
 */
public interface ApplicationListener {

    public void onStartApp();

    public void onPauseApp();

    public void onDestroyApp();
}

Change method names to remove collision with Android methods


package info.u_team.u_team_test.screen;

import info.u_team.u_team_core.screen.UBasicContainerScreen;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.BasicFluidInventoryContainer;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.api.distmarker.*;

@OnlyIn(Dist.CLIENT)
public class BasicFluidInventoryScreen extends UBasicContainerScreen<BasicFluidInventoryContainer> {

	public BasicFluidInventoryScreen(BasicFluidInventoryContainer container, PlayerInventory playerInventory, ITextComponent title) {
		super(container, playerInventory, title, new ResourceLocation(TestMod.MODID, "textures/gui/fluid_inventory.png"));
	}
}

package info.u_team.u_team_test.screen;

import info.u_team.u_team_core.screen.UBasicContainerScreen;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.BasicFluidInventoryContainer;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.api.distmarker.*;

@OnlyIn(Dist.CLIENT)
public class BasicFluidInventoryScreen extends UBasicContainerScreen<BasicFluidInventoryContainer> {

	private static final ResourceLocation BACKGROUND = new ResourceLocation(TestMod.MODID, "textures/gui/fluid_inventory.png");

	public BasicFluidInventoryScreen(BasicFluidInventoryContainer container, PlayerInventory playerInventory, ITextComponent title) {
		super(container, playerInventory, title, BACKGROUND);
	}
}

Add static field in basic fluiid inventory screen


package com.yammer.dropwizard.db;

import org.apache.tomcat.dbcp.dbcp.PoolingDataSource;
import org.apache.tomcat.dbcp.pool.ObjectPool;

import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

public class ManagedPooledDataSource extends PoolingDataSource implements ManagedDataSource {
    private final ObjectPool pool;

    public ManagedPooledDataSource(ObjectPool pool) {
        super(pool);
        this.pool = pool;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException("Doesn't use java.util.logging");
    }

    @Override
    public void start() throws Exception {
        // already started
    }

    @Override
    public void stop() throws Exception {
        pool.close();
    }
}

package com.yammer.dropwizard.db;

import org.apache.tomcat.dbcp.dbcp.PoolingDataSource;
import org.apache.tomcat.dbcp.pool.ObjectPool;

import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

public class ManagedPooledDataSource extends PoolingDataSource implements ManagedDataSource {
    private final ObjectPool pool;

    public ManagedPooledDataSource(ObjectPool pool) {
        super(pool);
        this.pool = pool;
    }

    // JDK6 has JDBC 4.0 which doesn't have this -- don't add @Override
    @SuppressWarnings("override")
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException("Doesn't use java.util.logging");
    }

    @Override
    public void start() throws Exception {
        // already started
    }

    @Override
    public void stop() throws Exception {
        pool.close();
    }
}

Fix JDBC 4.0 source compatibility.


/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury. All rights reserved.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

--*/

package com.nasmlanguage.psi;

import com.intellij.psi.tree.IElementType;
import com.nasmlanguage.NASMLanguage;
import org.jetbrains.annotations.*;

public class NASMTokenType extends IElementType {

    public NASMTokenType(@NotNull @NonNls String debugName) {
        super(debugName, NASMLanguage.INSTANCE);
    }

    @Override
    public String toString() {
        return "NASMTokenType." + super.toString();
    }
}

/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury

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 com.nasmlanguage.psi;

import com.intellij.psi.tree.IElementType;
import com.nasmlanguage.NASMLanguage;
import org.jetbrains.annotations.*;

public class NASMTokenType extends IElementType {

    public NASMTokenType(@NotNull @NonNls String debugName) {
        super(debugName, NASMLanguage.INSTANCE);
    }

    @Override
    public String toString() {
        return "NASMTokenType." + super.toString();
    }
}

Update copyright notice with MIT license


/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

public interface VideoRx {

	/**
	 * Receive a video frame.
	 *
	 * @param videoFrame
	 */
	public void putVideoFrameRx(VideoFrame videoFrame);

}

/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

public interface VideoRx {

	/**
	 * Receive a video frame.
	 *
	 * @param videoFrame
	 */
	public void putVideoFrameRx(VideoFrame videoFrame);

	/**
	 *
	 * @param size
	 *            in bytes. Must be multiple of (Integer.SIZE / 8).
	 * @return a int array (int[]) with length size/(Integer.SIZE / 8).
	 */
	public int[] getFrameBuffer(int size);

}

Add getFrameBuffer method to get a int array as frame buffer.


package com.kdemo.jooq.dao.impl;

import static com.kdemo.jooq.domain.Tables.USERS;

import java.util.List;

import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.kdemo.jooq.dao.UserDAO;
import com.kdemo.jooq.domain.tables.pojos.Users;
import com.kdemo.jooq.domain.tables.records.UsersRecord;

@Repository
@Transactional
public class UserDAOImpl implements UserDAO {

	@Autowired
	private DSLContext dsl;

	@Override
	public List<Users> getUsers() {
			return dsl
				.select(USERS.fields())
				.from(USERS)
				.fetchInto(Users.class);
	}

	@Override
	public int insert(Users user) {

		// option 1 : with fetch auto ID
		UsersRecord newRecord = dsl.newRecord(USERS, user);
		int store = newRecord.store();
		if(store > 0) {
			user.setId(newRecord.getId());
		}
		return store;

		// Otion 2
/*		return dsl.insertInto(USERS, USERS.NAME, USERS.GENDER)
			.values(user.getName(), user.getGender())
			.execute();*/

	}

}

package com.kdemo.jooq.dao.impl;

import static com.kdemo.jooq.domain.Tables.USERS;

import java.util.List;

import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.kdemo.jooq.dao.UserDAO;
import com.kdemo.jooq.domain.tables.pojos.Users;
import com.kdemo.jooq.domain.tables.records.UsersRecord;

@Repository
@Transactional
public class UserDAOImpl implements UserDAO {

	@Autowired
	private DSLContext dsl;

	@Override
	public List<Users> getUsers() {
			return dsl
				.select(USERS.fields())
				.from(USERS)
				.fetchInto(Users.class);
	}

	@Override
	public int insert(Users user) {

		// option 1 : with fetch auto ID
		UsersRecord newRecord = dsl.newRecord(USERS, user);
		int store = newRecord.insert();
		if(store > 0) {
			user.setId(newRecord.getId());
		}
		return store;

		// Otion 2
/*		return dsl.insertInto(USERS, USERS.NAME, USERS.GENDER)
			.values(user.getName(), user.getGender())
			.execute();*/

	}

}

Use insert instead store (update or insert)


package com.facebook.presto.sql.compiler;

import com.facebook.presto.sql.tree.Node;
import com.facebook.presto.sql.tree.NodeRewriter;
import com.facebook.presto.sql.tree.QualifiedNameReference;
import com.facebook.presto.sql.tree.TreeRewriter;
import com.google.common.collect.Iterables;

import java.util.List;
import java.util.Map;

public class NameToSymbolRewriter
        extends NodeRewriter<Void>
{
    private final TupleDescriptor descriptor;
    private final Map<Symbol, Type> symbols;

    public NameToSymbolRewriter(TupleDescriptor descriptor)
    {
        this.descriptor = descriptor;
        this.symbols = descriptor.getSymbols();
    }

    @Override
    public Node rewriteQualifiedNameReference(QualifiedNameReference node, Void context, TreeRewriter<Void> treeRewriter)
    {
        // try to resolve name
        List<Field> fields = descriptor.resolve(node.getName());

        if (fields.isEmpty() && symbols.containsKey(Symbol.fromQualifiedName(node.getName()))) {
            // if the name is not a valid field, is it a known symbol?
            return node;
        }

        Symbol symbol = Iterables.getOnlyElement(descriptor.resolve(node.getName())).getSymbol();
        return new QualifiedNameReference(symbol.toQualifiedName());
    }
}

package com.facebook.presto.sql.compiler;

import com.facebook.presto.sql.tree.Node;
import com.facebook.presto.sql.tree.NodeRewriter;
import com.facebook.presto.sql.tree.QualifiedNameReference;
import com.facebook.presto.sql.tree.TreeRewriter;
import com.google.common.collect.Iterables;

import java.util.List;
import java.util.Map;

public class NameToSymbolRewriter
        extends NodeRewriter<Void>
{
    private final TupleDescriptor descriptor;
    private final Map<Symbol, Type> symbols;

    public NameToSymbolRewriter(TupleDescriptor descriptor)
    {
        this.descriptor = descriptor;
        this.symbols = descriptor.getSymbols();
    }

    @Override
    public Node rewriteQualifiedNameReference(QualifiedNameReference node, Void context, TreeRewriter<Void> treeRewriter)
    {
        // is this a known symbol?
        if (!node.getName().getPrefix().isPresent() && symbols.containsKey(Symbol.fromQualifiedName(node.getName()))) { // symbols can't have prefixes
            return node;
        }

        // try to resolve name
        Symbol symbol = Iterables.getOnlyElement(descriptor.resolve(node.getName())).getSymbol();
        return new QualifiedNameReference(symbol.toQualifiedName());
    }
}

Fix issue with symbols vs attribute name disambiguation


package com.coreoz.plume.admin.webservices.security;

import java.util.Set;

import com.coreoz.plume.admin.jersey.WebSessionPermission;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * Contains secure data of a user
 */
@Getter
@Setter
@Accessors(chain = true)
@ToString
public class WebSessionAdmin implements WebSessionPermission {

	private long idUser;
	private String userName;
	private String fullName;
	private Set<String> permissions;
	private long expirationTime;

}

package com.coreoz.plume.admin.webservices.security;

import java.util.Set;

import com.coreoz.plume.admin.jersey.WebSessionPermission;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * Contains secure data of a user
 */
@Getter
@Setter
@Accessors(chain = true)
@ToString
public class WebSessionAdmin implements WebSessionPermission {

	@JsonSerialize(using = ToStringSerializer.class)
	private long idUser;
	private String userName;
	private String fullName;
	private Set<String> permissions;
	@JsonSerialize(using = ToStringSerializer.class)
	private long expirationTime;

}

Fix session serialization for Js


package com.hubspot.blazar.base;

import com.google.common.collect.SetMultimap;

import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;

public class DependencyGraph {
  private final SetMultimap<Integer, Integer> transitiveReduction;

  public DependencyGraph(SetMultimap<Integer, Integer> transitiveReduction) {
    this.transitiveReduction = transitiveReduction;
  }

  public Set<Integer> incomingVertices(int moduleId) {
    Set<Integer> incomingVertices = new HashSet<>();
    for (Entry<Integer, Integer> path : transitiveReduction.entries()) {
      if (path.getValue() == moduleId) {
        incomingVertices.add(path.getKey());
      }
    }

    return incomingVertices;
  }

  public Set<Integer> reachableVertices(int moduleId) {
    Set<Integer> reachableVertices = new HashSet<>();
    for (int vertex : outgoingVertices(moduleId)) {
      reachableVertices.add(vertex);
      reachableVertices.addAll(reachableVertices(vertex));
    }

    return reachableVertices;
  }

  public Set<Integer> outgoingVertices(int moduleId) {
    return transitiveReduction.get(moduleId);
  }

  @Override
  public String toString() {
    return transitiveReduction.toString();
  }
}

package com.hubspot.blazar.base;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.SetMultimap;

import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;

public class DependencyGraph {
  private final SetMultimap<Integer, Integer> transitiveReduction;

  @JsonCreator
  public DependencyGraph(@JsonProperty("transitiveReduction") SetMultimap<Integer, Integer> transitiveReduction) {
    this.transitiveReduction = transitiveReduction;
  }

  public SetMultimap<Integer, Integer> getTransitiveReduction() {
    return transitiveReduction;
  }

  public Set<Integer> incomingVertices(int moduleId) {
    Set<Integer> incomingVertices = new HashSet<>();
    for (Entry<Integer, Integer> path : transitiveReduction.entries()) {
      if (path.getValue() == moduleId) {
        incomingVertices.add(path.getKey());
      }
    }

    return incomingVertices;
  }

  public Set<Integer> reachableVertices(int moduleId) {
    Set<Integer> reachableVertices = new HashSet<>();
    for (int vertex : outgoingVertices(moduleId)) {
      reachableVertices.add(vertex);
      reachableVertices.addAll(reachableVertices(vertex));
    }

    return reachableVertices;
  }

  public Set<Integer> outgoingVertices(int moduleId) {
    return transitiveReduction.get(moduleId);
  }

  @Override
  public String toString() {
    return transitiveReduction.toString();
  }
}

Make it work with Jackson


package jp.ne.naokiur.design.pattern.composite;

public class App {

    public static void main(String[] args) {
        Carbon firstCarbon = new Carbon();
        firstCarbon.bond(new Hydrogen());
        firstCarbon.bond(new Hydrogen());
        firstCarbon.bond(new Hydrogen());

        Carbon secondCarbon = new Carbon();
        secondCarbon.bond(new Hydrogen());
        secondCarbon.bond(new Hydrogen());
        secondCarbon.bond(new Hydrogen());
        secondCarbon.bond(firstCarbon);

        System.out.println(secondCarbon.createChemicalFormula());
    }
}

package jp.ne.naokiur.design.pattern.composite;

public class App {

    public static void main(String[] args) {
        Carbon carbon = new Carbon();
        carbon.bond(new Hydrogen());
        carbon.bond(new Hydrogen());
        carbon.bond(new Hydrogen());

        Carbon basicCarbon = new Carbon();
        basicCarbon.bond(new Hydrogen());
        basicCarbon.bond(new Hydrogen());
        basicCarbon.bond(new Hydrogen());
        basicCarbon.bond(carbon);

        System.out.println(basicCarbon.createChemicalFormula());
    }
}

Optimize name. Structual Formula need circulation but Composite pattern is not suitable.


package com.canoo.dolphin.integration;

import com.canoo.platform.remoting.client.ClientContext;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Created by hendrikebbers on 25.08.17.
 */
public class ClientIdTest extends AbstractIntegrationTest {

    @Test(dataProvider = ENDPOINTS_DATAPROVIDER)
    public void testThatClientIdIsNotNull(String containerType, String endpoint) {
        ClientContext context = connect(endpoint);
        Assert.assertNotNull(context.connect());
    }

}

package com.canoo.dolphin.integration;

import com.canoo.platform.remoting.client.ClientContext;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Created by hendrikebbers on 25.08.17.
 */
public class ClientIdTest extends AbstractIntegrationTest {

    @Test(dataProvider = ENDPOINTS_DATAPROVIDER)
    public void testThatClientIdIsNotNull(String containerType, String endpoint) {
        ClientContext context = connect(endpoint);
        Assert.assertNotNull(context.getClientId());
    }

}

Test added bugfix - Danke Jochen :D


package org.nusco.narjillos.views.utilities;

public class PetriDishState {
	private volatile Light light = Light.ON;
	private volatile Speed speed = Speed.REALTIME;

	public Light getLight() {
		return light;
	}

	public Speed getSpeed() {
		return speed;
	}

	public void toggleLight() {
		if (light == Light.INFRARED)
			this.light = Light.ON;
		else if (light == Light.ON) {
			this.light = Light.OFF;
			this.speed = Speed.HIGH;
		}
		else {
			this.light = Light.ON;
			this.speed = Speed.REALTIME;
		}
	}

	public void toggleInfrared() {
		if (light == Light.OFF) {
			this.light = Light.INFRARED;
			this.speed = Speed.REALTIME;
		}
		else if (light == Light.INFRARED)
			this.light = Light.ON;
		else
			this.light = Light.INFRARED;
	}

	public void toggleSpeed() {
		if (speed == Speed.REALTIME)
			this.speed = Speed.HIGH;
		else
			this.speed = Speed.REALTIME;
	}
}

package org.nusco.narjillos.views.utilities;

public class PetriDishState {
	private volatile Light light = Light.ON;
	private volatile Speed speed = Speed.REALTIME;

	public Light getLight() {
		return light;
	}

	public Speed getSpeed() {
		return speed;
	}

	public void toggleLight() {
		switch (light) {
		case INFRARED:
			this.light = Light.ON;
			break;
		case ON:
			this.light = Light.OFF;
			this.speed = Speed.HIGH;
			break;
		case OFF:
			this.light = Light.ON;
			this.speed = Speed.REALTIME;
			break;
		}
	}

	public void toggleInfrared() {
		switch (light) {
		case INFRARED:
			this.light = Light.ON;
			break;
		case ON:
			this.light = Light.INFRARED;
			break;
		case OFF:
			this.light = Light.INFRARED;
			this.speed = Speed.REALTIME;
			break;
		}
	}

	public void toggleSpeed() {
		switch (speed) {
		case REALTIME:
			this.speed = Speed.HIGH;
			break;
		case HIGH:
			this.speed = Speed.REALTIME;
			break;
		}
	}
}

Refactor Petri Dish state machine


/*
 *
 * 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.ohdsi.webapi.cohortdefinition;

import java.io.Serializable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.Repository;

/**
 *
 * @author cknoll1
 */
public interface CohortDefinitionRepository extends CrudRepository<CohortDefinition, Integer> {
  Page<CohortDefinition> findAll(Pageable pageable);

  // Bug in hibernate, findById should use @EntityGraph, but details are not being feched. Workaround: mark details Fetch.EAGER,
  // but means findAll() will eager load definitions (what the @EntityGraph was supposed to solve)
  @EntityGraph(value = "CohortDefinition.withDetail", type = EntityGraph.EntityGraphType.LOAD)
  CohortDefinition findById(Integer id);

}

/*
 *
 * 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.ohdsi.webapi.cohortdefinition;

import java.io.Serializable;
import javax.transaction.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.Repository;

/**
 *
 * @author cknoll1
 */
public interface CohortDefinitionRepository extends CrudRepository<CohortDefinition, Integer> {
  Page<CohortDefinition> findAll(Pageable pageable);

  // Bug in hibernate, findById should use @EntityGraph, but details are not being feched. Workaround: mark details Fetch.EAGER,
  // but means findAll() will eager load definitions (what the @EntityGraph was supposed to solve)
  @EntityGraph(value = "CohortDefinition.withDetail", type = EntityGraph.EntityGraphType.LOAD)
  @Transactional
  CohortDefinition findById(Integer id);

}

Test setting @Transactional on findById repository method.


public class Widget {
    private boolean primitive;
    private Widget simpleObject;
    private Pair<? extends Pair<? extends Widget, ? super Widget>, ?> nestedGenerics;
    private Pair<Widget, ?>[] arrayOfGeneric;
    private int[][] multiDimensionalArray;

    public Widget() {
    }

    public boolean isPrimitive() {
        return primitive;
    }

    public Widget getSimpleObject() {
        return simpleObject;
    }

    public Pair<? extends Pair<? extends Widget, ? super Widget>, ?> getNestedGenerics() {
        return nestedGenerics;
    }

    public Pair<Widget, ?>[] getArrayOfGeneric() {
        return arrayOfGeneric;
    }

    public int[][] getMultiDimensionalArray() {
        return multiDimensionalArray;
    }

    public class Pair<U, V> {
    }
}

public class Widget {
    private boolean primitive;
    private Widget recursiveType;
    private Final finalType;
    private Pair<? extends Widget, ? super Widget> generics;
    private int[][] multiDimensionalArray;

    public Widget() {
    }

    public boolean isPrimitive() {
        return primitive;
    }

    public Widget getRecursiveType() {
        return recursiveType;
    }

    public Widget getFinalType() {
        return recursiveType;
    }

    public Pair<? extends Widget, ? super Widget> getGenerics() {
        return generics;
    }

    public int[][] getMultiDimensionalArray() {
        return multiDimensionalArray;
    }

    public class Pair<U, V> {
    }

    public final class Final {
    }
}

Update property-types test case with more realistic types.


/*
 * Copyright 2016 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.frontend.find.core.savedsearches;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.util.Set;
import java.util.UUID;

@Entity
@Table(name = "users")
@Data
@EqualsAndHashCode(exclude = {"searches", "userId"})
@NoArgsConstructor
public class UserEntity {

    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;
    private String domain;

    @Column(name = "user_store")
    private String userStore;

    private UUID uuid;
    private Long uid;

    @JsonIgnore
    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
    private Set<SavedSearch> searches;
}

/*
 * Copyright 2016 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.frontend.find.core.savedsearches;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.util.Set;
import java.util.UUID;

/**
 * Single entity that defines multiple types of user for our various implementations.
 *
 * We cannot use inheritance in this case because it would mean we would have to employ the
 * {@link org.hibernate.annotations.Any} annotation on the user entity of {@link SavedSearch}.
 *
 * This annotation requires you to define in place all the possible concrete types the field could
 * take at runtime.  This in turn would mean we have to define implementation-specific children of
 * {@link SavedSearch}, but then we would lose the centralisation of {@link SavedQuery} and other search types.
 */
@Entity
@Table(name = "users")
@Data
@EqualsAndHashCode(exclude = {"searches", "userId"})
@NoArgsConstructor
public class UserEntity {

    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;
    private String domain;

    @Column(name = "user_store")
    private String userStore;

    private UUID uuid;
    private Long uid;

    @JsonIgnore
    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
    private Set<SavedSearch> searches;
}

Add comment for user entity justifying lack of inheritance [rev: trivial]


/*
 * 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.jctools.queues;

import static org.jctools.util.UnsafeLongArrayAccess.*;

public abstract class ConcurrentSequencedCircularArrayQueue<E> extends ConcurrentCircularArrayQueue<E>
{
    protected final long[] sequenceBuffer;

    public ConcurrentSequencedCircularArrayQueue(int capacity)
    {
        super(capacity);
        int actualCapacity = (int) (this.mask + 1);
        // pad data on either end with some empty slots. Note that actualCapacity is <= MAX_POW2_INT
        sequenceBuffer = allocateLongArray(actualCapacity);
        for (long i = 0; i < actualCapacity; i++)
        {
            soLongElement(sequenceBuffer, calcCircularLongElementOffset(i, mask), i);
        }
    }
}

/*
 * 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.jctools.queues;

import static org.jctools.util.UnsafeLongArrayAccess.*;

abstract class ConcurrentSequencedCircularArrayQueue<E> extends ConcurrentCircularArrayQueue<E>
{
    protected final long[] sequenceBuffer;

    public ConcurrentSequencedCircularArrayQueue(int capacity)
    {
        super(capacity);
        int actualCapacity = (int) (this.mask + 1);
        // pad data on either end with some empty slots. Note that actualCapacity is <= MAX_POW2_INT
        sequenceBuffer = allocateLongArray(actualCapacity);
        for (long i = 0; i < actualCapacity; i++)
        {
            soLongElement(sequenceBuffer, calcCircularLongElementOffset(i, mask), i);
        }
    }
}

Reduce visibility of internal class


package com.openxc.openxcdiagnostic.diagnostic;

import java.util.ArrayList;
import java.util.List;

import android.widget.LinearLayout;

import com.openxc.messages.DiagnosticRequest;
import com.openxc.messages.DiagnosticResponse;
import com.openxc.openxcdiagnostic.R;

public class DiagnosticOutputTable {

    private DiagnosticActivity mContext;
    private List<DiagnosticOutputRow> rows = new ArrayList<>();
    private LinearLayout mView;
    private int rowNumber = 1;

    public DiagnosticOutputTable(DiagnosticActivity context) {
        mContext = context;
        mView = (LinearLayout) context.findViewById(R.id.outputRows);
    }

    public void addRow(DiagnosticRequest req, DiagnosticResponse resp) {

        DiagnosticOutputRow row = new DiagnosticOutputRow(mContext, this, req, resp, rowNumber++);
        rows.add(0, row);
        mView.addView(row.getView(), 0);
    }

    public void removeRow(DiagnosticOutputRow row) {
        mView.removeView(row.getView());
        rows.remove(row);
    }

    public void deleteAllRows() {
        mView.removeAllViews();
        rows.clear();
    }

}

package com.openxc.openxcdiagnostic.diagnostic;

import java.util.ArrayList;
import java.util.List;

import android.widget.LinearLayout;

import com.openxc.messages.DiagnosticRequest;
import com.openxc.messages.DiagnosticResponse;
import com.openxc.openxcdiagnostic.R;

public class DiagnosticOutputTable {

    private DiagnosticActivity mContext;
    private List<DiagnosticOutputRow> rows = new ArrayList<>();
    private LinearLayout mView;
    private int rowNumber = 1;

    public DiagnosticOutputTable(DiagnosticActivity context) {
        mContext = context;
        mView = (LinearLayout) context.findViewById(R.id.outputRows);
    }

    public void addRow(DiagnosticRequest req, DiagnosticResponse resp) {

        DiagnosticOutputRow row = new DiagnosticOutputRow(mContext, this, req, resp, rowNumber++);
        rows.add(0, row);
        mView.addView(row.getView(), 0);
    }

    public void removeRow(DiagnosticOutputRow row) {
        mView.removeView(row.getView());
        rows.remove(row);
    }

    public void deleteAllRows() {
        mView.removeAllViews();
        rows.clear();
        resetRowCounter();
    }

    private void resetRowCounter() {
        rowNumber = 1;
    }

}

Reset row number after deleting all responses.


package jp.ac.nii.prl.mape.redundancy.model;

import java.util.Collection;

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

import org.hibernate.validator.constraints.NotEmpty;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
public class RedundancyView {

	@GeneratedValue
	@Id
	@JsonIgnore
	private Long id;

	@NotEmpty
	@OneToMany(mappedBy="RedundancyView")
	private Collection<Instance> instances;

	public Long getId() {
		return id;
	}

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

	public Collection<Instance> getInstances() {
		return instances;
	}

	public void setInstances(Collection<Instance> instances) {
		this.instances = instances;
	}

	public void addInstance(Instance instance) {
		instances.add(instance);
	}

}

package jp.ac.nii.prl.mape.redundancy.model;

import java.util.Collection;

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

import org.hibernate.validator.constraints.NotEmpty;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
public class RedundancyView {

	@GeneratedValue
	@Id
	@JsonIgnore
	private Long id;

	@NotEmpty
	@OneToMany(mappedBy="redundancyView")
	private Collection<Instance> instances;

	public Long getId() {
		return id;
	}

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

	public Collection<Instance> getInstances() {
		return instances;
	}

	public void setInstances(Collection<Instance> instances) {
		this.instances = instances;
	}

	public void addInstance(Instance instance) {
		instances.add(instance);
	}

}

Fix typo in MappedBy annotation


package vg.civcraft.mc.civmodcore.ratelimiting;

public class TokenBucket {

	private int tokens;
	private long lastRefill;

	/**
	 * Local constructor to enforce creation via RateLimiting class
	 *
	 * @param initialCapacity Initial amount of tokens
	 */
	TokenBucket(int initialCapacity) {
		this.tokens = initialCapacity;
		this.lastRefill = System.currentTimeMillis();
	}

	public synchronized void refill(int maxTokens, int toAdd, long minDelay) {
		int refillMultiplier = (int) ((System.currentTimeMillis() - lastRefill) / minDelay);
		if (refillMultiplier >= 1) {
			lastRefill += refillMultiplier * minDelay;
		}
		tokens = Math.max(maxTokens, tokens + toAdd * refillMultiplier);
	}

	public synchronized int getTokensLeft() {
		return tokens;
	}

	public synchronized boolean pullToken() {
		if (tokens <= 0) {
			return false;
		}
		tokens--;
		return true;
	}

}

package vg.civcraft.mc.civmodcore.ratelimiting;

public class TokenBucket {

	private int tokens;
	private long lastRefill;

	/**
	 * Local constructor to enforce creation via RateLimiting class
	 *
	 * @param initialCapacity Initial amount of tokens
	 */
	TokenBucket(int initialCapacity) {
		this.tokens = initialCapacity;
		this.lastRefill = System.currentTimeMillis();
	}

	public synchronized void refill(int maxTokens, int toAdd, long minDelay) {
		int refillMultiplier = (int) ((System.currentTimeMillis() - lastRefill) / minDelay);
		if (refillMultiplier >= 1) {
			lastRefill += refillMultiplier * minDelay;
		}
		tokens = Math.min(maxTokens, tokens + toAdd * refillMultiplier);
	}

	public synchronized int getTokensLeft() {
		return tokens;
	}

	public synchronized boolean pullToken() {
		if (tokens <= 0) {
			return false;
		}
		tokens--;
		return true;
	}

}

Fix bug in tokenbucket refilling


package com.vikashkothary.life.data.model;

import android.os.Parcelable;

import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import java.util.Date;

@AutoValue
public abstract class Reminder implements Parcelable {
    public static Builder builder() {
        return new AutoValue_Reminder.Builder();
    }

    public static TypeAdapter<Reminder> typeAdapter(Gson gson) {
        return new AutoValue_Reminder.GsonTypeAdapter(gson);
    }

    public abstract long id();

    public abstract String message();

    public abstract Date datetime();

    @AutoValue.Builder
    public abstract static class Builder {
        public abstract Builder setId(long id);

        public abstract Builder setMessage(String message);

        public abstract Builder setDatetime(Date datetime);

        public abstract Reminder build();
    }
}

package com.vikashkothary.life.data.model;

import android.app.Notification;
import android.content.Context;
import android.os.Parcelable;

import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import java.util.Date;

import static com.vikashkothary.life.util.NotificationFactory.createSimpleNotification;

@AutoValue
public abstract class Reminder implements Parcelable {
    public static Builder builder() {
        return new AutoValue_Reminder.Builder();
    }

    public static TypeAdapter<Reminder> typeAdapter(Gson gson) {
        return new AutoValue_Reminder.GsonTypeAdapter(gson);
    }

    public abstract int id();

    public abstract String title();

    public abstract String text();

    public abstract Date datetime();

    public Notification notification(Context context) {
        return createSimpleNotification(context, title(), text());
    }

    @AutoValue.Builder
    public abstract static class Builder {
        public abstract Builder setId(long id);

        public abstract Builder setTitle(String title);

        public abstract Builder setText(String text);

        public abstract Builder setDatetime(Date datetime);

        public abstract Reminder build();
    }
}

Add notification function to reminder model


package com.team254.frc2015.subsystems.controllers;

import com.team254.lib.util.Controller;

public class BangBangFinishLineController extends Controller {

    private double m_position;
    private double m_goal;
    private double m_tolerance;
    private double m_direction = 0.0;

    public BangBangFinishLineController(double tolerance) {
        m_tolerance = tolerance;
    }

    public void setGoal(double goal) {
        m_goal = goal;
    }

    public double getGoal() {
        return m_goal;
    }

    @Override
    public void reset() {
        m_direction = 0.0;
    }

    @Override
    public boolean isOnTarget() {
        return (m_direction > 0 ? m_position > (m_goal - m_tolerance)
                : m_position < (m_goal + m_tolerance));
    }

    public double update(double position) {
        if (m_direction == 0.0) {
            m_direction = (position > m_goal ? -1.0 : 1.0);
        }
        m_position = position;
        if (m_direction > 0) {
            if (position < (m_goal - m_tolerance)) {
                return 1.0;
            } else {
                return 0.0;
            }
        } else {
            if (position > (m_goal + m_tolerance)) {
                return -1.0;
            } else {
                return 0.0;
            }
        }

    }

}

package com.team254.frc2015.subsystems.controllers;

import com.team254.lib.util.Controller;

public class BangBangFinishLineController extends Controller {

    private double m_position;
    private double m_goal;
    private double m_tolerance;
    private double m_direction = 0.0;

    public BangBangFinishLineController(double tolerance) {
        m_tolerance = tolerance;
    }

    public void setGoal(double goal) {
        m_goal = goal;
    }

    public double getGoal() {
        return m_goal;
    }

    @Override
    public void reset() {
        m_direction = 0.0;
    }

    @Override
    public boolean isOnTarget() {
        if (m_direction == 0.0) {
            return false;
        }
        return (m_direction > 0 ? m_position > (m_goal - m_tolerance)
                : m_position < (m_goal + m_tolerance));
    }

    public double update(double position) {
        if (m_direction == 0.0) {
            m_direction = (position > m_goal ? -1.0 : 1.0);
        }
        m_position = position;
        if (m_direction > 0) {
            if (position < (m_goal - m_tolerance)) {
                return 1.0;
            } else {
                return 0.0;
            }
        } else {
            if (position > (m_goal + m_tolerance)) {
                return -1.0;
            } else {
                return 0.0;
            }
        }

    }

}

Fix bug in isOnTarget BandBangController


package com.uber.okbuck.core.model.jvm;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public final class TestOptions {

  private final List<String> jvmArgs;
  private final TreeMap<String, Object> env;

  public TestOptions(List<String> jvmArgs, Map<String, Object> env) {
    this.jvmArgs = jvmArgs;
    this.env = new TreeMap<>(env);
  }

  public List<String> getJvmArgs() {
    return jvmArgs;
  }

  public TreeMap<String, Object> getEnv() {
    return env;
  }
}

package com.uber.okbuck.core.model.jvm;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public final class TestOptions {

  private final List<String> jvmArgs;
  private final TreeMap<String, Object> env;

  public TestOptions(List<String> jvmArgs, Map<String, Object> env) {
    this.jvmArgs = jvmArgs;
    this.env = new TreeMap<>(env);
  }

  public List<String> getJvmArgs() {
    return jvmArgs;
  }

  public Map<String, Object> getEnv() {
    return env;
  }
}

Use Map in getter instead of TreeMap


package org.valid4j.impl;

import org.valid4j.UnreachablePolicy;
import org.valid4j.exceptions.ContractViolation;
import org.valid4j.exceptions.NeverGetHereViolation;

import java.util.Queue;

import static org.valid4j.Message.withFormattedMessage;

/**
 * Policy for handling unreachable code by throwing an unrecoverable exception.
 */
public class NeverGetHerePolicy implements UnreachablePolicy {

  private final Queue<ContractViolation> violations;

  public NeverGetHerePolicy(Queue<ContractViolation> violations) {
    this.violations = violations;
  }

  @Override
  public void neverGetHere(Throwable cause, String msg, Object... values) {
    throw tracked(new NeverGetHereViolation(cause, withFormattedMessage(msg, values)));
  }

  private NeverGetHereViolation tracked(NeverGetHereViolation neverGetHereViolation) {
    violations.offer(neverGetHereViolation);
    return neverGetHereViolation;
  }
}

package org.valid4j.impl;

import org.valid4j.UnreachablePolicy;
import org.valid4j.exceptions.ContractViolation;
import org.valid4j.exceptions.NeverGetHereViolation;

import java.util.Queue;

import static org.valid4j.Message.withFormattedMessage;

/**
 * Policy for handling unreachable code by throwing an unrecoverable exception.
 */
public class NeverGetHerePolicy extends TrackingViolationPolicy implements UnreachablePolicy {

  public NeverGetHerePolicy(Queue<ContractViolation> violations) {
    super(violations);
  }

  @Override
  public void neverGetHere(Throwable cause, String msg, Object... values) {
    throw tracked(new NeverGetHereViolation(cause, withFormattedMessage(msg, values)));
  }
}

Use the tracking policy to track thrown never-get-here errors


package utils;

public class Parser {

	public static int parseScore(String s) {
		String[] parse = s.split(",");
		int i;
		for (i = 0; i < parse.length; i++) {
			System.out.println("Parsed : " + parse[i]);
		}
		System.out.println("Score : " + parse[2]);
		return Integer.parseInt(parse[2]);
	}
}

package utils;

public class Parser {

	public static int parseScore(String s) {
		String[] parse = s.split(",");
		int i;
		return Integer.parseInt(parse[2]);
	}
}

Remove printing of some lines


package com.alsash.reciper.logic.event;

import com.alsash.reciper.logic.action.RecipeAction;

public class RecipeEvent {

    public final RecipeAction action;
    public final String uuid;

    public RecipeEvent(RecipeAction action, String uuid) {
        this.action = action;
        this.uuid = uuid;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof RecipeEvent)) return false;

        RecipeEvent event = (RecipeEvent) o;

        if (action != event.action) return false;
        return uuid != null ? uuid.equals(event.uuid) : event.uuid == null;
    }

    @Override
    public int hashCode() {
        int result = action != null ? action.hashCode() : 0;
        result = 31 * result + (uuid != null ? uuid.hashCode() : 0);
        return result;
    }
}

Update ui - favorite button


package org.robotninjas.barge;

import com.google.common.collect.Maps;
import org.jetlang.core.BatchExecutorImpl;
import org.jetlang.core.EventReader;
import org.slf4j.MDC;

import java.util.Map;

class BatchExecutor extends BatchExecutorImpl {

  Map contextMap = Maps.newHashMap();

  @Override
  public void execute(EventReader toExecute) {

    Map oldContext = MDC.getCopyOfContextMap();
    MDC.setContextMap(contextMap);

    super.execute(toExecute);

    contextMap = MDC.getCopyOfContextMap();
    MDC.setContextMap(oldContext);

  }

}

package org.robotninjas.barge;

import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import org.jetlang.core.BatchExecutorImpl;
import org.jetlang.core.EventReader;
import org.slf4j.MDC;

import java.util.Map;

class BatchExecutor extends BatchExecutorImpl {

  Map contextMap = Maps.newHashMap();

  @Override
  public void execute(EventReader toExecute) {

    Optional<Map> oldContext = Optional.fromNullable(MDC.getCopyOfContextMap());
    MDC.setContextMap(contextMap);

    super.execute(toExecute);

    contextMap = MDC.getCopyOfContextMap();
    if (oldContext.isPresent()) {
      MDC.setContextMap(oldContext.get());
    }

  }

}

Handle case where MDC is null


package org.jvirtanen.nassau;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * MessageListener is the interface for inbound messages.
 */
public interface MessageListener {

    /**
     * Receive a message. The message is contained in the buffer between the
     * current position and the limit.
     *
     * @param buffer a buffer
     * @throws IOException if an I/O error occurs
     */
    void message(ByteBuffer buffer) throws IOException;

}

package org.jvirtanen.nassau;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * The interface for inbound messages.
 */
public interface MessageListener {

    /**
     * Receive a message. The message is contained in the buffer between the
     * current position and the limit.
     *
     * @param buffer a buffer
     * @throws IOException if an I/O error occurs
     */
    void message(ByteBuffer buffer) throws IOException;

}

Tweak documentation for message listener


package eu.nerro.wolappla.provider;

/**
 * Contract class for interacting with {@link DeviceProvider}.
 */
public class DeviceContract {
}

package eu.nerro.wolappla.provider;

import android.net.Uri;

/**
 * Contract class for interacting with {@link DeviceProvider}.
 */
public class DeviceContract {
  public static final String CONTENT_AUTHORITY = "eu.nerro.wolappla";
  public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);

  interface DevicesColumns {
    /** Name describing this device. */
    String DEVICE_NAME = "device_name";
    /** MAC address of the network card of this device. */
    String DEVICE_MAC_ADDRESS = "device_mac_address";
    /** Network broadcast IP. */
    String DEVICE_IP_ADDRESS = "device_ip_address";
    /** Port on which this device is listening for magic packets. */
    String DEVICE_PORT = "device_port";
  }
}

Add column description for device SQLite table


// Copyright 2019 Google LLC
//
// 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
//
//     https://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.google.sps.servlets;

public final class BlogConstants {
  public static String MESSAGE_PARAMETER = "text-input";
  public static String SENDER_PARAMETER = "sender";
  public static String TAG_PARAMETER = "tags";
  public static String PARENTID_PARAMETER = "parentID";
  public static String BLOG_ENTITY_KIND = "blogMessage";
  public static String ID_PARAMETER = "messageId";
  public static String TAG_QUERY = "followedTag";
  public static String NICKNAME = "nickname";
}

// Copyright 2019 Google LLC
//
// 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
//
//     https://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.google.sps.servlets;

public final class BlogConstants {
  public static String MESSAGE_PARAMETER = "text-input";
  public static String SENDER_PARAMETER = "sender";
  public static String TAG_PARAMETER = "tags";
  public static String PARENTID_PARAMETER = "parentID";
  public static String BLOG_ENTITY_KIND = "blogMessage";
  public static String ID_PARAMETER = "messageId";
  public static String TAG_QUERY = "followedTag";
  public static String NICKNAME = "nickname";
  public static String BLOG_USER = "BlogUser";
  public static String ID = "id";
  public static String EMAIL = "email";
  public static String TIME = "time";
}

Add new constants that are used throughout servlets.


package com.thoughtworks.xstream.core;

import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;

public class TreeMarshallerTest extends AbstractAcceptanceTest {

    class Thing {
        Thing thing;
    }

    protected void setUp() throws Exception {
        super.setUp();
        xstream.setMode(XStream.NO_REFERENCES);
    }

    public void testThrowsExceptionWhenDetectingCircularReferences() {
        Thing a = new Thing();
        Thing b = new Thing();
        a.thing = b;
        b.thing = a;

        try {
            xstream.toXML(a);
            fail("expected exception");
        } catch (TreeMarshaller.CircularReferenceException expected) {
            // good
        }
    }
}

package com.thoughtworks.xstream.core;

import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;

public class TreeMarshallerTest extends AbstractAcceptanceTest {

    static class Thing {
        Thing thing;
    }

    protected void setUp() throws Exception {
        super.setUp();
        xstream.setMode(XStream.NO_REFERENCES);
    }

    public void testThrowsExceptionWhenDetectingCircularReferences() {
        Thing a = new Thing();
        Thing b = new Thing();
        a.thing = b;
        b.thing = a;

        try {
            xstream.toXML(a);
            fail("expected exception");
        } catch (TreeMarshaller.CircularReferenceException expected) {
            // good
        }
    }
}

Fix unit test for JDK 1.3.


package com.bjorn;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import javax.xml.bind.annotation.XmlAttribute;
import java.util.HashMap;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class GameTest {
    UI mockUI;
    Board mockBoard;
    Game newGame;

    @Before
    public void setUp() {
        mockUI = Mockito.mock(UI.class);
        mockBoard = Mockito.mock(Board.class);
        newGame = new Game(mockUI, mockBoard);
        newGame.startGame();

    }

    @Test
    public void checkIfWelcomeIsCalled() {
        verify(mockUI, times(1)).printWelcome();
    }

    @Test
    public void checkIfPrintBoardIsCalled() {
        verify(mockUI, atLeastOnce()).printBoard(mockBoard);
    }

    @Test
    public void checkIfPromptForXCoordinateIsCalled() {
        verify(mockUI, atLeastOnce()).promptForXCoordinate();
    }

    @Test
    public void checkIfPromptForYCoordinateIsCalled() {
        verify(mockUI, atLeastOnce()).promptForYCoordinate();
    }

    @Test
    public void checkIfGetUserInputIsCalled() {
        verify(mockUI, atLeastOnce()).getUserInput();
    }

    @Test
    public void checkIfUpdateBoardStateIsCalled() {
        verify(mockBoard, atLeastOnce()).upDateBoardState(0, 0, "H");
    }

}

package com.bjorn;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class GameTest {
    UI mockUI;
    Board mockBoard;
    Game newGame;

    @Before
    public void setUp() {
        mockUI = Mockito.mock(UI.class);
        mockBoard = Mockito.mock(Board.class);
        newGame = new Game(mockUI, mockBoard);
        newGame.startGame();

    }

    @Test
    public void checkIfWelcomeIsCalled() {
        verify(mockUI, times(1)).printWelcome();
    }

    @Test
    public void checkIfPrintBoardIsCalled() {
        verify(mockUI, atLeastOnce()).printBoard(mockBoard);
    }

    @Test
    public void checkIfPromptForXCoordinateIsCalled() {
        verify(mockUI, atLeastOnce()).promptForXCoordinate();
    }

    @Test
    public void checkIfPromptForYCoordinateIsCalled() {
        verify(mockUI, atLeastOnce()).promptForYCoordinate();
    }

    @Test
    public void checkIfGetUserInputIsCalled() {
        verify(mockUI, atLeastOnce()).getUserInput();
    }

    @Test
    public void checkIfUpdateBoardStateIsCalled() {
        verify(mockBoard, atLeastOnce()).upDateBoardState(0, 0, "H");
    }

}

Remove unused imports in game tests


package org.motechproject.server.pillreminder.util;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Util {

    public static DateTime currentDateTime() {
        return new DateTime(DateTimeZone.UTC);
    }

    public static Date newDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        return cal.getTime();
    }

    public static boolean areDatesSame(Date date1, Date date2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        return dateFormat.format(date1).equals(dateFormat.format(date2));
    }

    public static Date getDateAfter(Date date, int numOfMonth) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, numOfMonth);
        return cal.getTime();
    }
}

package org.motechproject.server.pillreminder.util;

import org.joda.time.DateTime;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Util {

    public static DateTime currentDateTime() {
        return new DateTime();
    }

    public static Date newDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        return cal.getTime();
    }

    public static boolean areDatesSame(Date date1, Date date2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        return dateFormat.format(date1).equals(dateFormat.format(date2));
    }

    public static Date getDateAfter(Date date, int numOfMonth) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, numOfMonth);
        return cal.getTime();
    }
}

Remove UTC from time util<Manohar/Shruthi>


/*
 * Copyright (c) IBM Corporation (2009). All Rights Reserved.
 *
 * 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.osgi.test.cases.jndi.provider;

import java.util.Hashtable;

import javax.naming.NamingException;
import javax.naming.spi.ObjectFactory;

import org.osgi.test.cases.jndi.provider.CTObjectFactory;

/**
 * @version $Revision$ $Date$
 */
public class CTObjectFactoryBuilder implements javax.naming.spi.ObjectFactoryBuilder {

	public ObjectFactory createObjectFactory(Object obj, Hashtable var1)
			throws NamingException {
		if (obj instanceof CTReference) {
		return new CTObjectFactory();
		} else {
			return null;
		}
	}

}

Fix formatting of if statement


package org.datavaultplatform.common.metadata.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.datavaultplatform.common.model.Dataset;
import org.datavaultplatform.common.metadata.Provider;

// This mock metadata provider is for testing purposes only

public class MockProvider implements Provider {

    List<Dataset> datasets = new ArrayList<>();
    Map<String, String> projectIds = new HashMap<>();

    public MockProvider() {
        for (int i = 1; i < 6; i++) {
            Dataset d = new Dataset();
            d.setID("MOCK-DATASET-" + i);
            d.setName("Sample dataset " + i);
            d.setContent("Mock Metadata");
            d.setVisible(true);
            datasets.add(d);
            projectIds.put(d.getID(), "MOCK-PROJECTID-" + i);
        }
    }

    @Override
    public List<Dataset> getDatasetsForUser(String userID) {
        return datasets;
    }

    @Override
    public Dataset getDataset(String id) {
        for (Dataset d : datasets) {
            if (d.getID().equals(id)) {
                return d;
            }
        }
        return null;
    }

	@Override
	public Map<String, String> getPureProjectIds() {
		return projectIds;
	}

	@Override
	public String getPureProjectId(String datasetId) {
		return projectIds.get(datasetId);
	}
}

package org.datavaultplatform.common.metadata.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.datavaultplatform.common.model.Dataset;
import org.datavaultplatform.common.metadata.Provider;

// This mock metadata provider is for testing purposes only

public class MockProvider implements Provider {

    List<Dataset> datasets = new ArrayList<>();
    Map<String, String> projectIds = new HashMap<>();

    public MockProvider() {
        for (int i = 1; i < 6; i++) {
            Dataset d = new Dataset();
            d.setID("MOCK-DATASET-" + i);
            d.setName("Sample dataset " + i);
            d.setContent("Mock Metadata");
            d.setVisible(true);
            d.setCrisId("CRIS01");
            datasets.add(d);
            projectIds.put(d.getID(), "MOCK-PROJECTID-" + i);
        }
    }

    @Override
    public List<Dataset> getDatasetsForUser(String userID) {
        return datasets;
    }

    @Override
    public Dataset getDataset(String id) {
        for (Dataset d : datasets) {
            if (d.getID().equals(id)) {
                return d;
            }
        }
        return null;
    }

	@Override
	public Map<String, String> getPureProjectIds() {
		return projectIds;
	}

	@Override
	public String getPureProjectId(String datasetId) {
		return projectIds.get(datasetId);
	}
}

Fix Mocked Datsetws missing the CrisId field


package study.hard.javalib.file;

import java.io.File;
import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class FileTest {

	FileHandler fileHandler;
	File tempFile;

	@Before
	public void setUp() {
		fileHandler = new FileHandler();
	}

	@Test
	public void testCreateTempFile() throws IOException {
		tempFile = fileHandler.getTempFile("TEST_TEMP_FILE.txt");
		System.out.println("Absolute path of temporary file: " + tempFile.getAbsolutePath());
	}

	@After
	public void clean() {
		tempFile.delete();
	}
}

package study.hard.javalib.file;

import java.io.File;
import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class FileTest {

	FileHandler fileHandler;
	File tempFile;

	@Before
	public void setUp() {
		fileHandler = new FileHandler();
	}

	@Test
	public void testCreateTempFile() throws IOException {
		tempFile = fileHandler.getTempFile("TEST_TEMP_FILE.txt");
		System.out.println("Absolute path of temporary file: " + tempFile.getAbsolutePath());
	}

	@Test
	public void testGetTempDirectoryPath() {
		File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
		System.out.println(tempDirectory);
	}

	@After
	public void clean() {
		if (tempFile != null) {
			tempFile.delete();
		}
	}
}

Add a test case to get temp 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.
 */
@Version("1.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.json;

import aQute.bnd.annotation.Version;
import aQute.bnd.annotation.Export;

/*
 * 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.
 */
@Version("1.1.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.json;

import aQute.bnd.annotation.Version;
import aQute.bnd.annotation.Export;

Implement tooling for tracing a node through the revision history Bump package export version


package net.onrc.onos.core.newintent;

import com.google.common.collect.ImmutableList;
import net.onrc.onos.api.newintent.InstallableIntent;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * A class representing a result of intent compilation.
 */
public class IntentCompilationResult {
    private final List<InstallableIntent> result;

    /**
     * Constructs an instance containing the specified list of installable intents.
     *
     * @param result installable intents
     */
    public IntentCompilationResult(List<InstallableIntent> result) {
        checkNotNull(result);
        checkArgument(result.size() > 0,
                "result of intent compilation should be " +
                "more than 1 installable intents or more, but %s", result.size());

        this.result = new ArrayList<>(checkNotNull(result));
    }

    /**
     * Constructor for serializer.
     */
    protected IntentCompilationResult() {
        this.result = null;
    }

    /**
     * Returns list of installable intents that this object contains.
     *
     * @return installable intents
     */
    public List<InstallableIntent> getResult() {
        return ImmutableList.copyOf(result);
    }
}

package net.onrc.onos.core.newintent;

import com.google.common.collect.ImmutableList;
import net.onrc.onos.api.newintent.InstallableIntent;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * A class representing a result of intent compilation.
 */
public class IntentCompilationResult {
    private final List<InstallableIntent> result;

    /**
     * Constructs an instance containing the specified list of installable intents.
     *
     * @param result installable intents
     */
    public IntentCompilationResult(List<InstallableIntent> result) {
        checkNotNull(result);
        checkArgument(result.size() > 0,
                "result of intent compilation should be " +
                "at least one installable intent, but %s", result.size());

        this.result = new ArrayList<>(checkNotNull(result));
    }

    /**
     * Constructor for serializer.
     */
    protected IntentCompilationResult() {
        this.result = null;
    }

    /**
     * Returns list of installable intents that this object contains.
     *
     * @return installable intents
     */
    public List<InstallableIntent> getResult() {
        return ImmutableList.copyOf(result);
    }
}

Revise message explaining the cause of exception


/*
 * Copyright (c) 2015 Michal Srb
 *
 * 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 org.fedoraproject.jardeps.spi;

import java.io.IOException;
import java.util.Set;

/**
 * Reads class dependencies from bytecode
 *
 * @param data
 *            bytecode of a class
 * @throws IOException
 *             if bytecode is invalid or other error occurred during processing
 * @return list of classes on which given class depends
 */
public interface DependencyReader {
    public Set<String> getDependencies(byte[] data) throws IOException;
}

/*
 * Copyright (c) 2015 Michal Srb
 *
 * 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 org.fedoraproject.jardeps.spi;

import java.io.IOException;
import java.util.Set;

public interface DependencyReader {

    /**
     * Read class dependencies from bytecode
     *
     * @param data
     *            bytecode of a class
     * @throws IOException
     *             if bytecode is invalid or other error occurred during
     *             processing
     * @return list of classes on which given class depends
     */
    public Set<String> getDependencies(byte[] data) throws IOException;
}

Move javadoc comment where it belongs


package io.github.jordao76.quotes.filters;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.slf4j.*;
import org.springframework.stereotype.*;
import org.springframework.web.filter.*;

@Component
public class RequestLoggingFilter extends OncePerRequestFilter {

  private static final Logger LOGGER = LoggerFactory.getLogger(RequestLoggingFilter.class);

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

    filterChain.doFilter(request, response);

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("HTTP {} for {} {}",
        value("status", response.getStatus()),
        value("method", request.getMethod()),
        value("endpoint", request.getRequestURI()));
    }

  }

  // note: later to be replaced,
  // see https://github.com/logstash/logstash-logback-encoder/tree/logstash-logback-encoder-4.7#loggingevent_custom_event
  private Object value(String key, Object value) {
    return value;
  }

}

package io.github.jordao76.quotes.filters;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.slf4j.*;
import org.springframework.stereotype.*;
import org.springframework.web.filter.*;

@Component
public class RequestLoggingFilter extends OncePerRequestFilter {

  private final Logger logger = LoggerFactory.getLogger(getClass());

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

    filterChain.doFilter(request, response);

    if (logger.isDebugEnabled()) {
      logger.debug("HTTP {} for {} {}",
        value("status", response.getStatus()),
        value("method", request.getMethod()),
        value("endpoint", request.getRequestURI()));
    }

  }

  // note: later to be replaced,
  // see https://github.com/logstash/logstash-logback-encoder/tree/logstash-logback-encoder-4.7#loggingevent_custom_event
  private Object value(String key, Object value) {
    return value;
  }

}

Change filter logger to instance field


// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.identity;

import com.yahoo.vespa.athenz.api.AthenzService;

import javax.net.ssl.SSLContext;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * A helper class managing {@link ServiceIdentityProvider.Listener} instances for implementations of {@link ServiceIdentityProvider}.
 *
 * @author bjorncs
 */
public class ServiceIdentityProviderListenerHelper {

    private final Set<ServiceIdentityProvider.Listener> listeners = new ConcurrentSkipListSet<>();
    private final AthenzService identity;

    public ServiceIdentityProviderListenerHelper(AthenzService identity) {
        this.identity = identity;
    }

    public void addIdentityListener(ServiceIdentityProvider.Listener listener) {
        listeners.add(listener);
    }

    public void removeIdentityListener(ServiceIdentityProvider.Listener listener) {
        listeners.remove(listener);
    }

    public void onCredentialsUpdate(SSLContext sslContext) {
        listeners.forEach(l -> l.onCredentialsUpdate(sslContext, identity));
    }

    public void clearListeners() {
        listeners.clear();
    }

}

// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.identity;

import com.yahoo.vespa.athenz.api.AthenzService;

import javax.net.ssl.SSLContext;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * A helper class managing {@link ServiceIdentityProvider.Listener} instances for implementations of {@link ServiceIdentityProvider}.
 *
 * @author bjorncs
 */
public class ServiceIdentityProviderListenerHelper {

    private final Set<ServiceIdentityProvider.Listener> listeners = new CopyOnWriteArraySet<>();
    private final AthenzService identity;

    public ServiceIdentityProviderListenerHelper(AthenzService identity) {
        this.identity = identity;
    }

    public void addIdentityListener(ServiceIdentityProvider.Listener listener) {
        listeners.add(listener);
    }

    public void removeIdentityListener(ServiceIdentityProvider.Listener listener) {
        listeners.remove(listener);
    }

    public void onCredentialsUpdate(SSLContext sslContext) {
        listeners.forEach(l -> l.onCredentialsUpdate(sslContext, identity));
    }

    public void clearListeners() {
        listeners.clear();
    }

}

Use ConcurrentCopyOnWriteArraySet -- could alternatively provide a Comparator


package etomica.simulation;

import etomica.modules.catalysis.Catalysis;
import etomica.space3d.Space3D;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.profile.StackProfiler;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

@State(Scope.Benchmark)
@Fork(1)
public class BenchSimCatalysis {
    private Catalysis sim;

    @Param("20")
    private int nCellsZ;

    @Setup
    public void setup() {
        sim = new Catalysis(Space3D.getInstance(), nCellsZ);
        sim.integrator.reset();
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    @Warmup(time = 3, iterations = 5)
    @Measurement(time = 10, timeUnit = TimeUnit.SECONDS, iterations = 3)
    public long integratorStep() {
        sim.integrator.doStep();
        return sim.integrator.getStepCount();
    }

    public static void main(String[] args) throws RunnerException {
        Options opts = new OptionsBuilder()
                .include(BenchSimCatalysis.class.getSimpleName())
                .addProfiler(StackProfiler.class)
                .build();

        new Runner(opts).run();
    }
}

package etomica.simulation;

import etomica.modules.catalysis.Catalysis;
import etomica.space3d.Space3D;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.profile.StackProfiler;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

@State(Scope.Benchmark)
@Fork(1)
public class BenchSimCatalysis {
    private Catalysis sim;

    @Param("20")
    private int nCellsZ;

    @Setup(Level.Iteration)
    public void setup() {
        sim = new Catalysis(Space3D.getInstance(), nCellsZ);
        sim.integrator.reset();
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    @Warmup(time = 3, iterations = 5)
    @Measurement(time = 10, timeUnit = TimeUnit.SECONDS, iterations = 3)
    public long integratorStep() {
        sim.integrator.doStep();
        return sim.integrator.getStepCount();
    }

    public static void main(String[] args) throws RunnerException {
        Options opts = new OptionsBuilder()
                .include(BenchSimCatalysis.class.getSimpleName())
                .addProfiler(StackProfiler.class)
                .build();

        new Runner(opts).run();
    }
}

Make sure Catalysis benchmark sets up between each iteration