package amu.zhcetstudent;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see Testing documentation
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}

package amu.zhcetstudent;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import static org.junit.Assert.*;

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see Testing documentation
 */
@RunWith(JUnit4.class)
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}

Add JUnit4 Runner to test

fix: Add JUnit4 Runner to test


package com.veyndan.redditclient.ui.recyclerview.itemdecoration;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Px;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.veyndan.redditclient.post.DepthCalculatorDelegate;

public class TreeInsetItemDecoration extends RecyclerView.ItemDecoration {

    @Px private final int childInsetMultiplier;

    public TreeInsetItemDecoration(@NonNull final Context context,
                                   @DimenRes final int childInsetMultiplierRes) {
        childInsetMultiplier = context.getResources().getDimensionPixelOffset(childInsetMultiplierRes);
    }

    @Override
    public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent,
                               final RecyclerView.State state) {
        if (parent.getAdapter() instanceof DepthCalculatorDelegate) {
            final DepthCalculatorDelegate depthCalculatorDelegate = (DepthCalculatorDelegate) parent.getAdapter();
            final RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
            final int position = layoutParams.getViewLayoutPosition();
            final int inset = depthCalculatorDelegate.depthForPosition(position) * childInsetMultiplier;
            outRect.set(inset, 0, 0, 0);
        } else {
            throw new IllegalStateException("RecyclerView's Adapter must implement " +
                    "DepthCalculatorDelegate in order for TreeInsetItemDecoration to be used as " +
                    "a decoration");
        }
    }
}

package com.veyndan.redditclient.ui.recyclerview.itemdecoration;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Px;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.veyndan.redditclient.post.DepthCalculatorDelegate;

public class TreeInsetItemDecoration extends RecyclerView.ItemDecoration {

    @Px private final int childInsetMultiplier;

    public TreeInsetItemDecoration(@NonNull final Context context,
                                   @DimenRes final int childInsetMultiplierRes) {
        childInsetMultiplier = context.getResources().getDimensionPixelOffset(childInsetMultiplierRes);
    }

    @Override
    public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent,
                               final RecyclerView.State state) {
        if (parent.getAdapter() instanceof DepthCalculatorDelegate) {
            final DepthCalculatorDelegate depthCalculatorDelegate = (DepthCalculatorDelegate) parent.getAdapter();
            final int position = parent.getChildAdapterPosition(view);

            final int inset = position == RecyclerView.NO_POSITION
                    ? 0
                    : depthCalculatorDelegate.depthForPosition(position) * childInsetMultiplier;

            outRect.set(inset, 0, 0, 0);
        } else {
            throw new IllegalStateException("RecyclerView's Adapter must implement " +
                    "DepthCalculatorDelegate in order for TreeInsetItemDecoration to be used as " +
                    "a decoration");
        }
    }
}

Use adapter position instead of layout params position as causing IndexOutOfBoundsException otherwise


import org.realityforge.arez.annotations.Container;
import org.realityforge.arez.annotations.Observable;

@Container( singleton = true )
public class SingletonModel
{
  @Observable
  public long getTime()
  {
    return 0;
  }

  @Observable
  public void setTime( final long time )
  {
  }
}

import org.realityforge.arez.annotations.Action;
import org.realityforge.arez.annotations.Computed;
import org.realityforge.arez.annotations.Container;
import org.realityforge.arez.annotations.Observable;

@Container( singleton = true )
public class SingletonModel
{
  @Observable
  public long getTime()
  {
    return 0;
  }

  @Observable
  public void setTime( final long time )
  {
  }

  @Action
  public void doStuff( final long time )
  {
  }

  @Computed
  public int someValue()
  {
    return 0;
  }
}

Update input so we remember to check names of Actions and Computed


package jvmmonitor.io;

/*
*  Copyright (c) ${YEAR}, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. 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.
*/

public class ServerGCLogMonitor {
    private static final String SAMPLE_LOG_PATH = System.getProperty("user.dir") + "/gc.log.2.current";
}

package jvmmonitor.io;

/*
*  Copyright (c) ${YEAR}, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. 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.
*/

import communicator.DASPublisher;
import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException;
import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException;
import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException;
import org.wso2.carbon.databridge.agent.exception.DataEndpointException;
import org.wso2.carbon.databridge.commons.exception.TransportException;

import java.io.FileNotFoundException;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ServerGCLogMonitor {

    private static final String SAMPLE_LOG_PATH = System.getProperty("user.dir") + "/gc.log.2.current";

    public static void main(String[] args) throws DataEndpointException,
            SocketException,
            UnknownHostException,
            FileNotFoundException,
            DataEndpointConfigurationException,
            DataEndpointAuthenticationException,
            DataEndpointAgentConfigurationException,
            TransportException {

        DASPublisher dasPublisherObj = new DASPublisher();
        dasPublisherObj.publishXXgcLogData(SAMPLE_LOG_PATH);

    }
}

Add method for test GC log

Add method for test GC log


package ca.antonious.habittracker.models;

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

/**
 * Created by George on 2016-09-01.
 */
public class Habit {
    private String id;
    private String name;
    private List<Days> daysToComplete = new ArrayList<>();
    private List<HabitCompletion> completions = new ArrayList<>();

    public Habit() {
        setId(UUID.randomUUID().toString());
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<HabitCompletion> getCompletions() {
        return completions;
    }

    public void setCompletions(List<? extends HabitCompletion> completions) {
        this.completions.clear();
        this.completions.addAll(completions);
    }

    public HabitCompletion getCompletion(String completionId) {
        for (HabitCompletion habitCompletion: getCompletions()) {
            if (completionId.equals(habitCompletion.getId())) {
                return habitCompletion;
            }
        }

        return null;
    }

    public List<Days> getDaysToComplete() {
        return daysToComplete;
    }

    public void setDaysToComplete(List<Days> daysToComplete) {
        this.daysToComplete = daysToComplete;
    }

}

package ca.antonious.habittracker.models;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by George on 2016-09-01.
 */
public class Habit {
    private String id;
    private String name;
    private Date startDate;
    private List<Days> daysToComplete = new ArrayList<>();
    private List<HabitCompletion> completions = new ArrayList<>();

    public Habit() {
        setId(UUID.randomUUID().toString());
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public List<HabitCompletion> getCompletions() {
        return completions;
    }

    public void setCompletions(List<? extends HabitCompletion> completions) {
        this.completions.clear();
        this.completions.addAll(completions);
    }

    public HabitCompletion getCompletion(String completionId) {
        for (HabitCompletion habitCompletion: getCompletions()) {
            if (completionId.equals(habitCompletion.getId())) {
                return habitCompletion;
            }
        }

        return null;
    }

    public List<Days> getDaysToComplete() {
        return daysToComplete;
    }

    public void setDaysToComplete(List<Days> daysToComplete) {
        this.daysToComplete = daysToComplete;
    }

}

Add starting date to habit model

Add starting date to habit model


package crazypants.enderio.conduit.me;

import net.minecraft.item.ItemStack;
import crazypants.enderio.ModObject;
import crazypants.enderio.conduit.AbstractItemConduit;
import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.ItemConduitSubtype;

public class ItemMEConduit extends AbstractItemConduit {

  private static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] {
      new ItemConduitSubtype(ModObject.itemMEConduit.name(), "enderio:itemMEConduit"),
  };

  public static ItemMEConduit create() {
    ItemMEConduit result = new ItemMEConduit();
    result.init(subtypes);
    return result;
  }

  protected ItemMEConduit() {
    super(ModObject.itemMEConduit);
  }

  @Override
  public Class<? extends IConduit> getBaseConduitType() {
    return IMEConduit.class;
  }

  @Override
  public IConduit createConduit(ItemStack item) {
    return new MEConduit();
  }
}

package crazypants.enderio.conduit.me;

import net.minecraft.item.ItemStack;
import crazypants.enderio.ModObject;
import crazypants.enderio.conduit.AbstractItemConduit;
import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.ItemConduitSubtype;

public class ItemMEConduit extends AbstractItemConduit {

  private static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] {
      new ItemConduitSubtype(ModObject.itemMEConduit.name(), "enderio:itemMeConduit"),
  };

  public static ItemMEConduit create() {
    ItemMEConduit result = new ItemMEConduit();
    result.init(subtypes);
    return result;
  }

  protected ItemMEConduit() {
    super(ModObject.itemMEConduit);
  }

  @Override
  public Class<? extends IConduit> getBaseConduitType() {
    return IMEConduit.class;
  }

  @Override
  public IConduit createConduit(ItemStack item) {
    return new MEConduit();
  }
}

Fix broken ME conduit textures

Fix broken ME conduit textures


package uk.co.benjiweber.expressions;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import static uk.co.benjiweber.expressions.Using.using;

public class UsingTest {

    static class Foo implements AutoCloseable {

        public String result() {
            return "result";
        }

        boolean closed = false;
        public void close() throws Exception {
            closed = true;
        }
    }

    @Test public void should_return_value() {
        String result = using(Foo::new, foo -> {
            return foo.result();
        });
    }

    @Test public void should_close_closeable() {
        Foo closeable = using(Foo::new, foo -> {
            return foo;
        });

        Assert.assertTrue(closeable.closed);
    }

    Foo foo = new Foo();
    Foo getClosable() {
        return foo;
    }

    @Test public void should_close_closeable_when_exception() {
        try {
            using(this::getClosable, foo -> {
                if (true) throw new NullPointerException();
                return "";
            });
        } catch (NullPointerException e) {
            // Expected
        }

        Assert.assertTrue(foo.closed);
    }

}

package uk.co.benjiweber.expressions;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import static uk.co.benjiweber.expressions.Using.using;

public class UsingTest {

    @Test public void should_return_value() {
        String result = using(Foo::new, foo -> {
            return foo.result();
        });
    }

    @Test public void should_close_closeable() {
        Foo closeable = using(Foo::new, foo -> {
            return foo;
        });

        Assert.assertTrue(closeable.closed);
    }

    @Test public void should_close_closeable_when_exception() {
        try {
            using(this::getClosable, foo -> {
                if (true) throw new NullPointerException();
                return "";
            });
        } catch (NullPointerException e) {
            // Expected
        }

        Assert.assertTrue(foo.closed);
    }

    Foo foo = new Foo();
    Foo getClosable() {
        return foo;
    }

    static class Foo implements AutoCloseable {

        public String result() {
            return "result";
        }

        boolean closed = false;
        public void close() throws Exception {
            closed = true;
        }
    }

}

Move tests to the top

Move tests to the top


package clarifai2.test;

import clarifai2.api.ClarifaiUtil;
import clarifai2.api.request.ClarifaiRequest;
import clarifai2.dto.input.ClarifaiInput;
import clarifai2.dto.input.image.ClarifaiImage;
import clarifai2.dto.model.Model;
import clarifai2.dto.model.output_info.ConceptOutputInfo;
import clarifai2.dto.prediction.Concept;
import org.junit.Test;

public class ConvenienceMethodTests extends BaseClarifaiAPITest {

  @Test public void testAwaitTraining() {

    for (int i = 0; i < 1; i++) {
      assertSuccess(client.deleteAllModels());

      assertSuccess(client.createModel("mod1")
          .withOutputInfo(ConceptOutputInfo.forConcepts(
              Concept.forID("train")
          ))
      );

      assertSuccess(client.addInputs()
          .plus(
              ClarifaiInput.forImage(ClarifaiImage.of(METRO_NORTH_IMAGE_FILE))
                  .withConcepts(
                      Concept.forID("train")
                  )
          )
      );

      final ClarifaiRequest<Model<?>> request = ClarifaiUtil.trainAndAwaitCompletion(client, "mod1");
      if (i == 0) {
        assertSuccessAsync(request);
      } else {
        assertSuccess(request);
      }
    }
  }
}

package clarifai2.test;

import clarifai2.api.ClarifaiUtil;
import clarifai2.api.request.ClarifaiRequest;
import clarifai2.dto.input.ClarifaiInput;
import clarifai2.dto.input.image.ClarifaiImage;
import clarifai2.dto.model.Model;
import clarifai2.dto.model.output_info.ConceptOutputInfo;
import clarifai2.dto.prediction.Concept;
import org.junit.Test;

public class ConvenienceMethodTests extends BaseClarifaiAPITest {

  @Test public void testAwaitTraining() {

    for (int i = 0; i < 1; i++) {
      assertSuccess(client.deleteAllModels());

      assertSuccess(client.addInputs()
          .plus(
              ClarifaiInput.forImage(ClarifaiImage.of(METRO_NORTH_IMAGE_FILE))
                  .withConcepts(
                      Concept.forID("train")
                  )
          )
      );

      assertSuccess(client.createModel("mod1")
          .withOutputInfo(ConceptOutputInfo.forConcepts(
              Concept.forID("train")
          ))
      );

      final ClarifaiRequest<Model<?>> request = ClarifaiUtil.trainAndAwaitCompletion(client, "mod1");
      if (i == 0) {
        assertSuccessAsync(request);
      } else {
        assertSuccess(request);
      }
    }
  }
}

Move input-add before model-create in test


/*
 * Copyright 2015 RITcraft
 *
 * 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.justinwflory.ritcommandcenter;

import org.bukkit.plugin.java.JavaPlugin;

public class RitCommandCenter
        extends JavaPlugin
{
    public void onEnable()
    {
        getCommand("rit").setExecutor(new RitCommand());
    }
}

//TODO if (event getItemInHand().getItemMeta().getCustomName().equals(ChatColor GOLD + "Ritchie")) { //make golden tabby cat }

// if (tired) justin.goToSleep();

Add jumping off place for later work

Add jumping off place for later work


package com.elpatika.stepic.view;

import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.elpatika.stepic.R;
import com.elpatika.stepic.base.BaseFragmentActivity;

import roboguice.inject.InjectView;

public class RegisterActivity extends BaseFragmentActivity {

    @InjectView(R.id.createAccount_button_layout)
    RelativeLayout mCreateAccountButton;

    @InjectView (R.id.actionbar_close_btn)
    View mCloseButton;

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

        setContentView(R.layout.activity_register);
        overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.no_transition);

        mCreateAccountButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createAccount();
            }
        });
        mCloseButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.no_transition, R.anim.slide_out_to_bottom);
    }

    private void createAccount() {
        //todo: create account
        Toast toast =  Toast.makeText(this, "Sorry, this function is unimplemented", Toast.LENGTH_SHORT);
        toast.show();
    }

}

package com.elpatika.stepic.view;

import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.elpatika.stepic.R;
import com.elpatika.stepic.base.BaseFragmentActivity;

import roboguice.inject.InjectView;

public class RegisterActivity extends BaseFragmentActivity {

    @InjectView(R.id.createAccount_button_layout)
    RelativeLayout mCreateAccountButton;

    @InjectView (R.id.actionbar_close_btn)
    View mCloseButton;

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

        setContentView(R.layout.activity_register);
        overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.no_transition);

        hideSoftKeypad();

        mCreateAccountButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createAccount();
            }
        });
        mCloseButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.no_transition, R.anim.slide_out_to_bottom);
    }

    private void createAccount() {
        //todo: create account
        Toast toast =  Toast.makeText(this, "Sorry, this function is unimplemented", Toast.LENGTH_SHORT);
        toast.show();
    }

}

Hide software keypad, when open registration form


package org.kaaproject.data_migration;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.kaaproject.data_migration.utils.Options;

import java.sql.Connection;

import static com.mongodb.client.model.Filters.eq;

public class EndpointProfileMigration {
    private String host;
    private String dbName;
    private String nosql;

    public EndpointProfileMigration(String host, String db, String nosql) {
        dbName = db;
        this.host = host;
        this.nosql = nosql;
    }

    /**
     * Add field use_raw_configuration_schema to endpointProfile that used to support devices using SDK version 0.9.0
     * */
    public void transform() {
        Cluster cluster = Cluster.builder().addContactPoint(host).build();
        MongoClient client = new MongoClient(host);

        //mongo
        MongoDatabase database = client.getDatabase(dbName);
        MongoCollection<Document> endpointProfile = database.getCollection("endpoint_profile");
        endpointProfile.updateMany(new Document(), eq("$set", eq("use_raw_schema", false)));

        //cassandra
//        Session session = cluster.connect(dbName);
//        session.execute("");
//        session.close();
//        cluster.close();

    }
}

package org.kaaproject.data_migration;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.kaaproject.data_migration.utils.Options;

import java.sql.Connection;

import static com.mongodb.client.model.Filters.eq;

public class EndpointProfileMigration {
    private String host;
    private String dbName;
    private String nosql;

    public EndpointProfileMigration(String host, String db, String nosql) {
        dbName = db;
        this.host = host;
        this.nosql = nosql;
    }

    /**
     * Add field use_raw_configuration_schema to endpointProfile that used to support devices using SDK version 0.9.0
     * */
    public void transform() {
        //mongo
        MongoClient client = new MongoClient(host);
        MongoDatabase database = client.getDatabase(dbName);
        MongoCollection<Document> endpointProfile = database.getCollection("endpoint_profile");
        endpointProfile.updateMany(new Document(), eq("$set", eq("use_raw_schema", false)));

        //cassandra
        Cluster cluster = Cluster.builder().addContactPoint(host).build();
        Session session = cluster.connect(dbName);
        session.execute("ALTER TABLE ep_profile ADD use_raw_schema boolean");
        session.close();
        cluster.close();

    }
}

Add field use raw configuration schema toep_profile in Cassandra


package com.yahoo.sketches.tuple;

import java.util.function.Predicate;

/**
 * Class for filtering values from a {@link Sketch} given a {@link Summary}
 *
 * @param <T> Summary type against to which apply the {@link Predicate}
 */
public class Filter<T extends Summary> {
    private Predicate<T> predicate;

    /**
     * Filter constructor with a {@link Predicate}
     *  @param predicate Predicate to use in this filter. If the Predicate returns False, the element is discarded.
     *                 If the Predicate returns True, then the element is kept in the {@link Sketch}
     *
     */
    public Filter(Predicate<T> predicate) {
        this.predicate = predicate;
    }

    /**
     * Filters elements on the provided {@link Sketch}
     *
     * @param sketchIn The sketch against to which apply the {@link Predicate}
     * @return A new Sketch with some of the elements filtered based on the {@link Predicate}
     */
    public CompactSketch<T> filter(Sketch<T> sketchIn) {
        QuickSelectSketch<T> sketch = new QuickSelectSketch<>(sketchIn.getRetainedEntries(), 0, null);
        boolean empty = true;

        final SketchIterator<T> it = sketchIn.iterator();
        while (it.next()) {
            final T summary = it.getSummary();
            if (predicate.test(summary)) {
                sketch.insert(it.getKey(), summary.copy());
                empty = false;
            }
        }

        sketch.setThetaLong(sketchIn.getThetaLong());
        if (!empty)
            sketch.setNotEmpty();

        return sketch.compact();
    }
}

package com.yahoo.sketches.tuple;

import com.yahoo.sketches.ResizeFactor;

import java.util.function.Predicate;

/**
 * Class for filtering values from a {@link Sketch} given a {@link Summary}
 *
 * @param <T> Summary type against to which apply the {@link Predicate}
 */
public class Filter<T extends Summary> {
    private Predicate<T> predicate;

    /**
     * Filter constructor with a {@link Predicate}
     *  @param predicate Predicate to use in this filter. If the Predicate returns False, the element is discarded.
     *                 If the Predicate returns True, then the element is kept in the {@link Sketch}
     *
     */
    public Filter(Predicate<T> predicate) {
        this.predicate = predicate;
    }

    /**
     * Filters elements on the provided {@link Sketch}
     *
     * @param sketchIn The sketch against to which apply the {@link Predicate}
     * @return A new Sketch with some of the elements filtered based on the {@link Predicate}
     */
    public CompactSketch<T> filter(Sketch<T> sketchIn) {
        QuickSelectSketch<T> sketch = new QuickSelectSketch<>(sketchIn.getRetainedEntries(), ResizeFactor.X1.lg(), null);
        boolean empty = true;

        final SketchIterator<T> it = sketchIn.iterator();
        while (it.next()) {
            final T summary = it.getSummary();
            if (predicate.test(summary)) {
                sketch.insert(it.getKey(), summary.copy());
                empty = false;
            }
        }

        sketch.setThetaLong(sketchIn.getThetaLong());
        if (!empty)
            sketch.setNotEmpty();

        return sketch.compact();
    }
}

Use ResizeFactor parameter instead of hardcoded integer


package io.ifar.skidroad.dropwizard.config;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.DecimalMin;

/**
 *
 */
public class RequestLogPrepConfiguration {

    @JsonProperty("master_key")
    @NotEmpty
    private String masterKey;

    /**
     * Fixed master IV no longer used during encryption. May optionally be supplied
     * for decrypting legacy data.
     */
    @JsonProperty("master_iv")
    private String masterIV;

    @JsonProperty("report_unhealthy_at_queue_depth")
    @DecimalMin(value="1")
    private int reportUnhealthyAtQueueDepth = 10;

    @Range(min = 1)
    @JsonProperty("retry_interval_seconds")
    private int retryIntervalSeconds= 300;

    @Range(min = 1)
    @JsonProperty("max_concurrency")
    private Integer maxConcurrency = 5; //depends on network bandwidth, not CPUs

    public String getMasterIV() {
        return masterIV;
    }

    public String getMasterKey() {
        return masterKey;
    }

    public int getReportUnhealthyAtQueueDepth() {
        return reportUnhealthyAtQueueDepth;
    }

    public int getRetryIntervalSeconds() {
        return retryIntervalSeconds;
    }

    public Integer getMaxConcurrency() {
        return maxConcurrency;
    }
}

package io.ifar.skidroad.dropwizard.config;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.DecimalMin;

/**
 *
 */
public class RequestLogPrepConfiguration {

    @JsonProperty("master_key")
    //optional; only needed if using encryption
    private String masterKey;

    /**
     * Fixed master IV no longer used during encryption. May optionally be supplied
     * for decrypting legacy data.
     */
    @JsonProperty("master_iv")
    private String masterIV;

    @JsonProperty("report_unhealthy_at_queue_depth")
    @DecimalMin(value="1")
    private int reportUnhealthyAtQueueDepth = 10;

    @Range(min = 1)
    @JsonProperty("retry_interval_seconds")
    private int retryIntervalSeconds= 300;

    @Range(min = 1)
    @JsonProperty("max_concurrency")
    private Integer maxConcurrency = 5; //depends on network bandwidth, not CPUs

    public String getMasterIV() {
        return masterIV;
    }

    public String getMasterKey() {
        return masterKey;
    }

    public int getReportUnhealthyAtQueueDepth() {
        return reportUnhealthyAtQueueDepth;
    }

    public int getRetryIntervalSeconds() {
        return retryIntervalSeconds;
    }

    public Integer getMaxConcurrency() {
        return maxConcurrency;
    }
}

Make master_key config param optional to support unencrypted workflow


package gov.nih.nci.calab.service.workflow;

/**
 * Generalizes Mask functionality for masking Aliquot, File, etc.
 * @author doswellj
 * @param strType Type of Mask (e.g., aliquot, file, run, etc.)
 * @param strId	  The id associated to the type
 * @param strDescription The mask description associated to the mask type and Id.
 *
 */
public class MaskService
{

	//This functionality is pending the completed Object Model
	public void setMask(String strType, String strId, String strDescription)
    {
        if (strType.equals("aliquot"))
        {
            //TODO Find Aliquot record based on the strID

        	//TODO Set File Status record to "Masked".

        }
        if (strType.equals("file"))
        {
        	//TODO Find File record based on the its strID

        	//TODO Set File Status record to "Masked".
        }

    }

}

package gov.nih.nci.calab.service.workflow;

import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.Aliquot;
import gov.nih.nci.calab.domain.DataStatus;
import gov.nih.nci.calab.service.util.CalabConstants;

import java.util.List;

/**
 * Generalizes Mask functionality for masking Aliquot, File, etc.
 * @author doswellj
 * @param strType Type of Mask (e.g., aliquot, file, run, etc.)
 * @param strId	  The id associated to the type
 * @param strDescription The mask description associated to the mask type and Id.
 *
 */
public class MaskService
{

	//This functionality is pending the completed Object Model
	public void setMask(String strType, String strId, String strDescription) throws Exception
    {
        IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE);

		try {
	        ida.open();

	        if (strType.equals("aliquot"))
	        {
	            //TODO Find Aliquot record based on the strID
				List aliquots = ida.search("from Aliquot aliquot where aliquot.name='" + strId + "'");
				Aliquot aliquot = (Aliquot)aliquots.get(0);
				DataStatus maskStatus = new DataStatus();
				maskStatus.setReason(strDescription);
				maskStatus.setStatus(CalabConstants.MASK_STATUS);

				aliquot.setDataStatus(maskStatus);
				ida.store(aliquot);
	        }
	        if (strType.equals("file"))
	        {
	        	//TODO Find File record based on the its strID

	        	//TODO Set File Status record to "Masked".
	        }
			ida.close();
		}catch (Exception e) {

			ida.rollback();
			ida.close();

			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}

    }

}

Implement the mask aliquot section.

Implement the mask aliquot section.

SVN-Revision: 534


package seedu.address.logic.parser;

import java.util.regex.Pattern;

import seedu.address.logic.parser.ArgumentTokenizer.Prefix;

/**
 * Contains Command Line Interface (CLI) syntax definitions common to multiple commands
 */
public class CliSyntax {

    /* Prefix definitions */
    public static final Prefix PREFIX_BOOK_ADD_DATE = new Prefix("add");
    public static final Prefix PREFIX_BOOK_CHANGE_DATE = new Prefix("change");
    public static final Prefix PREFIX_BOOK_DATE = new Prefix("on ");
    public static final Prefix PREFIX_BOOK_DATE_DELIMITER = new Prefix(",");
    public static final Prefix PREFIX_BOOK_REMOVE_DATE = new Prefix("remove");
    public static final Prefix PREFIX_DEADLINE = new Prefix("by ");
    public static final Prefix PREFIX_TIMEINTERVAL_END = new Prefix("to ");
    public static final Prefix PREFIX_TIMEINTERVAL_START = new Prefix("from ");
    public static final Prefix PREFIX_LABEL = new Prefix("#");
    public static final Prefix PREFIX_STATUS_COMPLETED = new Prefix("completed");
    public static final Prefix PREFIX_STATUS_INCOMPLETE = new Prefix("incomplete");
    public static final Prefix PREFIX_CLEAR_DATES = new Prefix("clear dates");
    public static final Prefix PREFIX_RECURRENCE = new Prefix("repeat every ");
    public static final Prefix PREFIX_REMOVE_RECURRENCE = new Prefix("stop repeat");

    /* Patterns definitions */
    public static final Pattern KEYWORDS_ARGS_FORMAT =
            Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace

}

package seedu.address.logic.parser;

import java.util.regex.Pattern;

import seedu.address.logic.parser.ArgumentTokenizer.Prefix;

/**
 * Contains Command Line Interface (CLI) syntax definitions common to multiple commands
 */
public class CliSyntax {

    /* Prefix definitions */
    public static final Prefix PREFIX_BOOK_ADD_DATE = new Prefix(" add ");
    public static final Prefix PREFIX_BOOK_CHANGE_DATE = new Prefix(" change ");
    public static final Prefix PREFIX_BOOK_DATE = new Prefix(" on ");
    public static final Prefix PREFIX_BOOK_DATE_DELIMITER = new Prefix(",");
    public static final Prefix PREFIX_BOOK_REMOVE_DATE = new Prefix("remove");
    public static final Prefix PREFIX_DEADLINE = new Prefix("by ");
    public static final Prefix PREFIX_TIMEINTERVAL_END = new Prefix(" to ");
    public static final Prefix PREFIX_TIMEINTERVAL_START = new Prefix("from ");
    public static final Prefix PREFIX_LABEL = new Prefix("#");
    public static final Prefix PREFIX_STATUS_COMPLETED = new Prefix("completed");
    public static final Prefix PREFIX_STATUS_INCOMPLETE = new Prefix("incomplete");
    public static final Prefix PREFIX_CLEAR_DATES = new Prefix("clear dates");
    public static final Prefix PREFIX_RECURRENCE = new Prefix("repeat every ");
    public static final Prefix PREFIX_REMOVE_RECURRENCE = new Prefix("stop repeat");

    /* Patterns definitions */
    public static final Pattern KEYWORDS_ARGS_FORMAT =
            Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace

}

Add spaces for keywords to parse more accurately


package org.skywalking.apm.agent.core.plugin.interceptor.enhance;

/**
 * @author wusheng
 */
public interface EnhancedInstance {
    Object getSkyWalkingDynamicField();

    void setSkyWalkingDynamicField();
}

package org.skywalking.apm.agent.core.plugin.interceptor.enhance;

/**
 * @author wusheng
 */
public interface EnhancedInstance {
    Object getSkyWalkingDynamicField();

    void setSkyWalkingDynamicField(Object value);
}

Fix a dynamic interface bug.

Fix a dynamic interface bug.


package com.inmobi.messaging.consumer.databus;

import com.inmobi.databus.FSCheckpointProvider;

/**
 * Configuration properties and their default values for {@link DatabusConsumer}
 */
public interface DatabusConsumerConfig {

  public static final String queueSizeConfig = "databus.consumer.buffer.size";
  public static final int DEFAULT_QUEUE_SIZE = 5000;

  public static final String waitTimeForFlushConfig =
  "databus.consumer.waittime.forcollectorflush";
  public static final long DEFAULT_WAIT_TIME_FOR_FLUSH = 1000; // 1 second

  public static final String databusConfigFileKey = "databus.conf";
  public static final String DEFAULT_DATABUS_CONFIG_FILE = "databus.xml";

  public static final String databusClustersConfig = "databus.consumer.clusters";

  public static final String databusChkProviderConfig =
      "databus.consumer.chkpoint.provider.classname";
  public static final String DEFAULT_CHK_PROVIDER = FSCheckpointProvider.class
  .getName();

  public static final String checkpointDirConfig =
  "databus.consumer.checkpoint.dir";
  public static final String DEFAULT_CHECKPOINT_DIR = ".";

}

package com.inmobi.messaging.consumer.databus;

import com.inmobi.databus.FSCheckpointProvider;

/**
 * Configuration properties and their default values for {@link DatabusConsumer}
 */
public interface DatabusConsumerConfig {

  public static final String queueSizeConfig = "databus.consumer.buffer.size";
  public static final int DEFAULT_QUEUE_SIZE = 5000;

  public static final String waitTimeForFlushConfig =
  "databus.consumer.waittime.forcollectorflush";
  public static final long DEFAULT_WAIT_TIME_FOR_FLUSH = 1000; // 1 second

  public static final String databusConfigFileKey = "databus.conf";
  public static final String DEFAULT_DATABUS_CONFIG_FILE = "databus.xml";

  public static final String databusClustersConfig = "databus.consumer.clusters";

  public static final String databusChkProviderConfig =
      "databus.consumer.chkpoint.provider.classname";
  public static final String DEFAULT_CHK_PROVIDER = FSCheckpointProvider.class
  .getName();

  public static final String checkpointDirConfig =
  "databus.consumer.checkpoint.dir";
  public static final String DEFAULT_CHECKPOINT_DIR = ".";

  public static final String databusConsumerPrincipal =
      "databus.consumer.principal.name";
  public static final String databusConsumerKeytab =
      "databus.consumer.keytab.path";

}

Fix typo in Config name

Fix typo in Config name


/*
 * Copyright 2010-2011 Ning, Inc.
 *
 * Ning 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 com.ning.billing.util.tag;

public enum ControlTagType {
    AUTO_PAY_OFF("Suspends billing until removed.", true, false),
    AUTO_INVOICING_OFF("Suspends invoicing until removed.", false, true);

    private final String description;
    private final boolean autoPaymentOff;
    private final boolean autoInvoicingOff;

    ControlTagType(final String description, final boolean autoPaymentOff, final boolean autoInvoicingOff) {
        this.description = description;
        this.autoPaymentOff = autoPaymentOff;
        this.autoInvoicingOff = autoInvoicingOff;
    }

    public String getDescription() {
        return this.description;
    }

    public boolean autoPaymentOff() {
        return this.autoPaymentOff;
    }

    public boolean autoInvoicingOff() {
        return this.autoInvoicingOff;
    }
}

/*
 * Copyright 2010-2011 Ning, Inc.
 *
 * Ning 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 com.ning.billing.util.tag;

public enum ControlTagType {
    AUTO_PAY_OFF("Suspends payments until removed.", true, false),
    AUTO_INVOICING_OFF("Suspends invoicing until removed.", false, true);

    private final String description;
    private final boolean autoPaymentOff;
    private final boolean autoInvoicingOff;

    ControlTagType(final String description, final boolean autoPaymentOff, final boolean autoInvoicingOff) {
        this.description = description;
        this.autoPaymentOff = autoPaymentOff;
        this.autoInvoicingOff = autoInvoicingOff;
    }

    public String getDescription() {
        return this.description;
    }

    public boolean autoPaymentOff() {
        return this.autoPaymentOff;
    }

    public boolean autoInvoicingOff() {
        return this.autoInvoicingOff;
    }
}

Tag description change for AUTO_PAY_OFF

Tag description change for AUTO_PAY_OFF


package org.achacha.webcardgame.game.dbo;

import org.achacha.base.db.BaseIndexedDbo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Player
 */
public class PlayerDbo extends BaseIndexedDbo {
    private static final Logger LOGGER = LogManager.getLogger(PlayerDbo.class);

    /** Player id */
    protected long id;

    /** Login that owns this player */
    protected long loginId;

    /** Energy stores in the inventory */
    protected long energy;

    /** Inventory */
    protected InventoryDbo inventory;

    @Override
    public long getId() {
        return this.id;
    }

    @Override
    public void fromResultSet(ResultSet rs) throws SQLException {
        this.id = rs.getLong("id");
        this.loginId = rs.getLong("login__id");
        this.energy = rs.getLong("energy");
        this.inventory = InventoryDboFactory.getByPlayerId(this.id);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("fromResultSet: this="+this);
        }
    }

    public long getEnergy() {
        return energy;
    }
}

package org.achacha.webcardgame.game.dbo;

import org.achacha.base.db.BaseIndexedDbo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

/**
 * Player
 */
public class PlayerDbo extends BaseIndexedDbo {
    private static final Logger LOGGER = LogManager.getLogger(PlayerDbo.class);

    /** Player id */
    protected long id;

    /** Login that owns this player */
    protected long loginId;

    /** Energy stores in the inventory */
    protected long energy;

    /** Inventory */
    protected InventoryDbo inventory;

    /** Cards */
    protected Collection<CardDbo> cards;

    @Override
    public long getId() {
        return this.id;
    }

    @Override
    public void fromResultSet(ResultSet rs) throws SQLException {
        this.id = rs.getLong("id");
        this.loginId = rs.getLong("login__id");
        this.energy = rs.getLong("energy");

        this.inventory = InventoryDboFactory.getByPlayerId(this.id);
        this.cards = CardDboFactory.getByPlayerId(this.id);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("fromResultSet: this="+this);
        }
    }

    public long getEnergy() {
        return energy;
    }
}

Add cards loading to player

Add cards loading to player


/*
 *    Copyright 2010 The myBatis Team
 *
 *    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.mybatis.spring;

import org.apache.ibatis.session.SqlSession;
import org.springframework.transaction.support.ResourceHolderSupport;

/**
 *
 * @version $Id$
 */
public final class SqlSessionHolder extends ResourceHolderSupport {

    private final SqlSession session;

    public SqlSessionHolder(SqlSession session) {
        assert session != null;
        this.session = session;
    }

    public SqlSession getSqlSession() {
        return session;
    }

}

/*
 *    Copyright 2010 The myBatis Team
 *
 *    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.mybatis.spring;

import org.apache.ibatis.session.SqlSession;
import org.springframework.transaction.support.ResourceHolderSupport;
import org.springframework.util.Assert;

/**
 *
 * @version $Id$
 */
public final class SqlSessionHolder extends ResourceHolderSupport {

    private final SqlSession sqlSession;

    public SqlSessionHolder(SqlSession sqlSession) {
        Assert.notNull(sqlSession, "SqlSession must not be null");
        this.sqlSession = sqlSession;
    }

    public SqlSession getSqlSession() {
        return sqlSession;
    }

}

Replace 'assert session != null' with Assert.notnull(Object, String)


package org.wikipedia.navtab;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;

public class NavTabFragmentPagerAdapter extends FragmentStatePagerAdapter {
    private Fragment currentFragment;

    public NavTabFragmentPagerAdapter(FragmentManager mgr) {
        super(mgr);
    }

    @Nullable
    public Fragment getCurrentFragment() {
        return currentFragment;
    }

    @Override public Fragment getItem(int pos) {
        return NavTab.of(pos).newInstance();
    }

    @Override public int getCount() {
        return NavTab.size();
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        currentFragment = ((Fragment) object);
        super.setPrimaryItem(container, position, object);
    }
}

package org.wikipedia.navtab;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;

public class NavTabFragmentPagerAdapter extends FragmentPagerAdapter {
    private Fragment currentFragment;

    public NavTabFragmentPagerAdapter(FragmentManager mgr) {
        super(mgr);
    }

    @Nullable
    public Fragment getCurrentFragment() {
        return currentFragment;
    }

    @Override public Fragment getItem(int pos) {
        return NavTab.of(pos).newInstance();
    }

    @Override public int getCount() {
        return NavTab.size();
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        currentFragment = ((Fragment) object);
        super.setPrimaryItem(container, position, object);
    }
}

Change NavTab pager back to FragmentPagerAdapter.

When using a FragmentStatePagerAdapter, the action of swiping between our
Tabs feels noticeably less snappy, since the fragment gets recreated every
time the user swipes to it.

In this particular case, I think that proper memory management must give
way to snappiness.

Change-Id: Ifbce0e7231071d22718d1a2f6071fbe08569efdc


/*
 * Copyright 2005 Joe Walker
 *
 * 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.directwebremoting.extend;

/**
 * @author Joe Walker [joe at getahead dot ltd dot uk]
 */
public class AccessDeniedException extends SecurityException
{
    /**
     * @param s The exception message
     */
    public AccessDeniedException(String s)
    {
        super(s);
    }
}

/*
 * Copyright 2005 Joe Walker
 *
 * 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.directwebremoting.extend;

/**
 * TODO: Work out if this exception actually helps.
 * @author Joe Walker [joe at getahead dot ltd dot uk]
 */
public class AccessDeniedException extends SecurityException
{
    /**
     * Basic constructor - ensure all exceptions have messages
     * @param s The exception message
     */
    public AccessDeniedException(String s)
    {
        super(s);
    }
}

Improve comments Issue number: DWR-50

Improve comments
Issue number:  DWR-50

git-svn-id: ba1d8d5a2a2c535e023d6080c1e5c29aa0f5364e@1202 3a8262b2-faa5-11dc-8610-ff947880b6b2


package au.gov.ga.geodesy.interfaces.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.testng.annotations.BeforeClass;

import au.gov.ga.geodesy.support.spring.GeodesyTestConfig;
import au.gov.ga.geodesy.support.spring.PersistenceJpaConfig;

@ContextConfiguration(
        classes = {GeodesyTestConfig.class, RestConfig.class, PersistenceJpaConfig.class},
        loader = AnnotationConfigWebContextLoader.class)

@WebAppConfiguration
public class RestTest extends AbstractTransactionalTestNGSpringContextTests {

    @Autowired
    private WebApplicationContext webApplicationContext;

    protected static MockMvc mvc;

    @BeforeClass
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
}

package au.gov.ga.geodesy.interfaces.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import org.testng.annotations.BeforeClass;

import au.gov.ga.geodesy.support.spring.GeodesyRestConfig;
import au.gov.ga.geodesy.support.spring.GeodesyTestConfig;
import au.gov.ga.geodesy.support.spring.PersistenceJpaConfig;

@ContextConfiguration(
        classes = {GeodesyTestConfig.class, GeodesyRestConfig.class, PersistenceJpaConfig.class},
        loader = AnnotationConfigWebContextLoader.class)

@WebAppConfiguration
@Transactional("geodesyTransactionManager")
public class RestTest extends AbstractTransactionalTestNGSpringContextTests {

    @Autowired
    private WebApplicationContext webApplicationContext;

    protected static MockMvc mvc;

    @BeforeClass
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
}

Use geodesyTransactionManager in all rest tests.


package rewbot.minecraft.tutorial.crafting;

import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import rewbot.minecraft.tutorial.blocks.MmaBlocks;
import rewbot.minecraft.tutorial.items.MmaItems;

/**
 * Created by ashepherd on 5/22/2016.
 */
public class MmaRecipes {

    public static void initRecipes() {
        //addRecipe takes Java varargs as it's second argument. They let you pass any number of objects of a specific type, in this case object
        GameRegistry.addRecipe(new ItemStack(MmaBlocks.copperBlock),
                "###",
                "###",
                "###",
                '#', MmaItems.copperIngot
        );

        GameRegistry.addShapelessRecipe(new ItemStack(MmaItems.copperIngot, 9),
                MmaBlocks.copperBlock
        );
    }
}

package rewbot.minecraft.tutorial.crafting;

import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import rewbot.minecraft.tutorial.blocks.MmaBlocks;
import rewbot.minecraft.tutorial.items.MmaItems;

/**
 * Created by ashepherd on 5/22/2016.
 */
public class MmaRecipes {

    public static void initRecipes() {
        initCopperRecipes();
        initLaconianRecipes();
    }

    private static void initCopperRecipes() {
        //addRecipe takes Java varargs as it's second argument. They let you pass any number of objects of a specific type, in this case object
        GameRegistry.addRecipe(new ItemStack(MmaBlocks.copperBlock),
                "###",
                "###",
                "###",
                '#', MmaItems.copperIngot
        );

        GameRegistry.addShapelessRecipe(new ItemStack(MmaItems.copperIngot, 9),
                MmaBlocks.copperBlock
        );
    }

    private static void initLaconianRecipes() {
        //Shaped
        //Sword
        GameRegistry.addRecipe(new ItemStack(MmaItems.laconianSword),
                " L ",
                " L ",
                " W ",
                'L', MmaItems.laconianIngot,
                'W', Items.stick
        );

        //Shapeless
        GameRegistry.addShapelessRecipe(new ItemStack(MmaBlocks.laconianOre, 64), Items.diamond);
    }
}

Add recipes for Laconian items

Add recipes for Laconian items

*Diamond to 64 laconian ore
*Laconian sword


package ch.difty.scipamato.publ.web.paper.browse;

import org.apache.wicket.model.Model;

import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter;
import ch.difty.scipamato.publ.web.common.PanelTest;

public class SimpleFilterPanelTest extends PanelTest<SimpleFilterPanel> {

    private static final String PANEL = "panel";

    @Override
    protected SimpleFilterPanel makePanel() {
        return new SimpleFilterPanel(PANEL, Model.of(new PublicPaperFilter()));
    }

    @Override
    protected void assertSpecificComponents() {
        getTester().debugComponentTrees();
        getTester().assertComponent(PANEL, SimpleFilterPanel.class);

        assertLabeledTextField(PANEL, "methodsSearch");
        assertLabeledTextField(PANEL, "authorsSearch");
        assertLabeledTextField(PANEL, "pubYearFrom");
        assertLabeledTextField(PANEL, "pubYearUntil");
        assertLabeledMultiSelect(PANEL, "populationCodes");
        assertLabeledMultiSelect(PANEL, "studyDesignCodes");
    }

}

package ch.difty.scipamato.publ.web.paper.browse;

import org.apache.wicket.model.Model;

import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter;
import ch.difty.scipamato.publ.web.common.PanelTest;

public class SimpleFilterPanelTest extends PanelTest<SimpleFilterPanel> {

    private static final String PANEL = "panel";

    @Override
    protected SimpleFilterPanel makePanel() {
        return new SimpleFilterPanel(PANEL, Model.of(new PublicPaperFilter()));
    }

    @Override
    protected void assertSpecificComponents() {
        getTester().assertComponent(PANEL, SimpleFilterPanel.class);

        assertLabeledTextField(PANEL, "methodsSearch");
        assertLabeledTextField(PANEL, "authorsSearch");
        assertLabeledTextField(PANEL, "pubYearFrom");
        assertLabeledTextField(PANEL, "pubYearUntil");
        assertLabeledMultiSelect(PANEL, "populationCodes");
        assertLabeledMultiSelect(PANEL, "studyDesignCodes");
    }

}

Remove obsolete call to debugComponentTrees


package edu.usc.glidein.service.db;

import edu.usc.glidein.stubs.types.Glidein;
import edu.usc.glidein.stubs.types.GlideinStatus;

public interface GlideinDAO
{
	public int create(Glidein glidein) throws DatabaseException;
	public void store(Glidein glidein) throws DatabaseException;
	public Glidein load(int glideinId) throws DatabaseException;
	public void delete(int glideinId) throws DatabaseException;
	public GlideinStatus getStatus(int glideinId) throws DatabaseException;
	public void updateStatus(int glideinId, GlideinStatus status) throws DatabaseException;
}

package edu.usc.glidein.service.db;

import edu.usc.glidein.stubs.types.Glidein;
import edu.usc.glidein.stubs.types.GlideinStatus;

public interface GlideinDAO
{
	public int create(Glidein glidein) throws DatabaseException;
	public void store(Glidein glidein) throws DatabaseException;
	public Glidein load(int glideinId) throws DatabaseException;
	public void delete(int glideinId) throws DatabaseException;
	public void updateStatus(int glideinId, GlideinStatus status, String statusMessage) throws DatabaseException;
	public Glidein[] list(boolean longFormat) throws DatabaseException;
}

Remove getStatus
Add list
Modify updateStatus

git-svn-id: bdb5f82b9b83a1400e05d69d262344b821646179@1234 e217846f-e12e-0410-a4e5-89ccaea66ff7


package com.astoev.cave.survey;

/**
 * Created by IntelliJ IDEA.
 * User: astoev
 * Date: 1/29/12
 * Time: 5:21 PM
 * To change this template use File | Settings | File Templates.
 */
public class Constants {

    public static final String LOG_TAG_DB = "DB";
    public static final String LOG_TAG_UI = "CaveUI";
    public static final String LOG_TAG_SERVICE = "SRVC";

    public static final String DATE_FORMAT = "dd.MM.yyyy HH:mm:ss";

    public static final String LEG_SELECTED = "leg";
    public static final String LEG_NOTE = "legNote";

    public static enum Measures {distance, slope, angle, up, down, left, right}
}

package com.astoev.cave.survey;

/**
 * Created by IntelliJ IDEA.
 * User: astoev
 * Date: 1/29/12
 * Time: 5:21 PM
 * To change this template use File | Settings | File Templates.
 */
public class Constants {

    public static final String LOG_TAG_DB = "DB";
    public static final String LOG_TAG_UI = "CaveUI";
    public static final String LOG_TAG_SERVICE = "SRVC";

    public static final String DATE_FORMAT = "yyyyMMdd_HHmmss";

    public static final String LEG_SELECTED = "leg";
    public static final String LEG_NOTE = "legNote";

    public static enum Measures {distance, slope, angle, up, down, left, right}
}

Change date format not to include spaces


package org.springframework.roo.process.manager.internal;

import java.io.File;
import java.util.logging.Logger;

import org.springframework.roo.file.undo.FilenameResolver;
import org.springframework.roo.support.logging.HandlerUtils;
import org.springframework.roo.support.util.Assert;

public class ManagedMessageRenderer {
	private static final Logger logger = HandlerUtils.getLogger(ManagedMessageRenderer.class);
	private FilenameResolver filenameResolver;
	private File file;
	private String descriptionOfChange = null;
	private boolean createOperation;

	public void setDescriptionOfChange(String message) {
		this.descriptionOfChange = message;
	}

	public ManagedMessageRenderer(FilenameResolver filenameResolver, File file, boolean createOperation) {
		Assert.notNull(filenameResolver, "Filename resolver required");
		Assert.notNull(file, "File to manage required");
		this.filenameResolver = filenameResolver;
		this.file = file;
		this.createOperation = createOperation;
	}

	void logManagedMessage() {
		StringBuilder message = new StringBuilder();
		if (createOperation) {
			message.append("Created ");
		} else {
			message.append("Managed ");
		}
		message.append(filenameResolver.getMeaningfulName(file));
		if (descriptionOfChange != null && descriptionOfChange.length() > 0) {
			message.append(" [");
			message.append(descriptionOfChange);
			message.append("]");
		}
		logger.fine(message.toString());
	}
}

package org.springframework.roo.process.manager.internal;

import java.io.File;
import java.util.logging.Logger;

import org.springframework.roo.file.undo.FilenameResolver;
import org.springframework.roo.support.logging.HandlerUtils;
import org.springframework.roo.support.util.Assert;

public class ManagedMessageRenderer {
	private static final Logger logger = HandlerUtils.getLogger(ManagedMessageRenderer.class);
	private FilenameResolver filenameResolver;
	private File file;
	private String descriptionOfChange = null;
	private boolean createOperation;

	public void setDescriptionOfChange(String message) {
		this.descriptionOfChange = message;
	}

	public ManagedMessageRenderer(FilenameResolver filenameResolver, File file, boolean createOperation) {
		Assert.notNull(filenameResolver, "Filename resolver required");
		Assert.notNull(file, "File to manage required");
		this.filenameResolver = filenameResolver;
		this.file = file;
		this.createOperation = createOperation;
	}

	void logManagedMessage() {
		StringBuilder message = new StringBuilder();
		if (createOperation) {
			message.append("Created ");
		} else {
			message.append("Updated ");
		}
		message.append(filenameResolver.getMeaningfulName(file));
		if (descriptionOfChange != null && descriptionOfChange.length() > 0) {
			message.append(" [");
			message.append(descriptionOfChange);
			message.append("]");
		}
		logger.fine(message.toString());
	}
}

ROO-1875: Improve file system management messages by using "Updated" instead of "Managed" verb


package org.motechproject.appointments.api.osgi;

import org.motechproject.appointments.api.service.AppointmentService;
import org.motechproject.appointments.api.service.contract.CreateVisitRequest;
import org.motechproject.appointments.api.service.contract.VisitResponse;
import org.motechproject.testing.osgi.BaseOsgiIT;
import org.osgi.framework.ServiceReference;

import java.util.List;
import java.util.UUID;

import static java.util.Arrays.asList;

public class AppointmentsApiBundleIT extends BaseOsgiIT {

    public void testAppointmentService() {
        ServiceReference serviceReference = bundleContext.getServiceReference(AppointmentService.class.getName());
        assertNotNull(serviceReference);
        AppointmentService appointmentService = (AppointmentService) bundleContext.getService(serviceReference);
        assertNotNull(appointmentService);

        final String externalId = "AppointmentsApiBundleIT-" + UUID.randomUUID();
        String visitName = "Visit-" + externalId;
        CreateVisitRequest request = new CreateVisitRequest().setVisitName(visitName);
        appointmentService.addVisit(externalId, request);
        VisitResponse response = appointmentService.findVisit(externalId, visitName);
        assertNotNull(response);
        assertEquals(visitName, response.getName());
        // Delete the doc in the post-integration phase
    }

    @Override
    protected List<String> getImports() {
        return asList(
                "org.motechproject.appointments.api.service.contract",
                "org.motechproject.appointments.api.service"
        );
    }
}

package org.motechproject.appointments.api.osgi;

import org.motechproject.appointments.api.service.AppointmentService;
import org.motechproject.appointments.api.service.contract.CreateVisitRequest;
import org.motechproject.appointments.api.service.contract.VisitResponse;
import org.motechproject.testing.osgi.BaseOsgiIT;

import java.util.List;
import java.util.UUID;

import static java.util.Arrays.asList;

public class AppointmentsApiBundleIT extends BaseOsgiIT {

    public void testAppointmentService() {
        AppointmentService appointmentService = getService(AppointmentService.class);

        final String externalId = "AppointmentsApiBundleIT-" + UUID.randomUUID();
        String visitName = "Visit-" + externalId;
        CreateVisitRequest request = new CreateVisitRequest().setVisitName(visitName);
        appointmentService.addVisit(externalId, request);
        VisitResponse response = appointmentService.findVisit(externalId, visitName);
        assertNotNull(response);
        assertEquals(visitName, response.getName());
        // Delete the doc in the post-integration phase
    }

    @Override
    protected List<String> getImports() {
        return asList(
                "org.motechproject.appointments.api.service.contract",
                "org.motechproject.appointments.api.service"
        );
    }
}

Remove redundant code from bundle ITs

MOTECH-795: Remove redundant code from bundle ITs

After recent changes to OSGi ITs, some code can be removed.

Change-Id: I632f17113b22fa0de7483cbac1c1566c2d8d436f


/**
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.jboss.pnc.model;

/**
 * Statuses of build process.
 *
 * @author Jakub Bartecek <jbartece@redhat.com>
 *
 */
public enum BuildStatus {
    SUCCESS, FAILED, UNSTABLE, BUILDING, REJECTED, CANCELLED, SYSTEM_ERROR, UNKNOWN
}

/**
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.jboss.pnc.model;

/**
 * Status of a running or completed build.
 *
 * @author Jakub Bartecek <jbartece@redhat.com>
 *
 */
public enum BuildStatus {
    /**
     * Build completed successfully
     */
    SUCCESS,

    /**
     * Build failed
     */
    FAILED,

    /**
     * Build completed with test failures
     */
    UNSTABLE,

    /**
     * Build currently running
     */
    BUILDING,

    /**
     * Build rejected due to conflict with another build, or failed dependency build
     */
    REJECTED,

    /**
     * User cancelled the build
     */
    CANCELLED,

    /**
     * A system error prevented the build from completing
     */
    SYSTEM_ERROR,

    /**
     * It is not known what the build status is at this time
     */
    UNKNOWN
}

Add comments describing the build status enum


package org.jsmpp.session;

import org.jsmpp.bean.DeliverSm;
import org.jsmpp.extra.ProcessMessageException;

/**
 * This listener will listen to every incomming short message, recognized by
 * deliver_sm command. The logic on this listener should be accomplish in a
 * short time, because the deliver_sm_resp will be processed after the logic
 * executed. Normal logic will be return the deliver_sm_resp with zero valued
 * command_status, or throw {@link ProcessMessageException} that gave non-zero
 * valued command_status (in means negative response) depends on the given error
 * code specified on the {@link ProcessMessageException}.
 *
 * @author uudashr
 * @version 1.0
 * @since 2.0
 *
 */
public interface MessageReceiverListener {

    /**
     * Event that called when an short message accepted.
     *
     * @param deliverSm is the deliver_sm command.
     * @throws ProcessMessageException throw if there should be return Non-OK
     *         command_status for the response.
     */
    public void onAcceptDeliverSm(DeliverSm deliverSm)
            throws ProcessMessageException;
}

package org.jsmpp.session;

import org.jsmpp.bean.DeliverSm;
import org.jsmpp.extra.ProcessMessageException;

/**
 * This listener will listen to every incoming short message, recognized by
 * deliver_sm command. The logic on this listener should be accomplish in a
 * short time, because the deliver_sm_resp will be processed after the logic
 * executed. Normal logic will be return the deliver_sm_resp with zero valued
 * command_status, or throw {@link ProcessMessageException} that gave non-zero
 * valued command_status (in means negative response) depends on the given error
 * code specified on the {@link ProcessMessageException}.
 *
 * @author uudashr
 * @version 1.0
 * @since 2.0
 *
 */
public interface MessageReceiverListener {

    /**
     * Event that called when an short message accepted.
     *
     * @param deliverSm is the deliver_sm command.
     * @throws ProcessMessageException throw if there should be return Non-OK
     *         command_status for the response.
     */
    public void onAcceptDeliverSm(DeliverSm deliverSm)
            throws ProcessMessageException;
}

Update the comment spelling :-p

Update the comment spelling :-p

git-svn-id: 8aef34885c21801cc977f98956a081c938212632@12 1678c8a9-8d33-0410-b0a4-d546c816ed44


package org.traccar.protocol;

import org.junit.Test;
import org.traccar.ProtocolTest;

public class JpKorjarProtocolDecoderTest extends ProtocolTest {

    @Test
    public void testDecode() throws Exception {

        JpKorjarProtocolDecoder decoder = new JpKorjarProtocolDecoder(new JpKorjarProtocol());

        verifyPosition(decoder, text(
                "KORJAR.PL,329587014519383,160910144240,52.247254N,021.013375E,0.00,1,F:4.18V,1 260 01 794B 3517,"));

    }

}

package org.traccar.protocol;

import org.junit.Test;
import org.traccar.ProtocolTest;

public class JpKorjarProtocolDecoderTest extends ProtocolTest {

    @Test
    public void testDecode() throws Exception {

        JpKorjarProtocolDecoder decoder = new JpKorjarProtocolDecoder(new JpKorjarProtocol());

        verifyPosition(decoder, text(
                "KORJAR.PL,329587014519383,160910144240,52.247254N,021.013375E,0.00,1,F:4.18V,1 260 01 794B 3517,"));

        verifyPosition(decoder, text(
                "KORJAR.PL,329587014519383,160910144240,52.895515N,021.949151E,6.30,212,F:3.94V,0 260 01 794B 3519,"));

        verifyPosition(decoder, text(
                "KORJAR.PL,329587014519383,160910144240,52.895596N,021.949343E,12.46,087,L:2.18V,1 260 01 794B 3517,"));

    }

}

Add jpkorjar tests showcasing changing attributes


public class ArrayAnalyzerLarge {
  public static void main(String[] args) {
    ArrayUtil au = new ArrayUtil();
    //StopWatch sw = new StopWatch();

    int size = 10000000;
    int valueSize = 250000001;

    for (int i=0; i<11; i++) {
      int[] array = au.randomIntArray(size, valueSize);
      size += 10000000;

      evalArray(array, i);
    }
  }

  private static void evalArray(int[] array, int count) {
    StopWatch sw = new StopWatch();

    int min = array[0];
    int max = array[0];
    int average = 0;

    sw.reset();
    sw.start();

    for (int i=0; i<array.length; i++) {
      if (array[i] < min) {
        min = array[i];
      }

      if (array[i] > max) {
        max = array[i];
      }

      average += array[i];
    }
    average = average / array.length;

    sw.stop();

    System.out.println("[ARRAY #" + count + "] " + "Min: " + min + "; Max: " + max + "; Average: " + average +
                       "; Elapsed Time: " + sw.getElapsedTime() + " milliseconds");
  }
}

public class ArrayAnalyzerLarge {
  public static void main (String[] args) {

    ArrayUtil au = new ArrayUtil();
    //StopWatch sw = new StopWatch();

    int size = 10000000;
    int valueSize = 250000001;

    for (int i=0; i<11; i++) {
      int[] array = au.randomIntArray(size, valueSize);
      size += 10000000;

      evalArray(array, i);
    }
  }

  private static void evalArray(int[] array, int count) {
    StopWatch sw = new StopWatch();

    int min = array[0];
    int max = array[0];
    long average = 0;

    sw.reset();
    sw.start();

    for (int i=0; i<array.length; i++) {
      if (array[i] < min) {
        min = array[i];
      }

      if (array[i] > max) {
        max = array[i];
      }

      average += array[i];
    }
    average = average / array.length;

    sw.stop();

    System.out.println("[ARRAY #" + count + "] " + "Min: " + min + "; Max: " + max + "; Average: " + average +
                       "; Elapsed Time: " + sw.getElapsedTime() + " milliseconds");
  }
}

Change int to long - now runs as expected


package com.twu.biblioteca;

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

public class BibliotecaAppTest {

    @Test
    public void testWelcomeMessage() {
        ByteArrayOutputStream outContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outContent));

        BibliotecaApp.main(new String[] {});
        assertEquals("Welcome to Biblioteca!\n", outContent.toString());
    }
}

package com.twu.biblioteca;

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.StringBuilder;
import java.util.List;
import java.util.ArrayList;

public class BibliotecaAppTest {

    @Test
    public void testBibliotecaStartup() {
        List<String> bookList = new ArrayList<String>();
        bookList.add("Test-Driven Development By Example");
        bookList.add("The Agile Samurai");
        bookList.add("Head First Java");
        bookList.add("Don't Make Me Think, Revisited: A Common Sense Approach to Web Usability");

        StringBuilder startupOutput = new StringBuilder();
        startupOutput.append("Welcome to Biblioteca!\n");
        startupOutput.append("Book list:\n");
        for (String book : bookList) {
            startupOutput.append(book + "\n");
        }

        ByteArrayOutputStream outContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outContent));
        BibliotecaApp.main(new String[] {});

        assertEquals(startupOutput.toString(), outContent.toString());
    }
}

Test display welcome and book list on startup


package net.vexelon.currencybg.srv.reports;

import java.io.IOException;

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

import com.pengrad.telegrambot.Callback;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.TelegramBotAdapter;
import com.pengrad.telegrambot.request.SendDocument;
import com.pengrad.telegrambot.response.SendResponse;

import net.vexelon.currencybg.srv.GlobalConfig;

public class TelegramReporter extends AbstractReporter {

	private static final Logger log = LoggerFactory.getLogger(TelegramReporter.class);

	public TelegramReporter(String name) {
		super(name);
	}

	public TelegramReporter() {
		this("Telegram");
	}

	@Override
	public void send() throws IOException {

		TelegramBot bot = TelegramBotAdapter
				.build(/* "264497873:AAGjShbt3-CJkuSHJLwyMccTbvh-0PxNZ68" */GlobalConfig.INSTANCE.getBotToken());

		bot.execute(new SendDocument(/* "@ceco88" */GlobalConfig.INSTANCE.getBotChannel(),
				buffer.toString().getBytes("UTF-8")), new Callback<SendDocument, SendResponse>() {
					@Override
					public void onFailure(SendDocument request, IOException e) {
						log.error("Telegram SendDocument failed!", e);
					};

					@Override
					public void onResponse(SendDocument request, SendResponse response) {
						// do nothing
					};
				});
	}

}

package net.vexelon.currencybg.srv.reports;

import java.io.IOException;

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

import com.pengrad.telegrambot.Callback;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.TelegramBotAdapter;
import com.pengrad.telegrambot.request.SendDocument;
import com.pengrad.telegrambot.response.SendResponse;

import net.vexelon.currencybg.srv.GlobalConfig;

public class TelegramReporter extends AbstractReporter {

	private static final Logger log = LoggerFactory.getLogger(TelegramReporter.class);

	public TelegramReporter(String name) {
		super(name);
	}

	public TelegramReporter() {
		this("Telegram");
	}

	@Override
	public void send() throws IOException {
		if (!GlobalConfig.INSTANCE.getBotToken().isEmpty() && !GlobalConfig.INSTANCE.getBotChannel().isEmpty()) {

			TelegramBot bot = TelegramBotAdapter.build(GlobalConfig.INSTANCE.getBotToken());

			bot.execute(new SendDocument(/* "@ceco88" */GlobalConfig.INSTANCE.getBotChannel(),
					buffer.toString().getBytes("UTF-8")), new Callback<SendDocument, SendResponse>() {
						@Override
						public void onFailure(SendDocument request, IOException e) {
							log.error("Telegram SendDocument failed!", e);
						};

						@Override
						public void onResponse(SendDocument request, SendResponse response) {
							// do nothing
						};
					});
		}
	}

}

Send Telegram msg only if channel and bot properties are set


package uk.ac.ebi.spot.goci.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * Created by emma on 22/04/2016.
 *
 * @author emma
 *         <p>
 *         Model to process response from: http://rest.ensembl.org/lookup/symbol/homo_sapiens/SFRP1?content-type=application/json
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class GeneLookupJson {

    private String object_type;

    public String getObject_type() {
        return object_type;
    }

    public void setObject_type(String object_type) {
        this.object_type = object_type;
    }
}

package uk.ac.ebi.spot.goci.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * Created by emma on 22/04/2016.
 *
 * @author emma
 *         <p>
 *         Model to process response from: http://rest.ensembl.org/lookup/symbol/homo_sapiens/SFRP1?content-type=application/json
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class GeneLookupJson {

    private String object_type;

    private String seq_region_name;

    public String getObject_type() {
        return object_type;
    }

    public void setObject_type(String object_type) {
        this.object_type = object_type;
    }

    public String getSeq_region_name() {
        return seq_region_name;
    }

    public void setSeq_region_name(String seq_region_name) {
        this.seq_region_name = seq_region_name;
    }
}

Add attribute to capture seq region name


package org.rundeck.client.api.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by greg on 5/20/16.
 */

@JsonIgnoreProperties(ignoreUnknown = true)
public class DateInfo {
    public String date;
    public long unixtime;

    public DateInfo(final String date) {
        this.date = date;
    }

    public DateInfo() {
    }

    public Date toDate() throws ParseException {
        return toDate("yyyy-MM-dd'T'HH:mm:ss'Z'");
    }
    public Date toDate(final String format) throws ParseException {
        SimpleDateFormat asdf = new SimpleDateFormat(format, Locale.US);
        return asdf.parse(date);
    }

    public String toRelative() throws ParseException {
        Date now = new Date();
        return toRelative(now);
    }

    public String toRelative(final Date time) throws ParseException {
        long diff = time.getTime() - toDate().getTime();
        return String.format("%dms ago", diff);
    }

    @Override
    public String toString() {
        return "{" +
               date +
               ", unixtime=" + unixtime +
               '}';
    }
}

package org.rundeck.client.api.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.rundeck.client.util.Env;
import org.rundeck.client.util.Format;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by greg on 5/20/16.
 */

@JsonIgnoreProperties(ignoreUnknown = true)
public class DateInfo {
    public String date;
    public long unixtime;

    public DateInfo(final String date) {
        this.date = date;
    }

    public DateInfo() {
    }

    public Date toDate() throws ParseException {
        return toDate("yyyy-MM-dd'T'HH:mm:ss'Z'");
    }

    /**
     * Format using the default or configured date format
     * @return
     */
    public String format() {
        try {
            return Format.date(toDate(), Env.getString("DATE_FORMAT", "yyyy-MM-ddHH:mm:ssZ"));
        } catch (ParseException e) {
            return "?";
        }
    }

    public Date toDate(final String format) throws ParseException {
        SimpleDateFormat asdf = new SimpleDateFormat(format, Locale.US);
        return asdf.parse(date);
    }

    public String toRelative() throws ParseException {
        Date now = new Date();
        return toRelative(now);
    }

    public String toRelative(final Date time) throws ParseException {
        long diff = time.getTime() - toDate().getTime();
        return String.format("%dms ago", diff);
    }

    @Override
    public String toString() {
        return "{" +
               date +
               ", unixtime=" + unixtime +
               '}';
    }
}

Format date info using default format or env var DATE_FORMAT


/*
 * Copyright (c) 2008 Chris Pettitt
 */

package com.samsarin.gatu.primitive;

import java.util.BitSet;

/**
 * @author cpettitt@samsarin.com
 */
/* package private */ abstract class AbstractChromosome implements Chromosome {

    /**
     * Returns the chromosome as a {@link BitSet}.
     * @return the BitSet view of this chromosome
     */
    abstract BitSet bitSetValue();

    public boolean get(int index) {
        checkBounds(index);
        return bitSetValue().get(index);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) return true;

        if (!(obj instanceof AbstractChromosome)) return false;
        return bitSetValue().equals(((AbstractChromosome)obj).bitSetValue());
    }

    @Override
    public int hashCode() {
        return bitSetValue().hashCode();
    }

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

    private void checkBounds(int index) {
        if (index < 0 || index >= length()) {
            throw new IndexOutOfBoundsException("Index out of bounds. Expected 0 <= index < "
                    + length() + ". Actual: " + index);
        }
    }
}

/*
 * Copyright (c) 2008 Chris Pettitt
 */

package com.samsarin.gatu.primitive;

import java.util.BitSet;

/**
 * @author cpettitt@samsarin.com
 */
/* package private */ abstract class AbstractChromosome implements Chromosome {

    /**
     * Returns the chromosome as a {@link BitSet}.
     * @return the BitSet view of this chromosome
     */
    abstract BitSet bitSetValue();

    public boolean get(int index) {
        checkBounds(index);
        return bitSetValue().get(index);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) return true;

        if (!(obj instanceof AbstractChromosome)) return false;
        return bitSetValue().equals(((AbstractChromosome)obj).bitSetValue());
    }

    @Override
    public int hashCode() {
        return bitSetValue().hashCode();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Chromosome[");
        for (int i = 0; i < length(); ++i) {
            sb.append(get(i) ? '1' : '0');
        }
        sb.append("]");
        return sb.toString();
    }

    private void checkBounds(int index) {
        if (index < 0 || index >= length()) {
            throw new IndexOutOfBoundsException("Index out of bounds. Expected 0 <= index < "
                    + length() + ". Actual: " + index);
        }
    }
}

Change Chromosome toString() to show actual bit string


/*
 * 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.datasketches.memory.test;

import org.apache.datasketches.memory.internal.VirtualMachineMemory;
import org.testng.annotations.Test;

@SuppressWarnings("javadoc")
public class VirtualMachineMemoryTest {

    @Test
    public void maxDirectBufferMemory() {
       assert(VirtualMachineMemory.getMaxDBBMemory() >= 0);
    }

    @Test
    public void inertPageAlignment() {
        System.out.println("VM page alignment:" + VirtualMachineMemory.getIsPageAligned());
        assert(true);
    }
}

/*
 * 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.datasketches.memory.test;

import org.apache.datasketches.memory.internal.VirtualMachineMemory;
import org.testng.annotations.Test;

@SuppressWarnings("javadoc")
public class VirtualMachineMemoryTest {

    @Test
    public void maxDirectBufferMemory() {
       assert(VirtualMachineMemory.getMaxDBBMemory() >= 0);
    }

    @Test
    public void inertPageAlignment() {
      boolean result = VirtualMachineMemory.getIsPageAligned();
      //System.out.println("VM page alignment:" + result);
      assert(true); //no exception was thrown
    }
}

Disable test printing to stdOut

Disable test printing to stdOut


package de.danoeh.antennapod;

public final class AppConfig {
    public final static boolean DEBUG = false;
}

package de.danoeh.antennapod;

public final class AppConfig {
    public final static boolean DEBUG = true;
}

DEBUG should usually be set to true

DEBUG should usually be set to true


package org.baswell.routes;

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

public class RoutesServlet extends HttpServlet
{
  private RoutesEntry routesEntry;

  @Override
  public void init(ServletConfig config) throws ServletException
  {
    super.init(config);
    routesEntry = new RoutesEntry();
  }

  @Override
  protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException
  {
    if (!routesEntry.process(servletRequest, servletResponse))
    {
      servletResponse.sendError(404);
    }
  }
}

package org.baswell.routes;

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

public class RoutesServlet extends HttpServlet
{
  private static RoutesEntry routesEntry = new RoutesEntry();

  @Override
  protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException
  {
    if (!routesEntry.process(servletRequest, servletResponse))
    {
      servletResponse.setStatus(404);
    }
  }
}

Make RoutesEntry static incase servlet is instianted for each request.


package ca.islandora.sync.routes;

import org.apache.camel.builder.RouteBuilder;
import org.fcrepo.camel.JmsHeaders;
import org.fcrepo.camel.RdfNamespaces;
import ca.islandora.sync.processors.DrupalNodeCreateJsonTransform;

public class DrupalNodeCreate extends RouteBuilder {
    public void configure() throws Exception {

        from("activemq:topic:fedora")
            .routeId("fedoraIn")
            .filter(header(JmsHeaders.EVENT_TYPE).contains(RdfNamespaces.REPOSITORY + "NODE_ADDED"))
                .to("fcrepo:localhost:8080/fcrepo/rest")
                .process(new DrupalNodeCreateJsonTransform())
                .to("http4:localhost/islandora/node")
                .log("RESPONSE: ${headers} / ${body}")
                .to("mock:result");
    }
}

package ca.islandora.sync.routes;

import org.apache.camel.builder.RouteBuilder;
import org.fcrepo.camel.JmsHeaders;
import org.fcrepo.camel.RdfNamespaces;
import ca.islandora.sync.processors.DrupalNodeCreateJsonTransform;

public class DrupalNodeCreate extends RouteBuilder {
    public void configure() throws Exception {

        from("activemq:topic:fedora")
            .routeId("fedoraIn")
            .filter(header(JmsHeaders.EVENT_TYPE).contains(RdfNamespaces.REPOSITORY + "NODE_ADDED"))
                .to("fcrepo:localhost:8080/fcrepo/rest")
                .process(new DrupalNodeCreateJsonTransform())
                .to("http4:localhost:8000/islandora/node")
                .log("RESPONSE: ${headers} / ${body}")
                .to("mock:result");
    }
}

Use local port for now.

Use local port for now.


package com.philliphsu.bottomsheetpickers.view.numberpad;

import com.philliphsu.bottomsheetpickers.view.LocaleModel;

public class NumberPadTimePickerDialogPresenterTest extends NumberPadTimePickerPresenterTest {
    @Override
    Class<? extends INumberPadTimePicker.DialogView> getViewClass() {
        return INumberPadTimePicker.DialogView.class;
    }

    @Override
    INumberPadTimePicker.DialogPresenter createPresenter(INumberPadTimePicker.View view,
                                                   LocaleModel localeModel,
                                                   boolean is24HourMode) {
        return new NumberPadTimePickerDialogPresenter((INumberPadTimePicker.DialogView) view,
                localeModel, is24HourMode);
    }
}

package com.philliphsu.bottomsheetpickers.view.numberpad;

import com.philliphsu.bottomsheetpickers.view.LocaleModel;

public class NumberPadTimePickerDialogPresenterTest extends NumberPadTimePickerPresenterTest {

    @Override
    INumberPadTimePicker.DialogView getView(int mode) {
        return (INumberPadTimePicker.DialogView) super.getView(mode);
    }

    @Override
    INumberPadTimePicker.DialogPresenter getPresenter(int mode) {
        return (INumberPadTimePicker.DialogPresenter) super.getPresenter(mode);
    }

    @Override
    Class<? extends INumberPadTimePicker.DialogView> getViewClass() {
        return INumberPadTimePicker.DialogView.class;
    }

    @Override
    INumberPadTimePicker.DialogPresenter createPresenter(INumberPadTimePicker.View view,
                                                   LocaleModel localeModel,
                                                   boolean is24HourMode) {
        return new NumberPadTimePickerDialogPresenter((INumberPadTimePicker.DialogView) view,
                localeModel, is24HourMode);
    }
}

Change return type of getView() and getPresenter() for Dialogs.


package com.veyndan.redditclient;

import com.veyndan.redditclient.api.reddit.network.QueryBuilder;
import com.veyndan.redditclient.api.reddit.network.Sort;

public class SubredditFilter {

    final private String subreddit;
    final private Sort sort;
    final private QueryBuilder query;

    public SubredditFilter(final String subreddit, final Sort sort) {
        this(subreddit, sort, new QueryBuilder());
    }

    public SubredditFilter(final String subreddit, final Sort sort, final QueryBuilder query) {
        this.subreddit = subreddit;
        this.sort = sort;
        this.query = query;
    }

    public String getSubreddit() {
        return subreddit;
    }

    public Sort getSort() {
        return sort;
    }

    public QueryBuilder getQuery() {
        return query;
    }
}

package com.veyndan.redditclient;

import com.veyndan.redditclient.api.reddit.network.QueryBuilder;
import com.veyndan.redditclient.api.reddit.network.Sort;

public class SubredditFilter {

    private final String subreddit;
    private final Sort sort;
    private final QueryBuilder query;

    public SubredditFilter(final String subreddit, final Sort sort) {
        this(subreddit, sort, new QueryBuilder());
    }

    public SubredditFilter(final String subreddit, final Sort sort, final QueryBuilder query) {
        this.subreddit = subreddit;
        this.sort = sort;
        this.query = query;
    }

    public String getSubreddit() {
        return subreddit;
    }

    public Sort getSort() {
        return sort;
    }

    public QueryBuilder getQuery() {
        return query;
    }
}

Swap order of private and final keywords


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

import com.github.aureliano.achmed.command.CommandResponse;

public class RedHatService extends LinuxService {

	public RedHatService() {
		super();
	}

	@Override
	public CommandResponse enableBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public CommandResponse disableBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public boolean isEnabledInBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}
}

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

import org.apache.log4j.Logger;

import com.github.aureliano.achmed.command.CommandFacade;
import com.github.aureliano.achmed.command.CommandResponse;

public class RedHatService extends LinuxService {

	private static final Logger logger = Logger.getLogger(RedHatService.class);
	private static final String SERVICE = "/sbin/service";

	public RedHatService() {
		super();
	}

	@Override
	public boolean isRunning() {
		if ((super.properties.getHasStatus() != null) && (super.properties.getHasStatus())) {
			CommandResponse res = CommandFacade.executeCommand(SERVICE, super.properties.getName(), "status");
			return (res.getExitStatusCode() == 0);
		}

		return super.isRunning();
	}

	@Override
	public CommandResponse enableBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public CommandResponse disableBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public boolean isEnabledInBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}
}

Implement method to check whether service is running.