package processbuilder.utils;

import java.io.*;

/**
 * Created on 4/21/2015.
 */
public class ProcessBuilderUtilities {

    /**
     * Attaches standard and error writer as well as input to a process.
     * @param process Process which to attach Output, Error and Input to.
     * @param processOutput A data sink for the process standard output. If null nothing will ne attached.
     * @param processError A data sink for the process' error output. If null nothing will be attached.
     * @param processInput A data source to be streamed to the process. If null nothing will be attached.
     */
    public static void attachStreamsToProcess(Process process, Writer processOutput, Writer processError,
                                       Reader processInput) {
      if (processOutput != null ) {
          // Attach to std output
          attachToInputStream(new InputStreamReader(process.getInputStream()), processOutput);
      }

        if (processError != null) {
            // Attach error output
            attachToInputStream(new InputStreamReader(process.getErrorStream()), processError);
        }

        if (processInput != null) {
            // Attach process input
            attachToInputStream(processInput,new OutputStreamWriter(process.getOutputStream()));
        }
    }

    /**
     * Creates a thread which will constantly pipe data, only active when new data is available, from a source to an attached sink. After
     * reaching the end of the source stream the @Thread will silently be destroyed.
     * @param source Data source.
     * @param attachedSink Data sink.
     */
    public static void attachToInputStream(final Reader source, final Writer attachedSink) {
        new Thread() {
            public void run() {
                try {
                    pipe(source, attachedSink);
                } catch (IOException e) {
                    //Done
                }
            }
        }.start();
    }

    /**
     * Pipes all data from a reader (source) to a writer (sink) until an I/O exection occurs or the
     * end of the source is reached.
     * @param from Source of data.
     * @param to Sink of data.
     * @throws IOException
     */
    public static void pipe(Reader from, Writer to) throws IOException {
        char[] buff = new char[1024];
        int n = from.read(buff);
        while (n != -1) {
            to.write(buff, 0, n);
            to.flush();
            n = from.read(buff);
        }
        from.close();
    }
}

Add util methods to attach other streams to the process' streams. That is important in order to directly read the output from the process. With that it will be possible to determine the version of docker compose.


/*
 * $Id: TranslatableMarker.java 1417 2006-11-03 14:57:33 +0000 (Fri, 03 Nov 2006) rodneykinney $
 *
 * Copyright (c) 2000-2006 by Rodney Kinney, Brent Easton
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License (LGPL) as published by the Free Software Foundation.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, copies are available
 * at http://www.opensource.org.
 */
package VASSAL.i18n;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import VASSAL.build.AbstractConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.counters.GamePiece;
import VASSAL.counters.PlaceMarker;

/**
 *
 * @author Brent Easton
 *
 * A dummy AbstractConfigurable to hold a PlaceMarker or Replace definition while translating
 */
public class TranslatableMarker extends AbstractConfigurable {

  protected GamePiece markerDefinition;
  protected String[] names;
  protected String[] values;

  public TranslatableMarker(PlaceMarker p) {
    markerDefinition = p.createBaseMarker();
    setConfigureName(p.getDescription());

  }

  public static String getConfigureTypeName() {
    return "Marker Definition";
  }

  public ComponentI18nData getI18nData() {
    return new ComponentI18nData(this, markerDefinition);
  }

  public String getAttributeValueString(String attr) {
    return getI18nData().getLocalUntranslatedValue(attr);
  }

  public void setAttribute(String attr, Object value) {

  }

  public void add(Buildable child) {
  }

  public void addTo(Buildable parent) {

  }

  public void build(Element e) {

  }

  public Element getBuildElement(Document doc) {
    return null;
  }

  public String[] getAttributeDescriptions() {
    return null;
  }

  public Class[] getAttributeTypes() {
    return null;
  }

  public String[] getAttributeNames() {
    return null;
  }
  public Class[] getAllowableConfigureComponents() {
    return null;
  }
  public HelpFile getHelpFile() {
    return null;
  }
  public void removeFrom(Buildable parent) {

  }

}

Add missing file from previous merge

Add missing file from previous merge

git-svn-id: 3948e88432e1a59e1cb2bc472f8f957688004121@2113 67b53d14-2c14-4ace-a08f-0dab2b34000c


package Mapper;

public class InstanceEventListener {
    /*! The set of possible actions on an instance, used to
     *  register callbacks to inform them of what is happening. */
    public final int IN_NEW = 0x01;
    public final int IN_UPSTREAM_RELEASE = 0x02;
    public final int IN_DOWNSTREAM_RELEASE = 0x04;
    public final int IN_OVERFLOW = 0x08;
    public final int IN_ALL = 0xFF;

    public void onEvent(Mapper.Device.Signal sig,
                        Mapper.Db.Signal props,
                        int instance_id,
                        int event) {};
}

package Mapper;

public class InstanceEventListener {
    /*! The set of possible actions on an instance, used to
     *  register callbacks to inform them of what is happening. */
    public static final int IN_NEW = 0x01;
    public static final int IN_UPSTREAM_RELEASE = 0x02;
    public static final int IN_DOWNSTREAM_RELEASE = 0x04;
    public static final int IN_OVERFLOW = 0x08;
    public static final int IN_ALL = 0xFF;

    public void onEvent(Mapper.Device.Signal sig,
                        Mapper.Db.Signal props,
                        int instance_id,
                        int event) {};
}

JNI: Declare instance event type flags static.


package me.zhengjie.utils;

import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;

import static org.junit.Assert.*;
import static me.zhengjie.utils.FileUtil.*;

public class FileUtilTest {

    @Test
    public void testToFile() {
        long retval = toFile(new MockMultipartFile("foo", (byte[]) null)).getTotalSpace();
        assertEquals(500695072768L, retval);
    }

    @Test
    public void testGetExtensionName() {
        assertEquals("foo", getExtensionName("foo"));
        assertEquals("exe", getExtensionName("bar.exe"));
    }

    @Test
    public void testGetFileNameNoEx() {
        assertEquals("foo", getFileNameNoEx("foo"));
        assertEquals("bar", getFileNameNoEx("bar.txt"));
    }

    @Test
    public void testGetSize() {
        assertEquals("1000B   ", getSize(1000));
        assertEquals("1.00KB   ", getSize(1024));
        assertEquals("1.00MB   ", getSize(1048576));
        assertEquals("1.00GB   ", getSize(1073741824));
    }
}

Add unit tests for me.zhengjie.utils.FileUtil

These tests were written using Diffblue Cover.


package com.alsash.reciper.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;

import com.alsash.reciper.R;

public abstract class DrawerActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    protected abstract PagerAdapter getPagerAdapter(FragmentManager fm);

    protected abstract void setupFab(FloatingActionButton fab);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_drawer_tab);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        setupFab(fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.drawer_open, R.string.drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.drawer_nav);
        navigationView.setNavigationItemSelectedListener(this);

        // Set up the ViewPager with the implemented PagerAdapter.
        ViewPager viewPager = (ViewPager) findViewById(R.id.tab_container);
        viewPager.setAdapter(getPagerAdapter(getSupportFragmentManager()));

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Add abstract activities for navigation drawer implementation


package org.zeromq.czmq;

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

public class ZSockTest {
    @Test
    public void testZSockSendRecv() {
        try (final ZSock push = new ZSock(ZMQ.ZMQ_PUSH);
             final ZSock pull = new ZSock(ZMQ.ZMQ_PULL)) {
            ZMsg msg = new ZMsg();
            pull.bind("tcp://*:1234");
            push.connect("tcp://localhost:1234");
            String expected = "hello";
            msg.pushstr(expected);
            ZMsg.send(msg, push);
            ZMsg resp = ZMsg.recv(pull);
            String actual = resp.popstr();
            Assert.assertEquals(expected, actual);
            resp.close();
        }
    }
}

package org.zeromq.czmq;

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

public class ZSockTest {
    @Test
    public void testZSockSendRecv() {
        try (final ZSock push = new ZSock(ZMQ.ZMQ_PUSH);
             final ZSock pull = new ZSock(ZMQ.ZMQ_PULL)) {
            ZMsg msg = new ZMsg();
            pull.bind("tcp://*:1234");
            push.connect("tcp://127.0.0.1:1234");
            String expected = "hello";
            msg.pushstr(expected);
            ZMsg.send(msg, push);
            ZMsg resp = ZMsg.recv(pull);
            String actual = resp.popstr();
            Assert.assertEquals(expected, actual);
            resp.close();
        }
    }
}

Use 127.0.0.1 instead of localhost

Use 127.0.0.1 instead of localhost


package jfoley.vocabpress.feature;

import jfoley.vocabpress.movement.Mover;
import jfoley.vocabpress.scoring.CountPosting;
import jfoley.vocabpress.scoring.impl.SimpleCountPosting;
import org.junit.Test;

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

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

public class MapFeatureTest {

	@Test
	public void testHasFeature() throws Exception {
		Map<Integer, CountPosting> priors = new HashMap<>();
		priors.put(1, new SimpleCountPosting(1, 9));
		priors.put(2, new SimpleCountPosting(2, 6));
		priors.put(3, new SimpleCountPosting(3, 4));

		MapFeature<CountPosting> fpriors = new MapFeature<>(priors);

		assertTrue(fpriors.hasFeature(1));
		assertTrue(fpriors.hasFeature(2));
		assertTrue(fpriors.hasFeature(3));
		assertEquals(9, fpriors.getFeature(1).getCount());
		assertEquals(6, fpriors.getFeature(2).getCount());
		assertEquals(4, fpriors.getFeature(3).getCount());
	}

	@Test
	public void testMovement() throws Exception {
		Map<Integer, CountPosting> priors = new HashMap<>();
		priors.put(1, new SimpleCountPosting(1, 9));
		priors.put(2, new SimpleCountPosting(2, 6));
		priors.put(3, new SimpleCountPosting(3, 4));

		MapFeature<CountPosting> fpriors = new MapFeature<>(priors);

		int count = 0;
		for(Mover m = fpriors.getMover(); !m.isDone(); m.next()) {
			int doc = m.currentKey();
			count++;
			assertEquals(priors.get(doc).getCount(), fpriors.getFeature(doc).getCount());
			assertEquals(doc, fpriors.getFeature(doc).getKey());
		}

		assertEquals(3, count);
	}

}

Add a test for MapFeature

Add a test for MapFeature


/*
 * 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 problem70;

import com.github.pedrovgs.problem70.ReverseOrderOfBinaryNumber;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseOrderOfBinaryNumberTest {

  private ReverseOrderOfBinaryNumber reverseOrder;

  @Before public void setUp() {
    reverseOrder = new ReverseOrderOfBinaryNumber();
  }

  @Test public void shouldReturnZeroIfInputIsZero() {
    int input = 0; // 0

    int result = reverseOrder.reverse(input);

    assertEquals(0, result); // 0
  }

  @Test public void shouldReturnOneIfInputIsOne() {
    int input = 1; // 1

    int result = reverseOrder.reverse(input);

    assertEquals(1, result); // 1
  }

  @Test public void shouldReturnTheSameNumberIfIsFullOfOnes() {
    int input = 7; // 111

    int result = reverseOrder.reverse(input);

    assertEquals(7, result); // 11
  }

  @Test public void shouldReturnBinaryNumberOrder() {
    int input = 13; // 1101

    int result = reverseOrder.reverse(input);

    assertEquals(11, result); // 1011
  }
}

Add some tests to problem 70

Add some tests to problem 70


package org.realityforge.replicant.client;

import java.io.Serializable;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * The ChangeMapper is responsible for applying changes to the world.
 *
 *
The mapper will be invoked for each change message and is responsible for;

 *
 *

 *
creating the entity if it does not already exist

 *
registering or de-registering the entity in the {@link EntityRepository}

 *
applying the state changes to the entity

 *
generating change messages and propagating them through the {@link EntityChangeBroker}

 *

 *
 *
As the ChangeMapper is very specific to the domain model that is being replicated, the ChangeMapper
 * is typically generated from a description via a tool such as Domgen.

 */
public interface ChangeMapper
{
  /**
   * Apply a single change to the world.
   *
   * @param typeID the type code of the entities type.
   * @param designator the entities designator,
   * @param data the data to use to update the entity or null if the entity should be removed from the system.
   * @return the entity that was created, updated or removed.
   */
  Object applyChange( int typeID, Object designator, @Nullable Map<String, Serializable> data );
}

Add in an interface to map changes to a particular world. It will ultimately be implemented for each world


package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/rotate-image/
 */
public class Problem48 {
    public void rotate(int[][] matrix) {

    }

    public static void main(String[] args) {
		Problem48 prob = new Problem48();
		int n = 3;
		int[][] matrix = new int[n][n];
		int val = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				matrix[i][j] = val++;
			}
		}
		prob.rotate(matrix);
		for (int i = 0; i < n; i++) {
			System.out.println(Arrays.toString(matrix[i]));
		}
	}
}

Create skeleton for problem 48

Create skeleton for problem 48


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

package org.spine3.server.storage;

import org.spine3.SPI;

/**
 * A marker interface for the {@code enum}s representing the names of the fields used by the framework to store
 * its data.
 *
 *
Naming conventions for the {@code enum}s' fields may be changed in favor of the field names to be represented
 * accurately.
 *
 *
Owing to that, we may simply call {@link Enum#toString()} or {@link Enum#name()} to get a valid field name.
 *
 * @author Dmytro Dashenkov
 */
@SPI
public interface StorageField {
}

Add a marker interface for the storage field names.


package helpers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Operations regarding PID.
 */
public class PidManipulation {
    private static Logger logger = LoggerFactory.getLogger(PidManipulation.class);

    /**
     * Write program PID to file.
     * @param path where to write the pid.
     */
    public static void writeOwnPidToFile(String path) {
        try {
            File file = new File(path);
            file.getParentFile().mkdir();
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }

            FileWriter fw = new FileWriter(file.getAbsolutePath());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(getPid());
            bw.close();

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * Obtain PID.
     *
     * @return PID of program.
     */
    public static String getPid() {
        String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
        return processName.split("@")[0];
    }
}

Add class for operations regarding PID.

Add class for operations regarding PID.


@Value.Style(
    // @formatter:off
    typeAbstract = { "*" },
    get = { "is*", "get*" },
    with = "with*",
    defaults = @Value.Immutable(builder = false, prehash = true)
    // @formatter:on
)
package mb.nabl2.constraints;

import org.immutables.value.Value;

Add prehashing for NaBL2 constraints.

Add prehashing for NaBL2 constraints.


package com.mattbachmann.nlpexperiments.apps;

import com.mattbachmann.nlpexperiments.extraction.ExtractionException;
import com.mattbachmann.nlpexperiments.extraction.TextExtractor;

import java.io.File;

public class ExtractFile {
    public static void main(String[] args) {
        if(args.length != 1) {
            System.out.println("I only take one arg, which is the file to extract text from");
            return;
        }

        try {
            System.out.println(TextExtractor.extractText(new File(args[0])));
        } catch (ExtractionException e) {
            System.out.println("Failed to extract text from file");
        }
    }
}

Add utility to print the extracted text of a file


/*
 * Copyright (C) 2013 Brett Wooldridge
 *
 * 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.zaxxer.hikari.proxy;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Timer;

import com.zaxxer.hikari.util.ConcurrentBag.IBagManagable;

/**
 *
 * @author Brett Wooldridge
 */
public interface IHikariConnectionProxy extends Connection, IBagManagable
{
    void unclose();

    void realClose() throws SQLException;

    void untrackStatement(Object statement);

    void checkException(SQLException sqle);

    boolean isBrokenConnection();

    boolean isTransactionIsolationDirty();

    boolean isAutoCommitDirty();

    long getCreationTime();

    long getLastAccess();

    /* Leak Detection API */
    void captureStack(long leakThreshold, Timer houseKeepingTimer);
}

/*
 * Copyright (C) 2013 Brett Wooldridge
 *
 * 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.zaxxer.hikari.proxy;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Timer;

import com.zaxxer.hikari.util.ConcurrentBag.IBagManagable;

/**
 *
 * @author Brett Wooldridge
 */
public interface IHikariConnectionProxy extends Connection, IBagManagable
{
    void unclose();

    void realClose() throws SQLException;

    void untrackStatement(Object statement);

    void checkException(SQLException sqle);

    boolean isBrokenConnection();

    long getCreationTime();

    long getLastAccess();

    /* Leak Detection API */
    void captureStack(long leakThreshold, Timer houseKeepingTimer);
}

Remove unused methods from signature

Remove unused methods from signature


package com.kgp.core;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 * Generic Adapater for Handling the interfacing of Key and Mouse interactions
 * @author Nicholas Hydock
 *
 */
public class GameController implements KeyListener, MouseMotionListener, MouseListener {

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseDragged(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseMoved(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

}

Add generic class that's an adapter for Keys and Mouse input


package com.codingbat.test;

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

import com.codingbat.array1.Array1Test;
import com.codingbat.array2.Array2Test;
import com.codingbat.string1.String1Test;
import com.codingbat.string2.String2Test;
import com.codingbat.warmup1.Warmup1Test;
import com.codingbat.warmup2.Warmup2Test;

@RunWith(Suite.class)
@SuiteClasses({Warmup1Test.class, Warmup2Test.class, Array1Test.class, Array2Test.class,
    String1Test.class, String2Test.class})
public class AllTests {

}

Create test suite to run 6 test classes at once.


package pro.extsoft.comments.elements;

import org.testng.annotations.Test;

/**
 * @author Dmytro Serdiuk (dmytro.serdiuk@gmail.com)
 * @version $Id$
 * @since 0.1
 */
public class SmartCheckBoxTest {
    @Test
    public void testChecked() throws Exception {
        assert new SmartCheckBox(new CheckBox() {
            @Override
            public void check() {

            }

            @Override
            public void uncheck() {

            }

            @Override
            public boolean checked() {
                return true;
            }
        }).checked();
    }
}

Add unit test for SmartCheckBox

Add unit test for SmartCheckBox


package peergos.server;

import peergos.shared.*;
import peergos.shared.corenode.*;
import peergos.shared.crypto.hash.*;
import peergos.shared.merklebtree.*;
import peergos.shared.user.*;

import java.net.*;
import java.time.*;
import java.util.*;
import java.util.stream.*;

public class UserStats {

    public static void main(String[] args) throws Exception {
        Crypto crypto = Crypto.initJava();
        NetworkAccess network = NetworkAccess.buildJava(new URL("https://demo.peergos.net")).get();
        List<String> usernames = network.coreNode.getUsernames("").get();
        List<Summary> summaries = usernames.stream().parallel().flatMap(username -> {
            try {
                List<UserPublicKeyLink> chain = network.coreNode.getChain(username).get();
                UserPublicKeyLink last = chain.get(chain.size() - 1);
                LocalDate expiry = last.claim.expiry;
                Set<PublicKeyHash> ownedKeysRecursive = WriterData.getOwnedKeysRecursive(username, network.coreNode, network.mutable, network.dhtClient);
                long total = 0;
                for (PublicKeyHash writer : ownedKeysRecursive) {
                    MaybeMultihash target = network.mutable.getPointerTarget(writer, network.dhtClient).get();
                    if (target.isPresent())
                        total += network.dhtClient.getRecursiveBlockSize(target.get()).get();
                }
                String summary = "User: " + username + ", expiry: " + expiry + " usage: " + total + "\n";
                System.out.println(summary);
                return Stream.of(new Summary(username, expiry, total));
            } catch (Exception e) {
                System.err.println("Error for " + username);
                e.printStackTrace();
                return Stream.empty();
            }
        }).collect(Collectors.toList());

        summaries.sort((a, b) -> (int) (b.usage - a.usage));
        summaries.forEach(System.out::println);
    }

    private static class Summary {
        public final String username;
        public final LocalDate expiry;
        public final long usage;

        public Summary(String username, LocalDate expiry, long usage) {
            this.username = username;
            this.expiry = expiry;
            this.usage = usage;
        }

        public String toString() {
            return "User: " + username + ", expiry: " + expiry + " usage: " + usage;
        }
    }
}

Add util for calculating global public stats


import java.math.BigInteger;

/**
 * Problem: #278 First Bad Version
 *
 * Idea:
 *
 * Solutions:
 *  firstBadVersion: uses basic binary search, but StackOverflowError occurs.
 *
 * Note: #canbefaster
 */

/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */
public class FirstBadVersion {
    public int binarySearch(int left, int right) {
        int middle = (left + right)/2;

        if (isBadVersion(middle)  == true) {
            if (isBadVersion(middle - 1) == false) {
                return middle;
            } else {
                return binarySearch(left, middle-1);
            }
        }

        if (isBadVersion(middle) == false) {
            return binarySearch(middle + 1, right);
        }

        return -1;
    }

    public int firstBadVersion(int n) {
        return binarySearch(1, n);
    }

    private boolean isBadVersion(int n) {
        if (n >= 1702766719) return true;
        return false;
    }

    public static void main(String[] args) {
        System.out.println(new FirstBadVersion().firstBadVersion(2126753390));
    }
}

Add new solution but StackOverflowError exists


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fi.jgke.tagger.domain;

import java.util.UUID;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author jgke
 */
public class TypeTest {

    @Test
    public void testSetGetValue() {
        String value = UUID.randomUUID().toString();
        Tag instance = new Tag();
        instance.setValue(value);
        assertEquals(value, instance.getValue());
    }

}

Add simple test for Type

Add simple test for Type


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

/**
 * Core classes for the {@code gcloud-java} library.
 */
package com.google.gcloud;

Use groups to separate packages in javadoc's index


package org.jpos.qi.util;

import com.vaadin.data.ValidationResult;
import com.vaadin.data.Validator;
import com.vaadin.data.ValueContext;
import org.jpos.ee.DB;
import org.jpos.ee.DBManager;
import org.jpos.qi.QIHelper;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class UniqueValidator<T, FieldType> implements Validator<FieldType> {
    protected QIHelper helper;
    Class<T> clazz;
    Method idGetter;
    Method fieldGetter;
    String field;
    String errorMessageCode;

    public UniqueValidator(QIHelper helper, Class<T> clazz, String field)
            throws IntrospectionException
    {
        this(helper, clazz, field, "errorMessage." + field + "AlreadyExists");
    }

    public UniqueValidator(QIHelper helper, Class<T> clazz, String field, String errorMessageCode)
            throws IntrospectionException
    {
        this(helper, clazz, field, errorMessageCode, "id");
    }

    public UniqueValidator(QIHelper helper, Class<T> clazz, String field, String errorMessageCode, String idField)
            throws IntrospectionException
    {
        this.helper = helper;
        this.clazz = clazz;
        this.field = field;
        this.errorMessageCode = errorMessageCode;
        for (PropertyDescriptor property : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
            if (property.getName().equals(field)) fieldGetter = property.getReadMethod();
            else if (property.getName().equals(idField)) idGetter = property.getReadMethod();
        }
    }

    /**
     * Validates the given value. Returns a {@code ValidationResult} instance
     * representing the outcome of the validation.
     *
     * @param value   the input value to validate
     * @param context the value context for validation
     * @return the validation result
     */
    @Override
    public ValidationResult apply(FieldType value, ValueContext context) {
        @SuppressWarnings("unchecked")
        T originalEntity = (T) helper.getOriginalEntity();
        try {
            T found = DB.exec(db -> new DBManager<>(db, clazz).getItemByParam(field, value));
            if (found == null ||
                    originalEntity != null && idGetter.invoke(found).equals(idGetter.invoke(originalEntity)))
            {
                return ValidationResult.ok();
            } else {
                return ValidationResult.error(helper.getApp().getMessage(errorMessageCode, value));
            }
        } catch (Exception e) {
            helper.getApp().getLog().error(e);
            return ValidationResult.error(helper.getApp().getMessage(e.getClass().getName(), e.getMessage()));
        }

    }
}

Add generic unique QI validator for entities by field


package leetcode.lru_cache;

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

public class LRUCache {
	private static class CacheEntry{
		int key, val;
		CacheEntry prev, next;
		public CacheEntry(int key, int val){
			this.key = key;
			this.val = val;
		}
	}
	private int capacity;
	private CacheEntry mCacheHead, mCacheTail;
	private int mCacheSize;
	private Map<Integer, CacheEntry> mIndexMap;
    public LRUCache(int capacity) {
        this.capacity = capacity;
        mCacheHead = mCacheTail = null;
        mIndexMap = new HashMap<Integer, CacheEntry>();
        mCacheSize = 0;
    }

    public void moveToFirst(CacheEntry entry){
    	if(entry.prev != null){
    		CacheEntry next = entry.next;
    		CacheEntry prev = entry.prev;
    		prev.next = next;
    		if(next == null){
    			mCacheTail = prev;
    		}else{
    			next.prev = prev;
    		}
    		entry.next = mCacheHead;
    		entry.prev = null;
    		mCacheHead.prev = entry;
    		mCacheHead = entry;
    	}
    }

    public int get(int key) {
    	CacheEntry entry = mIndexMap.get(key);
    	if(entry == null) return -1;
    	moveToFirst(entry);
    	return entry.val;
    }

    public void set(int key, int value) {
        CacheEntry entry = mIndexMap.get(key);
        if(entry != null){
        	entry.val = value;
        	moveToFirst(entry);
        }else{
        	if(mCacheSize >= capacity){
        		moveToFirst(mCacheTail);
        		mIndexMap.remove(mCacheHead.key);
        		mCacheHead.val = value;
        		mCacheHead.key = key;
        	}else{
        		entry = new CacheEntry(key, value);
        		if(mCacheHead == null){
        			mCacheTail = mCacheHead = entry;
        		}else{
        			entry.next = mCacheHead;
        			mCacheHead.prev = entry;
        			mCacheHead = entry;
        		}
        		mCacheSize++;
        	}
        	mIndexMap.put(key, mCacheHead);
        }
    }

    public static void main(String[] args){
    	LRUCache cache = new LRUCache(8);
    	for(int i = 0; i < 10; i++){
    		cache.set(i, i + 100);
    	}
    	for(int i = 0; i < 10; i++){
    		System.err.println(cache.get(i));
    	}
    	cache.get(5);
    	cache.set(10, 110);
    	cache.set(11, 111);
    	CacheEntry entry = cache.mCacheHead;
    	while(entry != null){
    		System.err.println(entry.key + ": " + entry.val);
    		entry = entry.next;
    	}
    }
}

Add java solution for 146. LRU Cache

Add java solution for 146. LRU Cache

146. LRU Cache: https://leetcode.com/problems/lru-cache/


package jocket.bench;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import jocket.net.JocketSocket;

/**
 * Infinite benchmark, meant for profiling.
 *
 * @author pcdv
 */
public final class BenchClient2 implements Settings {

  private final byte[] buf;

  private final DataInputStream in;

  private final DataOutputStream out;

  public BenchClient2() throws IOException {
    this.buf = new byte[REPLY_SIZE];
    JocketSocket s = new JocketSocket(PORT);
    in = new DataInputStream(s.getInputStream());
    out = new DataOutputStream(s.getOutputStream());
  }

  /**
   * Benchmark's main loop.
   */
  public void bench() throws IOException {

    out.writeInt(REPS * BATCH + WARMUP);
    out.writeInt(REPLY_SIZE);

    while (true) {
      iter(BATCH);
    }
  }

  public void iter(int batch) throws IOException {
    for (int i = 0; i < batch; i++) {
      out.write(buf, 0, 4);
      out.flush();
      in.readFully(buf, 0, REPLY_SIZE);
    }
  }

  public static void main(String[] args) throws IOException {
    new BenchClient2().bench();
  }
}

Add infinite client benchmark for profiling.


/*
 * Copyright (C) 2004 - 2013 Brian McCallister
 *
 * 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.skife.jdbi.v2.sqlobject;

import java.sql.Connection;
import java.sql.SQLException;

import org.h2.jdbcx.JdbcDataSource;
import org.junit.Test;
import org.skife.jdbi.v2.DBI;

import junit.framework.TestCase;

/**
 * Sometimes the GC will call {@link #finalize()} on a SqlObject from
 * extremely sensitive places from within the GC machinery.  JDBI should not
 * open a {@link Connection} just to satisfy a (no-op) finalizer.
 * Issue #82.
 */
public class TestFinalizeBehavior extends TestCase
{
    private DBI    dbi;

    interface UselessDao
    {
        public void finalize();
    }

    @Test
    public void testFinalizeDoesntConnect() throws Exception
    {
        final UselessDao dao = dbi.onDemand(UselessDao.class);
        dao.finalize(); // Normally GC would do this, but just fake it
    }

    @Override
    public void setUp() throws Exception
    {
        final JdbcDataSource ds = new JdbcDataSource() {
            private static final long serialVersionUID = 1L;

            @Override
            public Connection getConnection() throws SQLException
            {
                throw new UnsupportedOperationException();
            }
        };
        dbi = new DBI(ds);
    }
}

Add a test case showing that SqlObject finalize() calls open Connections.


/*
 Copyright (C) 2003 EBI, GRL

 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package org.ensembl.healthcheck.testcase.funcgen;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check that certain views/tables required for the Biomart build are present.
 */

public class PreMartTables extends SingleDatabaseTestCase {

	/**
	 * Constructor.
	 */
	public PreMartTables() {

		// TODO - group specifically for this?
		setDescription("Check that certain views/tables required for the Biomart build are present.");

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return true if the test passed.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		for (String table : getBiomartFuncgenTablesAndViews()) {

			if (checkTableExists(con, table)) {

				ReportManager.correct(this, con, "Requried table " + table + " exists.");

			} else {

				ReportManager.problem(this, con, "Required table or view " + table + " does not exist");
				result = false;

			}

		}

		return result;

	} // run

} // PreMartTablesAndViews


package com.expidev.gcmapp.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by William.Randall on 1/15/2015.
 */
public class JsonStringReader
{
    public static String readFully(InputStream inputStream, String encoding) throws IOException
    {
        return new String(readFully(inputStream), encoding);
    }

    private static byte[] readFully(InputStream inputStream) throws IOException
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1)
        {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        return byteArrayOutputStream.toByteArray();
    }
}

Create a util class to handle turning the input stream into a string


package org.luxons.sevenwonders.game;

import java.util.Collection;

import org.junit.Test;
import org.luxons.sevenwonders.game.api.Action;
import org.luxons.sevenwonders.game.api.CustomizableSettings;
import org.luxons.sevenwonders.game.api.HandCard;
import org.luxons.sevenwonders.game.api.PlayerMove;
import org.luxons.sevenwonders.game.api.PlayerTurnInfo;
import org.luxons.sevenwonders.game.data.GameDefinitionLoader;
import org.luxons.sevenwonders.game.moves.MoveType;
import org.luxons.sevenwonders.game.test.TestUtils;

import static org.junit.Assert.assertEquals;

public class GameTest {

    @Test
    public void test() {
        int nbPlayers = 5;
        Game game = createGame(nbPlayers);
        Collection<PlayerTurnInfo> turnInfos = game.getCurrentTurnInfo();

        assertEquals(nbPlayers, turnInfos.size());

        for (PlayerTurnInfo turnInfo : turnInfos) {
            Action action = turnInfo.getAction();
            assertEquals(Action.PLAY, action);
            assertEquals(1, turnInfo.getCurrentAge());
            assertEquals(7, turnInfo.getHand().size());
            PlayerMove move = getFirstAvailableMove(turnInfo);
            game.prepareCard(turnInfo.getPlayerIndex(), move);
        }
    }

    private PlayerMove getFirstAvailableMove(PlayerTurnInfo turnInfo) {
        for (HandCard handCard : turnInfo.getHand()) {
            if (handCard.isPlayable()) {
                return createMove(handCard, MoveType.PLAY);
            }
        }
        return createMove(turnInfo.getHand().get(0), MoveType.DISCARD);
    }

    private PlayerMove createMove(HandCard handCard, MoveType play) {
        PlayerMove move = new PlayerMove();
        move.setCardName(handCard.getCard().getName());
        move.setType(play);
        return move;
    }

    private static Game createGame(int nbPlayers) {
        CustomizableSettings settings = TestUtils.createCustomizableSettings();
        return new GameDefinitionLoader().getGameDefinition().initGame(0, settings, nbPlayers);
    }
}

Add first draft of Game test

Add first draft of Game test


package com.team254.lib.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;

public class Subsystem implements Tappable {

	String name;
	public Subsystem(String name) {
		this.name = name;
		SystemManager.getInstance().add(this.getComponents());
	}

	public final Collection<Serializable> getComponents() {
		Field[] allFields = this.getClass().getDeclaredFields();
		Collection<Serializable> components = new ArrayList<Serializable>();

		for (Field f : allFields) {
			Serializable cur = null;
			if (Serializable.class.isAssignableFrom(f.getClass())) {
				Object obj = null;
				try {
					obj = f.get(this);
				} catch (IllegalArgumentException | IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				cur = (Serializable) obj;
			} else {
				cur = new SerialFieldContainer(name, f, this);
			}
			if (cur != null) {
				components.add(cur);
			}
		}
		return components;
	}

}

Add serializable Subsytem base class

Add serializable Subsytem base class

This class will reflect all of its members and add them to
the system manager.


/*******************************************************************************
 * Copyright (c) 2013 Benjamin Pabst and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Benjamin Pabst - initial API and implementation
 ******************************************************************************/

package com.xeviox.commons;

import com.xeviox.commons.util.Version;

/**
 * Common constants and info of the blackstrap library.
 */
public final class PackageInfo {

	/**
	 * Current blackstrap version.
	 */
	public static final Version VERSION = new Version(0, 0, 1);

	// prevent instantiation
	private PackageInfo() { }
}

Add new class to provide package info.

Add new class to provide package info.


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

import nom.bdezonia.zorbage.type.algebra.Group;
import nom.bdezonia.zorbage.type.algebra.MatrixMember;
import nom.bdezonia.zorbage.type.algebra.Multiplication;

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

	private MatrixDirectProduct() { }

	public static <T extends Group<T,U> & Multiplication<U>,U,W extends MatrixMember<U>>
		void compute(T group, W in1, W in2, W out)
	{
		U tmp1 = group.construct();
		U tmp2 = group.construct();
		U tmp3 = group.construct();
		if (out == in1 || out == in2)
			throw new IllegalArgumentException("output matrix must not be one of input matrices");
		out.alloc(in1.rows() * in2.rows(), in1.cols() * in2.cols());
		for (long r1 = 0; r1 < in1.rows(); r1++) {
			for (long c1 = 0; c1 < in1.cols(); c1++) {
				in1.v(r1, c1, tmp1);
				for (long r2 = 0; r2 < in2.rows(); r2++) {
					for (long c2 = 0; c2 < in2.cols(); c2++) {
						in2.v(r2, c2, tmp2);
						group.multiply(tmp1, tmp2, tmp3);
						out.setV(r1*in2.rows(), c1*in2.cols(), tmp3);
					}
				}
			}
		}
	}
}

Define a matrix direct product algorithm


package leetcode;

/**
 * https://leetcode.com/problems/minimum-path-sum/
 */
public class Problem64 {
    public int minPathSum(int[][] grid) {
    	// TODO: to be implemented
        return 0;
    }

    public static void main(String[] args) {
		Problem64 prob = new Problem64();
		int[][] grid = new int[][] {
			new int[]{1, 9, 4, 7},
			new int[]{6, 2, 1, 5},
			new int[]{1, 3, 8, 2}
		};
		System.out.println(prob.minPathSum(grid));
	}
}

Create a skeleton for problem 64

Create a skeleton for problem 64


package com.sferadev.danacast.servers;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;

public class Seriesblanco {
    public static Elements getSearchResults(String query) {
        try {
            Document document = Jsoup.connect("http://seriesblanco.com/finder.php")
                    .data("query", query)
                    .post();
            return document.select("a");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Elements getPopularContent() {
        try {
            Document document = Jsoup.connect("http://www.seriesblanco.com/")
                    .get();
            return document.select("#PopularPosts1 li");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Add initial series blanco server

Dana: Add initial series blanco server


package net.happygiraffe.jslint;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * A command line interface to {@link JSLint}.
 *
 * @author dom
 * @version $Id$
 */
public class Main {

    /**
     * The main entry point. Try passing in "--help" for more details.
     *
     * @param args
     *                One or more JavaScript files.
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        JSLint lint = new JSLint();
        lint.addOption(Option.EQEQEQ);
        lint.addOption(Option.UNDEF);
        lint.addOption(Option.WHITE);
        for (String file : args) {
            lintFile(lint, file);
        }
    }

    private static void lintFile(JSLint lint, String file) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file)));
            List<Issue> issues = lint.lint(file, reader);
            for (Issue issue : issues) {
                System.err.println(issue);
            }
        } catch (FileNotFoundException e) {
            System.err.println(file + ":no such file");
        }
    }

}

package net.happygiraffe.jslint;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * A command line interface to {@link JSLint}.
 *
 * @author dom
 * @version $Id$
 */
public class Main {

    /**
     * The main entry point. Try passing in "--help" for more details.
     *
     * @param args
     *                One or more JavaScript files.
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        Main main = new Main();
        for (String file : args) {
            main.lintFile(file);
        }
    }

    private JSLint lint;

    private Main() throws IOException {
        lint = new JSLint();
        lint.addOption(Option.EQEQEQ);
        lint.addOption(Option.UNDEF);
        lint.addOption(Option.WHITE);
    }

    private void lintFile(String file) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file)));
            List<Issue> issues = lint.lint(file, reader);
            for (Issue issue : issues) {
                System.err.println(issue);
            }
        } catch (FileNotFoundException e) {
            System.err.println(file + ":no such file");
        }
    }

}

Make into a real object instead of lots of static methods.


package net.wisedog.android.whooing.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringUtil {
	public static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

Add missing an util file

Add missing an util file


package se.lth.cs.connect;

import org.junit.Rule;
import org.junit.Test;

import com.jayway.restassured.response.Response;

import ro.pippo.test.PippoRule;
import ro.pippo.test.PippoTest;

public class TestUserAPI extends PippoTest {

	@Rule
	public PippoRule pippoRule = new PippoRule(new Connect());

	@Test
	public void testAccessDenied() {
		// These routes require an active session => they should fail (with status 401)
		when().get("/v1/account/login").then().statusCode(401);
		when().get("/v1/account/collections").then().statusCode(401);
		when().get("/v1/account/self").then().statusCode(401);
		when().post("/v1/account/logout").then().statusCode(401);
		when().post("/v1/account/delete").then().statusCode(401);
		when().post("/v1/account/change-password").then().statusCode(401);
		when().get("/v1/account/invites").then().statusCode(401);
		when().get("/v1/account/dat12asm@student.lu.se").then().statusCode(401);
	}

	// Register --> Logout --> Login --> Delete
	@Test
	public void testLifecycle() {
		Response reg = given().
				param("email", "test@serptest.test").
				param("passw", "hejsanhoppsan").
			post("/v1/account/register");

		reg.then().
			statusCode(200);

		given().
			cookie("JSESSIONID", reg.getCookie("JSESSIONID")).
		when().
			post("/v1/account/logout").
		then().
			statusCode(200);

		Response login = given().
				param("email", "test@serptest.test").
				param("passw", "hejsanhoppsan").
			post("/v1/account/login");

		reg.then().
			statusCode(200);

		given().
			cookie("JSESSIONID", login.getCookie("JSESSIONID")).
		when().
			post("/v1/account/delete").
		then().
			statusCode(200);
	}
}

Add sample test cases for user api

Add sample test cases for user api


package org.luxons.sevenwonders.game.cards;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class CardBackTest {

    @Test
    public void initializedWithImage() throws Exception {
        String imagePath = "whateverimage.png";
        CardBack back = new CardBack(imagePath);
        assertEquals(imagePath, back.getImage());
    }
}

Add test for CardBack initialization (coverage frenzy)


/**
 * Package for the requests regarding the episodes.

 * The associated documentation for these methods is available at
 * this address.
 * @author Alex
 */
package com.alexrnl.jbetaseries.request.episodes;

Add package for episodes requests

Add package for episodes requests


package leetcode.scramble_string;

public class Solution {
	public static class MyLetterHash{
		public static final int[] PRIMES = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,};
		public static final int SIZE = 26;
		public static final int MODULUS = 21262211;
		int hash, len;

		public MyLetterHash(String s){
			char[] chars = s.toCharArray();
			int tmp = 1;
			len = chars.length;
			for(int i = 0; i < len; i++){
				tmp *= PRIMES[chars[i] - 'a'];
				tmp %= MODULUS;
			}
			hash = tmp;
		}

		@Override
		public int hashCode() {
			return hash;
		}

		@Override
		public boolean equals(Object obj) {
			MyLetterHash cmp = (MyLetterHash)obj;
			return cmp.hash == this.hash && cmp.len == this.len;
		}

	}

	public boolean isScramble(String s1, String s2) {
    	int len = s1.length();
    	if(s1.equals(s2)) return true;
    	else{
    		for(int i = 1; i < len; i++){
    			String left1 = s1.substring(0, i);
    			String right1 = s1.substring(i);
    			MyLetterHash leftHash1 = new MyLetterHash(left1);
    			MyLetterHash rightHash1 = new MyLetterHash(right1);
    			String left2, right2;
    			MyLetterHash leftHash2, rightHash2;

    			left2 = s2.substring(0, i);
    			right2 = s2.substring(i);
    			leftHash2 = new MyLetterHash(left2);
    			rightHash2 = new MyLetterHash(right2);
    			if(leftHash1.equals(leftHash2) && rightHash1.equals(rightHash2)){
    				if(isScramble(left1, left2) && isScramble(right1, right2)) return true;
    			}

    			left2 = s2.substring(len - i);
    			right2 = s2.substring(0, len - i);
    			leftHash2 = new MyLetterHash(left2);
    			rightHash2 = new MyLetterHash(right2);
    			if(leftHash1.equals(leftHash2) && rightHash1.equals(rightHash2)){
    				if(isScramble(left1, left2) && isScramble(right1, right2)) return true;
    			}
    		}
    	}
    	return false;
    }

	public static void main(String[] args){
		System.err.println(new Solution().isScramble("rgtae", "great"));
	}
}

Add java solution for 87. Scramble String

87. Scramble String: https://leetcode.com/problems/scramble-string/


/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.core.instrument;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

/**
 * Tests for {@link Meter}.
 *
 * @author Johnny Lim
 */
class MeterTest {

    @Test
    void matchWhenTimeGaugeShouldUseFunctionForTimeGauge() {
        String matched = Meter.Type.match(
                mock(TimeGauge.class),
                (gauge) -> "gauge",
                (counter) -> "counter",
                (timer) -> "timer",
                (distributionSummary) -> "distributionSummary",
                (longTaskTimer) -> "longTaskTimer",
                (timeGauge) -> "timeGauge",
                (functionCounter) -> "functionCounter",
                (functionTimer) -> "functionTimer",
                (meter) -> "meter");
        assertThat(matched).isEqualTo("timeGauge");
    }

    @Test
    void consumeWhenTimeGaugeShouldUseConsumerForTimeGauge() {
        StringBuilder consumed = new StringBuilder();
        Meter.Type.consume(
                mock(TimeGauge.class),
                (gauge) -> consumed.append("gauge"),
                (counter) -> consumed.append("counter"),
                (timer) -> consumed.append("timer"),
                (distributionSummary) -> consumed.append("distributionSummary"),
                (longTaskTimer) -> consumed.append("longTaskTimer"),
                (timeGauge) -> consumed.append("timeGauge"),
                (functionCounter) -> consumed.append("functionCounter"),
                (functionTimer) -> consumed.append("functionTimer"),
                (meter) -> consumed.append("meter"));
        assertThat(consumed.toString()).isEqualTo("timeGauge");
    }

}

Add tests for match() and consume() in Meter.Type


package com.jun.common.util;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by Jun on 2016/5/3.
 * 描述：保存到 SharedPreferences 的数据
 *
 * @author Jun
 * @version v0.1.4
 */
public class SharePreferencesUtil {

    private static final String TAG = "SharePreferencesHelper";

    private SharedPreferences mPreferences;

    private SharedPreferences.Editor mEditor;

    private static SharePreferencesUtil mSPHelper;

    public static SharePreferencesUtil getInstance(Context context) {
        if (mSPHelper == null)
            mSPHelper = new SharePreferencesUtil(context);

        return mSPHelper;
    }

    public SharePreferencesUtil(Context context) {
        mPreferences = context.getSharedPreferences(TAG, Context.MODE_APPEND);
    }

    public boolean putString(String key, String value) {
        mEditor = mPreferences.edit();
        mEditor.putString(key, value);
        return mEditor.commit();
    }

    public String getString(String key) {
        return mPreferences.getString(key, "");
    }

    public String getString(String key, String defValue) {
        return mPreferences.getString(key, defValue);
    }

    public boolean putInt(String key, int value) {
        mEditor = mPreferences.edit();
        mEditor.putInt(key, value);
        return mEditor.commit();
    }

    public int getInt(String key) {
        return mPreferences.getInt(key, 0);
    }

    public int getInt(String key, int defValue) {
        return mPreferences.getInt(key, defValue);
    }

    public boolean putBoolean(String key, boolean value) {
        mEditor = mPreferences.edit();
        mEditor.putBoolean(key, value);
        return mEditor.commit();
    }

    public boolean getBoolean(String key) {
        return mPreferences.getBoolean(key, false);
    }

    public boolean getBoolean(String key, boolean defVaule) {
        return mPreferences.getBoolean(key, defVaule);
    }

}

Add save data to SharePreferences util class


/*
 * Copyright 2010-2015 Allette Systems (Australia)
 * http://www.allette.com.au
 *
 * 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.pageseeder.diffx.algorithm;

import org.pageseeder.diffx.DiffXException;
import org.pageseeder.diffx.sequence.EventSequence;

import java.io.IOException;

/**
 * Test case for Guano Diff-X algorithm.
 *
 * @author Christophe Lauret
 * @version 0.9.0
 */
public final class GuanoAlgorithm2Test extends BaseAlgorithmTest {

  /**
   * Default constructor.
   *
   * @param name Name of the test.
   */
  public GuanoAlgorithm2Test(String name) {
    super(name);
  }

  public DiffXAlgorithm makeDiffX(EventSequence first, EventSequence second) {
    return new GuanoAlgorithm(first, second);
  }

  /**
   * @throws IOException    Should an I/O exception occur.
   * @throws DiffXException Should an error occur while parsing XML.
   */
  public final void testSticky() throws IOException, DiffXException {
    String xml1 = "a white cat";
    String xml2 = "a black hat";
    String exp1 = "$w{a}$s{ }+$w{white}$s{ }+$w{cat}-$w{black}$s{ }-$w{hat}";
    String exp2 = "$w{a}$s{ }+$w{black}$s{ }+$w{cat}-$w{white}$s{ }-$w{hat}";
    assertDiffXMLOK(xml1, xml2, exp1);
    assertDiffXMLOK(xml2, xml1, exp2);
  }

  /**
   * @throws IOException    Should an I/O exception occur.
   * @throws DiffXException Should an error occur while parsing XML.
   */
  public final void testList() throws IOException, DiffXException {
    String xml1 = "

blue

red

green

";
    String xml2 = "

black

red

green

";
    String exp1 = "

+$w{blue}-$w{black}

$w{red}

$w{green}

";
    String exp2 = "

+$w{black}-$w{blue}

$w{red}

$w{green}

";
    assertDiffXMLOK(xml1, xml2, exp1);
    assertDiffXMLOK(xml2, xml1, exp2);
  }

}

Add some tests for new algorithm

Add some tests for new algorithm


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

package com.dmdirc.addons.ui_swing.components;

import javax.swing.ComboBoxModel;

/**
 * Generic combo box model, extends generic list model.
 *
 * @param <T> Model holds this type of object
 */
public class GenericComboBoxModel<T> extends GenericListModel<T> implements
        ComboBoxModel {

    /**
     * A version number for this class. It should be changed whenever the class
     * structure is changed (or anything else that would prevent serialized
     * objects being unserialized with the new class).
     */
    private static final long serialVersionUID = 2;
    /** Selected Object. */
    private T selectedObject;

    /** {@inheritDoc} */
    @Override
    @SuppressWarnings("unchecked")
    public void setSelectedItem(final Object anItem) {
        if ((selectedObject != null && !selectedObject.equals(anItem)) || selectedObject
                == null && anItem != null) {
            selectedObject = (T) anItem;
            fireContentsChanged(this, -1, -1);
        }
    }

    /** {@inheritDoc} */
    @Override
    public T getSelectedItem() {
        return selectedObject;
    }
}

Add generic combo box model.

Add generic combo box model.

Fixes issue 4230

Change-Id: I30cf8d2b3cc7e67357dd42cf0b320e1097983fba
Reviewed-on: http://gerrit.dmdirc.com/1312
Automatic-Compile: DMDirc Local Commits <fd7610eb81751244add0a62da2de7da51cfdce47@googlemail.com>
Reviewed-by: Chris Smith <711c73f64afdce07b7e38039a96d2224209e9a6c@dmdirc.com>


/*
 * Copyright 2011 SURFnet bv, The Netherlands
 *
 * 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 nl.surfnet.coin.teams.util;

import nl.surfnet.coin.teams.domain.Member;
import nl.surfnet.coin.teams.domain.Role;
import nl.surfnet.coin.teams.domain.Team;
import nl.surfnet.coin.teams.service.TeamService;
import org.opensocial.models.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * This class includes methods that are often used by controllers
 */
@Component("controllerUtil")
public class ControllerUtil {

  @Autowired
  private TeamService teamService;

  private ControllerUtil() {
  }

  /**
   * Get the team from the {@link HttpServletRequest} request.
   *
   * @param request the {@link HttpServletRequest}
   * @return The {@link Team} team
   * @throws RuntimeException if the team cannot be found
   */
  public Team getTeam(HttpServletRequest request) {
    String teamId = request.getParameter("team");
    Team team = null;

    if (StringUtils.hasText(teamId)) {
      team = teamService.findTeamById(teamId);
    }
    if (team == null) {
      throw new RuntimeException("Team (" + teamId + ") not found");
    }
    return team;
  }

  /**
   * Checks if the current user has administrative privileges (whether he is admin OR manager) for a given team.
   *
   * @param person {@link Person}
   * @param teamId {@link String} the team Id for which the person's privileges are checked
   * @return {@link boolean} true/code> if the user is admin AND/OR manager false if the user isn't
   */
  public boolean hasUserAdministrativePrivileges(Person person, String teamId) {
    // Check if the requester is member of the team AND
    // Check if the requester has the role admin or manager, so he is allowed to invite new members.
    Member member = teamService.findMember(teamId, person.getId());
    return member != null && (member.getRoles().contains(Role.Admin) || member.getRoles().contains(Role.Manager));
  }
}

Add controllerUtil for common methods among controllers

git-svn-id: 7f9817d80667deac6042fd45474745cdc98fb3cd@1770 3364c4cd-9065-40b6-aee7-261f90ce6533


/**
 *
 */
package jetty.async.test;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Issues an async write with contentlength != bytes writte before
 *
 * @author Christoph Läubrich
 */
public class DispatchFromTimeoutServlet extends HttpServlet {

    /**
     *
     */
    private static final String TIMEOUT_ATTRIBUTE = "Timeout";
    private static final long   serialVersionUID  = 3431896464670815605L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object timeoutMarker = req.getAttribute(TIMEOUT_ATTRIBUTE);
        System.out.println("Request: " + req.getRequestURI() + " Timeout: " + timeoutMarker + " Thread: " + Thread.currentThread().getName());
        if (timeoutMarker == null) {
            final AsyncContext async = req.startAsync();
            async.setTimeout(TimeUnit.SECONDS.toMillis(5));
            async.addListener(new DebugAsyncListener() {
                @Override
                public void onTimeout(javax.servlet.AsyncEvent event) throws IOException {
                    System.out.println("Timeout occured in Listener @ Thread: " + Thread.currentThread().getName());
                    event.getAsyncContext().getRequest().setAttribute(TIMEOUT_ATTRIBUTE, true);
                    event.getAsyncContext().dispatch();
                };
            });
        } else {
            System.out.println("Timeout occured in Thread: " + Thread.currentThread().getName());
        }
    }
}

Add Servlet for dispatch test

Add Servlet for dispatch test


package com.cdrussell.caster.rx.casterrxjava;

import android.os.SystemClock;
import android.util.Log;

class Database {

    private static final String TAG = Database.class.getSimpleName();

    static String readValue() {
        SystemClock.sleep(50);

        for (int i = 0; i < 100; i++) {
            Log.i(TAG, String.format("Reading value: %d%%", i));
            SystemClock.sleep(20);
        }
        Log.i(TAG, "Reading value: 100%");
        return "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.";
    }
}

Add fake database read call

Add fake database read call


package info.novatec.tr.config;

import org.flywaydb.core.Flyway;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.stereotype.Component;

@Component
public class FlywayConfig implements FlywayMigrationStrategy {
    @Override
    public void migrate(Flyway flyway) {
        flyway.setBaselineOnMigrate(true);
        flyway.migrate();
    }
}

BPT-162: Configure flyway to create schema even though tables already exist.


package lemming.api.ui;

import org.apache.wicket.markup.html.form.TextField;

/**
 * A non-trimming text field.
 */
public class NonTrimmingTextField extends TextField<String> {

    /**
     * Creates a non-trimming text field.
     *
     * @param id id of a text field
     */
    public NonTrimmingTextField(String id) {
        super(id);
    }

    /**
     * Determines whether or not this component should trim its input prior to processing it.
     *
     * @return True if the input should be trimmed.
     */
    @Override
    protected boolean shouldTrimInput() {
        return false;
    }
}

Add a text field which doesn’t trim content by default.


package com.sunny.grokkingalgorithms.fasttrack.week6;

import java.util.Stack;

/**
 * Created by sundas on 7/26/2018.
 */
public class StackSorter {

  /*
  Given a stack sort it in ascending order.
   */

  /**
   *
   * @param stack
   */
  public static Stack<Integer> stackSorter(Stack<Integer> stack){

    //System.out.println(stack);
    Stack<Integer> aux = new Stack<>();
    while(!stack.isEmpty()){
      int data = stack.peek();
      if(aux.isEmpty()){
        aux.push(data);
        stack.pop();
      }
      else{
        while(!aux.isEmpty()
            && data < aux.peek()){
          stack.push(aux.pop());
        }
        /*
        Found place
         */
        aux.push(data);
        while(!stack.isEmpty()
            && stack.peek() != data){
          aux.push(stack.pop());
        }
        stack.pop();
      }
    }
    while(!aux.isEmpty()){
      stack.push(aux.pop());
    }
    //System.out.println(stack);
    return stack;
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    int[] input = new int[]{5,1,4,2,3,10,0};
    //int[] input = new int[]{0,1};
    Stack<Integer> stack = new Stack<>();
    for(int i : input){
      stack.push(i);
    }
    System.out.println(stack);
    stackSorter(stack);
    while (!stack.isEmpty()){
      System.out.println(stack.pop());
    }
    //stackSorter(input);
  }

}

Sort a stack using auxillary stack.

Sort a stack using auxillary stack.


package org.cyclops.cyclopscore.command.argument;

import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.command.CommandSource;
import net.minecraft.command.ISuggestionProvider;
import net.minecraft.util.text.StringTextComponent;

import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * An argument type for a certain enum.
 * @author rubensworks
 */
public class ArgumentTypeEnum<T extends Enum<T>> implements ArgumentType<T> {

    private final Class<T> enumClass;

    public ArgumentTypeEnum(Class<T> enumClass) {
        this.enumClass = enumClass;
    }

    @Override
    public T parse(StringReader reader) throws CommandSyntaxException {
        try {
            return Enum.valueOf(this.enumClass, reader.readString().toUpperCase(Locale.ENGLISH));
        } catch (IllegalArgumentException e) {
            throw new SimpleCommandExceptionType(new StringTextComponent("Unknown value")).create();
        }
    }

    @Override
    public Collection<String> getExamples() {
        return Arrays.stream(this.enumClass.getEnumConstants())
                .map(Enum::name)
                .map(name -> name.toLowerCase(Locale.ENGLISH))
                .collect(Collectors.toList());
    }

    @Override
    public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
        return ISuggestionProvider.suggest(getExamples(), builder);
    }

    public static <T extends Enum<T>> T getValue(CommandContext<CommandSource> context, String name, Class<T> enumClass) {
        return context.getArgument(name, enumClass);
    }

}

Add enum argument type for commands

Add enum argument type for commands


package org.jdesktop.beans.editors;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * A demo program to showcase {@link PaintPicker}.
 *
 * @author Karl Schaefer
 */
@SuppressWarnings("all")
public class PaintPickerDemo extends JFrame {
    /**
     * {@inheritDoc}
     */
    @Override
    protected void frameInit() {
        super.frameInit();

        setTitle("PaintPicker Demo");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new PaintPicker());

        pack();
    }

    /**
     * Demo entry point.
     *
     * @param args
     *            unused
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new PaintPickerDemo().setVisible(true);
            }
        });
    }
}

Add demo for paint picker.

Add demo for paint picker.


import java.util.Scanner;

/**
 * This program creates an array of unique, inputted integers.
 **/
public class Array_Distinct_Insert {
    public static void main(String[] args) {
        System.out.println("Input array size");
        Scanner m = new Scanner(System.in);

        int size = m.nextInt();
        int length = 0;

        int a[] = new int[size];

        while (length < size) {
            System.out.println("Input value");
            int input = m.nextInt();

            int count = 0;

            // Check for duplicates before adding to the array
            for (int i = 0; i < size; i++) {
                if (a[i] == input) {
                    count++;
                }
            }

            // If there are no duplicates...
            if (count == 0) {
                a[length] = input;
                length++;
                System.out.print("Array: ");
                for (int i = 0; i < length; i++) {
                    System.out.print(a[i] + " ");
                }
                System.out.println();
            } else {
                System.out.println(input + " is already a value in the array");
            }
        }
    }
}

Add problem 6 to unit 2

Add problem 6 to unit 2


/**
 * Copyright 2009 Joe LaPenna
 */

package com.joelapenna.foursquared.test;

import android.test.suitebuilder.TestSuiteBuilder;

import junit.framework.Test;
import junit.framework.TestSuite;

/**
 * @author Joe LaPenna (joe@joelapenna.com)
 */
public class AllTests extends TestSuite {

    public static Test suite() {
        return new TestSuiteBuilder(AllTests.class).includeAllPackagesUnderHere().build();
    }

}

Create a test suite for testing.

Create a test suite for testing.

committer: Joe LaPenna <16a9a54ddf4259952e3c118c763138e83693d7fd@joelapenna.com>


/*
 * (C) Copyright 2020 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;

import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Isolated;
import org.slf4j.Logger;

@Isolated
class IsolatedTest {

    static final Logger log = getLogger(lookup().lookupClass());

    @Test
    void test01() {
        log.debug("IsolatedTest 1.1");
        log.debug("IsolatedTest 1.2");
    }

    @Test
    void test02() {
        log.debug("IsolatedTest 2.1");
        log.debug("IsolatedTest 2.2");
    }

    @Test
    void test03() {
        log.debug("IsolatedTest 3.1");
        log.debug("IsolatedTest 3.2");
    }
}

Include @Isolated test in junit5-parallel-execution project


/*
 * Copyright 2016 Philip Cohn-Cort
 *
 * 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.fuzz.indicator.text;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.fuzz.indicator.CutoutViewIndicator;
import com.fuzz.indicator.CutoutViewLayoutParams;
import com.fuzz.indicator.LayeredView;
import com.fuzz.indicator.LayeredViewGenerator;

/**
 * This generator is intended to animate stuff on TextViews
 *
 * @author Philip Cohn-Cort (Fuzz)
 */
public abstract class TextViewGenerator implements LayeredViewGenerator {
    @NonNull
    @Override
    public LayeredView createCellFor(@NonNull ViewGroup parent, int position) {
        CutoutViewLayoutParams lp = ((CutoutViewIndicator) parent).generateDefaultLayoutParams();

        TextView child = new TextView(parent.getContext());
        child.setText(getTextFor(parent.getContext(), position));
        child.setLayoutParams(lp);

        return new LayeredTextViewHolder(child);
    }

    @NonNull
    protected abstract Spannable getTextFor(@NonNull Context context, int position);

    @Override
    public void onBindChild(@NonNull View child, @NonNull CutoutViewLayoutParams lp) {
        child.setBackgroundResource(lp.cellBackgroundId);
    }
}

Add a new generator for encapsulating the basic TextView stuff


package arez.windowsize.util;

import elemental2.dom.Event;
import elemental2.dom.EventListener;
import elemental2.dom.EventTarget;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public final class TestEventTarget
  implements EventTarget
{
  private final Map<String, ArrayList<EventListener>> _listeners = new HashMap<>();

  @Override
  public void addEventListener( final String type,
                                final EventListener listener,
                                final AddEventListenerOptionsUnionType options )
  {
    throw new UnsupportedOperationException();
  }

  @Override
  public void addEventListener( final String type, final EventListener listener )
  {
    getEventListenersByType( type ).add( listener );
  }

  @Override
  public boolean dispatchEvent( final Event evt )
  {
    throw new UnsupportedOperationException();
  }

  @Override
  public void removeEventListener( final String type,
                                   final EventListener listener,
                                   final RemoveEventListenerOptionsUnionType options )
  {
    throw new UnsupportedOperationException();
  }

  @Override
  public void removeEventListener( final String type, final EventListener listener )
  {
    getEventListenersByType( type ).remove( listener );
  }

  public ArrayList<EventListener> getEventListenersByType( final String type )
  {
    return _listeners.computeIfAbsent( type, t -> new ArrayList<>() );
  }
}

Add test double for EventTarget

Add test double for EventTarget


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

/* $Id$ */
package org.apache.fop.pdf;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.io.ByteArrayOutputStream;
import java.io.File;

import javax.xml.transform.stream.StreamResult;

import org.junit.Test;

import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.fonts.FontInfo;
import org.apache.fop.render.intermediate.IFContext;
import org.apache.fop.render.intermediate.IFException;
import org.apache.fop.render.intermediate.extensions.Link;
import org.apache.fop.render.intermediate.extensions.URIAction;
import org.apache.fop.render.pdf.PDFDocumentHandler;
import org.apache.fop.render.pdf.extensions.PDFEmbeddedFileAttachment;

import junit.framework.Assert;

public class PDFAttachmentTestCase {
    private FOUserAgent ua = FopFactory.newInstance(new File(".").toURI()).newFOUserAgent();

    @Test
    public void testAddEmbeddedFile() throws IFException {
        PDFDocumentHandler docHandler = new PDFDocumentHandler(new IFContext(ua));
        docHandler.setFontInfo(new FontInfo());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        docHandler.setResult(new StreamResult(out));
        docHandler.startDocument();
        docHandler.startPage(0, "", "", new Dimension());
        docHandler.handleExtensionObject(new PDFEmbeddedFileAttachment("filename", "src", "desc"));
        docHandler.getDocumentNavigationHandler().renderLink(new Link(
                new URIAction("embedded-file:filename", false), new Rectangle()));
        docHandler.endDocument();
        Assert.assertTrue(out.toString().contains("<<\n  /Type /Filespec\n  /F (filename)"));
        Assert.assertTrue(out.toString().contains("<<\n/S /JavaScript\n"
                + "/JS (this.exportDataObject({cName:\"filename\", nLaunch:2});)\n>>"));
    }
}

Add test for PDF Attachment

Add test for PDF Attachment

git-svn-id: 102839466c3b40dd9c7e25c0a1a6d26afc40150a@1726835 13f79535-47bb-0310-9956-ffa450edef68


package edu.chl.proton.model;

/**
 * Anton Levholm
 * Created by antonlevholm on 2017-05-02.
 */
public enum DocumentType {
    MARKDOWN, PLAIN
}

Add Enum for document type

Add Enum for document type


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

package com.hp.autonomy.iod.client.converter;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Marks a type as something that should not be converted when used as a {@link retrofit.http.Part}
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DoNotConvert {
}

Add an annotation indicating that a type should not be converted when serialized for sending to IDOL OnDemand.


package org.realityforge.arez.browser.extras;

final class JsObjects
{
  static native <T> T get( Object object, String propertyName ) /*-{
    return object[ propertyName ];
  }-*/;

  static native void set( Object object, String propertyName, Object value ) /*-{
    object[ propertyName ] = value;
  }-*/;

  private JsObjects()
  {
  }
}

Add helper to get and set properties

Add helper to get and set properties


package com.mooo.aimmac23.hub.videostorage;

import java.io.IOException;
import java.io.InputStream;

public interface StoredVideoDownloadContext {

	/**
	 * Was the requested video found?
	 *
	 * @return
	 */
	boolean isVideoFound();

	/**
	 * If the video was found, return an Input stream for the content, or null otherwise.
	 *
	 * @return
	 */
	InputStream getStream() throws IOException;

	/**
	 *
	 * @return the content length in bytes of the video, or null if we are using a storage
	 * mechanism that doesn't tell us this.
	 */
	Long getContentLengthIfKnown();

	/**
	 * Frees any resources allocated to this storage request. Should always be called, even
	 * if the video is not found.
	 *
	 */
	void close();

}

Refactor the video download functionality to be more flexible, and better at cleaning up things


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2012, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This 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 software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package io.undertow.server;

import java.io.IOException;

/**
 * An exception indicating that the response channel was prematurely closed.  The response channel must be shut
 * down and flushed successfully after all requests, even those which do not send a response body.
 *
 * @author David M. Lloyd
 */
public class TruncatedResponseException extends IOException {

    /**
     * Constructs a {@code TruncatedResponseException} with no detail message. The cause is not initialized, and may
     * subsequently be initialized by a call to {@link #initCause(Throwable) initCause}.
     */
    public TruncatedResponseException() {
    }

    /**
     * Constructs a {@code TruncatedResponseException} with the specified detail message. The cause is not initialized,
     * and may subsequently be initialized by a call to {@link #initCause(Throwable) initCause}.
     *
     * @param msg the detail message
     */
    public TruncatedResponseException(final String msg) {
        super(msg);
    }

    /**
     * Constructs a {@code TruncatedResponseException} with the specified cause. The detail message is set to:
     *
(cause == null ? null : cause.toString())

     * (which typically contains the class and detail message of {@code cause}).
     *
     * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method)
     */
    public TruncatedResponseException(final Throwable cause) {
        super(cause);
    }

    /**
     * Constructs a {@code TruncatedResponseException} with the specified detail message and cause.
     *
     * @param msg the detail message
     * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method)
     */
    public TruncatedResponseException(final String msg, final Throwable cause) {
        super(msg, cause);
    }
}

Add exception type for truncated response


package uk.ac.ebi.phenotype.web.util;

import io.github.bucket4j.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class PerClientRateLimitInterceptor implements HandlerInterceptor {

    private final Logger log = LoggerFactory.getLogger(this.getClass().getCanonicalName());

    // Cache the most recent 50 hosts and apply rate limiting
    public static final int MAX_SIZE = 50;

    // MAX number of gene page requests from one host in a minute
    public static final long MAX_GENE_PAGE_REQUESTS = 10;

    // MIN number of seconds between gene page requests from one host
    public static final long DELAY_GENE_PAGE_REQUESTS = 2;

    private final Map<String, Bucket> buckets =  Collections.synchronizedMap(new LinkedHashMap<String, Bucket>(MAX_SIZE+1, .75F, true) {
        // This method is called just after a new entry has been added
        public boolean removeEldestEntry(Map.Entry eldest) {
            return size() > MAX_SIZE;
        }
    });

    /**
     * Rate limit the requests to one every 3 seconds and no more than 1 per second
     */
    private static Bucket rateLimitBucket() {
        return Bucket4j.builder()
                .addLimit(
                        Bandwidth.classic(MAX_GENE_PAGE_REQUESTS,
                            Refill.greedy(MAX_GENE_PAGE_REQUESTS, Duration.ofMinutes(1)))
                        .withInitialTokens(MAX_GENE_PAGE_REQUESTS))
                .addLimit(Bandwidth.classic(1,
                            Refill.greedy(1, Duration.ofSeconds(DELAY_GENE_PAGE_REQUESTS))))
                .build();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        log.debug("Buckets: " + String.join(", ", this.buckets.keySet()));
        String xForwarded = request.getHeader("x-forwarded-host");
        String host = StringUtils.isNotEmpty(xForwarded) ? xForwarded : request.getHeader("host");
        Bucket requestBucket = this.buckets.computeIfAbsent(host, key -> rateLimitBucket());

        log.debug("Using host: " + host + " With bucket: " + requestBucket);

        ConsumptionProbe probe = requestBucket.tryConsumeAndReturnRemaining(1);
        if (probe.isConsumed()) {
            response.addHeader("X-Rate-Limit-Remaining",
                    Long.toString(probe.getRemainingTokens()));
            return true;
        }

        response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); // 429
        response.addHeader("X-Rate-Limit-Retry-After-Milliseconds",
                Long.toString(TimeUnit.NANOSECONDS.toMillis(probe.getNanosToWaitForRefill())));

        return false;
    }

}

Reduce delay of gene page requests

Reduce delay of gene page requests