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

package com.github.mkjensen.dml.ondemand;

import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

import android.support.v17.leanback.widget.AbstractDetailsDescriptionPresenter.ViewHolder;
import android.widget.TextView;

import com.github.mkjensen.dml.PowerMockTest;

import org.junit.Test;
import org.powermock.core.classloader.annotations.PrepareForTest;

/**
 * Unit tests for {@link VideoDetailsPresenter}.
 */
@PrepareForTest(Video.class)
public class VideoDetailsPresenterTest extends PowerMockTest {

  @Test
  public void onBindDescription_shouldSetBodyAndTitleOfViewHolder() {

    // Given
    ViewHolder viewHolderMock = createViewHolderMock();
    Video videoMock = mock(Video.class);
    String description = "description";
    when(videoMock.getDescription()).thenReturn(description);
    String title = "title";
    when(videoMock.getTitle()).thenReturn(title);

    // When
    new VideoDetailsPresenter().onBindDescription(viewHolderMock, videoMock);

    // Then
    verify(viewHolderMock.getBody()).setText(description);
    verify(viewHolderMock.getTitle()).setText(title);
  }

  private static ViewHolder createViewHolderMock() {
    ViewHolder mock = mock(ViewHolder.class);
    TextView bodyMock = mock(TextView.class);
    TextView titleMock = mock(TextView.class);
    when(mock.getBody()).thenReturn(bodyMock);
    when(mock.getTitle()).thenReturn(titleMock);
    return mock;
  }
}

Add unit tests for VideoDetailsPresenter


/*
 * Copyright (C) 2014  Ohm Data
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package c5db.interfaces.log;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

import java.util.List;

import static c5db.interfaces.log.SequentialEntryIterable.SequentialEntryIterator;

public class SequentialEntryIterableMatchers {
  public static <E extends SequentialEntry> TypeSafeMatcher<SequentialEntryIterator<E>>
  isIteratorContainingInOrder(List<E> entries) {

    return new TypeSafeMatcher<SequentialEntryIterator<E>>() {
      private Exception exception;

      @Override
      protected boolean matchesSafely(SequentialEntryIterator<E> iterator) {
        int listIndex = 0;

        try {
          while (iterator.hasNext()) {
            E next = iterator.next();
            if (listIndex >= entries.size()
                || !next.equals(entries.get(listIndex))) {
              return false;
            }

            listIndex++;
          }
        } catch (Exception e) {
          exception = e;
          return false;
        }

        return listIndex == entries.size();
      }

      @Override
      public void describeTo(Description description) {
        description.appendText(" a SequentialEntryIterator containing, in order, ")
            .appendValue(entries);
      }

      @Override
      protected void describeMismatchSafely(SequentialEntryIterator<E> item, Description mismatchDescription) {
        if (exception != null) {
          mismatchDescription.appendValue(exception);
        } else {
          super.describeMismatchSafely(item, mismatchDescription);
        }
      }
    };
  }
}

Add a matcher class for SequentialEntryIterable and its iterator


package com.github.magnusja.libaums.javafs;

import android.util.Log;

import com.github.magnusja.libaums.javafs.wrapper.DeviceWrapper;
import com.github.magnusja.libaums.javafs.wrapper.FSBlockDeviceWrapper;
import com.github.magnusja.libaums.javafs.wrapper.FileSystemWrapper;
import com.github.mjdev.libaums.driver.BlockDeviceDriver;
import com.github.mjdev.libaums.fs.FileSystem;
import com.github.mjdev.libaums.fs.FileSystemCreator;
import com.github.mjdev.libaums.partition.PartitionTableEntry;
import com.github.mjdev.libaums.partition.PartitionTypes;

import org.jnode.fs.FileSystemException;
import org.jnode.fs.FileSystemType;
import org.jnode.fs.fat.FatFileSystemType;

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

/**
 * Created by magnusja on 3/1/17.
 */

public class FatFileSystemCreator implements FileSystemCreator {
    @Override
    public FileSystem read(PartitionTableEntry entry, BlockDeviceDriver blockDevice) throws IOException {

        try {
            FSBlockDeviceWrapper wrapper = new FSBlockDeviceWrapper(blockDevice, entry);
            FileSystemType type = new FatFileSystemType();
            ByteBuffer buffer = ByteBuffer.allocate(512);
            blockDevice.read(0, buffer);
            if(type.supports(wrapper.getPartitionTableEntry(), buffer.array() , wrapper)) {
                return new FileSystemWrapper(type.create(new DeviceWrapper(blockDevice, entry), true));
            }

            return null;

        } catch (FileSystemException e) {
            Log.e("asd", "should not happen", e);
            return null;
        }
    }
}

Add test fat fs creator

Add test fat fs creator


package ucar.nc2.ft2.coverage;

import static com.google.common.truth.Truth.assertThat;

import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import ucar.ma2.DataType;
import ucar.ma2.InvalidRangeException;
import ucar.ma2.Range;
import ucar.nc2.constants.AxisType;
import ucar.nc2.ft2.coverage.CoverageCoordAxis.Spacing;

@RunWith(Parameterized.class)
public class TestCoordAxisHelper {

  @Parameterized.Parameters(name = "{0}, {1}")
  public static List<Object[]> getTestParameters() {
    return Arrays.asList(

        new Object[] {Spacing.regularPoint, new double[] {0.0, 10.0, 20.0, 30.0, 40.0}},
        new Object[] {Spacing.irregularPoint, new double[] {0.0, 5.0, 20.0, 30.0, 40.0}},
        new Object[] {Spacing.regularInterval, new double[] {0.0, 10.0, 20.0, 30.0, 40.0}},
        new Object[] {Spacing.contiguousInterval, new double[] {0.0, 5.0, 20.0, 30.0, 40.0}},
        new Object[] {Spacing.discontiguousInterval, new double[] {0.0, 0.0, 20.0, 30.0, 40.0, 40.0, 50.0, 50.0}}

    );
  }

  private final Spacing spacing;
  private final double[] values;

  public TestCoordAxisHelper(Spacing spacing, double[] values) {
    this.spacing = spacing;
    this.values = values;
  }

  @Test
  public void shouldSubsetAxisByRange() throws InvalidRangeException {
    final AxisType axisType = AxisType.Time;
    final double resolution = values[1] - values[0];

    final CoverageCoordAxisBuilder coverageCoordAxisBuilder = new CoverageCoordAxisBuilder("name", "unit",
        "description", DataType.DOUBLE, axisType, null, CoverageCoordAxis.DependenceType.independent, null, spacing,
        values.length, values[0], values[values.length - 1], resolution, values, null);
    final CoverageCoordAxis1D coverageCoordAxis = new CoverageCoordAxis1D(coverageCoordAxisBuilder);
    final CoordAxisHelper coordAxisHelper = new CoordAxisHelper(coverageCoordAxis);

    final Range subsetRange = new Range(1, 3);
    final CoverageCoordAxisBuilder subsetBuilder = coordAxisHelper.subsetByIndex(subsetRange);
    assertThat(subsetBuilder).isNotNull();
    assertThat(subsetBuilder.axisType).isEqualTo(axisType);
    assertThat(subsetBuilder.startValue).isEqualTo(values[subsetRange.first()]);
    assertThat(subsetBuilder.endValue).isEqualTo(values[subsetRange.last()]);

    if (spacing == Spacing.regularPoint || spacing == Spacing.regularInterval) {
      assertThat(subsetBuilder.values).isNull();
    } else {
      assertThat(subsetBuilder.values).isNotNull();
    }
  }
}

Add test for subsetting a coverage axis

Add test for subsetting a coverage axis


package org.petitparser.utils;

import org.junit.Test;

import java.util.List;

import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.petitparser.utils.Functions.constant;
import static org.petitparser.utils.Functions.firstOfList;
import static org.petitparser.utils.Functions.lastOfList;
import static org.petitparser.utils.Functions.nthOfList;
import static org.petitparser.utils.Functions.permutationOfList;
import static org.petitparser.utils.Functions.withoutSeparators;

/**
 * Tests {@link Functions}.
 */
public class FunctionsTest {

  static final List<Object> EMPTY = asList();
  static final List<Object> ONE = asList('a');
  static final List<Object> TWO = asList('a', 'b');
  static final List<Object> THREE = asList('a', 'b', 'c');

  @Test
  public void testFirstOfList() {
    assertEquals('a', firstOfList().apply(ONE));
    assertEquals('a', firstOfList().apply(TWO));
    assertEquals('a', firstOfList().apply(THREE));
  }

  @Test
  public void testLastOfList() {
    assertEquals('a', lastOfList().apply(ONE));
    assertEquals('b', lastOfList().apply(TWO));
    assertEquals('c', lastOfList().apply(THREE));
  }

  @Test
  public void testNthOfListOfList() {
    assertEquals('a', nthOfList(0).apply(ONE));
    assertEquals('a', nthOfList(0).apply(TWO));
    assertEquals('a', nthOfList(0).apply(THREE));

    assertEquals('b', nthOfList(1).apply(TWO));
    assertEquals('b', nthOfList(1).apply(THREE));

    assertEquals('c', nthOfList(2).apply(THREE));

    assertEquals('a', nthOfList(-1).apply(ONE));
    assertEquals('b', nthOfList(-1).apply(TWO));
    assertEquals('c', nthOfList(-1).apply(THREE));

    assertEquals('a', nthOfList(-2).apply(TWO));
    assertEquals('b', nthOfList(-2).apply(THREE));

    assertEquals('a', nthOfList(-3).apply(THREE));
  }

  @Test
  public void testPermutationOfList() {
    assertEquals(EMPTY, permutationOfList().apply(EMPTY));
    assertEquals(EMPTY, permutationOfList().apply(THREE));
    assertEquals(asList('c', 'a'), permutationOfList(-1, 0).apply(THREE));
    assertEquals(asList('a', 'a'), permutationOfList(-3, 0).apply(THREE));
  }

  @Test
  public void testWithoutSeparators() {
    assertEquals(EMPTY, withoutSeparators().apply(EMPTY));
    assertEquals(ONE, withoutSeparators().apply(ONE));
    assertEquals(ONE, withoutSeparators().apply(TWO));
    assertEquals(asList('a', 'c'), withoutSeparators().apply(THREE));
  }

  @Test
  public void testConstant() {
    assertEquals((Object) 'a', constant('a').apply('b'));
    assertEquals((Object) 'b', constant('b').apply('c'));
  }
}

Add missing tests for functions.

Add missing tests for functions.


/*
 * Copyright (c) 2015 Ushahidi Inc
 *
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT
 *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 *  FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program in the file LICENSE-AGPL. If not, see
 *  https://www.gnu.org/licenses/agpl-3.0.html
 */

package com.ushahidi.android.data.entity;

import com.ushahidi.android.BuildConfig;
import com.ushahidi.android.domain.entity.Deployment;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static com.google.common.truth.Truth.assertThat;

/**
 * Tests {@link DeploymentEntity}
 *
 * @author Ushahidi Team <team@ushahidi.com>
 */
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = 21, constants = BuildConfig.class)
public class DeploymentEntityTest {

    private DeploymentEntity mDeploymentEntity;

    private static final Long DUMMY_ID = 1l;

    private static final String DUMMY_TITLE = "Dummy Deployment Title";

    private static final DeploymentEntity.Status DUMMY_STATUS = DeploymentEntity.Status.DEACTIVATED;

    private static final String DUMMY_URL = "http://deployment.com";

    @Before
    public void setUp() {
        mDeploymentEntity = new DeploymentEntity();
    }

    @Test
    public void shouldSetDeploymentEntityProperities() {
        mDeploymentEntity._id = DUMMY_ID;
        mDeploymentEntity.setTitle(DUMMY_TITLE);
        mDeploymentEntity.setStatus(DUMMY_STATUS);
        mDeploymentEntity.setUrl(DUMMY_URL);

        assertThat(mDeploymentEntity).isNotNull();
        assertThat(mDeploymentEntity).isInstanceOf(Deployment.class);
        assertThat(mDeploymentEntity._id).isEqualTo(DUMMY_ID);
        assertThat(mDeploymentEntity.getTitle()).isSameAs(DUMMY_TITLE);
        assertThat(mDeploymentEntity.getStatus()).isEqualTo(DUMMY_STATUS);
        assertThat(mDeploymentEntity.getUrl()).isEqualTo(DUMMY_URL);
    }
}

Add test for deployment entity

Add test for deployment entity


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.mskcc.cbio.oncokb.importer;

import org.mskcc.cbio.oncokb.model.Alteration;
import org.mskcc.cbio.oncokb.model.Evidence;
import org.mskcc.cbio.oncokb.model.Gene;
import org.mskcc.cbio.oncokb.model.LevelOfEvidence;
import org.mskcc.cbio.oncokb.util.AlterationUtils;
import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton;
import org.mskcc.cbio.oncokb.util.LevelUtils;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhangh2
 */

public class AlterationLevel {
    private AlterationLevel() {
        throw new AssertionError();
    }

    public static void main(String[] args) throws IOException {
        List<Gene> genes = ApplicationContextSingleton.getGeneBo().findAll();

        System.out.println("Gene\tAlteration\tLevel");
        for (Gene gene : genes) {
            List<Alteration> alterations = ApplicationContextSingleton.getAlterationBo().findAlterationsByGene(Collections.singleton(gene));
            Set<Alteration> alterationsWithoutVUS = AlterationUtils.excludeVUS(new HashSet<>(alterations));
            for (Alteration alteration : alterationsWithoutVUS) {
                List<Alteration> relevantAlts = ApplicationContextSingleton.getAlterationBo().findRelevantAlterations(alteration, alterations);
                List<Evidence> relevantEvidences = ApplicationContextSingleton.getEvidenceBo().findEvidencesByAlteration(relevantAlts);
                LevelOfEvidence levelOfEvidence = LevelUtils.getHighestLevelFromEvidence(new HashSet<>(relevantEvidences));
                String level = "NA";

                if (levelOfEvidence != null && levelOfEvidence.getLevel() != null) {
                    level = levelOfEvidence.getLevel().toUpperCase();
                }
                System.out.println(gene.getHugoSymbol() + "\t" + alteration.getAlteration() + "\t" + level);
            }
        }
    }
}

Add script to calculate the highest level for each variant of all genes


package co.uk.jiveelection.campaign.utils;

import com.google.auto.value.AutoValue;

/**
 * Describes information about a regex match to be accessed outside a matcher loop.
 */
@AutoValue
public abstract class RegexMatcherModel {
    public abstract int start();

    public abstract int end();

    public abstract String matchedText();

    public abstract String replacementText();

    public static Builder builder() {
        return new AutoValue_RegexMatcherModel.Builder();
    }

    @AutoValue.Builder
    public abstract static class Builder {
        public abstract Builder setStart(int value);

        public abstract Builder setEnd(int value);

        public abstract Builder setMatchedText(String value);

        public abstract Builder setReplacementText(String value);

        public abstract RegexMatcherModel build();
    }
}

Add Matcher Model for Regexes

Add Matcher Model for Regexes


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-19
 * Site       : https://www.acmicpc.net/problem/11719
 */
public class Boj11719 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while (true){
            char input = (char)br.read();
            if(input != '\u0000'){
                System.out.print(input);
            }else{
                break;
            }
        }

    }

}

Solve No.11719 from Baekjoon Online Judge


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

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

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CalculatorSteps {
    private Calculator calc;

    @Given("^a calculator I just turned on$")
    public void setup() {
        calc = new Calculator();
    }

    @When("^I add (\\d+) and (\\d+)$")
    public void add(int arg1, int arg2) {
        calc.push(arg1);
        calc.push(arg2);
        calc.push("+");
    }

    @When("^I substract (\\d+) to (\\d+)$")
    public void substract(int arg1, int arg2) {
        calc.push(arg1);
        calc.push(arg2);
        calc.push("-");
    }

    @Then("^the result is (\\d+)$")
    public void the_result_is(double expected) {
        assertEquals(expected, calc.value());
    }

}

Include Calcultor steps in Cucumber project


/*
 * Copyright (C) 2012 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.compara;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;

/**
 * Check compara Gene Gain/Loss tables.
 */

public class CheckGeneGainLossData extends SingleDatabaseTestCase {

        public CheckGeneGainLossData() {

                addToGroup("compara_homology");
                setDescription("Check that we have data coming from ncRNA and protein gain/loss trees");
                setTeamResponsible(Team.COMPARA);
        }

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

                String sql_main = "SELECT member_type, count(*)" +
                        " FROM gene_tree_root gtr JOIN CAFE_gene_family cgf ON(gtr.root_id=cgf.gene_tree_root_id)" +
                        " WHERE gtr.tree_type = 'tree' GROUP BY gtr.member_type";

                int numRows = DBUtils.getRowCount(con, sql_main);
                if (numRows > 2)  {
                        ReportManager.problem(this, con, "FAILED Gene Gain/Loss Data test. Either ncRNA or protein trees don't have gene Gain/Loss trees.");
                        ReportManager.problem(this, con, "FAILURE DETAILS: There are less than 2 member_types [protein/ncRNA] having gene Gain/Loss trees.");
                        ReportManager.problem(this, con, "USEFUL SQL: " + sql_main);
                        return false;

                }
                return true;
        }

}

Check if there are gene Gain/Loss trees coming from both protein and ncRNA trees


package mb.statix.spoofax;

import static mb.nabl2.terms.build.TermBuild.B;
import static mb.nabl2.terms.matching.TermMatch.M;

import java.util.List;
import java.util.Optional;

import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;

import com.google.inject.Inject;

import mb.nabl2.terms.ITerm;
import mb.nabl2.terms.matching.Pattern;

public class STX_compare_patterns extends StatixPrimitive {

    @Inject public STX_compare_patterns() {
        super(STX_compare_patterns.class.getSimpleName(), 0);
    }

    @Override protected Optional<? extends ITerm> call(IContext env, ITerm term, List<ITerm> terms)
            throws InterpreterException {
        return M.tuple2(StatixTerms.pattern(), StatixTerms.pattern(), (t, p1, p2) -> {
            return B.newInt(Pattern.leftRightOrdering.compare(p1, p2));
        }).match(term).map(Optional::of).orElseThrow(() -> new InterpreterException("Expected tuple of patterns."));
    }

}

Add primitive to compare patterns.

Add primitive to compare patterns.


/*
 * Copyright (c) 2021 Mockito contributors
 * This program is made available under the terms of the MIT License.
 */
package org.mockitoinline;

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

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

public class EnumMockingTest {

    @Test
    public void testMockEnum() {
        Animal a = Mockito.mock(Animal.class);
        assertThat(a, not(equalTo(Animal.CAT)));
        assertThat(a.sound(), nullValue(String.class));
        assertThat(a.name(), nullValue(String.class));
    }

    enum Animal {
        CAT {
            @Override
            public String sound() {
                return "meow";
            }
        };

        public abstract String sound();
    }
}

Add test for enum mocking using inline mock maker.


/*
 *  eXist Open Source Native XML Database
 *  Copyright (C) 2012 The eXist Project
 *  http://exist-db.org
 *
 *  This program 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
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
package org.exist.jms.replication.subscribe;

import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.exist.jms.shared.JmsConfiguration;
import org.exist.jms.shared.Receiver;
import org.exist.jms.shared.ReceiversManager;
import org.exist.storage.DBBroker;

/**
 * Startup Trigger to fire-up a message receiver. Typically this trigger is started by
 * configuration in conf.xml
 *
 * @author Dannes Wessels
 */
public class ReceiverStartupTrigger implements org.exist.storage.StartupTrigger {

    private final static Logger LOG = Logger.getLogger(ReceiverStartupTrigger.class);

    /*
     * Entry point for starting the trigger.
     */
    @Override
    public void execute(final DBBroker broker, final Map<String, List<? extends Object>> params) {

        ReceiversManager manager = ReceiversManager.getInstance();

        // Get from .xconf file, fill defaults when needed
        SubscriberParameters parameters = new SubscriberParameters();
        parameters.setSingleValueParameters(params);

        try {
            // Get parameters, fill defaults when needed
            parameters.processParameters();

            JmsConfiguration jmsConfig = new JmsConfiguration();
            jmsConfig.loadSubscriberParameters(parameters);

            // Setup listeners
            ReplicationJmsListener jmsListener = new ReplicationJmsListener(broker.getBrokerPool());

            Receiver receiver = new Receiver(jmsConfig, jmsListener);
            manager.register(receiver);

            receiver.initialize();
            receiver.start();

            LOG.info("Subscription was successful.");

        } catch (final Throwable t) {
            LOG.error(String.format("Unable to start subscription: %s", t.getMessage()), t);
        }
    }

}

Rename Class, hinted by check style

Rename Class, hinted by check style


package br.com.bloder.better_migrations;

import android.app.Application;

import com.facebook.stetho.Stetho;
import com.uphyca.stetho_realm.RealmInspectorModulesProvider;

/**
 * Created by bloder on 25/09/16.
 */
public class ExampleApplication extends Application {

  @Override
  public void onCreate() {
    super.onCreate();
    Stetho.initialize(
            Stetho.newInitializerBuilder(this)
                    .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
                    .enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
                    .build());

  }
}

Create example project application class


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

package com.google.gerrit.elasticsearch;

import com.google.gerrit.elasticsearch.ElasticTestUtils.ElasticNodeInfo;
import com.google.gerrit.server.query.project.AbstractQueryProjectsTest;
import com.google.gerrit.testing.ConfigSuite;
import com.google.gerrit.testing.InMemoryModule;
import com.google.gerrit.testing.IndexConfig;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.eclipse.jgit.lib.Config;
import org.junit.AfterClass;
import org.junit.BeforeClass;

public class ElasticV6QueryProjectsTest extends AbstractQueryProjectsTest {
  @ConfigSuite.Default
  public static Config defaultConfig() {
    return IndexConfig.createForElasticsearch();
  }

  private static ElasticNodeInfo nodeInfo;
  private static ElasticContainer<?> container;

  @BeforeClass
  public static void startIndexService() {
    if (nodeInfo != null) {
      // do not start Elasticsearch twice
      return;
    }

    container = ElasticContainer.createAndStart(ElasticVersion.V6_2);
    nodeInfo = new ElasticNodeInfo(container.getHttpHost().getPort());
  }

  @AfterClass
  public static void stopElasticsearchServer() {
    if (container != null) {
      container.stop();
    }
  }

  private String testName() {
    return testName.getMethodName().toLowerCase() + "_";
  }

  @Override
  protected void initAfterLifecycleStart() throws Exception {
    super.initAfterLifecycleStart();
    ElasticTestUtils.createAllIndexes(injector);
  }

  @Override
  protected Injector createInjector() {
    Config elasticsearchConfig = new Config(config);
    InMemoryModule.setDefaults(elasticsearchConfig);
    String indicesPrefix = testName();
    ElasticTestUtils.configure(elasticsearchConfig, nodeInfo.port, indicesPrefix);
    return Guice.createInjector(new InMemoryModule(elasticsearchConfig, notesMigration));
  }
}

Elasticsearch: Add tests for project queries against version 6

Bug: Issue 9112
Change-Id: I83b25ac02b932babe5b51185af0d7a7057bc2fac


package net.starwix;

import java.awt.AWTException;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;

/**
 * @author starwix
 */
public class ImageArray {
	private int[][] data;
	private int type;

	public ImageArray(BufferedImage image, int type) {
		int w = image.getWidth();
		int h = image.getHeight();

		if (image.getType() != type) {
			BufferedImage temp = new BufferedImage(w, h, type);
			Graphics g = temp.getGraphics();
			g.drawImage(image, 0, 0, null);
			g.dispose();
			image = temp;
		}
		this.type = type;

		DataBuffer t = image.getRaster().getDataBuffer(); // work fast
		data = new int[h][w];
		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				data[y][x] = t.getElem(y * w + x);
			}
		}
	}

	public ImageArray(BufferedImage image) throws AWTException {
		this(image, image.getType());
	}

	public int[][] getData() {
		return data;
	}

	public int getType() {
		return type;
	}

	public int getHeight() {
		return data.length;
	}

	public int getWidth() {
		return data[0].length;
	}
}

Add the class that allows to work with image as array.


package com.smartx;

/**
 * Leetcode2
 *

 *
 *

 * @author kext
 */
public class Leetcode2 {

	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		// 算出两个节点的长度，取出最长的作为循环
		int l1Size = 0;
		int l2Size = 0;
		ListNode l1Temp = l1;
		ListNode l2Temp = l2;
		while (l1Temp != null) {
			l1Size++;
			l1Temp = l1Temp.next;
		}
		while (l2Temp != null) {
			l2Size++;
			l2Temp = l2Temp.next;
		}
		int size = l1Size >= l2Size ? l1Size : l2Size;
		// 用于标识两个数相加是否超过10
		int oneOrZero = 0;
		// 结果
		ListNode result = null;
		// 当前节点
		ListNode cur = null;
		// 上一个节点
		ListNode last = null;
		for (int i = 0; i < size; i++) {
			int val1 = 0;
			int val2 = 0;
			if (l1 != null) {
				// 取出当前值和移到下一个节点
				val1 = l1.val;
				l1 = l1.next;
			}
			if (l2 != null) {
				val2 = l2.val;
				l2 = l2.next;
			}
			int tempVal = val1 + val2 + oneOrZero;
			int val = tempVal >= 10 ? tempVal - 10 : tempVal;
			oneOrZero = tempVal >= 10 ? 1 : 0;
			if (i == 0) {
				result = new ListNode(val);
				cur = result;
				last = result;
			} else {
				cur = new ListNode(val);
				// 上一个节点的下一个节点是当前节点
				last.next = cur;
				// 当前节点变为上一个节点
				last = cur;
			}
			// 最后一个大于10要拼接一个1
			if (i == size - 1 && oneOrZero == 1) {
				cur.next = new ListNode(1);
			}
		}
		return result;
	}
}

Add Leetcode 2 java code

Add Leetcode 2 java code


package org.skyscreamer.jsonassert.comparator;

import org.json.JSONException;
import org.skyscreamer.jsonassert.Customization;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.JSONCompareResult;
import org.skyscreamer.jsonassert.ValueMatcherException;

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

public class CustomComparator extends DefaultComparator {

    private final Collection<Customization> customizations;

    public CustomComparator(JSONCompareMode mode,  Customization... customizations) {
        super(mode);
        this.customizations = Arrays.asList((Customization[])customizations);
    }

    @Override
    public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
    	Customization customization = getCustomization(prefix);
        if (customization != null) {
        	try {
    			if (!customization.matches(prefix, actualValue, expectedValue, result)) {
   					result.fail(prefix, expectedValue, actualValue);
    			}
        	}
        	catch (ValueMatcherException e) {
       			result.fail(prefix, e);
        	}
        } else {
            super.compareValues(prefix, expectedValue, actualValue, result);
        }
    }

    private Customization getCustomization(String path) {
        for (Customization c : customizations)
            if (c.appliesToPath(path))
                return c;
        return null;
    }
}

package org.skyscreamer.jsonassert.comparator;

import org.json.JSONException;
import org.skyscreamer.jsonassert.Customization;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.JSONCompareResult;
import org.skyscreamer.jsonassert.ValueMatcherException;

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

public class CustomComparator extends DefaultComparator {

    private final Collection<Customization> customizations;

    public CustomComparator(JSONCompareMode mode,  Customization... customizations) {
        super(mode);
        this.customizations = Arrays.asList(customizations);
    }

    @Override
    public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
        Customization customization = getCustomization(prefix);
        if (customization != null) {
        	try {
    			if (!customization.matches(prefix, actualValue, expectedValue, result)) {
   					result.fail(prefix, expectedValue, actualValue);
    			}
        	}
        	catch (ValueMatcherException e) {
       			result.fail(prefix, e);
        	}
        } else {
            super.compareValues(prefix, expectedValue, actualValue, result);
        }
    }

    private Customization getCustomization(String path) {
        for (Customization c : customizations)
            if (c.appliesToPath(path))
                return c;
        return null;
    }
}

Remove minor unwanted code change

Remove minor unwanted code change


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
package com.facebook.imagepipeline.debug;

import com.facebook.cache.common.CacheKey;
import com.facebook.imagepipeline.cache.DefaultCacheKeyFactory;
import com.facebook.imagepipeline.request.ImageRequest;
import javax.annotation.Nullable;

public class FlipperCacheKeyFactory extends DefaultCacheKeyFactory {

  private final @Nullable DebugImageTracker mDebugImageTracker;

  public FlipperCacheKeyFactory(@Nullable DebugImageTracker debugImageTracker) {
    mDebugImageTracker = debugImageTracker;
  }

  @Override
  public CacheKey getBitmapCacheKey(ImageRequest request, Object callerContext) {
    CacheKey bitmapCacheKey = super.getBitmapCacheKey(request, callerContext);
    if (mDebugImageTracker != null) {
      mDebugImageTracker.trackImage(request, bitmapCacheKey);
    }
    return bitmapCacheKey;
  }
}

Add Flipper debug cache key factory

Add Flipper debug cache key factory

Reviewed By: oprisnik

Differential Revision: D14598273

fbshipit-source-id: a34c6e0df9b725d9b4887124fb7542eb56e9cec8


package com.github.onsdigital.perkin.helper;

import com.github.onsdigital.perkin.json.Survey;
import com.github.onsdigital.perkin.json.SurveyParser;
import com.github.onsdigital.perkin.json.SurveyTemplate;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

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

/**
 * Created by ian on 01/04/2016.
 */
public class TemplateLoaderTest {

    private TemplateLoader loader;

    private static String TEST_TEMPLATE_JSON = "templates/023.0203.survey.json";
    private static String TEST_TEMPLATE_PDF = "templates/023.0203.pdf.fo";
    private static String TEST_SURVEY_JSON = "survey.ftp.json";

    @Before
    public void setUp() {
        loader = TemplateLoader.getInstance();
    }

    @Test
    public void shouldLoadTemplate() throws IOException {
        String surveyContent = FileHelper.loadFile(TEST_TEMPLATE_JSON);

        assertThat(surveyContent, is(loader.getTemplate(TEST_TEMPLATE_JSON)));
    }

    @Test
    public void shouldLoadPdfTemplate() throws IOException {
        String pdfTemplateContent = FileHelper.loadFile(TEST_TEMPLATE_PDF);
        Survey testSurvey = new SurveyParser().parse(FileHelper.loadFile(TEST_SURVEY_JSON));

        assertThat(pdfTemplateContent, is(loader.getPdfTemplate(testSurvey)));
    }
}

Add some tests for new template loader class


package com.skraylabs.poker.model;

import static com.skraylabs.poker.model.PokerFormatExceptionTest.assertMessageAndInvalidString;

import org.junit.Test;

public class GameStateFormatExceptionTest {

  @Test
  public void testDefaultConstructor() {
    // Exercise
    GameStateFormatException exception = new GameStateFormatException();
    // Verify
    assertMessageAndInvalidString(exception, GameStateFormatException.MSG_DEFAULT, null);
  }

  @Test
  public void testInitializingConstructor() {
    // Set up
    String expectedMessage = GameStateFormatException.MSG_MIN_POCKET_NUM;
    // Exercise
    GameStateFormatException exception = new GameStateFormatException(expectedMessage);
    // Verify
    assertMessageAndInvalidString(exception, expectedMessage, null);
  }

  @Test
  public void testInitializingConstructor_nullMessage() {
    // Exercise
    GameStateFormatException exception = new GameStateFormatException(null);
    // Verify
    assertMessageAndInvalidString(exception, null, null);
  }

  @Test
  public void testInitializingConstructor_emptyMessage() {
    // Exercise
    GameStateFormatException exception = new GameStateFormatException("");
    // Verify
    assertMessageAndInvalidString(exception, "", null);
  }

  @Test
  public void testInitializingConstructor_blankMessage() {
    // Exercise
    GameStateFormatException exception = new GameStateFormatException(" ");
    // Verify
    assertMessageAndInvalidString(exception, " ", null);
  }

}

Add test class for GameStateFormatException.


package seedu.address.model.task;

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

import org.junit.Test;

public class NameTest {

    @Test
    public void isValidName() {
        // invalid name
        assertFalse(Name.isValidName("")); // empty string
        assertFalse(Name.isValidName(" ")); // spaces only
        assertFalse(Name.isValidName("^")); // only non-alphanumeric characters
        assertFalse(Name.isValidName("peter*")); // contains non-alphanumeric characters

        // valid name
        assertTrue(Name.isValidName("peter jack")); // alphabets only
        assertTrue(Name.isValidName("12345")); // numbers only
        assertTrue(Name.isValidName("peter the 2nd")); // alphanumeric characters
        assertTrue(Name.isValidName("Capital Tan")); // with capital letters
        assertTrue(Name.isValidName("David Roger Jackson Ray Jr 2nd")); // long names
    }
}

Add test cases for Name

Add test cases for Name


//@@author A0147944U
package guitests;

import org.junit.Test;

import seedu.task.commons.core.Messages;
import seedu.task.logic.commands.BackupCommand;
import seedu.task.testutil.TypicalTestTasks;

import static org.junit.Assert.assertTrue;

public class BackupCommandTest extends TaskManagerGuiTest {

    public static final String filepath_A = "data/empty";
    public static final String filepath_B = "data/notempty";
    public static final String filepath_C = "c:/inaccessible";
    public static final String filepath_D = "invalid:/drive";
    public static final String filepath_E = "c:/invalid>character";

    @Test
    public void backup() {

        //verify an empty TaskManager can be backed up in a valid directory
        commandBox.runCommand("clear");
        assertListSize(0);
        assertResultMessage("Task manager has been cleared!");
        commandBox.runCommand("backup " + filepath_A);
        assertResultMessage(String.format(BackupCommand.MESSAGE_BACKUP_SUCCESS, filepath_A + ".xml"));
        //assertBackupCommandSuccess();

        //verify a non-empty TaskManager can be backed up in a valid directory
        commandBox.runCommand(TypicalTestTasks.taskH.getAddCommand());
        assertTrue(taskListPanel.isListMatching(TypicalTestTasks.taskH));
        commandBox.runCommand("backup " + filepath_B);
        assertResultMessage(String.format(BackupCommand.MESSAGE_BACKUP_SUCCESS, filepath_B + ".xml"));
        //assertBackupCommandSuccess();

      //verify TaskManager can be backed up in a valid directory onto an existing backup
        commandBox.runCommand("backup " + filepath_A);
        assertResultMessage(String.format(BackupCommand.MESSAGE_BACKUP_SUCCESS, filepath_A + ".xml"));
        //assertBackupCommandSuccess();

        //verify a TaskManager can't be backed up in an inaccessible directory
        commandBox.runCommand("backup " + filepath_C);
        assertResultMessage(String.format(BackupCommand.MESSAGE_BACKUP_FAILURE, filepath_C + ".xml"));
        //assertBackupCommandFailure();

        //verify a TaskManager can't be backed up in an invalid directory
        commandBox.runCommand("backup " + filepath_D);
        assertResultMessage(String.format(BackupCommand.MESSAGE_BACKUP_FAILURE, filepath_D + ".xml"));
        //assertBackupCommandFailure();
        commandBox.runCommand("backup " + filepath_E);
        assertResultMessage(String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, BackupCommand.MESSAGE_USAGE));
        //assertBackupCommandFailure();
    }

    /* Needs more in depth testing
     * 1) Check content of successful backup
     * private void assertBackupCommandSuccess() {

    }

    private void assertBackupCommandFailure() {

    }*/
}

Add JUnit test for BackupCommand

Add JUnit test for BackupCommand


package learn_to_code.java_api.net.tiny_chat_over_local_socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * This server will open port 10000 on your machine (Can be changed obviously), accept MULTIPLE connection
 * at once. When a new connection is established (When call to serverSocket.accept() returns), a thread is started
 * to work with this connection and then the server start listening to the port again.
 * <br>
 * The communication is defined by {@link learn_to_code.java_api.net.local_one_time_one_connection.SimpleNetworkProtocol} class
 * Client can be {@link learn_to_code.java_api.net.local_one_time_one_connection.SingleConnectionLocalClient}
 */
public class LocalChatServer {

    private static ExecutorService executor = Executors.newCachedThreadPool();

    public static void main(String[] args) throws IOException {

        try (ServerSocket serverSocket = new ServerSocket(10000)) {
        }

        /*
        1. Start

            > Hello
            > I can do stuff
            > 1. To login under existing user print "login"
            > 2. To create new user print "new"

            1.1.

            Login <

            1.1. Login
                 > Your login?
                login <

                > Your password ?
                password <

                SERVER CHECKS IF USER EXISTS

                1.1.1. User exists

                    > Connected successfully!

                    LOGIN SUCCESSFUL

                1.1.2. User does not exist.

                    > Login failure!

                    GO BACK TO 1.

            1.2. New user

                new <
                > New login?
                login <

                > New password ?
                password <

                CHECK IF LOGIN IS AVAILABLE

                1.2.1. Login available

                    SERVER IS CREATING NEW USER IN IT'S DATABASE(?).
                    > New user created

                    GO TO 2.

                1.2.2. Login is not available

                    > Login is not available, please try again

                    GO TO 1.2.

        2. Login successful
            > Login successful. What would you like to do next?
            > 1. To check your contact list print "contacts"
            > 2. To connect to other online user print "connect %USER_LOGIN%". Note: active users are marked with * after call to contacts.

            ...

        */
    }
}

Add new package and class for local chat example

This local chat will be able to work with multiple connections in one. I
play to later on put it in another maven-module to this project and add
awesome stuff like authorization, message history saving, maybe even GUI


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

package tachyon.worker.block.evictor;

import java.io.File;
import java.util.Collections;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import tachyon.worker.block.BlockMetadataManager;
import tachyon.worker.block.BlockMetadataManagerView;

/*
 * Test EvictorFactory by passing different AllocatorType
 * and test if it generate the correct Evictor instance.
 */
public class EvictorFactoryTest {
  private static BlockMetadataManager sBlockMetadataManager;
  private static BlockMetadataManagerView sBlockMetadataManagerView;

  @Rule
  public TemporaryFolder mTestFolder = new TemporaryFolder();

  @Before
  public void before() throws Exception {
    File tempFolder = mTestFolder.newFolder();
    if (sBlockMetadataManagerView == null) {
      if (sBlockMetadataManager == null) {
        sBlockMetadataManager = EvictorTestUtils.defaultMetadataManager(
           tempFolder.getAbsolutePath());
      }
      sBlockMetadataManagerView = new BlockMetadataManagerView(sBlockMetadataManager,
          Collections.<Integer>emptySet(), Collections.<Long>emptySet());
    }
  }

  @Test
  public void createGreedyAllocatorTest() {
    Evictor evictor = EvictorFactory.create(EvictorType.GREEDY, sBlockMetadataManagerView);
    Assert.assertTrue(evictor instanceof GreedyEvictor);
  }

  @Test
  public void createLRUAllocatorTest() {
    Evictor evictor = EvictorFactory.create(EvictorType.LRU, sBlockMetadataManagerView);
    Assert.assertTrue(evictor instanceof LRUEvictor);
  }

  @Test
  public void createDefaultAllocatorTest() {
    Evictor evictor = EvictorFactory.create(EvictorType.DEFAULT, sBlockMetadataManagerView);
    Assert.assertTrue(evictor instanceof LRUEvictor);
  }
}

Add unit test of EvictorFactory

[TACHYON-648] Add unit test of EvictorFactory


public class BucketSortTest {

	public static void main(String[] args) {
		int items[] = { 65, 2, 5, 1, -3, 12, 34, 0, 13 };
		BucketSort.sort(items);
		for (int i = 0; i < items.length - 1; i++) {
			if (items[i] > items[i + 1]) {
			  System.out.println("Items are not sorted -> Test failed");
			  System.exit(1);
			}
		}

		System.out.println("Test was successful!");
	}
}

Add test for java bucket sort

Add test for java bucket sort


package org.monospark.spongematchers.parser.type;

import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches;

import org.junit.Test;
import org.monospark.spongematchers.matcher.SpongeMatcher;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.StringElementParser;

public class MatcherTypeTest {

    @Test
    public void parseMatcher_MatcherWithConjunctions_ReturnsCorrectMatcher() throws SpongeMatcherParseException {
        String input = "(('test1'|'test2')&!('test2'))";

        SpongeMatcher<String> matcher = MatcherType.STRING.parseMatcher(StringElementParser.parseStringElement(input));

        assertThat(matcher, matches("test1"));
        assertThat(matcher, not(matches("test2")));
    }
}

Add a unit test for parsing logical conjunctions


package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

import java.util.ArrayList;

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

/**
 * JUnit test for Resources class.
 *
 * @author wscott
 *
 */
public class ResourcesTest {

    private Resources resources;

    private static final String BASE = "base";
    private static final ArrayList<Documentation> DOC = new ArrayList<Documentation>(0);
    private static final ArrayList<Resource> RESOURCE_LIST = new ArrayList<Resource>(0);

    @Before
    public void setup() throws Exception {
        resources = new Resources(BASE, DOC, RESOURCE_LIST);
    }

    @Test(expected = NullPointerException.class)
    public void testNullBase() {
        new Resources(null, DOC, RESOURCE_LIST);
    }

    @Test(expected = NullPointerException.class)
    public void testNullResourceList() {
        new Resources(BASE, DOC, null);
    }

    @Test
    public void testGetBase() {
        assertEquals(BASE, resources.getBase());
    }

    @Test
    public void testGetResources() {
        assertEquals(RESOURCE_LIST, resources.getResources());
    }

    @Test
    public void testToString() {
        assertTrue(!"".equals(resources.toString()));
    }

}

Add JUnit test for Resources class in rest modeling module.


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

import org.eclipse.swt.internal.cocoa.NSPoint;
import org.eclipse.swt.widgets.Composite;

public final class SmoothTable extends AbstractSmoothTable.Scrollable {
	public SmoothTable(Composite parent, int tableStyle) {
		super(parent, tableStyle);
	}

	@Override
	protected void setTopPixelWithinTable(int topPixel) {
		NSPoint pt = new NSPoint();
		pt.x = 0;
		pt.y = topPixel;
		table.view.scrollPoint(pt);
	}
}

Add the missing mac aarch64 code.

Add the missing mac aarch64 code.


public class RemoveDuplicatesFromSortedList {
    /**
     * @param ListNode head is the head of the linked list
     * @return: ListNode head of linked list
     */
    public static ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) return head;

        ListNode curr = head;
        while (curr != null && curr.next != null) {
            if (curr.val == curr.next.val) {
                curr.next = curr.next.next;
            } else {
                curr = curr.next;
            }
        }

        return head;
    }
}

Add one more easy level linked list problem.


/*******************************************************************************
 * Copyright (C) 2017 Push Technology Ltd.
 *
 * 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.pushtechnology.diffusion.transform.messaging.send;

import static com.pushtechnology.diffusion.transform.transformer.Transformers.identity;

/**
 * Factory for creating instances of {@link UnboundRequestSenderBuilder}s.
 *
 * @author Push Technology Limited
 */
public final class RequestBuilders {
    private RequestBuilders() {
    }

    /**
     * Create a {@link UnboundRequestSenderBuilder}.
     *
     * @return the request sender builder
     */
    public static <U, V> UnboundRequestSenderBuilder<U, V> requestSenderBuilder(
            Class<U> requestType,
            Class<V> responseType) {
        return new UnboundRequestSenderBuilderImpl<>(requestType, responseType, identity(), identity());
    }
}

Add factory for request sender builders.


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

import org.junit.Test;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

/**
 * An example of using {@link ColumnType} {@code interface}.
 *
 * @author Dmytro Dashenkov
 */
public class ColumnTypeShould {

    private static final int VALUE = 42;
    private static final String KEY = "the Answer";

    private static final String EXPECTED_RESULT = "the Answer: 42";

    @Test
    public void convert_java_type_to_store_as_type() {
        final String stringValue = String.valueOf(VALUE);
        final ColumnType<Integer, String, ?, ?> type = new TestColumnType<>();
        final String storedValue = type.convertColumnValue(VALUE);
        assertEquals(stringValue, storedValue);
    }

    @Test
    public void store_value_to_a_container() {
        final String stringValue = String.valueOf(VALUE);
        final StringBuilder container = new StringBuilder(16);
        final ColumnType<?, String, StringBuilder, String> type = new TestColumnType<>();
        type.setColumnValue(container, stringValue, KEY);

        assertThat(container.toString(), containsString(EXPECTED_RESULT));
    }

    @Test
    public void provide_interface_for_entire_storage_preparation_flow() {
        final ColumnType<Integer, String, StringBuilder, String> type = new TestColumnType<>();
        final StringBuilder container = new StringBuilder(16);

        type.setColumnValue(container, type.convertColumnValue(VALUE), KEY);

        assertThat(container.toString(), containsString(EXPECTED_RESULT));
    }

    private static class TestColumnType<T> implements ColumnType<T, String, StringBuilder, String> {

        @Override
        public String convertColumnValue(T fieldValue) {
            return String.valueOf(fieldValue);
        }

        @Override
        public void setColumnValue(StringBuilder storageRecord,
                                   String value,
                                   String columnIdentifier) {
            storageRecord.append(columnIdentifier)
                         .append(": ")
                         .append(value);
        }
    }
}

Add tests-sample for the ColumnType.

Add tests-sample for the ColumnType.


package org.simpleframework.xml.core;

import java.io.StringWriter;

import junit.framework.TestCase;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;

public class PathConstructorAmbiguityTest extends TestCase {

   @Root(name="test1")
   public static class Test1 {

      @Attribute(name="iri")
      final String identifier;

      @Path(value="resource")
      @Attribute(name="iri")
      final String identifier1;

      public Test1(
            @Attribute(name="iri")  String identifier,
            @Path(value="resource") @Attribute(name="iri") String identifier1)
      {
         this.identifier = identifier;
         this.identifier1 = identifier1;
      }
   }

      public void testParameters() throws Exception{
         Serializer s = new Persister();
         StringWriter sw = new StringWriter();
         s.write(new Test1("a", "b"), sw);
         String serializedForm = sw.toString();
         System.out.println(serializedForm);
         Test1 o = s.read(Test1.class, serializedForm);
      }
}

Add test for attribute ambiguity

Add test for attribute ambiguity

git-svn-id: 4741f78aa2d3279ddd0a34c053c42ca3ce19451b@1976 124fc276-1b20-0410-8d16-dc08e6bff5e9


/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.webkit;

import android.content.Context;
import android.graphics.Bitmap;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import org.mozilla.focus.R;
import org.mozilla.focus.webkit.matcher.UrlMatcher;

public class TrackingProtectionWebViewClient extends WebViewClient {

    private String currentPageURL;
    private final UrlMatcher matcher;

    public TrackingProtectionWebViewClient(final Context context) {
        matcher = new UrlMatcher(context, R.raw.blocklist, R.raw.entitylist);
    }

    /*
     * The new undeprecated version of this methods is API 21+.
     */
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        if (matcher.matches(url, currentPageURL)) {
            return new WebResourceResponse(null, null, null);
        }

        return super.shouldInterceptRequest(view, url);
    }

    /**
     * Notify that the user has requested a new URL. This MUST be called before loading a new URL
     * into the webview: sometimes content requests might begin before the WebView itself notifies
     * the WebViewClient via onpageStarted/shouldOverrideUrlLoading. If we don't know the current page
     * URL then the entitylist whitelists might not work if we're trying to load an explicitly whitelisted
     * page.
     */
    public void notifyCurrentURL(final String url) {
        currentPageURL = url;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        currentPageURL = url;

        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        currentPageURL = url;

        return super.shouldOverrideUrlLoading(view, url);
    }

}

Add WebViewClient to wrap URL matching.

Add WebViewClient to wrap URL matching.


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

package org.curioswitch.common.server.framework.grpc;

import com.google.common.util.concurrent.ListenableFuture;
import com.spotify.futures.FuturesExtra;
import io.grpc.stub.StreamObserver;

/** A utility for using gRPC with producer graphs. */
public final class GrpcGraphUtil {

  /**
   * Wires the result of a {@link ListenableFuture} to the response handling methods of a {@link
   * StreamObserver}.
   */
  public static <T> void unary(ListenableFuture<T> graphFuture, StreamObserver<T> observer) {
    FuturesExtra.addCallback(
        graphFuture,
        response -> {
          observer.onNext(response);
          observer.onCompleted();
        },
        observer::onError);
  }
}

Add small utility for simplifying graph invocation in grpc services.


package org.xdi.service.cdi.event;

import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author Yuriy Movchan Date: 04/13/2017
 */
@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER, TYPE })
@Documented
public @interface ApplicationInitialized {

    public static final class Literal extends AnnotationLiteral<ApplicationInitialized> implements ApplicationInitialized {

        private static final long serialVersionUID = 4891987789146132930L;

        public static final Literal INSTANCE = new Literal();
    }

}

Add event to notify plugins about finish application initialization


package org.msf.records.ui.chart;

import android.test.AndroidTestCase;

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.msf.records.data.app.AppModel;
import org.msf.records.events.CrudEventBus;
import org.msf.records.net.OpenMrsChartServer;
import org.msf.records.ui.FakeEventBus;
import org.msf.records.ui.chart.PatientChartController.ObservationsProvider;
import org.msf.records.ui.chart.PatientChartController.OdkResultSender;

/**
 * Tests for {@link PatientChartController}.
 */
public class PatientChartControllerTest extends AndroidTestCase {

	private PatientChartController mController;
	@Mock private AppModel mMockAppModel;
	@Mock private OpenMrsChartServer mMockServer;
	@Mock private CrudEventBus mMockCrudEventBus; // TODO: replace with a fake
	@Mock private PatientChartController.Ui mMockUi;
	@Mock private OdkResultSender mMockOdkResultSender;
	@Mock private ObservationsProvider mMockObservationsProvider;
	private FakeEventBus mFakeEventBus;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		MockitoAnnotations.initMocks(this);

		mFakeEventBus = new FakeEventBus();

		mController = new PatientChartController(
				mMockAppModel,
				mMockServer,
				mFakeEventBus,
				mMockCrudEventBus,
				mMockUi,
				mMockOdkResultSender,
				mMockObservationsProvider,
				null);
	}

	public void testSuspend_UnregistersFromEventBus() {
		// GIVEN an initialized controller
		mController.init();
		// WHEN the controller is suspended
		mController.suspend();
		// THEN the controller unregisters from the event bus
		assertEquals(0, mFakeEventBus.countRegisteredReceivers());
	}

}

Add a unit test for PatientChartController.


/*
 * Copyright 2016 peter.
 *
 * 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 onl.area51.filesystem.http.client;

import java.util.Map;
import onl.area51.filesystem.io.FileSystemIO;
import onl.area51.filesystem.io.overlay.OverlayFileSystemIO;
import org.kohsuke.MetaInfServices;

/**
 * {@link OverlayFileSystemIO} implementation to retrieve content from a remote HTTP/HTTPS server
 *
 * @author peter
 */
@MetaInfServices(OverlayFileSystemIO.class)
public class HttpAsyncRead
        extends OverlayFileSystemIO
{

    public HttpAsyncRead( FileSystemIO delegate, Map<String, Object> env )
    {
        super( delegate, new HttpRetriever( delegate, env ) );
    }

}

Add async (i.e. non-synchronized) http read


package com.marcusman.packageify;

import java.io.File;

/**
* Packageify puts files that were originally all in the same folder
* in organized packages based on input information.
*
* <pre>
* Program arguments:
* (path to folder with all java files) (package definition txt file) (output folder)
*
* Example of package definition file:
* AnimatedSprite;com.marcusman.graphics.AnimatedSprite
* Game;com.marcusman.Game
* GameObject;com.marcusman.utils.GameObject
* GUI;com.marcusman.graphics.gui.GUI
* GUIButton;com.marcusman.graphics.gui.GUIButton
* KeyBoardListener;com.marcusman.input.KeyBoardListener
* Map;com.marcusman.logic.Map
* MouseEventListener;com.marcusman.input.MouseEventListener
* Player;com.marcusman.logic.Player
* Rectangle;com.marcusman.utils.Rectangle
* RenderHandler;com.marcusman.graphics.RenderHandler
* SDKButton;com.marcusman.graphics.gui.SDKButton
* Sprite;com.marcusman.graphics.Sprite
* SpriteSheet;com.marcusman.graphics.SpriteSheet
* Tiles;com.marcusman.logic.Tiles
* </pre>
* @author Marcus Dubreuil
* @version 1.0
*/
public class Packageify {

	private File inputFolder;
	private File definitionFile;
	private File outputFolder;

	/**
	* Packageify the given directory with the description given above
	* @param args args[0] = inputFolder args[1] = definitionFile args[2] = outputFolder
	*/
	public Packageify(String[] args) throws IllegalArgumentException {
		if(args.length < 3)
			throw new IllegalArgumentException("Expected at least 3 arguments and Received " + args.length + "!");

		inputFolder = new File(args[0]);
		definitionFile = new File(args[1]);
		outputFolder = new File(args[2]);
		validateFiles();

	}

	/**
	* Validate that all 3 files and directories (inputFolder, definitionFile, and outputFile) exist
	* or are accessible
	*/
	private void validateFiles() {
		if(!inputFolder.exists())
			throw new IllegalArgumentException("Input folder does not exist!");

		if(!inputFolder.isDirectory())
			throw new IllegalArgumentException("Input folder is not a directory!");

		File[] files = inputFolder.listFiles();

		if(files.length == 0)
			throw new IllegalArgumentException("Input folder contains no files!");

		boolean foundJava = false;

		for(int i = 0; i < files.length; i++)
			if(files[i].getName().endsWith(".java"))
				foundJava = true;

		if(!foundJava)
			throw new IllegalArgumentException("Input folder does not contain any Java files!");

		if(!definitionFile.exists())
			throw new IllegalArgumentException("Package Definition File does not exist!");

		outputFolder.mkdirs();

	}

    public static void main(String[] args) {
        new Packageify(args);
    }
}

Create main file and Add checks for arguments


/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2017 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, Max Planck
 * Institute of Molecular Cell Biology and Genetics, University of
 * Konstanz, and KNIME GmbH.
 * %%
 * 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.
 * #L%
 */

package org.scijava;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;

import org.junit.Test;
import org.scijava.plugin.PluginInfo;

/**
 * Tests {@link SciJava}.
 *
 * @author Curtis Rueden
 */
public class SciJavaTest {

	@Test
	public void testInfo() {
		final SciJava sj = new SciJava();

		final PluginInfo<?> infoFromObject = sj.getInfo();
		final PluginInfo<?> infoFromServiceNoType = //
			sj.plugin().getPlugin(SciJava.class);
		final PluginInfo<Gateway> infoFromServiceWithType = //
			sj.plugin().getPlugin(SciJava.class, Gateway.class);
		assertSame(infoFromServiceNoType, infoFromObject);
		assertSame(infoFromServiceWithType, infoFromObject);

		assertNotNull(infoFromObject);
		assertSame(Gateway.class, infoFromObject.getPluginType());

		assertEquals(Priority.NORMAL, sj.getPriority(), 0);

		sj.dispose();
	}
}

Add some simple tests for the SciJava gateway

These tests fail before the previous commit's improvements.


package org.eclipse.birt.report.resource;

import java.util.Locale;

import org.eclipse.birt.core.i18n.ResourceHandle;

public class ViewerResourceHandle extends ResourceHandle
{

	/**
	 * Constructs the resource handle with a specific resource bundle, which is
	 * associated with locale.
	 *
	 * @param locale
	 *            the locale of ULocale type
	 */

	public ViewerResourceHandle( Locale locale )
	{
		super( locale );
	}

}

Change the Viewer Birt resources to handle multiple resource locales.


package com.box.l10n.mojito.cli.command;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.box.l10n.mojito.cli.console.ConsoleWriter;
import com.box.l10n.mojito.phabricator.DifferentialRevision;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
@Parameters(commandNames = {"phab-add-msg"}, commandDescription = "Add a message to a Phabricator revision")
public class PhabricatorAddMessageCommand extends Command {
    /**
     * logger
     */
    static Logger logger = LoggerFactory.getLogger(PhabricatorAddMessageCommand.class);

    @Qualifier("ansiCodeEnabledFalse")
    @Autowired
    ConsoleWriter consoleWriterAnsiCodeEnabledFalse;

    @Autowired(required = false)
    DifferentialRevision differentialRevision;

    @Parameter(names = {"--object-id", "-o"}, arity = 1, required = true, description = "the object id of the revision")
    String objectId;

    @Parameter(names = {"--message", "-m"}, arity = 1, required = true, description = "message to add")
    String message;

    @Override
    public void execute() throws CommandException {
        if (differentialRevision == null) {
            throw new CommandException("Phabricator must be configured with properties: l10n.phabricator.url and l10n.phabricator.token");
        }

        differentialRevision.addComment(objectId, message);
    }
}

Add command to add a message to a phabricator revision


package com.facebook.react.uimanager;

import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;

public abstract class BaseViewManagerAdapter<T extends View>
    implements BaseViewManagerInterface<T> {
  @Override
  public void setAccessibilityActions(@NonNull T view, ReadableArray accessibilityActions) {}

  @Override
  public void setAccessibilityHint(@NonNull T view, String accessibilityHint) {}

  @Override
  public void setAccessibilityLabel(@NonNull T view, String accessibilityLabel) {}

  @Override
  public void setAccessibilityLiveRegion(@NonNull T view, @Nullable String liveRegion) {}

  @Override
  public void setAccessibilityRole(@NonNull T view, @Nullable String accessibilityRole) {}

  @Override
  public void setViewState(@NonNull T view, @Nullable ReadableMap accessibilityState) {}

  @Override
  public void setBackgroundColor(@NonNull T view, int backgroundColor) {}

  @Override
  public void setBorderRadius(@NonNull T view, float borderRadius) {}

  @Override
  public void setBorderBottomLeftRadius(@NonNull T view, float borderRadius) {}

  @Override
  public void setBorderBottomRightRadius(@NonNull T view, float borderRadius) {}

  @Override
  public void setBorderTopLeftRadius(@NonNull T view, float borderRadius) {}

  @Override
  public void setBorderTopRightRadius(@NonNull T view, float borderRadius) {}

  @Override
  public void setElevation(@NonNull T view, float elevation) {}

  @Override
  public void setImportantForAccessibility(
      @NonNull T view, @Nullable String importantForAccessibility) {}

  @Override
  public void setNativeId(@NonNull T view, String nativeId) {}

  @Override
  public void setOpacity(@NonNull T view, float opacity) {}

  @Override
  public void setRenderToHardwareTexture(@NonNull T view, boolean useHWTexture) {}

  @Override
  public void setRotation(@NonNull T view, float rotation) {}

  @Override
  public void setScaleX(@NonNull T view, float scaleX) {}

  @Override
  public void setScaleY(@NonNull T view, float scaleY) {}

  @Override
  public void setTestId(@NonNull T view, String testId) {}

  @Override
  public void setTransform(@NonNull T view, @Nullable ReadableArray matrix) {}

  @Override
  public void setTranslateX(@NonNull T view, float translateX) {}

  @Override
  public void setTranslateY(@NonNull T view, float translateY) {}

  @Override
  public void setZIndex(@NonNull T view, float zIndex) {}
}

Migrate FbReactTTRCStepRenderFlagManager to JS codegen

Summary: This diff migrates `FbReactTTRCStepRenderFlagManager` to use the generated `TTRCStepRenderFlagManagerDelegate` for setting its properties. A bit more work was required to migrate this view manager since it doesn't extend `BaseViewManager`, so I had to add an adapter which made it possible to pass an instance of `FbReactTTRCStepRenderFlagManager` to `TTRCStepRenderFlagManagerDelegate`.

Reviewed By: mdvacca

Differential Revision: D16984172

fbshipit-source-id: 7bf8c1342435c4e615eb9e7ca711f53c63ed3438


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

package com.google.gwtexpui.globalkey.client;

import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.user.client.ui.FlowPanel;

public class NpFlowPanel extends FlowPanel {
  public NpFlowPanel() {
    addDomHandler(GlobalKey.STOP_PROPAGATION, KeyPressEvent.getType());
  }
}

Add FlowPanel without key event propagation

Change-Id: Idfdda3fca94619df6293c5be33cfbefd681a607a


package ch.squix.esp8266.fontconverter.rest.font;

import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class FontResource extends ServerResource {

    @Get(value = "json")
    public List<FontDto> execute() throws FontFormatException, IOException {
        String fontFamily = (String) this.getRequestAttributes().get("fontFamily");
        List<FontDto> fonts = new ArrayList<>();
        GraphicsEnvironment graphicEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        for (Font font : graphicEnvironment.getAllFonts()) {
            if (fontFamily == null || fontFamily.equals(font.getFamily())) {
                FontDto dto = new FontDto();
                dto.setName(font.getFontName());
                dto.setFontFamily(font.getFamily());
                dto.setPlain(font.isPlain());
                dto.setItalic(font.isItalic());
                dto.setBold(font.isBold());
                fonts.add(dto);
            }
        }
        return fonts;
    }

}

Update build infrastructure. Add binary font rest resource


package leetcode.remove_element;

public class Solution {
    public int removeElement(int[] A, int elem) {
    	if(A == null) return 0;
    	int tail = A.length - 1;
    	for(int i = 0; i < A.length; i++){
    		if(A[i] == elem){
    			while(tail >= 0 && A[tail] == elem){
    				tail--;
    			}
    			if(tail > i){
    				A[i] = A[tail];
    				tail--;
    			}
    			else break;
    		}
    	}
    	return tail + 1;
    }

    public static void main(String[] args){
    	int[] ary = new int[]{3, 2, 2, 2, 5, 8, 3, 3};
    	int len = new Solution().removeElement(ary, 3);
    	System.err.println("len = " + len);
    	for(int i = 0; i < len; i++){
    		System.err.print(ary[i] + ", ");
    	}
    	System.err.println("");
    }
}

Add java solution for 27. Remove Element

27. Remove Element: https://leetcode.com/problems/remove-element/


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.client.block.policy.options;

import alluxio.CommonTestUtils;
import alluxio.util.CommonUtils;

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

import java.io.IOException;
import java.util.Random;

/**
 * Tests for the {@link CreateOptions} class.
 */
public final class CreateOptionsTest {
  /**
   * Tests for defaults {@link CreateOptions}.
   */
  @Test
  public void defaults() throws IOException {
    CreateOptions options = CreateOptions.defaults();

    Assert.assertEquals(1, options.getDeterministicHashPolicyNumShards());
    Assert.assertEquals(null, options.getLocationPolicyClassName());
  }

  /**
   * Tests getting and setting fields.
   */
  @Test
  public void fields() {
    Random random = new Random();
    int deterministicHashPolicyNumShards = random.nextInt();
    String locationPolicyClassName = CommonUtils.randomAlphaNumString(10);

    CreateOptions options = CreateOptions.defaults();
    options.setDeterministicHashPolicyNumShards(deterministicHashPolicyNumShards);
    options.setLocationPolicyClassName(locationPolicyClassName);
    Assert.assertEquals(deterministicHashPolicyNumShards,
        options.getDeterministicHashPolicyNumShards());
    Assert.assertEquals(locationPolicyClassName, options.getLocationPolicyClassName());
  }

  @Test
  public void equalsTest() throws Exception {
    CommonTestUtils.testEquals(CreateOptions.class);
  }
}

[ALLUXIO-2806] Add unit tests for block policy CreateOptions.


package no.ssb.vtl.script.error;

/*
 * ========================LICENSE_START=================================
 * Java VTL
 * %%
 * Copyright (C) 2016 - 2017 Hadrien Kohl
 * %%
 * 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.
 * =========================LICENSE_END==================================
 */

import org.antlr.v4.runtime.ParserRuleContext;

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

/**
 * A {@link RuntimeException} that contains the context in which it happened.
 */
public class ContextualRuntimeException extends RuntimeException {

    private final ParserRuleContext context;

    public ContextualRuntimeException(ParserRuleContext context) {
        this.context = checkNotNull(context);
    }

    public ContextualRuntimeException(String message, ParserRuleContext context) {
        super(message);
        this.context = checkNotNull(context);
    }

    public ContextualRuntimeException(String message, Throwable cause, ParserRuleContext context) {
        super(message, cause);
        this.context = checkNotNull(context);
    }

    public ContextualRuntimeException(Throwable cause, ParserRuleContext context) {
        super(cause.getMessage(), cause);
        this.context = checkNotNull(context);
    }

    public ContextualRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, ParserRuleContext context) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.context = checkNotNull(context);
    }

    public ParserRuleContext getContext() {
        return context;
    }
}

Add a RuntimeException subclass that contains the context of the error


package de.asw.web2.demo;

import static java.util.Arrays.asList;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
class SimpleWebCalculator {

	/**
	 * List's available operations.
	 *
	 * {@code curl http://localhost:8080/calc/ops }
	 *
	 * @param formData
	 * @return
	 */
	@GetMapping("/calc/ops")
	List<String> listSupportedOperations() {
		return asList("add:(x + y)", "subtract:(x - y)", "multiply:(x * y)", "divide:(x / y)", "pow:(x ^ y)");
	}

	/**
	 * Computes the result for the given operations and operands.
	 *
	 * {@code curl -d "x=2&y=10&op=pow" http://localhost:8080/calc }
	 *
	 * @see #listSupportedOperations() for the list of supported op-codes.
	 * @param formData
	 * @return
	 */
	@PostMapping("/calc")
	ResponseEntity<String> calc(@RequestBody MultiValueMap<String, String> formData) {

		Object result;
		try {

			BigDecimal x = new BigDecimal(formData.getFirst("x"));
			BigDecimal y = new BigDecimal(formData.getFirst("y"));
			String op = formData.getFirst("op");

			switch (op) {
			case "add":
				result = x.add(y);
				break;
			case "subtract":
				result = x.subtract(y);
				break;
			case "multiply":
				result = x.multiply(y);
				break;
			case "divide":
				result = x.divide(y);
				break;
			case "pow":
				result = x.pow(y.intValue());
				break;
			default:
				return ResponseEntity.badRequest().body("Error: don't know how to: " + op);
			}

		} catch (NumberFormatException nfe) {
			return ResponseEntity.badRequest().body(nfe.toString());
		}

		return ResponseEntity.ok(result.toString());
	}
}

Add simple calculator for HTML Form examples.


package learntocode.javaapi.io_and_nio.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;g

public class ByteChannelAndByteBufferExample {

    public static void main(String[] args) throws IOException, InterruptedException {
        Path path = FilesCreatorNIO.createFiles()[0];
        String str = "Hello, world!";

        /* Create write channel to path */
        try (SeekableByteChannel byteChannel = Files.newByteChannel(path, StandardOpenOption.WRITE)) {

            /* Create buffer and put data from string to this buffer. Rewind buffer, because after putting data buffer's pointer is at the end */
            ByteBuffer buffer = ByteBuffer.allocate(str.length());
            buffer.put(str.getBytes());
            buffer.rewind();

            /* Put buffer to channel */
            while (buffer.hasRemaining())
                byteChannel.write(buffer);

            System.out.println("'Hello, world!' should now be written to file");
        }

        /* Create read channel to path*/
        try (SeekableByteChannel byteChannel = Files.newByteChannel(path, StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(str.length());

            /* Read data from channel to buffer */
            while (byteChannel.read(buffer) > 0) {
            }

            /* Rewind buffer, because after reading buffer's pointer is at the end */
            buffer.rewind();
            System.out.println("Output from file is: ");

            /* print out data in buffer */
            while (buffer.hasRemaining())
                System.out.print((char)buffer.get());
        }
    }
}

Add byte buffer and byte channel example to NIO


/*
 * Copyright 2012 Shared Learning Collaborative, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 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.slc.sli.modeling.wadl.helpers;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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

import org.junit.Test;
import org.slc.sli.modeling.rest.Application;
import org.slc.sli.modeling.rest.Resource;
import org.slc.sli.modeling.rest.Resources;

/**
 * JUnit test for WadlWalker class.
 *
 * @author wscott
 *
 */
public class WadlWalkerTest {

    @Test(expected = NullPointerException.class)
    public void testConstructorNullHandler() {
        new WadlWalker(null);
    }

    @Test(expected = NullPointerException.class)
    public void testWalkNullApplication() {
        WadlHandler mockHandler = mock(WadlHandler.class);
        WadlWalker ww = new WadlWalker(mockHandler);
        ww.walk(null);
    }

    @Test
    public void testWalk() {
        WadlHandler wadlHandler = mock(WadlHandler.class);
        WadlWalker ww = new WadlWalker(wadlHandler);

        List<Resource> emptyResourcesList = new ArrayList<Resource>(0);

        Resources mockResources = mock(Resources.class);
        when(mockResources.getResources()).thenReturn(emptyResourcesList);

        Application mockApplication = mock(Application.class);
        when(mockApplication.getResources()).thenReturn(mockResources);

        ww.walk(mockApplication);

        verify(wadlHandler).beginApplication(mockApplication);
        verify(wadlHandler).endApplication(mockApplication);
    }

}

Add JUnit test for WadlWalker class.

Add JUnit test for WadlWalker class.


/*-
 * Copyright 2015 Diamond Light Source Ltd.
 *
 * 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
 */

package org.eclipse.dawnsci.analysis.api.io;

import org.eclipse.dawnsci.analysis.api.dataset.IDataset;
import org.eclipse.dawnsci.analysis.api.dataset.SliceND;
import org.eclipse.dawnsci.analysis.api.monitor.IMonitor;

/**
 * Used by lazy writeable datasets to write slices to a file
 */
public interface ILazySaver extends ILazyLoader {
	/**
	 *
	 * @return true if file is writeable
	 */
	public boolean isFileWriteable();

	/**
	 * @param mon
	 * @param data
	 * @param slice
	 * @throws Exception
	 */
	public void setSlice(IMonitor mon, IDataset data, SliceND slice) throws Exception;
}

Add new saver interface for use by lazy writeable dataset


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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelAwsDdbTest extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelAwsDdbTest.class);

    @Test
    public void test() throws Exception {
        testComponent(COMPONENT, "aws-ddb");
        testComponent(COMPONENT, "aws-ddbstream");
    }

}

Camel-AWS: Create single Karaf feature tests for single components, aws-ddb test


import java.util.*;

class NP {

  int x;
  static Map m = new HashMap();
  public static void main(String args[]) {
	NP n = (NP) m.get("Foo");

	if (n != null)
		System.out.println(n.x);
	}
}

Test case for Null Pointer Dereference

Test case for Null Pointer Dereference

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@1081 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package leetcode.course_schedule;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        Map<Integer, Set<Integer>> mapForward = new HashMap<Integer, Set<Integer>>();
        Map<Integer, Set<Integer>> mapBackward = new HashMap<Integer, Set<Integer>>();
        if(prerequisites == null) return true;
        for(int[] prerequisite : prerequisites){
            if(prerequisite[0] == prerequisite[1]) return false;
            Set<Integer> s;

            s = mapBackward.get(prerequisite[0]);
            if(s == null){
                s = new HashSet<Integer>();
                mapBackward.put(prerequisite[0], s);
            }
            s.add(prerequisite[1]);

            s = mapForward.get(prerequisite[1]);
            if(s == null){
                s = new HashSet<Integer>();
                mapForward.put(prerequisite[1], s);
            }
            s.add(prerequisite[0]);
        }
        Queue<Integer> queue = new LinkedList<Integer>();
        for(int x : mapForward.keySet()){
            Set<Integer> s = mapBackward.get(x);
            if(s == null || s.size() == 0){
                queue.offer(x);
            }
        }
        while(!queue.isEmpty()){
            int x = queue.remove();
            Set<Integer> s = mapForward.get(x);
            if(s != null){
                for(int y : s){
                    Set<Integer> s2 = mapBackward.get(y);
                    s2.remove(x);
                    if(s2.isEmpty()){
                        queue.offer(y);
                    }
                }
            }
        }
        for(Set<Integer> s : mapBackward.values()){
            if(!s.isEmpty()) return false;
        }
        return true;
    }
}

Add java solution for 207. Course Schedule

207. Course Schedule: https://leetcode.com/problems/course-schedule/


package leetcode;

/**
 * https://leetcode.com/problems/burst-balloons/
 */
public class Problem312 {
    public int maxCoins(int[] nums) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem312 prob = new Problem312();
        System.out.println(prob.maxCoins(new int[]{3, 1, 5, 8})); // 167
    }
}

Create a skeleton for problem 312

Create a skeleton for problem 312


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-16
 * Site       : https://www.acmicpc.net/problem/2557
 */
public class Boj2557 {

    public static void main(String[] args) throws IOException {
        System.out.print("Hello World!");
    }

}

Solve No.2557 from Baekjoon Online Judge


package leetcode;

/**
 * https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
 */
public class Problem116 {
    public static class TreeLinkNode {
        int val;
        TreeLinkNode left, right, next;

        TreeLinkNode(int x) {
            val = x;
        }
    }

    public void connect(TreeLinkNode root) {

    }

    public static void main(String[] args) {
        Problem116 prob = new Problem116();

        TreeLinkNode root = new TreeLinkNode(1);
        root.left = new TreeLinkNode(2);
        root.right = new TreeLinkNode(3);
        root.left.left = new TreeLinkNode(4);
        root.left.right = new TreeLinkNode(5);
        root.right.left = new TreeLinkNode(6);
        root.right.right = new TreeLinkNode(7);

        prob.connect(root);

        for (TreeLinkNode node = root.left; node != null; node = node.next) {
            System.out.println(node.val);
        }
        System.out.println("-------------------------------------------------");
        for (TreeLinkNode node = root.left.left; node != null; node = node.next) {
            System.out.println(node.val);
        }
    }
}

Create a skeleton for problem 116

Create a skeleton for problem 116


package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/wiggle-sort-ii/
 */
public class Problem324 {
    public void wiggleSort(int[] nums) {
        // TODO:
    }

    public static void main(String[] args) {
        Problem324 prob = new Problem324();

        int[] nums = new int[]{1, 5, 1, 1, 6, 4};
        prob.wiggleSort(nums);
        System.out.println(Arrays.toString(nums)); // [1, 4, 1, 5, 1, 6]

        nums = new int[]{1, 3, 2, 2, 3, 1};
        prob.wiggleSort(nums);
        System.out.println(Arrays.toString(nums)); // [2, 3, 1, 3, 1, 2]
    }
}

Create a skeleton for problem 324

Create a skeleton for problem 324