package com.interview.tree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * http://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/
 * Assumption that both a and b are unique in tree.
 * Test cases:
 * Empty tree
 * Tree with only root
 * Tree and input with a and b as cousin node
 * Tree and input with a and b not cousin node
 */
public class CousinNodes {

	public boolean areCousins(Node root,int a, int b){
		Deque<Node> queue = new LinkedList<Node>();
		queue.offerFirst(root);
		int levelSize=1;
		int tempLevelSize = 1;
		boolean foundFirst = false;
		while(!queue.isEmpty()){
			levelSize = 0;
			while(tempLevelSize > 0){
				Node node = queue.pollLast();
				if(node.data == a || node.data == b){
					if(foundFirst){
						return true;
					}
					foundFirst = true;
				}
				if(node.left!=null){
					queue.offerFirst(node.left);
					levelSize++;
				}
				if(node.right != null){
					queue.offerFirst(node.right);
					levelSize++;
				}
				tempLevelSize--;
			}
			if(foundFirst){
				return false;
			}
			tempLevelSize = levelSize;
		}
		return false;
	}

	public static void main(String args[]){
		BinaryTree bt = new BinaryTree();
		Node head = null;
		head = bt.addNode(10, head);
		head = bt.addNode(15, head);
		head = bt.addNode(5, head);
		head = bt.addNode(7, head);
		head = bt.addNode(19, head);
		head = bt.addNode(20, head);
		head = bt.addNode(-1, head);
		head = bt.addNode(21, head);
		head = bt.addNode(-6, head);
		CousinNodes cn = new CousinNodes();
		System.out.println(cn.areCousins(head, 10, 19));
		System.out.println(cn.areCousins(head, 19, 7));
		System.out.println(cn.areCousins(head, 19, -1));
		System.out.println(cn.areCousins(head, 19, -6));
	}
}

Check if two nodes are cousins


package com.kryptnostic.rhizome.hazelcast.processors;

import java.util.Map.Entry;

import com.google.common.collect.Sets;

import java.util.Set;

public abstract class SetContainsAnyEntryProcessor<T> extends AbstractRhizomeEntryProcessor<T, Set<T>> {

    private static final long serialVersionUID = -1578286848277056995L;
    private final Set<T>      objectsToCheck;

    public SetContainsAnyEntryProcessor( Set<T> objectsToCheck ) {
        super( false /* don't apply on backup nodes */ );
        this.objectsToCheck = objectsToCheck;
    }

    public Set<T> getObjectsToCheck() {
        return objectsToCheck;
    }

    @Override
    public Object process( Entry<T, Set<T>> entry ) {
        Set<T> value = entry.getValue();
        if ( value == null || value.isEmpty() ) {
            return null;
        }
        return !Sets.intersection( value, objectsToCheck ).isEmpty();
    }

}

Add EntryProcessor for checking set intersections


package com.sinyuk.yuk.utils;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ViewAnimator;

/**
 * Custom View Animator which is more easier to be uesd
 */
public class BetterViewAnimator extends ViewAnimator {
  public BetterViewAnimator(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public void setDisplayedChildId(int id) {
    if (getDisplayedChildId() == id) {
      return;
    }
    for (int i = 0, count = getChildCount(); i < count; i++) {
      if (getChildAt(i).getId() == id) {
        setDisplayedChild(i);
        return;
      }
    }
    String name = getResources().getResourceEntryName(id);
    throw new IllegalArgumentException("No view with ID " + name);
  }

  public int getDisplayedChildId() {
    return getChildAt(getDisplayedChild()).getId();
  }
}

Add a custom view animator implement


/*
 * Flow-Design for Java
 *
 * Copyright (c) 2015 Falko Schumann
 * Released under the terms of the MIT License (MIT).
 */

package de.muspellheim.flowdesign;

/**
 * Zeigt wie Functional-Units in Methoden überführt werden können.
 *
 * @author Falko Schumann <falko.schumann@muspellheim.de>
 */
public class MethodsCheatSheet {

    /**
     * Ein einfaches Beispiel einer Functional-Unit mit einem Input T und einem Output U.
     */
    public <U, T> U a(T input) {
        U u = null;
        // ...
        return u;
    }

    /**
     * Ein zusammengesetzten Beispiel. Die beiden Parts A und B werden zum Board X zusammengesteckt.
     */
    public <U, S, T> U x(T input) {
        S s = a(input);
        U u = b(s);
        return u;
    }

    private <U, T> U b(T input) {
        U u = null;
        // ...
        return u;
    }

    /**
     * Eine Functional-Unit mit zwei Input-Pins zu einem Tuple vereint.
     */
    public <T, U> void a(Tuple<T, U> input) {
        // ...
    }

    /**
     * Eine Functional-Unit mit zwei Output-Pins zu einem Tuple vereint.
     */
    public <T, U> Tuple<T, U> a() {
        // ...
        return null;
    }

    /**
     * Eine Functional-Unit mit zwei Output-Pins als Output-Parameter.
     */
    public <T, U> void a(T outputT, U outputU) {
        // ...
    }

    /**
     * Split von A auf B und C sowie Join von B und C auf D.
     */
    public <T, U, S, V> void foo() {
        T t = null;
        U u = null;
        a(t, u);

        S s = b(t);
        V v = c(u);

        d(Tuple.of(s, v));
    }

    private <U, T> U c(T input) {
        U u = null;
        // ...
        return u;
    }

    private <U, T> void d(Tuple<T, U> input) {
        // ...
    }

}

Create cheat sheet for translating to methods


// Copyright 2021 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.data;

/**
 * Class representing user data specific to a competition
 */
public class CompetitorInfo {

    /** The current ranking of the user in this competition based on networth */
    private int rank;

    /** The rank of the user yesterday for purposes of displaying rises/falls in leaderboard */
    private int rankYesterday;

    /** The competitor's name */
    private String name;

    /** The competitor's idap */
    private String idap;

    /** The networth of the competitor */
    private long networth;

    /** The amount the user has available for additional investments */
    private long amtAvailable;

    public CompetitorInfo(int rank, int rankYesterday, String name, String idap, long networth, long amtAvailable) {
        this.rank = rank;
        this.rankYesterday = rankYesterday;
        this.name = name;
        this.idap = idap;
        this.networth = networth;
        this.amtAvailable = amtAvailable;
    }
}

Add class representing user data for a single competition


package info.u_team.u_team_core.gui.render;

import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;

import info.u_team.u_team_core.util.RGBA;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.inventory.container.PlayerContainer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;

public class FluidInventoryRenderer extends AbstractGui {

	private static final ResourceLocation ATLAS = PlayerContainer.LOCATION_BLOCKS_TEXTURE;

	@SuppressWarnings("deprecation")
	public void drawFluid(MatrixStack matrixStack, int x, int y, FluidStack stack) {
		if (stack == null || stack.isEmpty()) {
			return;
		}

		final TextureAtlasSprite sprite = getFluidSprite(stack);
		Minecraft.getInstance().getTextureManager().bindTexture(ATLAS);

		RenderSystem.enableBlend();
		RenderSystem.enableAlphaTest();

		final RGBA rgba = RGBA.fromARGB(stack.getFluid().getAttributes().getColor(stack));
		RenderSystem.color4f(rgba.getRedComponent(), rgba.getGreenComponent(), rgba.getBlueComponent(), rgba.getAlphaComponent());

		blit(matrixStack, x, y, 100, 16, 16, sprite);

		RenderSystem.color4f(1, 1, 1, 1);

		RenderSystem.disableAlphaTest();
		RenderSystem.disableBlend();
	}

	private TextureAtlasSprite getFluidSprite(FluidStack stack) {
		return Minecraft.getInstance().getAtlasSpriteGetter(ATLAS).apply(stack.getFluid().getAttributes().getStillTexture(stack));
	}
}

Copy to new class with renamed name


/*
 * Copyright (c) 2007 Mozilla Foundation
 *
 * 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.whattf.datatype;

import org.relaxng.datatype.DatatypeException;

public class CharsetList extends AbstractDatatype {

    /**
     * The singleton instance.
     */
    public static final CharsetList THE_INSTANCE = new CharsetList();

    private enum State {
        WS_BEFORE_TOKEN
    }

    private CharsetList() {
        super();
    }

    @Override
    public void checkValid(CharSequence literal) throws DatatypeException {
        State state = State.WS_BEFORE_TOKEN;
        for (int i = 0; i < literal.length(); i++) {
            char c = literal.charAt(i);
            switch (state) {
            }
        }
        switch (state) {
        }
    }

    private boolean isTokenChar(char c) {
        return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '!'
                || c == '#' || c == '$' || c == '%' || c == '&' || c == '\''
                || c == '+' || c == '-' || c == '^' || c == '_' || c == '`'
                || c == '{' || c == '}' || c == '~';
    }

    @Override
    public String getName() {
        return "character encoding list";
    }

}

Save charset list awaiting input from Hixie


package boa.datagen.forges.github;

import java.io.File;

import boa.datagen.util.FileIO;

public class JsonSplitter {

	final private int Num_Threads;
	private String outDir;
	private String inDir;

	JsonSplitter(int threads, String outDir, String inDir){
		this.Num_Threads = threads;
		this.outDir = outDir;
		this.inDir = inDir;
	}

	public static void main(String[] args) {
		JsonSplitter JS = new JsonSplitter(Integer.parseInt(args[0]), args[1], args[2]);
		JS.split();
	}

	public void split () {
		Splitter[] workers = new Splitter[Num_Threads];
		for (int i = 0; i < Num_Threads; i++) {
			Splitter worker = new Splitter(i, outDir);
			workers[i] = worker;
		}
		File[] files = new File(inDir).listFiles();

		for (int i = 0; i < files.length; i ++) {
			if (!files[i].getPath().contains(".json"))
				continue;
			boolean assigned = false;
			while (!assigned) {
				for (int j = 0; j < Num_Threads; j++) {
					if (workers[j].isAvailable()){
						workers[j].setFile(files[i]);
						new Thread(workers[j]).start();
						try {
							Thread.sleep(10);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						assigned = true;
						break;
					}
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private class Splitter implements Runnable {
		private boolean available = true;
		private File file;
		private String dir;
		private int id;
		Splitter(int id, String outDir) {
			this.id = id;
			this.dir = outDir + id;
			File output = new File(dir);
			if (!output.exists())
				output.mkdirs();
		}

		public boolean isAvailable() { return available; }

		public void setFile(File file) {
			this.file = file;
		}

		private void proccessFile(){
			String content = FileIO.readFileContents(file);
			System.out.println(id + " is processing " + file.getName());
			FileIO.writeFileContents(new File(dir +"/" + file.getName()), content);
		}

		@Override
		public void run() {
			available = false;
			proccessFile();
			try {
				Thread.sleep(150 * Num_Threads + 1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			available = true;
		}

	}
}

Divide json metadata to be run on multiple processes.


package io.sigpipe.sing.adapters;

import io.sigpipe.sing.dataset.feature.Feature;
import io.sigpipe.sing.dataset.feature.FeatureType;
import io.sigpipe.sing.graph.FeatureHierarchy;
import io.sigpipe.sing.graph.Sketch;
import io.sigpipe.sing.query.Expression;
import io.sigpipe.sing.query.Operator;
import io.sigpipe.sing.query.RelationalQuery;
import io.sigpipe.sing.util.PerformanceTimer;
import io.sigpipe.sing.util.TestConfiguration;

public class QueryTest {

    public static void main(String[] args)
    throws Exception {
        for (String featureName : TestConfiguration.FEATURE_NAMES) {
            ReadMetaBlob.activeFeatures.add(featureName);
        }

        FeatureHierarchy fh = new FeatureHierarchy();
        for (String featureName : TestConfiguration.FEATURE_NAMES) {
            System.out.println(
                    TestConfiguration.quantizers.get(featureName).numTicks()
                    + "   " + featureName);
            fh.addFeature(featureName, FeatureType.FLOAT);
        }
        fh.addFeature("location", FeatureType.STRING);
        Sketch s = new Sketch(fh);

        for (String f : args) {
            ReadMetaBlob.loadData(f, s);
        }

        RelationalQuery mq = new RelationalQuery();
        mq.addExpression(new Expression(Operator.STR_PREFIX, new Feature("location", "9xqj")));
        mq.addExpression(
                new Expression(
                    Operator.RANGE_INC,
                    new Feature("temperature_surface", 300.0f),
                    new Feature(320.0f)));
        mq.addExpression(
                new Expression(
                    Operator.GREATER,
                    new Feature("relative_humidity_zerodegc_isotherm", 70.0f)));

        mq.execute(s.getRoot());
        PerformanceTimer statQuery = new PerformanceTimer("relQuery");
        for (int i = 0; i < 1000; ++i) {
        statQuery.start();
        s.query(mq);
        statQuery.stopAndPrint();
        }
    }
}

Add very simple query test harness


package com.reactlibrary;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import org.tensorflow.Operation;

public class RNTensorflowGraphOperationsModule extends ReactContextBaseJavaModule {

    private Operation graphOperation;

    public RNTensorflowGraphOperationsModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "TensorflorGraphOperation";
    }

    @ReactMethod
    public void init(Operation graphOperation) {
        this.graphOperation = graphOperation;
    }

    @ReactMethod
    public void inputListLength(String s, Promise promise) {
        try {
            promise.resolve(graphOperation.inputListLength(s));
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void name(Promise promise) {
        try {
            promise.resolve(graphOperation.name());
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void numOutputs(Promise promise) {
        try {
            promise.resolve(graphOperation.numOutputs());
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void output(int output, Promise promise) {
        try {
            promise.resolve(graphOperation.output(output));
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void outputList(int i, int ii, Promise promise) {
        try {
            promise.resolve(graphOperation.outputList(i, ii));
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void outputListLength(String s, Promise promise) {
        try {
            promise.resolve(graphOperation.outputListLength(s));
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void type(Promise promise) {
        try {
            promise.resolve(graphOperation.type());
        } catch (Exception e) {
            promise.reject(e);
        }
    }
}

Implement first draft for graph operations


package com.es.lib.common.time;

import com.es.lib.common.DateUtil;
import com.es.lib.common.Pluralizer;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.Date;

/**
 * @author Zuzoev Dmitry - zuzoev.d@ext-system.com
 * @since 10.05.2018
 */
public final class PeriodUtil {

    private static final int MINUTES_PER_HOUR = 60;
    private static final int SECONDS_PER_MINUTE = 60;
    private static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;

    public static String pretty(Date date, boolean useBraces) {
        return pretty(DateUtil.convert(date), useBraces);
    }

    public static String pretty(LocalDateTime date, boolean useBraces) {
        return pretty(date, LocalDateTime.now(), useBraces);
    }

    public static String pretty(Date date, Date dateNext, boolean useBraces) {
        return pretty(DateUtil.convert(date), DateUtil.convert(dateNext), useBraces);
    }

    public static String pretty(LocalDateTime date, LocalDateTime dateNext, boolean useBraces) {
        if (date == null || dateNext == null) {
            return null;
        }
        Period period = Period.between(date.toLocalDate(), dateNext.toLocalDate());
        long[] time = getTime(date, dateNext);
        StringBuilder sb = new StringBuilder();
        if (period.getYears() > 0) {
            sb.append(period.getYears()).append(" ").append(Pluralizer.evaluate(period.getYears(), "год", "года", "лет"));
        }
        if (period.getMonths() > 0) {
            sb.append(period.getMonths()).append(" мес.");
        }
        if (period.getDays() > 0) {
            sb.append(period.getDays()).append(" дн.");
        }
        if (time[0] > 0) {
            sb.append(time[0]).append(" ч.");
        }
        if (time[1] > 0) {
            sb.append(time[1]).append(" м.");
        }
        if (time[2] > 0) {
            sb.append(time[2]).append(" c.");
        }
        String result = sb.toString();
        if (useBraces) {
            result = "(" + result + ")";
        }
        return result;
    }

    private static long[] getTime(LocalDateTime date, LocalDateTime dateNext) {
        LocalDateTime original = LocalDateTime.of(dateNext.getYear(),
            dateNext.getMonthValue(), dateNext.getDayOfMonth(), date.getHour(), date.getMinute(), date.getSecond());
        Duration duration = Duration.between(original, dateNext);

        long seconds = duration.getSeconds();

        long hours = seconds / SECONDS_PER_HOUR;
        long minutes = ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
        long secs = (seconds % SECONDS_PER_MINUTE);

        return new long[]{hours, minutes, secs};
    }
}

Add pretty print interval util


package info.u_team.u_team_core.intern.init;

import info.u_team.u_team_core.item.USpawnEggItem;
import net.minecraft.block.DispenserBlock;
import net.minecraft.entity.*;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.Direction;
import net.minecraftforge.client.event.ColorHandlerEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.*;

public class UCoreLazySpawnEggs {

	private static void setup(FMLCommonSetupEvent event) {
		event.enqueueWork(() -> {
			USpawnEggItem.LAZY_EGGS.forEach(pair -> {
				final EntityType<?> type = pair.getKey().getValue();
				final USpawnEggItem item = pair.getValue();

				item.typeIn = type;

				DispenserBlock.registerDispenseBehavior(item, (source, stack) -> {
					final Direction direction = source.getBlockState().get(DispenserBlock.FACING);
					final EntityType<?> entityType = ((USpawnEggItem) stack.getItem()).getType(stack.getTag());
					entityType.spawn(source.getWorld(), stack, (PlayerEntity) null, source.getBlockPos().offset(direction), SpawnReason.DISPENSER, direction != Direction.UP, false);
					stack.shrink(1);
					return stack;
				});
			});
		});
	}

	private static void colorItem(ColorHandlerEvent.Item event) {
		USpawnEggItem.LAZY_EGGS.forEach(pair -> {
			final USpawnEggItem item = pair.getValue();

			event.getItemColors().register((stack, color) -> {
				return item.getColor(color);
			}, item);
		});
	}

	private static void loadComplete(FMLLoadCompleteEvent event) {
		event.enqueueWork(() -> {
			USpawnEggItem.LAZY_EGGS.forEach(pair -> {
				final EntityType<?> type = pair.getKey().getValue();
				final USpawnEggItem item = pair.getValue();

				USpawnEggItem.EGGS.put(type, item);
			});
		});
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(UCoreLazySpawnEggs::setup);
		bus.addListener(UCoreLazySpawnEggs::colorItem);
		bus.addListener(UCoreLazySpawnEggs::loadComplete);
	}

}

Add core lazy spawn eggs handler


package eme.model;

import static org.junit.Assert.assertEquals;

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

public class IntermediateModelTest {

    IntermediateModel model;

    @Before
    public void setUp() throws Exception {
        model = new IntermediateModel("TestModel");
    }

    @Test
    public void testAutoAdd() {
        addMVCPackages();
        model.add(new ExtractedClass("NormalClass", false));
        model.add(new ExtractedClass("main.AbstractClass", true));
        model.add(new ExtractedInterface("main.model.Interface"));
        model.add(new ExtractedEnumeration("main.view.Enumeration"));
        model.add(new ExtractedClass("main.controller.OuterClass$InnerClass", false));
        checkTypeAmount(model.getRoot(), 1);
    }

    @Test
    public void testDuplicatePackage() {
        addMVCPackages();
        addMVCPackages();
        assertEquals(4, countPackages(model.getRoot()));
    }

    @Test(expected = RuntimeException.class)
    public void testUnknownPackage() {
        addMVCPackages();
        model.add(new ExtractedPackage("illegal.subpackage"));
        model.add(new ExtractedPackage("main.illegal.subpackage"));
    }

    private void addMVCPackages() {
        model.add(new ExtractedPackage(""));
        model.add(new ExtractedPackage("main"));
        model.add(new ExtractedPackage("main.model"));
        model.add(new ExtractedPackage("main.view"));
        model.add(new ExtractedPackage("main.controller"));
    }

    private void checkTypeAmount(ExtractedPackage fromPackage, int amountPerPackage) {
        assertEquals(amountPerPackage, fromPackage.getTypes().size());
        for (ExtractedPackage subpackage : fromPackage.getSubpackages()) {
            checkTypeAmount(subpackage, amountPerPackage);
        }
    }

    private int countPackages(ExtractedPackage inPackage) {
        int amount = 0;
        for (ExtractedPackage subpackage : inPackage.getSubpackages()) {
            amount += 1 + countPackages(subpackage);
        }
        return amount;
    }
}

Test case for the intermediate model.


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

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import javax.servlet.Filter;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.samples.mvc.config.WebMvcConfiguration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * @author Rob Winch
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={RootConfiguration.class, WebMvcConfiguration.class})
@WebAppConfiguration
public class SecurityConfigTests {
    private MockMvc mvc;

    @Autowired
    private WebApplicationContext context;

    @Autowired
    private Filter springSecurityFilterChain;

    @Before
    public void setup() {
        mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .addFilters(springSecurityFilterChain)
                .build();
    }

    @Test
    public void composeMessage() throws Exception {
        MockHttpServletRequestBuilder composeMessage =
            post("/")
                .param("summary", "New Message")
                .param("text", "This is a new message");

        mvc.perform(composeMessage)
            .andExpect(redirectedUrlPattern("/*"));
    }
}

Add MockMvc tests for insecuremvc


package com.pinterest.secor.parser;

import com.pinterest.secor.common.SecorConfig;

import java.util.Date;

public class NoDateStampJsonMessageParser extends JsonMessageParser {
    public NoDateStampJsonMessageParser(SecorConfig config) {
        super(config);
    }

    @Override
    protected String[] generatePartitions(long timestampMillis, boolean usingHourly)
        throws Exception {
            return new String[]{};
    }
}

Add prefixless overload of JsonMessageParser.


package com.redhat.ceylon.common.test;

import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.redhat.ceylon.common.Authentication;
import com.redhat.ceylon.common.CeylonConfig;
import com.redhat.ceylon.common.ConfigParser;
import com.redhat.ceylon.common.Proxies;
import com.redhat.ceylon.common.Proxies.Proxy;

public class ProxyTool {

    public static void main(String[] args) throws Exception {
        if (args.length != 3) {
            usage("Wrong number of arguments");
        }
        String mode = args[0];

        File configFile = new File(args[1]);
        if (!configFile.exists()) {
            usage("Config file doesn't exist");
            return;
        }

        final URL url;
        try {
            url  = new URL(args[2]);
        } catch (MalformedURLException e) {
            usage("Malformed URL");
            return;
        }

        CeylonConfig config = ConfigParser.loadConfigFromFile(configFile);
        Authentication auth = Authentication.fromConfig(config);
        Proxy proxy = Proxies.withConfig(config).getProxy();
        final URLConnection conn;
        switch (mode){
        case "proxy":
            java.net.Proxy netProxy = auth.getProxy();
            conn = url.openConnection(netProxy);
            break;
        case "install":
            auth.installProxy();
            conn = url.openConnection();
            break;
        default:
            throw new RuntimeException("Unsupported mode");
        }

        InputStream in = conn.getInputStream();
        try {
            int ch = in.read();
            while (ch != -1) {
                System.out.append((char)ch);
                ch = in.read();
            }
        } finally {
            in.close();
        }

    }

    private static void usage(String error) {
        if (error != null) {
            System.err.println(error);
        }
        System.err.println("Expect 3 arguments: proxy|install <configfile> <url>");
        System.exit(1);
    }

}

Add a simple tool for manual testing of the Proxy configuration


package com.elmakers.mine.bukkit.action.builtin;

/**
 * Not deprecating this yet, but prefer to use EquipAction.
 */
public class WearAction extends EquipAction {
}

Add in a placeholder Wear action for compatibility


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem32;

/**
 * Given two strings passed as argument, can you write a method to return true if the second
 * contains the first one?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class Contains {

}

Add statement to problem 32


package hudson.remoting;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;

/**
 * Takes a directory of jars and populates them into the given jar cache
 * directory with the correct hash names.
 *
 *
Ideally this class should exist outside hudson.remoting but unfortunately
 * it needs access to package-private methods in hudson.remoting.
 *
 * @author Akshay Dayal
 */
public class InitializeJarCacheMain {

    private static final FilenameFilter JAR_FILE_FILTER = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar");
        }
    };

    /**
     * Requires 2 parameters:
     *

     *
The source jar directory.
     *
The jar cache directory.
     *

     */
    public static void main(String[] argv) throws Exception {
        if (argv.length != 2) {
            throw new IllegalArgumentException(
                    "Usage: java -cp slave.jar hudson.remoting.InitializeJarCacheMain " +
                    "<source jar dir> <jar cache dir>");
        }

        File sourceJarDir = new File(argv[0]);
        File jarCacheDir = new File(argv[1]);
        FileSystemJarCache jarCache = new FileSystemJarCache(jarCacheDir, false);

        File[] jars = sourceJarDir.listFiles(JAR_FILE_FILTER);
        for (File jar : jars) {
            Checksum checksum = Checksum.forFile(jar);
            File newJarLocation = jarCache.map(checksum.sum1, checksum.sum2);

            newJarLocation.getParentFile().mkdirs();
            copyFile(jar, newJarLocation);
        }
    }

    /**
     * Util method to copy file from one location to another.
     *
     *
We don't have access to Guava, apache or Java7, so we have to write
     * our own from scratch.
     */
    private static void copyFile(File src, File dest) throws Exception {
        FileInputStream input = null;
        FileOutputStream output = null;
        try {
            input = new FileInputStream(src);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024 * 1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        }
    }
}

Add a utility main that can populate a jar cache dir given another directory of jars.


/*
 * Copyright 2008 FatWire Corporation. 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 com.fatwire.gst.foundation.facade.logging;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Utility class for Loggers.
 *
 * @author Dolf Dijkstra
 *
 */
public class LogUtil {

    /**
     * Returns the Log for the provided class based on the package name of the
     * class.
     *
     * @param clazz
     * @return
     */
    public static Log getLog(Class<?> clazz) {
        return LogFactory.getLog(clazz.getPackage().getName());
    }

}

Add utility class to work with loggers. Initial method is to help with loggers naming convention, based on package name of the class.


/**
 * Copyright 2013 Julien Silland
 *
 * 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.soliton.protobuf.plugin;

import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.Descriptors;
import com.google.protobuf.compiler.PluginProtos;
import io.soliton.protobuf.plugin.testing.Testing;
import org.junit.Assert;
import org.junit.Test;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import java.io.ByteArrayOutputStream;
import java.net.URI;

public class ProtoServiceHandlerTest {

  private static class JavaSourceFromString extends SimpleJavaFileObject {

    final String code;

    /**
     * Constructs a new JavaSourceFromString.
     * @param name the name of the compilation unit represented by this file object
     * @param code the source code for the compilation unit represented by this file object
     */
    JavaSourceFromString(String name, String code) {
      super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension),
          Kind.SOURCE);
      this.code = code;
    }

    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) {
      return code;
    }
  }

  @Test
  public void testHandle() throws Exception {
    Descriptors.Descriptor personDescriptor = Testing.Person.getDescriptor();
    DescriptorProtos.FileDescriptorProto protoFile = personDescriptor.getFile().toProto();
    TypeMap types = TypeMap.of(protoFile);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ProtoServiceHandler serviceHandler = new ProtoServiceHandler(
        "io.soliton.protobuf.plugin.testing", types, output);
    serviceHandler.handle(protoFile.getServiceList().get(0));
    PluginProtos.CodeGeneratorResponse response = PluginProtos.CodeGeneratorResponse.parseFrom(
        output.toByteArray());
    Assert.assertNotNull(response);
    Assert.assertEquals(1, response.getFileCount());
    Assert.assertEquals("io/soliton/protobuf/plugin/testing/PhoneBookService.java",
        response.getFile(0).getName());
    String fileContent = response.getFile(0).getContent();
    JavaFileObject file = new JavaSourceFromString
        ("io/soliton/protobuf/plugin/testing/PhoneBookService.java", fileContent);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  }
}

Add test code for the plugin


/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * 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.gravitee.management.rest.resource;

import io.gravitee.management.model.MemberEntity;
import io.gravitee.management.service.ApiService;
import io.gravitee.management.service.ApplicationService;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Set;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public class ApplicationMembersResource {

    @Inject
    private ApplicationService applicationService;

    @PathParam("applicationName")
    private String applicationName;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Set<MemberEntity> members() {
        // Check that the API exists
        applicationService.findByName(applicationName);

        return applicationService.getMembers(applicationName, null);
    }
}

Add members list per application


import java.util.HashMap;
import java.util.Map;

/**
 * Created by drfish on 25/06/2017.
 */
public class _013RomanToInteger {
    public int romanToInt(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>() {{
            put('M', 1000);
            put('D', 500);
            put('C', 100);
            put('L', 50);
            put('X', 10);
            put('V', 5);
            put('I', 1);
        }};
        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            if (i > 0 && map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) {
                result -= map.get(s.charAt(i - 1));
                result += map.get(s.charAt(i)) - map.get(s.charAt(i - 1));
            } else {
                result += map.get(s.charAt(i));
            }
        }
        return result;
    }

    public static void main(String[] args) {
        _013RomanToInteger solution = new _013RomanToInteger();
        assert 12 == solution.romanToInt("XII");
        assert 21 == solution.romanToInt("XXI");
        assert 99 == solution.romanToInt("XCIX");
    }
}

Add java solution for 13


package com.boundary.metrics.vmware;

import io.dropwizard.configuration.ConfigurationFactory;
import io.dropwizard.jackson.Jackson;

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

import javax.validation.Validation;
import javax.validation.Validator;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.io.Resources;

public class VMWareTestUtils {

	public static VMwarePerfAdapterConfiguration getConfiguration(String resource) throws Exception {

		VMwarePerfAdapterConfiguration configuration = null;
		File validFile = new File(Resources.getResource(resource).toURI());
		System.out.println(resource);

		Validator validator = Validation.buildDefaultValidatorFactory()
				.getValidator();
		ConfigurationFactory<VMwarePerfAdapterConfiguration> factory = new ConfigurationFactory<VMwarePerfAdapterConfiguration>(
				VMwarePerfAdapterConfiguration.class, validator,
				Jackson.newObjectMapper(), "dw");

		try {
			configuration = factory.build(validFile);
		} catch (JsonParseException e) {

			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return configuration;
	}
}

Add utility class loads VMWare adapter configuration file


package com.xtremelabs.robolectric.util;

import org.junit.Test;

import java.io.InputStream;
import java.io.StringBufferInputStream;

import static junit.framework.Assert.assertEquals;

public class StringsTest {
    @Test
    public void shouldGetStringFromStream() throws Exception {
        InputStream stream = new StringBufferInputStream("some random string");
        assertEquals("some random string", Strings.fromStream(stream));
    }
}

Test for Strings utility class


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

package com.dtolabs.rundeck.core.jobs;

import com.dtolabs.rundeck.core.execution.workflow.StepExecutionContext;
import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class ExecutionLifecycleStatusImpl
        implements ExecutionLifecycleStatus
{
    private final boolean successful;
    private final String errorMessage;
    private final boolean useNewValues;
    private final StepExecutionContext executionContext;
}

Add utility impl for ExecutionLifecycleStatus


package arez.integration.verify;

import arez.Arez;
import arez.Disposable;
import arez.annotations.ArezComponent;
import arez.annotations.Reference;
import arez.annotations.ReferenceId;
import arez.annotations.Repository;
import arez.component.Identifiable;
import arez.component.TypeBasedLocator;
import arez.component.Verifiable;
import arez.integration.AbstractArezIntegrationTest;
import java.util.HashMap;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.testng.annotations.Test;

public class VerifyIntegrationTest
  extends AbstractArezIntegrationTest
{
  @Test
  public void scenario()
    throws Throwable
  {
    final VerifyIntegrationTest_Model2Repository repository =
      VerifyIntegrationTest_Model2Repository.newRepository();

    final TypeBasedLocator locator = new TypeBasedLocator();
    Arez.context().registerLocator( locator );

    final HashMap<Object, Model1> entities1 = new HashMap<>();
    final HashMap<Object, Model2> entities2 = new HashMap<>();
    locator.registerLookup( Model1.class, entities1::get );
    locator.registerLookup( Model2.class, entities2::get );

    final Model2 model2a = repository.create();
    final Object model2aId = Objects.requireNonNull( Identifiable.getArezId( model2a ) );
    entities2.put( model2aId, model2a );

    final Model1 model1 = Model1.create( model2aId );
    final Object model1Id = Objects.requireNonNull( Identifiable.getArezId( model1 ) );
    entities1.put( model1Id, model1 );

    // Should verify as will link correctly
    Verifiable.verify( model1 );

    {
      entities2.clear();

      // Fail to verify as related is missing
      assertInvariant( () -> Verifiable.verify( model1 ),
                       "Reference method named 'getModel2' invoked on component named 'Model1.0' missing related entity. Id = 0" );
      entities2.put( model2aId, model2a );
    }

    {
      entities1.clear();

      // Fail to verify as missing self
      assertInvariant( () -> Verifiable.verify( model1 ),
                       "Attempted to lookup self in Locator with type VerifyIntegrationTest.Model1 and id '0' but unable to locate self. Actual value: null" );

      entities1.put( model1Id, model1 );
    }

    Disposable.dispose( model1 );

    // Fail to verify as disposed
    assertInvariant( () -> Verifiable.verify( model1 ),
                     "Method named 'verify' invoked on disposed component named 'Model1.0'" );
  }

  @ArezComponent( allowEmpty = true )
  static abstract class Model1
  {
    @Nonnull
    private final Object _model2Id;

    static Model1 create( @Nonnull final Object model2Id )
    {
      return new VerifyIntegrationTest_Arez_Model1( model2Id );
    }

    Model1( @Nonnull final Object model2Id )
    {
      _model2Id = model2Id;
    }

    @Reference
    abstract Model2 getModel2();

    @ReferenceId
    @Nonnull
    final Object getModel2Id()
    {
      return _model2Id;
    }
  }

  @Repository
  @ArezComponent( allowEmpty = true )
  static abstract class Model2
  {
  }
}

Add integration test for verify


package org.kohsuke.args4j;

// a 'custom' exception
import javax.management.InvalidAttributeValueException;

public class CustomExceptionTest extends Args4JTestBase<CustomExceptionTest> {

    private String errMsgX = "this is a usual CLI exception";
    private String errMsgY = "this is a 'custom' exception";

    @Option(name="-x")
    public void setX(String x) {
        throw new IllegalArgumentException(errMsgX);
    }

    @Option(name="-y")
    public void setY(String y) throws InvalidAttributeValueException {
        throw new InvalidAttributeValueException(errMsgX);
    }

    @Override
    public CustomExceptionTest getTestObject() {
        return this;
    }

    protected void tryThis(String expected, Class expectedExceptionClass, String... parserArgs) {
        String expMsg = expectedExceptionClass.getName() + ": " + expected;
        try {
            parser.parseArgument(parserArgs);
            fail("Exception expected.");
        } catch (RuntimeException e) {
            // RuntimeExceptions are passed through the parser to the caller.
            assertEquals("Lost exception message.", expMsg, e.toString());
        } catch (CmdLineException e) {
            // Other Exceptions are wrapped into a CLE so we must ensure not to loose the
            // message.
            assertEquals("Lost exception message.", expMsg, e.getMessage());
        } catch (Exception e) {
            fail("Wrong exception type thrown.");
        }
    }

    public void testRuntimeException() throws Exception {
        tryThis(errMsgX, IllegalArgumentException.class, "-x", "value");
    }

    public void testCustomException() throws Exception {
        tryThis(errMsgX, InvalidAttributeValueException.class, "-y", "value");
    }

}

Add a test how to handle thrown exceptions thrown in setters.


// Copyright 2015 Google Inc. 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 com.google.devtools.build.lib.analysis.util;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.DefaultsPackage;
import com.google.devtools.build.lib.analysis.config.FragmentOptions;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsParsingException;

/**
 * Helper class for testing {@link DefaultsPackage}.
 */
public class DefaultsPackageUtil {

  public static String getDefaultsPackageForOptions(Class<? extends FragmentOptions> optionsClass,
      String... options) throws OptionsParsingException {
    OptionsParser parser = OptionsParser.newOptionsParser(
        ImmutableList.<Class<? extends OptionsBase>>of(
            BuildConfiguration.Options.class, optionsClass));
    parser.parse(options);
    return DefaultsPackage.getDefaultsPackageContent(BuildOptions.of(
        ImmutableList.<Class<? extends FragmentOptions>>of(
            BuildConfiguration.Options.class, optionsClass), parser));
  }
}

Split up the DefaultsPackageTest into C++ and Java parts. Move some tests out of BuildConfigurationTest into a new test class.


/*
 * Copyright 2013 Erwin Müller <erwin.mueller@deventm.org>
 *
 * This file is part of globalpom-utils.
 *
 * globalpom-utils is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * globalpom-utils 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 Lesser General Public License
 * along with globalpom-utils. If not, see <http://www.gnu.org/licenses/>.
 */
package com.anrisoftware.globalpom.constants;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.anrisoftware.globalpom.measurement.ExactAverageValueFactory;
import com.anrisoftware.globalpom.measurement.Value;
import com.google.inject.Provider;

/**
 * Provides the value of the absolute zero {@code T→0=-273.15 °C} that
 * calculates error propagation using simpler average errors.
 *
 * @author Erwin Mueller, erwin.mueller@deventm.org
 * @since 1.9
 */
@Singleton
public class AverageAbsoluteZeroProvider implements Provider<Value> {

	@Inject
	private ExactAverageValueFactory factory;

	@Override
	public Value get() {
		return factory.create(-273.15d);
	}

}

Add absolute zero constant -273.15 °C


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

package com.example.asadkhan.sunshine.utils;

import junit.framework.Assert;

import java.util.concurrent.Callable;

public abstract class PollingCheck {
    private static final long TIME_SLICE = 50;
    private long mTimeout = 3000;

    public PollingCheck() {
    }

    public PollingCheck(long timeout) {
        mTimeout = timeout;
    }

    protected abstract boolean check();

    public void run() {
        if (check()) {
            return;
        }

        long timeout = mTimeout;
        while (timeout > 0) {
            try {
                Thread.sleep(TIME_SLICE);
            } catch (InterruptedException e) {
                Assert.fail("unexpected InterruptedException");
            }

            if (check()) {
                return;
            }

            timeout -= TIME_SLICE;
        }

        Assert.fail("unexpected timeout");
    }

    public static void check(CharSequence message, long timeout, Callable<Boolean> condition)
            throws Exception {
        while (timeout > 0) {
            if (condition.call()) {
                return;
            }

            Thread.sleep(TIME_SLICE);
            timeout -= TIME_SLICE;
        }

        Assert.fail(message.toString());
    }
}

Add Android Util Unit Test Classes


package com.sleekbyte.tailor.utils;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * Tests for {@link Pair}.
 */
@RunWith(MockitoJUnitRunner.class)
public final class PairTest {

    Pair pair;

    @Before
    public void setUp() {
        pair = new Pair<>("Left", "Right");
    }

    @Test
    public void testUnequalPairs() {
        Pair candidatePair = new Pair<>(1, 2);
        assertFalse(pair.equals(candidatePair));
    }

    @Test
    public void testEqualPairs() {
        Pair candidatePair = new Pair<>("Left", "Right");
        assertEquals(pair, candidatePair);
    }

}

Add additional tests for Pair.java


package org.libreoffice.example.helper;

import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XModel;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.text.XTextDocument;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;

public class DocumentHelper {

	/** Returns the curerent XDesktop */
	public static XDesktop getCurrentDesktop(XComponentContext xContext) {
		XMultiComponentFactory xMCF = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class,
				xContext.getServiceManager());
        Object desktop = null;
		try {
			desktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
		} catch (Exception e) {
			return null;
		}
        return (XDesktop) UnoRuntime.queryInterface(com.sun.star.frame.XDesktop.class, desktop);
	}

	/** Returns the current XComponent */
    private static XComponent getCurrentComponent(XComponentContext xContext) {
        return (XComponent) getCurrentDesktop(xContext).getCurrentComponent();
    }

    /** Returns the current frame */
    public static XFrame getCurrentFrame(XComponentContext xContext) {
    	XModel xModel = (XModel) UnoRuntime.queryInterface(XModel.class, getCurrentComponent(xContext));
    	return xModel.getCurrentController().getFrame();
    }

    /** Returns the current text document (if any) */
    public static XTextDocument getCurrentDocument(XComponentContext xContext) {
        return (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class, getCurrentComponent(xContext));
    }
}

Add helper to retrieve frame, document etc


package com.interview.recursion;

import java.util.*;

/**
 * Created by tushar_v_roy on 2/23/16.
 */
public class RemoveInvalidParenthesis {

    public List<String> removeInvalidParentheses(String s) {
        Set<String> res = new HashSet<>();
        int rmL = 0, rmR = 0;
        for(int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == '(') rmL++;
            if(s.charAt(i) == ')') {
                if(rmL != 0) rmL--;
                else rmR++;
            }
        }
        DFS(res, s, 0, rmL, rmR, 0, new StringBuilder());
        return new ArrayList<String>(res);
    }

    public void DFS(Set<String> res, String s, int i, int rmL, int rmR, int open, StringBuilder sb) {
        if(i == s.length() && rmL == 0 && rmR == 0 && open == 0) {
            res.add(sb.toString());
            return;
        }
        if(i == s.length() || rmL < 0 || rmR < 0 || open < 0) return;

        char c = s.charAt(i);
        int len = sb.length();

        if(c == '(') {
            DFS(res, s, i + 1, rmL - 1, rmR, open, sb);
            DFS(res, s, i + 1, rmL, rmR, open + 1, sb.append(c));

        } else if(c == ')') {
            DFS(res, s, i + 1, rmL, rmR - 1, open, sb);
            DFS(res, s, i + 1, rmL, rmR, open - 1, sb.append(c));

        } else {
            DFS(res, s, i + 1, rmL, rmR, open, sb.append(c));
        }

        sb.setLength(len);
    }

    public static void main(String args[]) {

        String s = "(r(()()(";
        RemoveInvalidParenthesis rmp = new RemoveInvalidParenthesis();
        List<String> result = rmp.removeInvalidParentheses(s);
        result.forEach(s1 -> System.out.println(s1));
    }
}

Remove invalid parentheses to get all combinations of result


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem61;

/**
 * You have two numbers represented by a linked list, where each node contains a single digit.The
 * digit are stored in reverse order,such that the 1's digit is at the head of the list. Write a
 * function that adds the two numbers and returns the sum as a linked list.
 *
 * Suppose the digits are stored in forward order. Repeat the above problem.
 *
 * Negative numbers are not allowed.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class SumLists {

}

Add statement to problem 61


package io.castle.client;

import io.castle.client.model.*;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;

import static okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE;

public class CastleArchiveDevicesHttpTest extends AbstractCastleHttpLayerTest {

    public CastleArchiveDevicesHttpTest() {
        super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
    }

    @Test public void archiveDevices() throws Exception {
        MockResponse mockResponse = new MockResponse();
        mockResponse.setBody("{\"id\":\"userId\",\"created_at\":null,\"updated_at\":\"2019-03-26T11:31:19.968Z\",\"last_seen_at\":\"2019-03-26T09:38:43.339Z\",\"flagged_at\":null,\"risk\":0.0,\"leaks_count\":3,\"devices_count\":2,\"email\":\"admin@example.com\",\"name\":\"Doe\",\"username\":null,\"phone\":null,\"address\":{\"street\":null,\"city\":null,\"postal_code\":null,\"region\":null,\"country\":null},\"custom_attributes\":{}}");
        server.enqueue(mockResponse);

        // And a mock Request
        HttpServletRequest request = new MockHttpServletRequest();

        // And an devices request is made
        CastleUser result = sdk.onRequest(request).archiveUserDevices("userId");

        // Then
        RecordedRequest recordedRequest = server.takeRequest();
        Assert.assertEquals(testServerBaseUrl.resolve("v1/users/userId/archive_devices"), recordedRequest.getRequestUrl());
        Assert.assertEquals("PUT", recordedRequest.getMethod());

        // and the correct Success model object is extracted
        CastleUser expected = new CastleUser();
        expected.setId("userId");
        expected.setUpdatedAt("2019-03-26T11:31:19.968Z");
        expected.setLastSeenAt("2019-03-26T09:38:43.339Z");
        expected.setLeaksCount(3);
        expected.setDevicesCount(2);
        expected.setEmail("admin@example.com");
        expected.setName("Doe");
        expected.setAddress(new CastleUserAddress());
        expected.setCustomAttributes(new HashMap<String, String>());

        Assertions.assertThat(result).isEqualToComparingFieldByFieldRecursively(expected);
    }

    @Test(expected = CastleRuntimeException.class)
    public void archiveDevicesTimeoutTest() {

        // given backend request timeouts
        server.enqueue(new MockResponse().setSocketPolicy(NO_RESPONSE));
        HttpServletRequest request = new MockHttpServletRequest();
        String userId = "userId";

        //when a review request is made
        sdk.onRequest(request).archiveUserDevices(userId);
    }
}

Add tests for archive devices api


package seedu.tache.logic.parser;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.tache.logic.commands.AddCommand;
import seedu.tache.logic.commands.Command;
import seedu.tache.logic.commands.IncorrectCommand;

public class AddCommandParserTest {

    @Test
    public void parse_emptyArgument_failure() {
        Command invalidFormat = new AddCommandParser().parse("");
        assertIncorrectCommandType(invalidFormat);
    }

    @Test
    public void parse_correctArgument_success() {
        Command correctArgument = new AddCommandParser().parse("study form 10am to 10pm everday");
        assertAddCommandType(correctArgument);
    }

    private void assertIncorrectCommandType(Command command) {
        boolean isSameType = false;
        isSameType = command instanceof IncorrectCommand;
        assertTrue(isSameType);
    }

    private void assertAddCommandType(Command command) {
        boolean isSameType = false;
        isSameType = command instanceof AddCommand;
        assertTrue(isSameType);
    }
}

Add Test case for AddCommandParser


package com.google.sps.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/newEnvironment")
public class NewEnvironment extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {}
}

Add a servlet to pull an image and tag it.


package com.novoda.downloadmanager;

import android.app.Notification;

import static com.novoda.downloadmanager.NotificationCustomizer.NotificationStackState.SINGLE_PERSISTENT_NOTIFICATION;
import static org.mockito.Mockito.mock;

class NotificationInformationFixtures {

    private int id = 0;
    private Notification notification = mock(Notification.class);
    private NotificationCustomizer.NotificationStackState notificationStackState = SINGLE_PERSISTENT_NOTIFICATION;

    static NotificationInformationFixtures notificationInformation() {
        return new NotificationInformationFixtures();
    }

    NotificationInformationFixtures withId(int id) {
        this.id = id;
        return this;
    }

    NotificationInformationFixtures withNotification(Notification notification) {
        this.notification = notification;
        return this;
    }

    NotificationInformationFixtures withNotificationStackState(NotificationCustomizer.NotificationStackState notificationStackState) {
        this.notificationStackState = notificationStackState;
        return this;
    }

    NotificationInformation build() {
        return new NotificationInformation() {
            @Override
            public int getId() {
                return id;
            }

            @Override
            public Notification getNotification() {
                return notification;
            }

            @Override
            public NotificationCustomizer.NotificationStackState notificationStackState() {
                return notificationStackState;
            }
        };
    }
}

Create NotificationInformation fixtures for testing.


/*-
 * Copyright © 2016 Diamond Light Source Ltd.
 *
 * This file is part of GDA.
 *
 * GDA 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.
 *
 * GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>.
 */

package org.eclipse.scanning.api.ui;

import java.beans.PropertyChangeListener;

public interface IStageScanConfiguration {

	void addPropertyChangeListener(PropertyChangeListener listener);

	void removePropertyChangeListener(PropertyChangeListener listener);

	String getActiveFastScanAxis();

	String getActiveSlowScanAxis();

}

Add interface for mapping stage configuration


package com.basho.riak.client.core.query.UserMetadata;

import com.basho.riak.client.core.util.BinaryValue;
import org.junit.Test;

import java.nio.charset.Charset;

import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class RiakUserMetadataTest
{
    final Charset utf16 = Charset.forName("UTF-16");
    final String oddKey = "\uD834\uDD1E\uD835\uDD65";
    final String oddValue = "\uD835\uDFF6\uD840\uDC8A";
    final BinaryValue oddKeyBV = BinaryValue.create(oddKey, utf16);
    final BinaryValue oddValueBV = BinaryValue.create(oddValue, utf16);

    @Test
    public void getSetMetadata_string_altCharset()
    {
        RiakUserMetadata md = new RiakUserMetadata();
        md.put(oddKey, oddValue, utf16);
        final String gotValue = md.get(oddKey, utf16);

        assertEquals(oddValue, gotValue);
        assertNotEquals(gotValue, md.get(oddKey));
    }

    @Test
    public void getSetMetadata_binaryValue_altCharset()
    {
        RiakUserMetadata md = new RiakUserMetadata();
        md.put(oddKeyBV, oddValueBV);
        final BinaryValue gotValue = md.get(oddKeyBV);

        assertEquals(oddValueBV, gotValue);
        assertNotEquals(gotValue, md.get(oddKey));
    }

    @Test
    public void getSetMetadata_mixedInterfaces_altCharset()
    {
        RiakUserMetadata md = new RiakUserMetadata();
        md.put(oddKeyBV, oddValueBV);

        final String gotValue = md.get(oddKey, utf16);

        assertEquals(oddValue, gotValue);
    }
}

Add a few tests for charset options in RiakUserMetadata


/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.server.trace.stackdriver;

import com.google.common.testing.NullPointerTester;
import io.spine.core.BoundedContextName;
import io.spine.core.MessageId;
import io.spine.system.server.EntityTypeName;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static com.google.common.testing.NullPointerTester.Visibility.PROTECTED;

@DisplayName("SignalSpan should")
class SignalSpanTest {

    @Test
    @DisplayName("not accept nulls on construction")
    void nulls() {
        NullPointerTester tester = new NullPointerTester();
        tester.setDefault(BoundedContextName.class, BoundedContextName.getDefaultInstance())
              .setDefault(MessageId.class, MessageId.getDefaultInstance())
              .setDefault(EntityTypeName.class, EntityTypeName.getDefaultInstance());
        tester.testAllPublicInstanceMethods(SignalSpan.newBuilder());
        tester.testConstructors(SignalSpan.class, PROTECTED);
    }
}

Add a null tolerance test


package com.itmill.toolkit.tests;

import com.itmill.toolkit.ui.*;
import com.itmill.toolkit.ui.Button.ClickEvent;
import com.itmill.toolkit.ui.Button.ClickListener;

public class TestSetVisibleAndCaching extends com.itmill.toolkit.Application {

	Panel panelA = new Panel("Panel A");
	Panel panelB = new Panel("Panel B");
	Panel panelC = new Panel("Panel C");

	Button buttonNextPanel = new Button("Show next panel");

	int selectedPanel = 0;

	public void init() {
		Window mainWindow = new Window("TestSetVisibleAndCaching");
		setMainWindow(mainWindow);

		panelA.addComponent(new Label(
				"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
		panelB.addComponent(new Label(
				"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"));
		panelC.addComponent(new Label(
				"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"));

		mainWindow.addComponent(new Label(
				"Inspect transfered data from server to "
						+ "client and see how widgets are re-used,"
						+ " after each panel is once shown in GUI then"
						+ " their contents are not resend."));
		mainWindow.addComponent(buttonNextPanel);
		mainWindow.addComponent(panelA);
		mainWindow.addComponent(panelB);
		mainWindow.addComponent(panelC);

		selectPanel(selectedPanel);

		buttonNextPanel.addListener(new ClickListener() {
			public void buttonClick(ClickEvent event) {
				selectedPanel++;
				if (selectedPanel > 2)
					selectedPanel = 0;
				selectPanel(selectedPanel);
			}
		});

	}

	private void selectPanel(int selectedPanel) {
		System.err.println("Selecting panel " + selectedPanel);
		switch (selectedPanel) {
		case 0:
			panelA.setVisible(true);
			panelB.setVisible(false);
			panelC.setVisible(false);
			break;
		case 1:
			panelA.setVisible(false);
			panelB.setVisible(true);
			panelC.setVisible(false);
			break;
		case 2:
			panelA.setVisible(false);
			panelB.setVisible(false);
			panelC.setVisible(true);
			break;
		}
	}
}

Test that caching widgets works. Inspect transfered data from server to client and see how widgets are re-used after each panel is once shown in GUI then" their contents are not resend.


package com.beust.jcommander;

import org.testng.Assert;
import org.testng.annotations.Test;

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

/**
 *
Test that parameter order specified via order attributes is respected

 */
public class ParameterOrderTest {

  private static class ManualOrder1 {
    @Parameter(order=1, names = "--arg_b")
    public boolean isB;
    @Parameter(order=0, names = "--arg_a")
    public boolean isA;
    @Parameter(order=2, names = "--arg_c")
    public boolean isC;
  }

  @Test
  public void testOrder1() {
    testOrder(new ManualOrder1(), "--arg_a","--arg_b","--arg_c");
  }

  private static class ManualOrder2 {
    @Parameter(order=1, names = "--arg_b")
    public boolean isZ;
    @DynamicParameter(order=0, names = "--arg_a")
    public Map<String,String> mapA;
    @Parameter(order=2, names = "--arg_c")
    public boolean isC;
  }

  @Test
  public void testOrder2() {
    testOrder(new ManualOrder2(), "--arg_a","--arg_b","--arg_c");
  }

  private static class ManualOrder3 {
    @Parameter(order=1, names = "--arg_b")
    public boolean isB;
    @Parameter(order=0, names = "--arg_a")
    public boolean isA;
    @Parameter(names = "--arg_d")
    public boolean isD;
    @Parameter(order=2, names = "--arg_c")
    public boolean isC;
  }

  @Test
  public void testOrder3() {
    testOrder(new ManualOrder3(), "--arg_a","--arg_b","--arg_c", "--arg_d");
  }

  public void testOrder(Object cmd, String ... expected) {
    JCommander commander = new JCommander(cmd);

    StringBuilder out = new StringBuilder();
    commander.getUsageFormatter().usage(out);
    String output = out.toString();
    List<String> order = new ArrayList<>();
    for (String line : output.split("[\\n\\r]+")) {
      String trimmed = line.trim();
      if (!trimmed.contains(":")) {
        order.add(trimmed);
      }
    }
    Assert.assertEquals(order, Arrays.asList(expected));
  }
}

Add a test for Parameter order usage


/**
 *
 */
package config;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 * @author Peter Vollmer
 *
 */
public class ConfigManager {

	private static ConfigManager instance = null;

	/**
	 * 	Parses the config file in JSON format.
	 */
	private final JSONParser parser = new JSONParser();

	/**
	 * Storage of configuration entries
	 */
	private Map<String, Object> confMap = null;

	/**
	 * Construct the ConfigManager for centralize all configurations of the server
	 *
	 * @param configPath
	 * @throws Exception
	 */
	private ConfigManager(String configPath) throws Exception {
		BufferedReader reader = null;
		reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(configPath), Charset.forName("UTF-8")));
		JSONObject requestJSON = (JSONObject) parser.parse(reader);

		this.confMap = requestJSON;

	}

	/**
	 * Initialize the config management and construct the configManager.
	 * To do before getInstance
	 *
	 * @param configPath
	 *
	 * @throws Exception
	 */
	public static void Init (String configPath) throws Exception {
		instance = new ConfigManager(configPath);
	}

	/**
	 * Return the value of a given key or the given defaultValue
	 *
	 * @param key
	 * @param defaultValue
	 * @return value
	 *			 of a given key or the given defaultValue
	 */
	public String getEntry(String key, String defaultValue){
		String value = null;
		if (confMap.containsKey(key)){
			value = (String)confMap.get(key);
		} else {
			value = defaultValue;
		}
		return value;
	}

	/**
	 * Returns the value of the given key
	 *
	 * @param key
	 * 			to give the
	 * @return value (default value is null)
	 */
	public String getEntry (String key){
		String value = null;
		if (confMap.containsKey(key)){
			value = (String)confMap.get(key);
		}
		return value;
	}

	/**
	 * Return an instance of a constructed ConfigManager. Need Init before.
	 *
	 *
	 * @return instance of ConfigManager
	 */
	public static ConfigManager getInstance()	{
		return instance;
	}

}

Add the config manager funtionality to the server


package com.sunny.grokkingalgorithms.basic_2020.warmup;

import java.util.Stack;

public class DuplicateParenthesis {

	public static boolean duplicateParenthesis(String s) {
		Stack<Character> stack = new Stack<Character>();
		int i = 0;
		while(i < s.length()) {
			char current = s.charAt(i);
			if(current != ')') {
				stack.push(current);
			}else {
				if(stack.peek() == '(') {
					return true;
				}
				while(stack.peek() != '(') {
					stack.pop();
				}
				stack.pop();
			}
			i++;
		}
		return false;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        String s = "((x+y))";
        System.out.println(duplicateParenthesis(s));
        s = "((x+y)+(y+z))";
        System.out.println(duplicateParenthesis(s));
	}

}

Duplicate parenthesis checking using stack.


package com.amitness.photon.utils;

/**
 * Provides a abstraction to the flashlight hardware
 */

class FlashLight {
    // TODO: Implement the methods

    public void turnOn() {
    }

    public void turnOff() {
    }

    public void release() {
    }
}

Make structure for utility classes


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem69;

/**
 * Given two integers passed as argument, can you write a function to determine the number of bits
 * required to convert integer A to integer B.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BitsToTransform {

}

/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem69;

/**
 * Given two integers passed as argument, can you write a function to determine the number of bits
 * required to convert integer A to integer B.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BitsToTransform {

  /**
   * Iterative algorithm created to calculate a XOR using the input integers. Once you have the XOR
   * you can iterate through the XOR to count the number of bits equals to 1. To iterate over the
   * integer we are going to modify the value of the XOR integer using & operator with XOR & XOR
   * -1.
   *
   * For example:
   *
   * numA = 001
   * numB = 101
   * XOR  = 100
   *
   * Iteration 1 -> XOR = 100
   * Iteration 2 -> XOR = 100 & 011 = 000 // Loop body not executed.
   */
  public int calculate(int numA, int numB) {
    int differentBits = 0;
    for (int XOR = numA ^ numB; XOR != 0; XOR = XOR & (XOR - 1)) {
      differentBits++;
    }
    return differentBits;
  }
}

Add solution to problem 69


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that deletes the keywords.*/
@WebServlet("/delete-keywords")
public class DeleteKeywordsServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String keyString = request.getParameter("k");
    Key key = KeyFactory.stringToKey(keyString);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.delete(key);
  }
}

Add Servlet to delete keywords


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

package com.github.pedrovgs.nox;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.assertTrue;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
@Config(emulateSdk = 18) @RunWith(RobolectricTestRunner.class) public class NoxItemCatalogTest {

  @Test public void test() {
    assertTrue(true);
  }
}

Create empty test case for NoxItemCatalog


/*
 * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Mateusz Parzonka - initial API and implementation
 */
package prm4j.indexing.realtime;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import prm4j.AbstractTest;
import prm4j.api.fsm.FSM;
import prm4j.api.fsm.FSMSpec;
import prm4j.indexing.BaseMonitor;
import prm4j.indexing.StatefulMonitor;
import prm4j.indexing.staticdata.StaticDataConverter;
import prm4j.spec.FiniteParametricProperty;
import prm4j.spec.FiniteSpec;

public class GarbageCollectionTest extends AbstractTest {

    protected StaticDataConverter converter;
    protected DefaultBindingStore bindingStore;
    protected DefaultNodeStore nodeStore;
    protected BaseMonitor prototypeMonitor;
    protected DefaultParametricMonitor pm;

    public void createDefaultParametricMonitorWithAwareComponents(FSM fsm, int cleaningInterval) {
	FiniteSpec finiteSpec = new FSMSpec(fsm);
	converter = new StaticDataConverter(new FiniteParametricProperty(finiteSpec));
	bindingStore = new DefaultBindingStore(finiteSpec.getFullParameterSet(), 1);
	nodeStore = new DefaultNodeStore(converter.getMetaTree());
	prototypeMonitor = new StatefulMonitor(finiteSpec.getInitialState());
	pm = new DefaultParametricMonitor(bindingStore, nodeStore, prototypeMonitor, converter.getEventContext());
    }

    @Test
    public void aliveBinding_nodeIsPersistent() throws Exception {

	FSM_obj_obj fsm = new FSM_obj_obj();
	createDefaultParametricMonitorWithAwareComponents(fsm.fsm, 1);

	// exercise
	Object object = new Object();
	LowLevelBinding[] bindings = bindingStore.getBindings(array(object));
	Node node = nodeStore.getOrCreateNode(bindings);

	// verify
	assertEquals(node, nodeStore.getNode(bindings));
    }

    @Test
    public void aliveBinding_bindingIsPersistent() throws Exception {

	FSM_obj_obj fsm = new FSM_obj_obj();
	createDefaultParametricMonitorWithAwareComponents(fsm.fsm, 1);

	// exercise
	Object object = new Object();
	LowLevelBinding[] bindings = bindingStore.getBindings(array(object));
	nodeStore.getOrCreateNode(bindings);

	// verify
	assertEquals(1, bindingStore.size());
    }

}

Add test for garbage collection


// ========================================================================
// Copyright 2011 NEXCOM Systems
// ------------------------------------------------------------------------
// 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.cipango.plus.sipapp;

import javax.servlet.sip.SipErrorEvent;
import javax.servlet.sip.SipErrorListener;

public class Listener implements SipErrorListener
{

	public void noAckReceived(SipErrorEvent arg0)
	{
	}

	public void noPrackReceived(SipErrorEvent arg0)
	{
	}

}

Fix CIPANGO-139: cipango-plus is broken


/*
 * Copyright 2018, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.server.command;

import org.junit.Test;

public class CommandShould {

    @Test
    public void be_applied() {

    }

    @Test
    public void not_be_applied_when_reused() {

    }
}

Declare tests to be implemented to test command idempotence.


package org.bouncycastle.crypto.tls;

/**
 * RFC 2246 7.4.4
 */
public class ClientCertificateType
{
    public static final short rsa_sign = 1;
    public static final short dss_sign = 2;
    public static final short rsa_fixed_dh = 3;
    public static final short dss_fixed_dh = 4;

    /*
     * RFC 4492 5.5
     */
    public static final short ecdsa_sign = 64;
    public static final short rsa_fixed_ecdh = 65;
    public static final short ecdsa_fixed_ecdh = 66;
}

Add another new TLS name space


package org.motechproject.uitest.page;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class DataServicesPage extends AbstractBasePage {

    public static final By ENTITY_NAME_FIELD = By.name("inputEntityName");
    public static final By NEW_ENTITY_BUTTON = By.id("newEntityButton");
    public static final By SAVE_ENTITY_BUTTON = By.id("saveNewEntityButton");
    public static final By DATA_SERVICES_BUTTON = By.id("data-services");
    public static final By SCHEMA_EDITOR_BUTTON = By.id("schemaEditor");
    public static final By BROWSE_INSTANCES_BUTTON = By.id("browseInstancesButton");
    public static final By ADD_NEW_INSTANCE_BUTTON = By.id("addNewInstanceButton");

    public static final String HOME_PATH = "/module/server/home#";

    public DataServicesPage(WebDriver driver) {
        super(driver);
    }

    public void createNewEntity(String entityName) throws InterruptedException {
        waitForElement(DATA_SERVICES_BUTTON);
        clickWhenVisible(DATA_SERVICES_BUTTON);
        waitForElement(SCHEMA_EDITOR_BUTTON);
        clickWhenVisible(SCHEMA_EDITOR_BUTTON);
        waitForElement(NEW_ENTITY_BUTTON);
        clickWhenVisible(NEW_ENTITY_BUTTON);
        waitForElement(ENTITY_NAME_FIELD);
        setTextToFieldNoEnter(ENTITY_NAME_FIELD, entityName);
        waitForElement(SAVE_ENTITY_BUTTON);
        clickOn(SAVE_ENTITY_BUTTON);
        waitForElement(BROWSE_INSTANCES_BUTTON);
    }

    public void goToEntityTable(String entityName) throws InterruptedException {
        waitForElement(DATA_SERVICES_BUTTON);
        clickWhenVisible(DATA_SERVICES_BUTTON);
        waitForElement(By.id(String.format("entity_%s", entityName)));
        clickWhenVisible(By.id(String.format("entity_%s", entityName)));
        waitForElement(ADD_NEW_INSTANCE_BUTTON);
    }

    @Override
    public String expectedUrlPath() {
        return HOME_PATH;
    }

    @Override
    public void goToPage() {
        getDriver().get(getMotechUrl() + HOME_PATH);
    }
}

Add selenium test for adding a new entity in MDS


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem74;

/**
 * Given an array full of integers implement a bubble sort algorithm to sort the content inside the
 * array.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BubbleSort {

}

Add statement to problem 74


package net.restlesscoder.sandbox;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

import net.imagej.ImageJ;

public class IJDispose {

	public static void main(final String... args) {
		final ImageJ ij = new ImageJ();
		ij.ui().showUI();

		final JFrame frame = new JFrame("Hello");
		final JButton b = new JButton("Close ImageJ");
		b.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(final ActionEvent e) {
				ij.thread().getExecutorService().shutdownNow();
				ij.getContext().dispose();
			}
		});
		frame.getContentPane().add(b);
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}

}

Add a little test of ImageJ2's context disposal


package org.ethereum.net.shh;

import org.ethereum.crypto.ECKey;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

/**
 * Created by kest on 6/26/15.
 */
public class FilterTest {

    byte[] to = new ECKey().decompress().getPubKey();
    byte[] from = new ECKey().decompress().getPubKey();
    String[] topics = {"topic1", "topic2", "topic3", "topic4"};

    @Test
    public void test1() {
        Filter matcher = new Filter(null, null, new TopicMatcher(new String[]{}));
        Filter message = new Filter(to, from, new TopicMatcher(topics));

        assertTrue(matcher.match(message));
    }

    @Test
    public void test2() {
        Filter matcher = new Filter(to, null, new TopicMatcher(new String[]{}));
        Filter message = new Filter(to, from, new TopicMatcher(topics));

        assertTrue(matcher.match(message));
    }

    @Test
    public void test3() {
        Filter matcher = new Filter(to, null, new TopicMatcher(new String[]{}));
        Filter message = new Filter(null, from, new TopicMatcher(topics));

        assertTrue(!matcher.match(message));
    }

    @Test
    public void test4() {
        Filter matcher = new Filter(null, from, new TopicMatcher(new String[]{}));
        Filter message = new Filter(to, from, new TopicMatcher(topics));

        assertTrue(matcher.match(message));
    }

    @Test
    public void test5() {
        Filter matcher = new Filter(null, from, new TopicMatcher(new String[]{}));
        Filter message = new Filter(to, null, new TopicMatcher(topics));

        assertTrue(!matcher.match(message));
    }

    @Test
    public void test6() {
        Filter matcher = new Filter(null, from, new TopicMatcher(topics));
        Filter message = new Filter(to, from, new TopicMatcher(topics));

        assertTrue(matcher.match(message));
    }

    @Test
    public void test7() {
        Filter matcher = new Filter(null, null, new TopicMatcher(topics));
        Filter message = new Filter(to, from, new TopicMatcher(new String[]{}));

        assertTrue(!matcher.match(message));
    }
}

Add the whisper filter tests


package com.mycompany.lab3;

/**
 *
 * @author Burgy Benjamin
 */
public final class Settings_default
{
    public String OpenStack_user = "";
    public String OpenStack_tenant_name = "";
    public String OpenStack_service_region = "";
    public String OpenStack_auth_url = "";
    public String OpenStack_password = "";

    public String Amazon_accessKey = "";
    public String Amazon_secretKey = "";
}

Save the structure of the settings file.


/*
 * Copyright 2015 Timothy Brooks
 *
 * 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 net.uncontended.precipice.metrics.registry;

import net.uncontended.precipice.PrecipiceFunction;
import net.uncontended.precipice.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MetricRegistry {

    private Map<String, Summary> services = new HashMap<>();
    private volatile PrecipiceFunction<Map<String, Summary>> callback;
    // TODO: Name thread
    private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    public MetricRegistry() {
        executorService.scheduleAtFixedRate(new Task(), 0, 10, TimeUnit.SECONDS);
    }

    public void register(Service service) {
        services.put(service.getName(), new Summary(service));
    }

    public Summary getSummary(String name) {
        Summary summary = services.get(name);
        if (summary == null) {
            throw new IllegalArgumentException("Service: " + name + " not registered.");
        }
        return summary;
    }

    public void setUpdateCallback(PrecipiceFunction<Map<String, Summary>> callback) {
        this.callback = callback;
    }

    public void shutdown() {
        executorService.shutdown();
    }

    private static class Summary {
        private final Service service;

        private Summary(Service service) {
            this.service = service;
        }

        private void refresh() {

        }
    }

    private class Task implements Runnable {

        @Override
        public void run() {
            for (Summary summary : services.values()) {
                summary.refresh();
            }

            if (callback != null) {
                callback.apply(services);
            }
        }
    }
}

Add class for the new metric registry


package co.nstant.in.cbor;

import org.junit.Assert;
import org.junit.Test;

public class CborExceptionTest {

    @Test
    public void shouldHaveMessage() {
        CborException cborException = new CborException("message");
        Assert.assertEquals("message", cborException.getMessage());
    }

    @Test
    public void shouldHaveThrowable() {
        Throwable throwable = new Throwable();
        CborException cborException = new CborException(throwable);
        Assert.assertEquals(throwable, cborException.getCause());
    }

    @Test
    public void shouldHaveMessageAndThrowable() {
        Throwable throwable = new Throwable();
        CborException cborException = new CborException("message", throwable);
        Assert.assertEquals("message", cborException.getMessage());
        Assert.assertEquals(throwable, cborException.getCause());
    }

}

Add unit test for CborException


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.algorithm;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.data.float64.real.Float64VectorMember;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestRModuleZero {

	@Test
	public void test1() {
		Float64Member value = G.DBL.construct();
		Float64VectorMember vec = new Float64VectorMember(new double[] {1,2,3,4});
		RModuleZero.compute(vec);
		for (long i = 0; i < vec.length(); i++) {
			vec.v(i, value);
			assertEquals(0, value.v(), 0);
		}
	}
}

Define a test for the RModuleZero algorithm


package agaricus.mods.oredupefix;

import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PostInit;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;

@Mod(modid = "OreDupeFix", name = "OreDupeFix", version = "1.0")
@NetworkMod(clientSideRequired = false, serverSideRequired = false)
public class OreDupeFix {
    @PostInit
    public static void postInit(FMLPostInitializationEvent event) {
        System.out.println("loading OreDupeFix!");
    }
}

Add new empty FML mod


package com.github.aureliano.achmed.os;

import com.github.aureliano.achmed.resources.types.OS;
import com.github.aureliano.achmed.resources.types.OperatingSystemFamily;

public interface IOperatingSystem {

	public abstract OS getOperatingSystem();

	public abstract OperatingSystemFamily getOperatingSystemFamily();
}

Create interface to operating system types.