/**
 * Aeronica's mxTune MOD
 * Copyright {2016} Paul Boese a.k.a. Aeronica
 *
 * 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.aeronica.mods.mxtune.network.client;

import java.io.IOException;

import net.aeronica.mods.mxtune.groups.PlayManager;
import net.aeronica.mods.mxtune.network.AbstractMessage.AbstractClientMessage;
import net.aeronica.mods.mxtune.sound.ClientAudio;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class StopPlayMessage extends AbstractClientMessage<StopPlayMessage>
{

    private Integer playID;

    public StopPlayMessage() {}

    public StopPlayMessage(Integer playID) {this.playID = playID;}

    @Override
    protected void read(PacketBuffer buffer) throws IOException
    {
        playID = ByteBufUtils.readVarInt(buffer, 5);
    }

    @Override
    protected void write(PacketBuffer buffer) throws IOException
    {
        ByteBufUtils.writeVarInt(buffer, playID, 5);
    }

    @Override
    public void process(EntityPlayer player, Side side)
    {
        if (side.isClient())
        {
            handleClientSide(player);
        } else
        {
            handleServerSide(player);
        }
    }

    @SideOnly(Side.CLIENT)
    public void handleClientSide(EntityPlayer playerSP)
    {
        // TODO: More Cleanup for playing - resetting all the players PlayStatuses
        ClientAudio.stop(playID);
    }

    public void handleServerSide(EntityPlayer playerMP)
    {
        //PlayManager.stopPlayID(playID);
    }

}

Rework Play Music chain to improve reliability, eliminate clicks and pops on abrupt cutoff. Part 1


package leetcode.unique_binary_search_trees;

public class Solution {
    public int numTrees(int n) {
        return Catalan(n);
    }
    public static int Catalan(int n){
    	long ans = 1;
    	for(int i = 1; i <= n; i++){
    		ans *= (2 * n - i + 1);
    		ans /= i;
    	}
    	return (int)(ans / (n + 1));
    }

    public static void main(String[] args){
    	for(int i = 0; i < 10; i++){
    		System.err.println(Solution.Catalan(i));
    	}
    }
}

Add java solution for 96. Unique Binary Search Trees

96. Unique Binary Search Trees: https://leetcode.com/problems/unique-binary-search-trees/


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

package com.google.sps.servlets;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/registration")
public class RegistrationServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String role = request.getParameter("role");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    List<String> topics = Arrays.asList(request.getParameter("math"), request.getParameter("english"), request.getParameter("other"));

    topics = topics
            .stream()
            .filter(t -> t!= null)
            .collect(Collectors.toList());

    response.setContentType("text/html;");
    response.getWriter().println("
Student or tutor? " + role + "
");
    response.getWriter().println("
Name: " + name + "
");
    response.getWriter().println("
Email: " + email + "
");
    response.getWriter().println("
Subject(s): " + topics + "
");
  }
}

Add basic servlet that responds with user info


package leetcode.evaluate_reverse_polish_notation;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;

public class Solution {
    public int evalRPN(String[] tokens) {
    	Stack<String> stack = new Stack<String>();
    	Set<String> operatorSet = new HashSet<String>(Arrays.asList(new String[]{"+", "-", "*", "/"}));
    	for(String token : tokens){
    		if(operatorSet.contains(token)){
    			int operand2 = Integer.parseInt(stack.pop());
    			int operand1 = Integer.parseInt(stack.pop());
    			if(token.equals("+")){
    				stack.push(Integer.toString(operand1 + operand2));
    			}else if(token.equals("-")){
    				stack.push(Integer.toString(operand1 - operand2));
    			}else if(token.equals("*")){
    				stack.push(Integer.toString(operand1 * operand2));
    			}else if(token.equals("/")){
    				stack.push(Integer.toString(operand1 / operand2));
    			}
    		}else{
    			stack.push(token);
    		}
    	}
    	return Integer.parseInt(stack.pop());
    }

    public static void main(String[] args){
    	System.err.println(new Solution().evalRPN(new String[]{"2", "1", "+", "3", "*"}));
    }
}

Add java solution for 150. Evaluate Reverse Polish Notation

150. Evaluate Reverse Polish Notation: https://leetcode.com/problems/evaluate-reverse-polish-notation/


package com.github.aureliano.achmed.os.pkg;

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.resources.properties.PackageProperties;

public class YumPackageManager implements IPackageManager {

	private PackageProperties properties;

	public YumPackageManager() {
		super();
	}

	public CommandResponse install() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public CommandResponse uninstall() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public String latest() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public void setPackageProperties(PackageProperties properties) {
		this.properties = properties;
	}

	public PackageProperties getPackageProperties() {
		return this.properties;
	}
}

Create template of yum package manager.

Create template of yum package manager.


package edu.agh.tunev.model.kkm;

import java.util.Vector;

import edu.agh.tunev.model.AbstractModel;
import edu.agh.tunev.model.PersonProfile;
import edu.agh.tunev.statistics.Statistics.AddCallback;
import edu.agh.tunev.world.World;
import edu.agh.tunev.world.World.ProgressCallback;

public final class Model extends AbstractModel {

	public final static String MODEL_NAME = "Autorski (\u00a9 2012 Jakub Rakoczy)";

	public Model(World world) {
		super(world);
	}

	@Override
	public void simulate(double duration, Vector<PersonProfile> profiles,
			ProgressCallback progressCallback, AddCallback addCallback) {
		// TODO Auto-generated method stub

	}

}

Create main class od KKM model

Create main class od KKM model


package to.etc.domui.component.form;

import to.etc.domui.util.*;

public class InstanceReadOnlyModel<T> implements IReadOnlyModel<T> {
	private T m_instance;

	public InstanceReadOnlyModel(T instance) {
		m_instance = instance;
	}

	@Override
	public T getValue() throws Exception {
		return m_instance;
	}
}

Add instance model helper class

Add instance model helper class


/**
 * Copyright (C) 2012 Gist Labs, LLC. (http://gistlabs.com)
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package com.gistlabs.mechanize.integration.test;

import static org.junit.Assert.*;

import org.json.JSONException;
import org.junit.Test;

import com.gistlabs.mechanize.MechanizeAgent;
import com.gistlabs.mechanize.json.JsonPage;

/**
 *
 */
public class AndroidJsonApiIT {

	@Test
	public void testAndroidJsonApiDemo() throws JSONException {
		MechanizeAgent agent = new MechanizeAgent();
		JsonPage page = (JsonPage) agent.get("http://api.androidhive.info/contacts/");

		assertNotNull(page.json().getJSONArray("contacts"));
	}
}

Add Json integration test for reading and parsing Json


package com.box.l10n.mojito.collect;

import com.google.common.collect.ImmutableMap;

import java.util.Map;
import java.util.stream.Collector;

public class ImmutableMapCollectors {
    public static <K,V> Collector<Map.Entry<K, V>, ?, ImmutableMap<K, V>> MapEntriesToImmutableMap() {
        return ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue);
    }
}

Add simple collect for Map entries to ImmutableMap


package io.vertx.example.shell.prompt;

import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;
import io.vertx.ext.shell.Shell;
import io.vertx.ext.shell.ShellServer;
import io.vertx.ext.shell.ShellService;
import io.vertx.ext.shell.ShellServiceOptions;
import io.vertx.ext.shell.command.CommandResolver;
import io.vertx.ext.shell.term.TelnetTermOptions;
import io.vertx.ext.shell.term.TermServer;
import io.vertx.ext.shell.term.impl.TelnetTermServer;

import java.util.concurrent.atomic.AtomicInteger;

public class PromptCommand  extends AbstractVerticle {
  // Convenience method so you can run it in your IDE
  public static void main(String[] args) {
    Runner.runExample(PromptCommand.class);
  }

  @Override
  public void start() throws Exception {

    ShellServer server = ShellServer.create(vertx);
    AtomicInteger ai = new AtomicInteger(0);
    server.shellHandler(shell -> {
      shell.setPrompt(s -> {
        try {
          return "C: " + ai.incrementAndGet();
        } catch (Exception e) {
          System.err.println("Counter");
          e.printStackTrace();
        }
        return "NOOP";
      });
    });
    TelnetTermOptions tto = new TelnetTermOptions().setPort(3000).setHost("localhost");
    TermServer telnetTermServer = TermServer.createTelnetTermServer(vertx,tto);
    server.registerTermServer(telnetTermServer);

    server.registerCommandResolver(CommandResolver.baseCommands(vertx));

    server.listen(ar -> {
      if (!ar.succeeded()) {
        ar.cause().printStackTrace();
      }
    });

  }
}

Add example on how to set the prompt

Add example on how to set the prompt

(cherry picked from commit 2b6757d)


package org.beanmaker.util;

import org.jcodegen.html.DivTag;

import java.util.ResourceBundle;

public interface HtmlDefaultButtonsHelper {

    DivTag getDefaultDialogButtons(
            final HtmlFormHelper htmlFormHelper,
            final long id,
            final String name,
            final ResourceBundle resourceBundle);

    DivTag getDefaultDialogButtons(
            final HtmlFormHelper htmlFormHelper,
            final long id,
            final String name,
            final ResourceBundle resourceBundle,
            final boolean submitDisabled);

    DivTag getLonelyCloseButton(final ResourceBundle resourceBundle);

}

Add interface for parameterization of buttons in forms


package jenkins.bugs;

import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import hudson.security.HudsonPrivateSecurityRealm;
import jenkins.model.Jenkins;

public class Jenkins41511Test {

    @BeforeClass
    public static void setUpClass() {
        System.setProperty(Jenkins.class.getName()+".slaveAgentPort", "10000");
        System.setProperty(Jenkins.class.getName()+".slaveAgentPortEnforce", "true");
    }

    @Rule
    public JenkinsRule j = new JenkinsRule();

    @Test
    public void configRoundTrip() throws Exception {
        Jenkins.getInstance().setSecurityRealm(new HudsonPrivateSecurityRealm(true, false, null));
        j.submit(j.createWebClient().goTo("configureSecurity").getFormByName("config"));
    }
}

Add a test showing the problem

[JENKINS-41511] Add a test showing the problem

(cherry picked from commit a26d71153d7609094e449d371d3ab0f8415b887f)


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

package gerrit;

import com.google.gerrit.server.rules.StoredValues;
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Predicate;
import com.googlecode.prolog_cafe.lang.Prolog;
import com.googlecode.prolog_cafe.lang.Term;
import org.eclipse.jgit.revwalk.RevCommit;

/**
 * Prolog fact for the number of parents of a given commit
 *
 * <pre>
 *   'commit_parent_count'(-Count)
 * </pre>
 */
public class PRED_commit_parent_count_1 extends Predicate.P1 {
  public PRED_commit_parent_count_1(Term a1, Operation n) {
    arg1 = a1;
    cont = n;
  }

  @Override
  public Operation exec(Prolog engine) throws PrologException {
    engine.setB0();
    Term a1 = arg1.dereference();

    RevCommit commit = StoredValues.COMMIT.get(engine);

    if (!a1.unify(new IntegerTerm(commit.getParentCount()), engine.trail)) {
      return engine.fail();
    }
    return cont;
  }
}

Add prolog predicate to determine number of parents

This change introduces a new prolog predicate for the
number of parents of a given patch set. This can be used to determine
from within the "rules.pl" file whether a change
is a merge commit or not.

This can be useful in order to evaluate a different set of
submit rules for merge commits.

Example usage:
submit_rule(submit(Parents)) :-
    Parents = label('Is-Merge', need(_)).
submit_rule(submit(Parents)) :-
    gerrit:commit_parent_count(A),
    A > 1,
    Parents = label('Is-Merge', ok(user(ID))).

Change-Id: I306163510e201606e936d95caea5ffa0bb957236


package org.opennms.web.svclayer;

public class ProgressMonitor {

	private int m_phaseCount = 1;
	private int m_phase = 0;
	private String m_phaseLabel = "Loading";
	private Object m_result = null;
	private Exception m_exception = null;

	public int getPhaseCount() {
		return m_phaseCount;
	}

	public void setPhaseCount(int phaseCount) {
		m_phaseCount = phaseCount;
	}

	public String getPhaseLabel() {
		return m_phaseLabel;
	}

	public int getPhase() {
		return m_phase;
	}

	public void beginNextPhase(String phaseLabel) {
		m_phaseLabel = phaseLabel;
		m_phase++;
	}

	public void finished(Object result) {
		m_result = result;
		m_phaseLabel = "Done";
		m_phase = m_phaseCount;
	}

	public boolean isFinished() {
		return m_result != null;
	}

	public Object getResult() {
		return m_result;
	}

	public boolean isError() {
		return m_exception != null;
	}

	public Exception getException() {
		return m_exception;
	}

	public void errorOccurred(Exception e) {
		m_exception = e;
	}

}

Add progress bar to loading of Surveillence page


package com.google.sps.tool;

import com.google.appengine.api.datastore.Entity;
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.util.List;
import java.util.ArrayList;
import com.google.sps.data.Card;
import com.google.sps.data.Folder;

public class EntityTestingTool {

  public static boolean checkForNoNullValues(Entity card) {
    return (card.getProperty("blobKey") != null  &&
      card.getProperty("labels") != null &&
      card.getProperty("textTranslated") != null &&
      card.getProperty("textNotTranslated") != null &&
      card.getProperty("fromLang") != null &&
      card.getProperty("toLang") != null &&
      card.getProperty("cardKey") != null);
  }

  public static List<Folder> populateDatastoreWithFolders(Folder FOLDER_A, Folder FOLDER_B, DatastoreService datastore, String USERKEY) {

    Entity folderA_Entity = FOLDER_A.createEntity(KeyFactory.stringToKey(USERKEY));
    Entity folderB_Entity = FOLDER_B.createEntity(KeyFactory.stringToKey(USERKEY));

    // Update entity in datastore
    datastore.put(folderA_Entity);
    datastore.put(folderB_Entity);

    List<Folder> folders = new ArrayList<>();
    folders.add(Folder.EntityToFolder(folderA_Entity));
    folders.add(Folder.EntityToFolder(folderB_Entity));

    return folders;
  }

  public static List<Card> populateDatastoreWithCards(Card CARD_A, Card CARD_B, DatastoreService datastore, String FOLDERKEY) {

    Entity CardA_Entity = CARD_A.createEntity(KeyFactory.stringToKey(FOLDERKEY));
    Entity CardB_Entity = CARD_B.createEntity(KeyFactory.stringToKey(FOLDERKEY));

    // Update entity in datastore
    datastore.put(CardA_Entity);
    datastore.put(CardB_Entity);

    List<Card> cards = new ArrayList<>();
    cards.add(Card.EntityToCard(CardA_Entity));
    cards.add(Card.EntityToCard(CardB_Entity));

    return cards;
  }

}

Implement a class with testing methods

Implement a class with testing methods


package org.numenta.nupic.util;

import static org.junit.Assert.*;

import org.junit.Test;

public class MethodSignatureTest {

    @Test
    public void testSetParam() {
        MethodSignature ms = new MethodSignature(2);

        int param1 = 5;
        ms.setParam(param1, 0);
        assertEquals(5, ms.get(0));

        String test = "test";
        ms.setParam(test, 1);
        assertEquals("test", ms.get(1));

        try {
            ms.setParam("fail", 2);
            fail();
        }catch(Exception e) {
            assertEquals(e.getClass(), ArrayIndexOutOfBoundsException.class);
        }
    }

    @Test
    public void testSetParams() {
        MethodSignature ms = new MethodSignature(2);

        int param1 = 5;
        String test = "test";
        ms.setParams(param1, test);
        assertEquals(5, ms.get(0));
        assertEquals("test", ms.get(1));

        try {
            ms.setParam("fail", 2);
            fail();
        }catch(Exception e) {
            assertEquals(e.getClass(), ArrayIndexOutOfBoundsException.class);
        }
    }

}

Add Test class to appease github bellyaching


package datamodel;

public class CommandPidAndResults {
    private long commadnPid;
    private String commandResults;

    public CommandPidAndResults(long commadnPid, String commandResults) {
        this.commadnPid = commadnPid;
        this.commandResults = commandResults;
    }

    public long getCommadnPid() {
        return commadnPid;
    }

    public void setCommadnPid(long commadnPid) {
        this.commadnPid = commadnPid;
    }

    public String getCommandResults() {
        return commandResults;
    }

    public void setCommandResults(String commandResults) {
        this.commandResults = commandResults;
    }
}

Add datamodel for mentaining information abbout process pid and process output.


package ca.corefacility.bioinformatics.irida.service;

import ca.corefacility.bioinformatics.irida.model.Project;
import ca.corefacility.bioinformatics.irida.model.Role;
import ca.corefacility.bioinformatics.irida.model.User;
import org.springframework.transaction.annotation.Transactional;

/**
 * A specialized service layer for projects.
 *
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 */
@Transactional
public interface ProjectService extends CRUDService<String, Project> {

    /**
     * Add the specified user to the project with a role. If the user is a
     * manager for the project, then the user should be added to the project
     * with the 'ROLE_MANAGER' role.
     *
     * @param project the project to add the user to.
     * @param user the user to add to the project.
     * @param role the role that the user plays on the project.
     */
    public void addUserToProject(Project project, User user, Role role);
}

Add support for persisting Projects.

Add support for persisting Projects.


/*
 * 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.prestosql.sql.query;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestPredicatePushdown
{
    private QueryAssertions assertions;

    @BeforeClass
    public void init()
    {
        assertions = new QueryAssertions();
    }

    @AfterClass(alwaysRun = true)
    public void teardown()
    {
        assertions.close();
        assertions = null;
    }

    @Test
    public void testConditionalExpressionWithFailingExpression()
    {
        assertions.assertQuery("" +
                        "WITH t (k, a) AS ( " +
                        "    VALUES " +
                        "        (1, 1), " +
                        "        (2, 0) " +
                        ")," +
                        "u (k, v) AS ( " +
                        "    VALUES" +
                        "        (1, 'x'), " +
                        "        (2, 'y') " +
                        ") " +
                        "SELECT * " +
                        "FROM ( " +
                        "    SELECT v, if(v = 'x', 1 / a) AS r" +
                        "    FROM t JOIN u ON t.k = u.k " +
                        ") " +
                        "WHERE v = 'x' AND r IS NOT NULL",
                "VALUES ('x', 1)");

        assertions.assertQuery(
                "WITH t (k, v) AS ( " +
                        "    VALUES " +
                        "        (1, 1), " +
                        "        (2, 0) " +
                        "), " +
                        "u (k) AS ( " +
                        "    VALUES 1, 2 " +
                        ") " +
                        "SELECT * " +
                        "FROM ( " +
                        "    SELECT t.k, if(t.k = 1, 1 / t.v) AS r " +
                        "    FROM t JOIN u ON t.k = u.k " +
                        ") " +
                        "WHERE k = 1 AND r <> 0",
                "VALUES (1, 1)");

        assertions.assertQuery(
                "WITH t (k, v) AS ( " +
                        "    VALUES " +
                        "        (1, 1), " +
                        "        (2, 0) " +
                        "), " +
                        "u (k) AS ( " +
                        "    VALUES 1, 2 " +
                        ") " +
                        "SELECT * " +
                        "FROM ( " +
                        "    SELECT t.k, if(t.k = 1, 1 / t.v) AS r " +
                        "    FROM t LEFT JOIN u ON t.k = u.k " +
                        ") " +
                        "WHERE k = 1 AND r <> 0",
                "VALUES (1, 1)");
    }
}

Add tests for pedicate pushdown

Add tests for pedicate pushdown


/**
 * Provides the classes necessary to create and process client request filters.
 *

 * {@link uk.ac.ebi.quickgo.rest.search.filter.RequestFilter} instances are usually created by QuickGO REST endpoints
 * when a client would like to filter down results from a query that (s)he has supplied.
 *

 * The complexity of a request filter is based on the field(s) declared within the filter. Fields may:
 *

 *
Exist in a table/collection of underlying data-source: It is most likely that no complex processing
 *     is necessary, and that the filter can be directly executed from within the data source.
 *

 *
Not exist in table/collection of the underlying data-source: Using this field as a filter will
 *     require extra processing, usually in the form of a join between two tables/collections, or querying other
 *     services for the required information

 *

 * The {@link uk.ac.ebi.quickgo.rest.search.filter.FilterConverterFactory} is the class responsible for deciding how a
 * {@link uk.ac.ebi.quickgo.rest.search.filter.RequestFilter} is to be processed. Note that the factory does not do
 * the actual processing, it delegates this task to {@link uk.ac.ebi.quickgo.rest.search.filter.FilterConverter}.
 * There exist several implementations of the {@link uk.ac.ebi.quickgo.rest.search.filter.FilterConverter} interface,
 * each one tries to obtain the required information in a different way, e.g. contact another service, create a join
 * between two tables/collections or create a simple filter query. Any extra configuration required by the converter
 * is fed to them via the {@link uk.ac.ebi.quickgo.rest.search.filter.FilterExecutionConfig}.
 *
 * @author Ricardo Antunes
 */
package uk.ac.ebi.quickgo.rest.search.filter;

Add a package level Javadoc to try to clarify how the filter solution works.


package com.lucene;

public class LuceneConstants {

	public static final String DATA_DIRECTORY 			= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Data";
	public static final String INDEX_DIRECTORY 			= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Index";

	public static final String DEFAULT_FIELD 			= "core_newsurl";

	public static final String CORE_NEWSURL 			= "core_news_url";
	public static final String CORE_NEWSNUMBER 			= "core_news_number";
	public static final String CORE_NEWSTITLE 			= "core_new_title";
	public static final String CORE_NEWSBODY			= "core_news_body";
	public static final String CORE_NEWSDATE			= "core_news_date";
	public static final String CORE_NEWSSOURCE 			= "core_news_source";

	public static final String COMMENT_ID 				= "comment_id";
	public static final String COMMENT_PARENTID 		= "comment_parentId";
	public static final String COMMENT_COMMENTER 		= "comment_commenter";
	public static final String COMMENT_LOCATION 		= "comment_location";
	public static final String COMMENT_DATE 			= "comment_date";
	public static final String COMMENT_LIKECOMMENT 		= "comment_like_comment";
	public static final String COMMENT_DISLIKECOMMENT	= "comment_dislike_comment";
	public static final String COMMENT_RESPONSECOUNT 	= "comment_response_count";
	public static final String COMMENT_BODY 			= "comment_body";

	public static final String CATEGORY_NEWS 			= "core_category";
	public static final String LABEL_NEWS 				= "core_label";

	public static final String FILE_NAME				= "filename";
	public static final String FILE_PATH				= "filepath";

	public static final String FILE_PATH_CORENEWS 		= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Data/Core.xls";
	public static final String FILE_PATH_COMMENTS		= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Data/Comments.xls";
	public static final String FILE_PATH_CATEGORY		= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Data/Category.xls";
	public static final String FILE_PATH_LABELS			= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Data/Label.xls";

	public static final int MAX_SEARCH = 50000;

	public static final String MESSAGE_INDEXING 		= "Wait for Merging raw data and Indexing!";
	public static final String MESSAGE_INDEXED 			= "Ready to Use, Give it a try!";
	public static final String MESSAGE_SEARCH 			= " Documents Found in ";

}

Create Constants Class for All Hardcoded Texts and URLs


package org.positronicnet.sample.todo_cp;

import android.net.Uri;

// ContentProvider "Contract" declarations for the Todo ContentProvider
// in tests for ContentExporter, etc.

public class TodoContract {

  // URIs for common queries/updates

  public static String TODO_PREFIX =
    "content://org.positronicnet.sample.todo_cp/";

  public static String TODO_LISTS_PREFIX = TODO_PREFIX + "lists";
  public static Uri    TODO_LISTS_URI = Uri.parse( TODO_LISTS_PREFIX );

  public static Uri todoListUri( Long id )
  {
    return Uri.withAppendedPath( TODO_LISTS_URI, Long.toString( id ));
  }

  public static String TODO_LIST_ITEMS_PATTERN = TODO_LISTS_PREFIX + "/=/items";

  public static Uri todoListItemsUri( Long listId )
  {
    return Uri.withAppendedPath( TODO_LISTS_URI,
                                 Long.toString( listId ) + "/items" );
  }

  public static String TODO_LIST_ITEM_PATTERN = TODO_LISTS_PREFIX+"/=/items/=";

  public static Uri todoListItemUri( Long listId, Long itemId )
  {
    return Uri.withAppendedPath( TODO_LISTS_URI,
                                 Long.toString( listId ) + "/items/" + itemId );
  }

  public static String TODO_LIST_TYPE = "vnd.org.positronicnet.todolist";
  public static String TODO_ITEM_TYPE = "vnd.org.positronicnet.todoitem";

  // Columns for individual tables

  static class List {
    public static String _ID  = "_id";
    public static String NAME = "name";
  }

  static class Item {

    // Note that todo_list_id is implicit in the URI scheme above,
    // and the provider is smart enough to use the values in the URIs
    // on inserts and updates, so there's no need to explicitly map it.

    public static String _ID          = "_id";
    public static String DESCRIPTION  = "description";
    public static String IS_DONE      = "is_done";
  }

  // Generating content-types to match platform conventions.
  // Might want these somewhere where they'd be more generally useful

  public static String dirContentType( String s )
  {
    return "vnd.android.cursor.dir/"+s;
  }

  public static String rowContentType( String s )
  {
    return "vnd.android.cursor.item/"+s;
  }
}

Add ContentProvider Contract class for ContentProvider sample app.

Left out of the initial commit for the app.  (oops)

I try to avoid Java stubs in sample apps, but in this case, we need
to define one to follow platform conventions.  (It's a bag of "vals"
and functions defining conventions for accessing our app's
ContentProvider.)


package uk.gov.register.functional;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.junit.Assert;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class AssetsBundleCustomErrorHandlerTest extends FunctionalTestBase {
    @Test
    public void displays404pageForNonexistentAssets() {
        Response response = getRequest("/assets/not-an-assets");

        assertThat(response.getStatus(), equalTo(404));
        assertThat(response.getMediaType().isCompatible(MediaType.TEXT_HTML_TYPE), equalTo(true));

        Document doc = Jsoup.parse(response.readEntity(String.class));
        Elements notFoundHeader = doc.select("main h1");
        Assert.assertThat(notFoundHeader.first().text(), equalTo("Page not found"));
    }
}

Add test for handling not found assets

Add test for handling not found assets


package ie.gmit.sw;

/**
 * Created by Ross Byrne on 10/01/17.
 * A singleton factory for handling the instances of
 * the metric calculators.
 */
public class MetricCalculatorFactory {

    // private, instantiated factory object for singleton pattern
    private MetricCalculatorFactory factory = new MetricCalculatorFactory();

    // private constructor for singleton pattern, so no one can create another instance.
    private MetricCalculatorFactory(){}

    /**
     * Method for obtaining an instance of the singleton factory
     *
     * @return
     * Returns the instance of the singleton factory, MetricCalculatorFactory.
     */
    public MetricCalculatorFactory getInstance(){

        return this.factory;

    } // getInstance()

} // class

Create the metricCalculator singleton factory.


/*
 * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.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.github.bonigarcia.test.advance;

//tag::snippet-in-doc[]
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.safari.SafariDriver;

import io.github.bonigarcia.DriverOptions;
import io.github.bonigarcia.Option;
import io.github.bonigarcia.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class SafariWithOptionsJupiterTest {

    @Disabled("SafariDriver requires Safari 10 running on OSX El Capitan or greater.")
    @Test
    public void safariTest(
            @DriverOptions(options = {
                    @Option(name = "useCleanSession", value = "true"),
                    @Option(name = "useTechnologyPreview", value = "false") }) SafariDriver safari)
            throws InterruptedException {
        safari.get(
                "https://webrtc.github.io/samples/src/content/devices/input-output/");

        Thread.sleep(3000); // Wait 3 seconds to see the page
    }

}
// end::snippet-in-doc[]

Include Safari test using options

Include Safari test using options


//
// ScriptLanguage.java
//

/*
ImageJ software for multidimensional image processing and analysis.

Copyright (c) 2010, ImageJDev.org.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the names of the ImageJDev.org developers nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

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 imagej.script;

import imagej.plugin.ImageJPlugin;

import javax.script.ScriptEngineFactory;

/**
 * The base interface for script language adapters
 *
 * @author Johannes Schindelin
 */
public interface ScriptLanguage extends ScriptEngineFactory, ImageJPlugin {
	// just so we can annotate the factories with @Plugin...
}

Add the annotation for discovering script languages

These will be discovered by the upcoming script service. Script
languages which are not added via Java 1.6' scripting framework need to
implement this interface so that ImageJ2 discovers them.

Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>


package org.estatio.dom.lease;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;

public class LeaseTermForTaxTest_changeRegistration {

    @Before
    public void setUp() throws Exception {

    }

    @Test
    public void test() {
        // given
        LeaseTermForTax term = new LeaseTermForTax();
        term.setRegistrationDate(new LocalDate(2014, 1, 1));
        term.setRegistrationNumber("registrationNumber");
        term.setOfficeCode("officeCode");
        term.setOfficeName("officeName");
        term.setDescription("description");

        // when
        term.changeRegistration(new LocalDate(2014, 1, 1), "registrationNumber", "officeCode", "officeName", "description");

        assertThat(term.getRegistrationDate(), is(new LocalDate(2014, 1, 1)));
        assertThat(term.getRegistrationNumber(), is("registrationNumber"));
        assertThat(term.getOfficeCode(), is("officeCode"));
        assertThat(term.getOfficeName(), is("officeName"));
        assertThat(term.getDescription(), is("description"));

    }
}

EST-373: Add additional test for lease term for test


/*
 * 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.ngrinder.operation.cotroller;

import org.ngrinder.common.controller.BaseController;
import org.ngrinder.common.controller.RestAPI;
import org.ngrinder.operation.service.SystemConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.http.HttpEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import static org.ngrinder.common.util.Preconditions.checkNotEmpty;

/**
 * Developer Feature.
 *
 * @since 3.3
 */
@Controller
@RequestMapping("/dev")
public class DevController extends BaseController {

	@Autowired
	private ReloadableResourceBundleMessageSource messageSource;

	/**
	 * Refresh the messages.
	 *
	 * @param model model
	 * @return "redirect:/"
	 */
	@RequestMapping("/msg")
	public String refreshMessage(ModelMap model) {
		messageSource.clearCacheIncludingAncestors();
		model.clear();
		return "redirect:/";
	}

}

Add the message refresh for dev

[NOBTS] Add the message refresh for dev


package com.coderevisited.coding;

public class ReplaceWithNextGreatest
{
    public static void main(String[] args)
    {
        int[] array = new int[]{16, 6, 9, 10, 11, 17, 4, 3, 9, 8, 5, 2, 14};
        replaceWithNextGreatest(array);

        for (int i : array) {
            System.out.print(i + " ");
        }
        System.out.println();
    }

    private static void replaceWithNextGreatest(int[] array)
    {
        int max = -1;
        for (int i = array.length - 1; i >= 0; i--) {
            int current = array[i];
            array[i] = max;
            max = max > current ? max : current;
        }
    }
}

Replace With next greatest element

Replace With next greatest element


package com.evgenii.jsevaluatortests;

import android.test.ActivityInstrumentationTestCase2;

public class EvaluateJsActivityTests extends
		ActivityInstrumentationTestCase2<EvaluateJsStringActivity> {

	private EvaluateJsStringActivity mActivity;

	public EvaluateJsActivityTests() {
		super(EvaluateJsStringActivity.class);
	}

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		mActivity = getActivity();
	}

	public void testPreconditions() {
		assertNotNull("mActivity is null", mActivity);
	}
}

Add test for evaluatejs activity

Add test for evaluatejs activity


package roart.config;

public class MLConstants {
    public static final String MCP = "MCP";
    public static final String LR = "LR";
    public static final String OVR = "OVR";
    public static final String DNN = "DNN";
    public static final String DNNL = "DNNL";
    public static final String L = "L";
}

Add constants for ML classifier names.

Add constants for ML classifier names.


package ch.rasc.eds.starter.config;

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebFontMimeMapper implements EmbeddedServletContainerCustomizer {

	@Override
	public void customize(ConfigurableEmbeddedServletContainer container) {
		MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
		mappings.add("svg", "image/svg+xml");
		mappings.add("eot", "application/vnd.ms-fontobject");
		mappings.add("woff", "application/font-woff");
		mappings.add("woff2", "application/font-woff2");
		mappings.add("ttf", "application/font-sfnt");
		mappings.add("otf", "application/font-sfnt");
		container.setMimeMappings(mappings);
	}
}

Add mimetype mapping for self hosted webfonts


package com.tngtech.jgiven.junit;

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

import com.tngtech.jgiven.Stage;
import com.tngtech.jgiven.annotation.AfterStage;
import com.tngtech.jgiven.annotation.BeforeStage;
import com.tngtech.jgiven.annotation.ScenarioStage;
import org.junit.Ignore;
import org.junit.Test;

public class SimpleStageRepetitionUseTest
    extends SimpleScenarioTest<SimpleStageRepetitionUseTest.RepeatLifecycleMethods> {

    @ScenarioStage
    DontRepeatLifecycleMethods dontRepeatLifecycleMethods;

    /* FIXME:
    We use the change of a stage class to detect that there is a new stage.
    Hence, repeatedly using the same stage does not work!
    */
    @Test
    @Ignore("Feature not implemented yet")
    public void lifecycle_methods_of_a_shared_stage_are_called_individually() {
        given().a_simple_stage_containing_before_and_after_methods();
        when().the_test_is_executed();
        then().the_before_stage_was_called_$_times(3).and()
            .the_after_stage_method_was_called_$_times(2); //we assert before the last call to 'afterStage'
    }

    @Test
    public void non_repeatable_methods_are_called_exactly_once() {
        dontRepeatLifecycleMethods.given().a_simple_stage_containing_before_and_after_methods();
        dontRepeatLifecycleMethods.when().the_test_is_executed();
        dontRepeatLifecycleMethods.then().the_before_stage_was_called_$_times(1).and()
            .the_after_stage_method_was_called_$_times(0);
    }

    static class DontRepeatLifecycleMethods extends AllTestSteps<DontRepeatLifecycleMethods> {
        @BeforeStage
        protected void beforeStage() {
            callBeforeStage();
        }

        @AfterStage
        protected void afterStage() {
            callAfterStage();
        }
    }

    static class RepeatLifecycleMethods extends AllTestSteps<RepeatLifecycleMethods> {
        @BeforeStage(repeatable = true)
        protected void beforeStage() {
            callBeforeStage();
        }

        @AfterStage(repeatable = true)
        protected void afterStage() {
            callAfterStage();
        }
    }

    static class AllTestSteps<T extends AllTestSteps<?>> extends Stage<T> {

        private int beforeStageCalled = 0;
        private int afterStageCalled = 0;

        protected void callBeforeStage() {
            beforeStageCalled++;
        }

        protected void callAfterStage() {
            afterStageCalled++;
        }

        T a_simple_stage_containing_before_and_after_methods() {
            return self();
        }

        T the_test_is_executed() {
            return self();
        }

        T the_after_stage_method_was_called_$_times(int numberOfCalls) {
            assertThat(afterStageCalled).isEqualTo(numberOfCalls);
            return self();
        }

        T the_before_stage_was_called_$_times(int numberOfCalls) {
            assertThat(beforeStageCalled).isEqualTo(numberOfCalls);
            return self();
        }
    }
}

Issue-102: Test repeatable after stage methods when used in two consecutive stages

Signed-off-by: l-1sqared <927badf1468b689b17391b1b1cb5895e9b797b96@users.noreply.github.com>


package com.wildducktheories.api.impl;

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

import com.wildducktheories.api.API;

public class APIManagerTest {

	static class TestAPI implements API {

		public boolean reset = false;

		@Override
		public void reset() {
			reset = true;
		}

	}

	static class TestAPIManager extends AbstractAPIManagerImpl<TestAPI>
	{
		public TestAPI create()
		{
			return new TestAPI();
		};
	}

	/**
	 * Test that resets causes a different object to be allocated. That the same
	 * object will be returned without a reset and that the reset method is called on reset.
	 */
	@Test
	public void testReset() {
		final  TestAPIManager manager = new TestAPIManager();

		TestAPI api1 = manager.get();
		TestAPI api2 = manager.get();
		Assert.assertFalse(api1.reset);
		manager.reset();
		TestAPI api3 = manager.get();

		Assert.assertNotNull(api1);
		Assert.assertNotNull(api3);
		Assert.assertSame(api1, api2);
		Assert.assertNotSame(api1, api3);
		Assert.assertTrue(api1.reset);
		Assert.assertFalse(api3.reset);
	}
}

Add a test for the reset case.

Add a test for the reset case.

Signed-off-by: Jon Seymour <13015cd9b4bd75fb137ba1a80810e07fcd27c10e@gmail.com>


import java.io.File;
import java.io.FileWriter;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.*;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;

class ParseExamples {
    public static void main(String[] args) throws java.lang.Exception {
        String[] classNames = RunExamples.classNames();

        // e.g. com.opengamma.Class used in com.opengamma.example.ExampleClass:MethodName
        JSONObject classesUsed = new JSONObject();

        for (int k = 0; k < classNames.length; k++) {
            String className = classNames[k];
            JavaClass clazz = Repository.lookupClass(className);
            ConstantPool pool = clazz.getConstantPool();

            // Check each method in this class to see which OpenGamma classes it uses
            Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                Code code = method.getCode();

                // code.toString calls Utilities.codeToString which does lots
                // of useful parsing but then stores everything in a String
                // instead of a more accessible format, so we need to parse the string
                String[] codeLines = code.toString().split("\n");
                for (int m = 0; m < codeLines.length; m++) {
                    String line = codeLines[m];
                    int x = line.indexOf("invokespecial");
                    int y = line.indexOf(".<init>");
                    if (x > 0 && y > 0) {
                        String usedClassName = line.substring(x+13, y).trim();
                        if (usedClassName.startsWith("com.opengamma")) {
                            // This is one we are interested in!
                            JSONArray methodsUsedIn;

                            if (classesUsed.containsKey(usedClassName)) {
                                // Get existing array...
                                methodsUsedIn = (JSONArray)classesUsed.get(usedClassName);
                            } else {
                                // Init new array...
                                methodsUsedIn = new JSONArray();
                            }
                            String methodKey = className + ":" + method.getName();
                            methodsUsedIn.add(methodKey);
                            classesUsed.put(usedClassName, methodsUsedIn);
                        }
                    }
                }

                File f;
                FileWriter file;

                f = new File("../dexy--depends.json");
                file = new FileWriter(f);
                classesUsed.writeJSONString(file);
                file.close();
            }
        }
    }
}

Add script to detect which classes are being used (i.e. a new instance being creaetd) in examples.


//
// IJDelegationSelectionTool.java
//

/*
ImageJ software for multidimensional image processing and analysis.

Copyright (c) 2010, ImageJDev.org.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the names of the ImageJDev.org developers nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

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 imagej.ui.swing.overlay;

import org.jhotdraw.draw.tool.DelegationSelectionTool;

@SuppressWarnings("serial")
public class IJDelegationSelectionTool extends DelegationSelectionTool
	implements JHotDrawTool
{

}

Add an adapter for JHotDraw's selection tool

This will allow us to require more functionality of our JHotDraw-based
tools.

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>

This used to be revision r5035.


/*
 * Copyright 2005-2010 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
 *
 * 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.kuali.kra.iacuc.auth;

import org.kuali.kra.iacuc.actions.amendrenew.IacucProtocolModule;

/**
 * The Modify Protocol Others Authorizer determines if
 * the user can modify the other parts of a protocol.
 */
public class ModifyIacucProtocolOthersAuthorizer extends ModifyIacucAmendmentAuthorizer {

    public ModifyIacucProtocolOthersAuthorizer() {
        super(IacucProtocolModule.OTHERS);
    }
}

KCIAC-120: Create authorizer and permission for IACUC Custom Data


package com.faforever.api.data.domain;

import com.yahoo.elide.annotation.Include;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.sql.Time;
import java.util.Objects;

@Entity
@Table(name = "coop_leaderboard")
@Include(rootLevel = true, type = "coop_leaderboard")
public class CoopLeaderboard {

  private int id;
  private short mission;
  private Replay replay;
  private boolean secondaryObjectives;
  private Time duration;
  private short playerCount;

  @Id
  @Column(name = "id")
  public int getId() {
    return id;
  }

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

  @Basic
  @Column(name = "mission")
  public short getMission() {
    return mission;
  }

  public void setMission(short mission) {
    this.mission = mission;
  }

  @OneToOne
  @JoinColumn(name = "gameuid")
  public Replay getReplay() {
    return replay;
  }

  public void setReplay(Replay gameuid) {
    this.replay = gameuid;
  }

  @Basic
  @Column(name = "secondary")
  public boolean getSecondaryObjectives() {
    return secondaryObjectives;
  }

  public void setSecondaryObjectives(boolean secondary) {
    this.secondaryObjectives = secondary;
  }

  @Basic
  @Column(name = "time")
  public Time getDuration() {
    return duration;
  }

  public void setDuration(Time time) {
    this.duration = time;
  }

  @Basic
  @Column(name = "player_count")
  public short getPlayerCount() {
    return playerCount;
  }

  public void setPlayerCount(short playerCount) {
    this.playerCount = playerCount;
  }

  @Override
  public int hashCode() {
    return Objects.hash(id, mission, replay, secondaryObjectives, duration, playerCount);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    CoopLeaderboard that = (CoopLeaderboard) o;
    return id == that.id &&
        mission == that.mission &&
        replay == that.replay &&
        secondaryObjectives == that.secondaryObjectives &&
        Objects.equals(duration, that.duration) &&
        Objects.equals(playerCount, that.playerCount);
  }
}

Add coop leaderboard (without ranking)

Add coop leaderboard (without ranking)


/*
 * Copyright 2015 Michael Rozumyanskiy
 *
 * 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.
 */

// Just add a class to make the compiler happy.
public class Main {
    public static void main(final String[] args) {
    }
}

Make compiler happy by adding a java file to the injection-test project


/**
 * The {@code learningrate} package contains strategy classes to parametrize
 * self-organizing maps.  The classes are intended to be created by the user
 * and given to a self-organizing map, which will assume control.  These
 * classes all derive from {@link cs437.som.LearningRateFunction} in
 * {@link cs437.som}.
 */
package cs437.som.learningrate;

Add a package annotation to learningrate.


/*
Copyright (c) 2014, Colorado State University
All rights reserved.

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 holder 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.
*/

/**
 * Tests server-side support for listening on different ports with the
 * ServerMessageRouter, and distinguishing between the originating ports with
 * {@link MessageContext} instances.
 */
package galileo.test.multiport;

Add package info for multiport tests

Add package info for multiport tests


package com.thoughtworks.xstream.converters.reflection;

import junit.framework.TestCase;

import java.util.Iterator;
import java.lang.reflect.Field;

public class FieldDictionaryTest extends TestCase {

    private FieldDictionary fieldDictionary;

    protected void setUp() throws Exception {
        super.setUp();
        fieldDictionary = new FieldDictionary();
    }

    class SomeClass {
        private String a;
        private String c;
        private String b;
    }

    public void testListsFieldsInClassInDefinitionOrder() {
        Iterator fields = fieldDictionary.serializableFieldsFor(SomeClass.class);
        assertEquals("a", ((Field)fields.next()).getName());
        assertEquals("c", ((Field)fields.next()).getName());
        assertEquals("b", ((Field)fields.next()).getName());
        assertFalse("No more fields should be present", fields.hasNext());
    }

    class SpecialClass extends SomeClass {
        private String brilliant;
    }

    public void testIncludesFieldsInSuperClasses() {
        Iterator fields = fieldDictionary.serializableFieldsFor(SpecialClass.class);
        assertEquals("brilliant", ((Field)fields.next()).getName());
        assertEquals("a", ((Field)fields.next()).getName());
        assertEquals("c", ((Field)fields.next()).getName());
        assertEquals("b", ((Field)fields.next()).getName());
        assertFalse("No more fields should be present", fields.hasNext());
    }
}

Test that fields come out in same order they are defined.


package org.jaexcel.framework.JAEX.definition;

/**
 * This will define the title orientation type when writing into the Excel.

 *
 * {@value = TitleOrientationType.TOP } Will paint the title over the element.

 * {@value = TitleOrientationType.LEFT } Will paint the title at the left of the element.

 * {@value = TitleOrientationType.RIGHT } Will paint the title at the right of the element.

 * {@value = TitleOrientationType.BOTTOM } Will paint the title under the element.

 *
 * @version 1.0
 * @author Carlos CRISTO ABREU
 */
public enum TitleOrientationType {

	// right
	TOP(0), LEFT(1), RIGHT(2), BOTTOM(3);

	private int code;

	private TitleOrientationType(int s) {
		code = s;
	}

	public int getCode() {
		return code;
	}
}

Create enum responsible to : define the title orientation type when writing into the Excel.


package org.biojava.nbio.structure.align.quaternary;

/**
 * The Quaternary Structure Relation describes the pairwise relation between two
 * quaternary structures.
 *
 * @author Aleix Lafita
 * @since 5.0.0
 *
 */
public enum QsRelation {

	/**
	 * All the Subunits of one Structure have an equivalent in the other
	 * Structure.
	 *

	 * An example of this relation is comparing an A2B2 complex with C2 symmetry
	 * against a similar A2B2 complex with the same C2 symmetry axis (same
	 * topology).
	 **/
	EQUIVALENT,

	/**
	 * All the Subunits of one Structure have an equivalent in the other
	 * Structure, but the other Structure contains additional non-matched
	 * Subunits.
	 *

	 * An example of this relation is comparing an A2B2 complex with C2 symmetry
	 * against a similar A2 complex with the same C2 symmetry axis. Another
	 * example is comparing an A4 complex with D2 symmetry against an A2 complex
	 * with the same C2 symmetry axis as one of the D2 axes.
	 */
	PARTIAL_COMPLETE,

	/**
	 * Only a subset of Subunits of one Structure have an equivalent in the
	 * other Structure, and the other Structure also contains additional
	 * non-matched Subunits.
	 *

	 * An example of this relation is comparing an A2B2 complex with C2 symmetry
	 * against an A2C2 complex, where As are similar but B and C differ, with
	 * the same C2 symmetry axis. Only the A2 part of the structure matches.
	 */
	PARTIAL_INCOMPLETE,

	/**
	 * None of the Subunits of one Structure have an equivalent in the other
	 * Structure.
	 *

	 * Two quaternary structures are different if they are not
	 * {@link #EQUIVALENT}, {@link #PARTIAL_COMPLETE} or
	 * {@link #PARTIAL_INCOMPLETE}.
	 */
	DIFFERENT;
}

Create quaternary alignment relations ENUM


/*
 * Copyright 2018 Michael Rozumyanskiy
 *
 * 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.michaelrocks.lightsaber;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target(TYPE)
@Retention(RUNTIME)
@Documented
public @interface Factory {
  @Target(CONSTRUCTOR)
  @Retention(RUNTIME)
  @Documented
  @interface Inject {
  }
}

Add an annotation for factory interfaces


/*
	This class tests class Permutation
*/

package permutation;
import java.util.ArrayList;
import permutation.Permutation;
import java.util.Arrays;

class TestPermutation{

	// tests kth_permutation

	public static void testkth(int k){

		System.out.println("Test kth");

		Integer arr[] = {1,2,3,4,5,6,7,8,9};

		ArrayList<Integer> v = new ArrayList<Integer>(Arrays.asList(arr));

		ArrayList<Integer> result = Permutation.kth_permutation(v, k);

		for(Integer x: result)
			System.out.print(x+" ");
	}

	// tests next_permutation

	public static void test_next_permutation(){

		System.out.println("Test next permutation for: 1 2 3 4");

		Integer arr[] = {1,2,3,4};

		ArrayList<Integer> v = new ArrayList<Integer>( Arrays.asList(arr) );

		System.out.println("Further permutations: ");

		while(Permutation.next_permutation(v)){
			System.out.println();
			for(Integer x: v)
				System.out.print(x+" ");

		}

	}

	public static void main(String[] args){

		int k = 1;

		if( args.length > 0 )
			k = new Integer(args[0]);

		testkth(k);

		test_next_permutation();

	}

}

Add test class for class permutation

Add test class for class permutation


package com.formulasearchengine.mathosphere.mlp.gold;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.junit.Ignore;
import org.junit.Test;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Moritz on 02.01.2016.
 */
public class AddTitles {

  @Test
  @Ignore
  public void addTitles() throws IOException {
    final File file = new File(getClass().getResource("gold.json").getFile());
    Map<Integer,String> titles = new HashMap<>();
    FileReader in = new FileReader(new File(getClass().getResource("titles.csv").getFile()));
    Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
    for (CSVRecord record : records) {
      titles.put(Integer.valueOf(record.get(0)),record.get(1));
    }
    ObjectMapper mapper = new ObjectMapper();
    List userData = mapper.readValue(file, List.class);
    for (Object o : userData) {
      final Map entry = (Map) o;
      Map formula = (Map) entry.get("formula");
      formula.put("title",titles.get(Integer.parseInt(String.valueOf(formula.get("oldId"))) ));
    }
    mapper.writeValue(file, userData);
  }
}

Add program to add titles

Add program to add titles


package org.jenkinsci.plugins.ewm.utils;

import org.junit.Test;

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

/**
 * Tests for {@link RandomUtil}.
 *
 * @author Alexandru Somai
 */
public class RandomUtilTest {

    @Test
    public void generateRandomHexStringLength() {
        String generatedString = RandomUtil.generateRandomHexString(32);
        assertThat(generatedString.length(), is(32));
    }
}

Write test for RandomUtil class

Write test for RandomUtil class


package binarytree;

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

import datastructures.tree.BinaryTree;
import datastructures.tree.TreeNode;

public class CountHalfNodesBinaryTree {
  private BinaryTree<Integer> tree = null;
  private Map<Integer, TreeNode<Integer>> nodesMap = null;
  private TreeNode<Integer> root = null;

  public CountHalfNodesBinaryTree() {
    tree = new BinaryTree<Integer>();
    nodesMap = new HashMap<Integer, TreeNode<Integer>>();
  }

  public void constructTree(String[] input) {
    for (String line : input) {
      String[] values = line.split(" ");
      int val = 0;
      switch (values[0]) {
      case "insertRoot":
        val = Integer.parseInt(values[1]);
        TreeNode<Integer> root = tree.insertRoot(val);
        if (root != null) {
          nodesMap.put(val, root);
          this.root = root;
        }
        break;
      case "insertLeft":
        insert(values[1], values[2], true);
        break;
      case "insertRight":
        insert(values[1], values[2], false);
        break;
      }
    }
  }

  private void insert(String parentStr, String nodeStr, boolean isLeft) {
    int parentVal = Integer.parseInt(parentStr);
    int nodeVal = Integer.parseInt(nodeStr);
    TreeNode<Integer> parentNode = nodesMap.get(parentVal);
    if (parentNode == null) {
      return;
    }

    TreeNode<Integer> node = new TreeNode<Integer>(nodeVal);
    nodesMap.put(nodeVal, tree.insert(parentNode, node, isLeft));
  }

  public int countHalfNodes() {
    return countHalfNodes(root);
  }

  private int countHalfNodes(TreeNode<Integer> root) {
    if (root == null || (root.left == null && root.right == null)) {
      return 0;
    } else {
      int numHalfNodes = (root.left == null || root.right == null) ? 1 : 0;
      return countHalfNodes(root.left) + countHalfNodes(root.right) + numHalfNodes;
    }
  }
}

Add solution for count half nodes in a binary tree


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

/**
 * Given a matrix representing a word search, can you write a method to return true if a word
 * passed
 * as argument is inside the word search?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class WordSearch {

}

Add statement to problem 48

Add statement to problem 48


/*
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
package com.facebook.cache.common;

/**
 * No-op implementation of {@link CacheEventListener} so that listeners can extend and implement
 * only the events they're interested in.
 */
public class BaseCacheEventListener implements CacheEventListener {

  @Override
  public void onHit(CacheEvent cacheEvent) {
  }

  @Override
  public void onMiss(CacheEvent cacheEvent) {
  }

  @Override
  public void onWriteAttempt(CacheEvent cacheEvent) {
  }

  @Override
  public void onWriteSuccess(CacheEvent cacheEvent) {
  }

  @Override
  public void onReadException(CacheEvent cacheEvent) {
  }

  @Override
  public void onWriteException(CacheEvent cacheEvent) {
  }

  @Override
  public void onEviction(CacheEvent cacheEvent) {
  }

  @Override
  public void onCleared() {
  }
}

Create abstract implementation of CacheEventListener

Summary: Add `BaseCacheEventListener` which implements all methods to ease the creation of listeners which are only interested in particular events.

Reviewed By: lambdapioneer

Differential Revision: D4938357

fbshipit-source-id: 98c997e3b977e6e6abb70793664285523556a692


import java.util.*;

public class Solution {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        // Write your solution here
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = scan.nextInt();
        }

        scan.close();

        // Prints each sequential element in array a
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}

Solve java 1d array intro

Solve java 1d array intro


package edu.grinnell.callaway;

import static org.junit.Assert.*;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Vector;

import org.junit.Test;

public class JSONTester
{
  JSONParser1 parser1 = new JSONParser1();
  ToString str = new ToString();

  @Test
  public void toStrTestVals()
    throws Exception
  {
    assertEquals("1. true", "true", str.toStr(true));
    assertEquals("2. false", "false", str.toStr(false));
    assertEquals("3. num", "2.34", str.toStr(2.34));
    assertEquals("4. enum", "2.3E35", str.toStr(23e34));
    assertEquals("5. null", "null", str.toStr(null));
  } // toStrTestVals

  @Test
  public void toStrTestObVec()
    throws Exception
  {
    HashMap<String, Object> hash = new HashMap<String, Object>(8);

    Vector<Serializable> vector = new Vector<Serializable>(3);
    vector.add(1);
    vector.add(2);

    assertEquals("1. vector alone", "[1,2]", str.toStr(vector));

    Vector<Serializable> vector2 = new Vector<Serializable>(3);
    vector2.add(vector);
    vector2.add(2);

    assertEquals("2. vector in vector", "[[1,2],2]", str.toStr(vector2));

    HashMap<String, Object> hmap = new HashMap<String, Object>(3);

    hmap.put("x", "it");
    hmap.put("y", 2.7e-4);

    assertEquals("3. hashMap", "{\"y\":2.7E-4,\"x\":\"it\"}", str.toStr(hmap));

    vector.add(hmap);

    assertEquals("4. hashMap in vector", "[1,2,{\"y\":2.7E-4,\"x\":\"it\"}]",
                 str.toStr(vector));

    hash.put("a", true);
    hash.put("b", 2.7e-4);
    hash.put("c", "The");
    hash.put("j", vector2);
    hash.put("d", vector);
    hash.put("e", null);
    hash.put("f", hmap);

    assertEquals("5. things within things",
                 "{\"f\":{\"y\":2.7E-4,\"x\":\"it\"},\"d\":[1,2,{\"y\":2.7E-4,\"x\":\"it\"}],\"e\":null,\"j\":[[1,2,{\"y\":2.7E-4,\"x\":\"it\"}],2],\"b\":2.7E-4,\"c\":\"The\",\"a\":true}",
                 str.toStr(hash));
  } // toStrTestObVec
} // class JSONTester

Create tester... add tests for toStr

Create tester...  add tests for toStr


package com.sunny.grokkingalgorithms.fasttrack.week1;

import com.sunny.grokkingalgorithms.ctci.c4.util.BinaryTreeNode;
import com.sunny.grokkingalgorithms.ctci.c4.util.TreeUtils;

/**
 * Created by sundas on 6/21/2018.
 */
public class CheckIfBinaryTreeIsFull {

  /**
   *
   * @param root
   * @return
   */
  public static boolean isFull(BinaryTreeNode root){
    if(root ==  null){
      return true;
    }
    if(root.right == null
        && root.right == null){
      return true;
    }
    if((root.left != null && root.right == null) ||
        (root.left == null && root.right != null)){
      return false;
    }
    boolean leftSubTreeFull = isFull(root.left);
    boolean rightSubTreeFull = isFull(root.right);
    return leftSubTreeFull && rightSubTreeFull;
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    BinaryTreeNode root = TreeUtils.createBalancedBinaryTree();
    TreeUtils.performBfsLevelMarker(root);
    System.out.println(isFull(root));
    System.out.println("##################");
    root = TreeUtils.createBST();
    TreeUtils.performBfsLevelMarker(root);
    System.out.println(isFull(root));
  }

}

Check if a binary tree is full.

Check if a binary tree is full.


import edu.pdx.cs510.agile.team3.db.DBManager;
import org.junit.Test;
import org.junit.Assert;

import java.sql.SQLException;

/**
 * Created by dsanchez on 8/1/17.
 */
public class DBTest {

    @Test
    public void canConnect() {
        try {
            DBManager.connect();
            DBManager.close();
        } catch (SQLException e) {
            Assert.assertTrue(e.getMessage(), false);
        }
    }

    @Test
    public void canSave() {
        try {
            DBManager.connect();
            DBManager.saveConnection("testuser", "testpass", "testhost");
            DBManager.close();
        } catch (SQLException e) {
            Assert.assertTrue(e.getMessage(), false);
        }
    }

    @Test
    public void canLogin() {
        try {
            DBManager.connect();
            DBManager.saveConnection("testuser", "testpass", "testhost");
            boolean loggedIn = DBManager.login("testuser", "testpass");
            DBManager.close();
            Assert.assertTrue(loggedIn);
        } catch (SQLException e) {
            Assert.assertTrue(e.getMessage(), false);
        }
    }
}

Add tests for database manager

Add tests for database manager


package leetcode;

/**
 * https://leetcode.com/problems/maximum-product-of-word-lengths/
 */
public class Problem318 {
    public int maxProduct(String[] words) {
        // TODO:
        return 0;
    }

    public static void main(String[] args) {
        Problem318 prob = new Problem318();
        System.out.println(prob.maxProduct(new String[]{"abcw", "baz", "foo", "bar", "xtfn", "abcdef"})); // 16
        System.out.println(prob.maxProduct(new String[]{"a", "ab", "abc", "d", "cd", "bcd", "abcd"})); // 4
        System.out.println(prob.maxProduct(new String[]{"a", "aa", "aaa", "aaaa"})); // 0
    }
}

Add skeleton for problem 318

Add skeleton for problem 318


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Author:
 *     Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 *
 */
package org.jenetics.util;

import java.util.concurrent.atomic.AtomicInteger;

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

/**
 * @author Franz Wilhelmstötter
 * @version $Date: 2013-06-21 $
 */
public abstract class SeqTestBase<T> {

	protected abstract Seq<T> newSeq(final int length);

	@Test
	public void forEach() {
		final Seq<T> seq = newSeq(1000);

		final AtomicInteger counter = new AtomicInteger(0);
		seq.forEach(new Function<T, Void>() {
			@Override public Void apply(final T value) {
				counter.incrementAndGet();
				return null;
			}
		});

		Assert.assertEquals(counter.get(), seq.length());
	}

}

Add test base class for 'Seq' interface.


package org.mifos.application.rolesandpermission.business;

import junit.framework.TestCase;

import org.mifos.framework.TestUtils;
import org.mifos.framework.components.logger.TestLogger;

public class RoleActivityEntityTest extends TestCase {

	public void testEquals() throws Exception {
		RoleBO role77 = new RoleBO(new TestLogger(), 77);
		RoleBO another77 = new RoleBO(new TestLogger(), 77);
		RoleBO role78 = new RoleBO(new TestLogger(), 78);

		ActivityEntity activity66 = new ActivityEntity(66);

		TestUtils.assertAllEqual(
			new Object[] {
				new RoleActivityEntity(role77, activity66),
				new RoleActivityEntity(role77, activity66),
				new RoleActivityEntity(another77, activity66)
			});
		TestUtils.assertIsNotEqual(
			new RoleActivityEntity(role77, activity66),
			new RoleActivityEntity(role78, activity66));
		TestUtils.assertIsNotEqual(
			new RoleActivityEntity(role77, activity66),
			"object of some other type");
	}

}

Add file which should have been part of last checkin.

git-svn-id: 6bd94cac40bd5c1df74b384d972046d926de6ffa@11375 a8845c50-7012-0410-95d3-8e1449b9b1e4


import org.junit.Test;
import java.util.Arrays;

public class SelectionSortTest {

    @Test
    public void test() {
        int list[] = { -5, 8, 0, 12, 55, 1, -66, 35, 3 };
        SelectionSort selectionSort = new SelectionSort();
        selectionSort.sort(list);
        for (int i = 0; i < list.length - 1; i++) {
            assert (list[i] <= list[i + 1]);
        }
    }

    @Test
    public void nullList(){
        int list[] = {};
        int expectedList[] = {};
        SelectionSort selectionSort = new SelectionSort();
        selectionSort.sort(list);
        assert (Arrays.equals(list, expectedList));
    }
}

Add selection sort test for Java implementation


package org.trello4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.junit.Test;
import org.trello4j.model.Card;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

/**
 * @author Johan Mynhardt
 */
public class CardServiceTest {
	@Test
	public void testAddNewCardUsingPost() {
		Properties properties = new Properties();
		try {
			properties.load(CardServiceTest.class.getResourceAsStream("/cardservice.properties"));
		} catch (NullPointerException e) {
			fail("Could not load properties to test CardService: " + e.getMessage());
		} catch (IOException e) {
			fail(e.getMessage());
		}

		String developerKey = properties.getProperty("developerKey");
		String token = properties.getProperty("token");
		String listId = properties.getProperty("listId");

		String name = "Trello4J CardService: Add Card using POST";
		String description = "Something awesome happened :)";

		Map<String, String> keyValueMap = new HashMap<String, String>();
		keyValueMap.put("desc", description);

		Trello trello = new TrelloImpl(developerKey, token);
		Card card = trello.addNewCard(listId, name, keyValueMap);

		assertNotNull(card);

		assertThat(card.getName(), equalTo(name));
		assertThat(card.getDesc(), equalTo(description));
	}
}

Test for adding a card using POST.

Test for adding a card using POST.

Signed-off-by: joelso <18eaca8d2012d90d448985477d4cb18b3fab3fa4@gmail.com>


package org.robockets.stronghold.robot.intake;

import org.robockets.stronghold.robot.Robot;
import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class ChevalDeFrise extends CommandGroup {

	double encooder; // Dummy variable for now until a method is made for receiving encoder output
	// Assuming position fully down is 0 and fully up is 90.
    public ChevalDeFrise() {
    	Robot.driveTrain.gyroPID.setSetpoint(0); // 0 for now -Jake B. 2016
    	if (encooder > 80) { // Temporary way to check if arm is up
    		addSequential(new SetIntake(0));
    	} else if (encooder < 80) { // Temporary way to check if arm is down
    		addSequential(new SetIntake(90));
    		addSequential(new SetIntake(0));
    	}

        addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.GYRO, 1, 0)); // Dummy inputs for distance and relativeAngle
    	addParallel(new SetIntake(90)); // Slowly lift arm as robot moves across
    }
}

Add basic skeleton for automatic shoveling.


public class Solution {

    public boolean canConstruct(String ransomNote, String magazine) {

        int[] alphabetsCount = new int[26];

        for (int i = 0; i < magazine.length(); i++) {
            alphabetsCount[magazine.charAt(i) - 'a']++;
        }

        for (int i = 0; i < ransomNote.length(); i++) {

            alphabetsCount[ransomNote.charAt(i) - 'a']--;

            if (alphabetsCount[ransomNote.charAt(i) - 'a'] < 0) {
                return false;
            }

        }

        return true;

    }

}

Create : 383 Ransom Note

Create : 383 Ransom Note


public class Solution {

    public int findLUSlength(String a, String b) {

        if (a.equals(b)) {
            return -1;
        } else {
            return Math.max(a.length(), b.length());
        }

    }

}

Create : 521 Longest Uncommon Subsequence I


/*
 * Copyright 2016 Will Knez <wbknez.dev@gmail.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.solsticesquared.schelling.move;

import com.solsticesquared.schelling.Agent;
import com.solsticesquared.schelling.SchellingExplorer;

import java.util.ArrayList;

/**
 * Represents a mechanism for performing a single "movement" step in a
 * simulation, whereby one agent (or agents) try and move to a new location.
 */
public interface MovementMethod {

    /**
     * Returns the minimum number of agents that must be in an agent list in
     * order for this movement method to work.
     *
     * @return The minimum number of agents required.
     */
    int getMinimumNumberOfAgentsRequired();

    /**
     * Performs a single "movement" operation on the specified list of agents
     * using some arbitrary logic.
     *
     *

     *     The specifics of the algorithm used are irrelevant, however there
     *     are two important requirements that all implementations must meet:
     *

     *
The agent, or agents, that are moved must removed from
     *         the specified agent list.

     *
The agent, or agents, that are moved must have their
     *         positions updated before this method completes; this also
     *         applies to the empty cell list (that is why it consists of
     *         mutable coordinate objects).

     *

     *

     *
     *

     *     However, it should be noted that this project guarantees that by
     *     the time this method is called, all appropriate pre-requisites
     *     have been met.  In particular, the number of agents required for a
     *     single, successful movement operation (as defined by
     *     {@link #getMinimumNumberOfAgentsRequired()}) have been verified;
     *     there is no need for implementations to check.
     *

     *
     * @param agents
     *        The list of agents to use.
     * @param model
     *        The model to use.
     * @throws NullPointerException
     *         If either {@code agents} or {@code model} are {@code null}.
     */
    void move(final ArrayList<Agent> agents,
              final SchellingExplorer model);
}

Add mechanism for performing a single movement operation on an agent list.


package com.braintreegateway.unittest;

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

import com.braintreegateway.Dispute;
import com.braintreegateway.util.SimpleNodeWrapper;
import java.math.BigDecimal;
import java.text.ParseException;
import com.braintreegateway.testhelpers.CalendarTestUtils;

public class DisputeTest {
    @Test
    public void includesFields() throws ParseException {
        String xml = "<dispute>" +
            "<received-date type=\"date\">2017-01-02</received-date>" +
            "<reply-by-date type=\"date\">2017-01-04</reply-by-date>" +
            "<date-opened type=\"date\">2017-01-02</date-opened>" +
            "<date-won type=\"date\">2017-01-03</date-won>" +
            "<currency-iso-code>GBP</currency-iso-code>" +
            "<reason>fraud</reason>" +
            "<status>won</status>" +
            "<kind>chargeback</kind>" +
            "<amount>100.00</amount>" +
            "<id>dispute_id</id>" +
            "<transaction>" +
            "  <id>transaction_id</id>" +
            "  <amount>500.00</amount>" +
            "</transaction>" +
            "</dispute>";
        SimpleNodeWrapper node = SimpleNodeWrapper.parse(xml);

        Dispute dispute = new Dispute(node);

        assertEquals(CalendarTestUtils.date("2017-01-02"), dispute.getReceivedDate());
        assertEquals(CalendarTestUtils.date("2017-01-04"), dispute.getReplyByDate());
        assertEquals(CalendarTestUtils.date("2017-01-02"), dispute.getOpenedDate());
        assertEquals(CalendarTestUtils.date("2017-01-03"), dispute.getWonDate());
        assertEquals(Dispute.Reason.FRAUD, dispute.getReason());
        assertEquals(Dispute.Status.WON, dispute.getStatus());
        assertEquals(Dispute.Kind.CHARGEBACK, dispute.getKind());
        assertEquals(new BigDecimal("100.00"), dispute.getAmount());
        assertEquals("GBP", dispute.getCurrencyIsoCode());
        assertEquals("dispute_id", dispute.getId());
        assertEquals("transaction_id", dispute.getTransactionDetails().getId());
    }
}

Add basic unit test for Disputes

Add basic unit test for Disputes


/*
 * (C) Copyright 2019 Boni Garcia (http://bonigarcia.github.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.github.bonigarcia.seljup.test.constructor;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.seljup.Arguments;
import io.github.bonigarcia.seljup.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class ChromeInConstructorWithOptionsJupiterTest {

    ChromeDriver driver;

    public ChromeInConstructorWithOptionsJupiterTest(
            @Arguments({ "--use-fake-device-for-media-stream",
                    "--use-fake-ui-for-media-stream" }) ChromeDriver driver) {
        this.driver = driver;
    }

    @Test
    public void testGlobalChrome() {
        driver.get(
                "https://webrtc.github.io/samples/src/content/devices/input-output/");
        assertThat(driver.findElement(By.id("video")).getTagName(),
                equalTo("video"));
    }

}

Include test using options and driver in constructor


/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.support;

import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.text.Spannable;
import com.pyamsoft.pydroid.util.StringUtil;

public abstract class RatingActivity extends DonationActivity
    implements RatingDialog.ChangeLogProvider {

  @NonNull @Override public final Spannable getChangeLogText() {
    // The changelog text
    final String title = "What's New in Version " + getVersionName();
    final String[] lines = getChangeLogLines();

    // Turn it into a spannable
    final String[] fullLines = new String[lines.length + 1];
    fullLines[0] = title;
    System.arraycopy(lines, 0, fullLines, 1, fullLines.length - 1);
    final Spannable spannable = StringUtil.createLineBreakBuilder(fullLines);

    int start = 0;
    int end = title.length();
    final int largeSize =
        StringUtil.getTextSizeFromAppearance(this, android.R.attr.textAppearanceLarge);
    final int largeColor =
        StringUtil.getTextColorFromAppearance(this, android.R.attr.textAppearanceLarge);
    final int smallSize =
        StringUtil.getTextSizeFromAppearance(this, android.R.attr.textAppearanceSmall);
    final int smallColor =
        StringUtil.getTextColorFromAppearance(this, android.R.attr.textAppearanceSmall);

    StringUtil.boldSpan(spannable, start, end);
    StringUtil.sizeSpan(spannable, start, end, largeSize);
    StringUtil.colorSpan(spannable, start, end, largeColor);

    start += end + 2;
    for (final String line : lines) {
      end += 2 + line.length();
    }

    StringUtil.sizeSpan(spannable, start, end, smallSize);
    StringUtil.colorSpan(spannable, start, end, smallColor);

    return spannable;
  }

  @CheckResult @NonNull protected abstract String[] getChangeLogLines();

  @CheckResult @NonNull protected abstract String getVersionName();
}

Update changelog to use new activity

Update changelog to use new activity


package com.yammer.stresstime.entities;

import com.yammer.stresstime.managers.EmployeeManager;
import com.yammer.stresstime.test.DatabaseTest;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.assertNotNull;

public class EmployeeTest extends DatabaseTest {

    private EmployeeManager mEmployeeManager;

    @Before
    @Override
    public void setUp() throws Exception {
        super.setUp();
        mEmployeeManager = new EmployeeManager(getSessionFactory());
    }

    @Test
    public void testNewHasEmptyAssignmentsAfterRetrievedFromDb() {
        Employee employee = new Employee();
        employee.setName("John Doe");
        employee.setYammerId("lorem");
        mEmployeeManager.save(employee);
        refresh(employee);

        assertNotNull(employee.getAssignments());
        assertThat(employee.getAssignments(), empty());

        mEmployeeManager.delete(employee);
    }
}

Add test for Employee entity

Add test for Employee entity

Just test for the assignments association.


package to.etc.testutil;

/**
 * @author Frits Jalvingh
 * Created on 15-04-22.
 */
final public class TestUtil {
	private TestUtil() {}

	public static void nonTestPrintln(String text) {
		if(! inTest())
			System.out.println(text);
	}

	static public boolean inTest() {
		return System.getProperty("surefire.real.class.path") != null || System.getProperty("surefire.test.class.path") != null;
	}

}

Add utility class that decides whether code runs under test, to control things like debug logs


package fuzion24.device.vulnerability.vulnerabilities.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Base64;

import java.io.File;
import java.security.MessageDigest;
import java.util.HashSet;
import java.util.Scanner;

import fuzion24.device.vulnerability.util.SharedPreferencesUtils;

/**
 * Created by fuzion24 on 12/4/15.
 */
public class DeviceUpdateChecker {
    public static boolean wasDeviceUpdated(Context ctx){

        /*
            Take a hash of the build.prop and /proc/version
            If this changes, assume the device has been updated
        */
        String buildPropFile = readFile("/system/build.prop");
        String procVersion   = readFile("/proc/version");

        String fingerprint = hashString(buildPropFile + procVersion);
        String lastFingerprint = SharedPreferencesUtils.getBuildUpdateFingerprint(ctx);
        if(fingerprint.equals(lastFingerprint)){
            return false;
        } else {
            SharedPreferencesUtils.setBuildUpdateFingerPrint(ctx, fingerprint);
            return true;
        }
    }

    private static String hashString(String data){
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(data.getBytes());
            byte[] hash = md.digest();
            return Base64.encodeToString(hash, Base64.DEFAULT);
        } catch (Exception e) {
            return "";
        }
    }

    private static String readFile(String filename){
        try {
            return new Scanner(new File(filename)).useDelimiter("\\Z").next();
        }catch(Exception e){
            return "";
        }
    }

}

Add a class with our hueristics to check if a device was updated


package rotateit.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
public class LabelWebhookController {
    @RequestMapping(value = "/api/labelPostEvent", method = POST, consumes = APPLICATION_JSON_VALUE)
    @ResponseStatus(OK)
    public void labelPostEvent(@RequestBody String labelPayload) {

    }
}

Add webhook endpoint for github's label payload


/*
 * Copyright 2017 Isaac Pateau
 *
 * 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.zaclimon.iptvproviderlibrary.persistence;

import com.zaclimon.iptvproviderlibrary.model.AvContent;

import java.util.List;

/**
 * Persistence API for {@link AvContent}.
 * Will mostly be used if a content must be persisted to the disk (For caching or other reasons)
 *
 * @author zaclimon
 * Creation date: 11/08/17
 */

public interface ContentPersistence {

    /**
     * Gives a content to be persisted
     *
     * @param avContent the content that will be saved
     */
    void insert(AvContent avContent);

    /**
     * Gives a list of content to be to be persisted
     *
     * @param avContents the list that will be saved
     */
    void insert(List<AvContent> avContents);

    /**
     * Deletes a category based on {@link AvContent#mContentCategory}
     *
     * @param category the category which will get deleted.
     */
    void deleteCategory(String category);

    /**
     * Deletes all the items that have been persisted.
     */
    void deleteAllItems();

    /**
     * Lists all the items that have been persisted.
     *
     * @return the list of all the {@link AvContent} that have been persisted
     */
    List<AvContent> listAllItems();

    /**
     * Gives a list of the {@link AvContent} belonging to a given category. The list can be sorted
     * or not.
     *
     * @param category the given category for a content
     * @param isAlphabeticallySorted whether the retrieved contents should be sorted by alphabetical order
     * @return the list of contents
     */
    List<AvContent> searchCategory(String category, boolean isAlphabeticallySorted);

    /**
     * Gets the total size of the persistence medium
     *
     * @return the total number of elements for this medium.
     */
    int size();

    /**
     * Gets the size for a given category in the persistence medium
     *
     * @param category the category in which a size is wanted
     * @return the total number of elements for that given category.
     */
    int size(String category);
}

Implement a basic API for AvContent persistence

AvContent can be used on other stuff than TV Channels.
Because of this, some clients might want to save them
for future use. Implement an API that possibly gives the
possibility to do so.