package game;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import game.MenuScreens.MainMenu;

/**
 * Created by eriks on 26/10/2016.
 */

/**
 * Games entry point.
 */
public class BlueSky extends Game {

    // Game world size in arbitrary scale, these are not pixels
    public static final int GAME_WIDTH = 640;
    public static final int GAME_HEIGHT = 640;

    // Game version for global use
    public static final double VERSION = 0.2;

    SpriteBatch batch;

    private static SimpleLogger myLog = SimpleLogger.getLogger();

    /**
     * Analogue to instantiation. Loads all the assets to the memory. Creates a {@link SimpleLogger} and {@link SpriteBatch}.
     */
    public void create(){
        batch = new SpriteBatch();

        // Pre-loading all the assets for the game
        Assets.load();

        myLog.setLogFile("BlueSky");
        myLog.setLogLevel(SimpleLogger.DEBUG);
        myLog.info("Starting...");
        this.setScreen(new MainMenu(this));
    }

    /**
     * Renders a {@link Screen}
     */
    public void render(){
        super.render();
    }

    /**
     * Disposes of all teh assets that are not collected by garbage collector. This method runs automatically.
     */
    public void dispose(){
        batch.dispose();
        Assets.dispose();
    }
}

package game;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import game.MenuScreens.MainMenu;

/**
 * Created by eriks on 26/10/2016.
 */

/**
 * Games entry point.
 */
public class BlueSky extends Game {

    // Game world size in arbitrary scale, these are not pixels
    public static final int GAME_WIDTH = 640;
    public static final int GAME_HEIGHT = 640;

    // Game version for global use
    public static final double VERSION = 0.2;

    SpriteBatch batch;

    private static SimpleLogger myLog = SimpleLogger.getLogger();

    /**
     * Analogue to instantiation. Loads all the assets to the memory. Creates a {@link SimpleLogger} and {@link SpriteBatch}.
     */
    public void create(){
        batch = new SpriteBatch();

        // Pre-loading all the assets for the game
        Assets.load();

        myLog.setLogFile("BlueSky");
        myLog.setLogLevel(SimpleLogger.INFO);
        myLog.info("Starting...");
        this.setScreen(new MainMenu(this));
    }

    /**
     * Renders a {@link Screen}
     */
    public void render(){
        super.render();
    }

    /**
     * Disposes of all teh assets that are not collected by garbage collector. This method runs automatically.
     */
    public void dispose(){
        batch.dispose();
        Assets.dispose();
    }
}

Set log level to info

Set log level to info

Set log level to info for presentation


package com.molina.cvmfs.directoryentry;

import com.molina.cvmfs.directoryentry.exception.ChunkFileDoesNotMatch;

/**
 * @author Jose Molina Colmenero
 *         <p/>
 *         Wrapper around file chunks in the CVMFS catalogs
 */
public class Chunk {

    protected int offset;
    protected int size;
    protected String contentHash;
    protected int contentHashType;

    public Chunk(Object[] chunkData, int contentHashType) throws ChunkFileDoesNotMatch {
        if (chunkData.length != 5)
            throw new ChunkFileDoesNotMatch();
        this.offset = (Integer) chunkData[2];
        this.size = (Integer) chunkData[3];
        this.contentHash = new String((byte[]) chunkData[4]);
        this.contentHashType = contentHashType;
    }

    public static String catalogDatabaseFields() {
        return "md5path_1, md5path_2, offset, size, hash";
    }

    public String contentHashString() {
        String suffix = ContentHashTypes.toSuffix(contentHashType);
        StringBuilder sb = new StringBuilder();
        for (byte b : contentHash.getBytes())
            sb.append(String.format("%02X ", b));
        return sb.toString().toLowerCase() + suffix;
    }
}

package com.molina.cvmfs.directoryentry;

import com.molina.cvmfs.directoryentry.exception.ChunkFileDoesNotMatch;

import org.sqldroid.SQLDroidBlob;

import java.sql.SQLException;

/**
 * @author Jose Molina Colmenero
 *         <p/>
 *         Wrapper around file chunks in the CVMFS catalogs
 */
public class Chunk {

    protected int offset;
    protected int size;
    protected String contentHash;
    protected int contentHashType;

    public Chunk(Object[] chunkData, int contentHashType) throws ChunkFileDoesNotMatch {
        if (chunkData.length != 5)
            throw new ChunkFileDoesNotMatch();
        this.offset = (Integer) chunkData[2];
        this.size = (Integer) chunkData[3];
        this.contentHashType = contentHashType;
        if (chunkData[4] instanceof byte[]) {
            this.contentHash = new String((byte[]) chunkData[4]);
        } else if (chunkData[4] instanceof SQLDroidBlob){
            SQLDroidBlob blob = (SQLDroidBlob) chunkData[4];
            try {
                this.contentHash = new String(blob.getBytes(0, (int) blob.length()));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static String catalogDatabaseFields() {
        return "md5path_1, md5path_2, offset, size, hash";
    }

    public String contentHashString() {
        String suffix = ContentHashTypes.toSuffix(contentHashType);
        StringBuilder sb = new StringBuilder();
        for (byte b : contentHash.getBytes())
            sb.append(String.format("%02X ", b));
        return sb.toString().toLowerCase() + suffix;
    }
}

Fix chunks when using the SQLDroid library


package ninja;

import ninja.utils.NinjaConstant;

import com.google.inject.Inject;

/**
 *
 * @author svenkubiak
 *
 */
public class AuthenticityFilter implements Filter {

    private NinjaDefault ninjaDefault;

    @Inject
    public AuthenticityFilter(NinjaDefault ninjaDefault) {
        this.ninjaDefault = ninjaDefault;
    }

    @Override
    public Result filter(FilterChain filterChain, Context context) {
        String authenticityToken = context.getParameter(NinjaConstant.AUTHENTICITY_TOKEN);
        if (!context.getSession().getAuthenticityToken().equals(authenticityToken)) {
            return ninjaDefault.getForbiddenResult(context);
        }

        return filterChain.next(context);
    }
}

package ninja;

import ninja.utils.NinjaConstant;

import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author svenkubiak
 *
 */
public class AuthenticityFilter implements Filter {
    static private final Logger logger = LoggerFactory.getLogger(AuthenticityFilter.class);

    private final Ninja ninja;

    @Inject
    public AuthenticityFilter(Ninja ninja) {
        this.ninja = ninja;
    }

    @Override
    public Result filter(FilterChain filterChain, Context context) {
        String authenticityToken = context.getParameter(NinjaConstant.AUTHENTICITY_TOKEN);

        if (!context.getSession().getAuthenticityToken().equals(authenticityToken)) {
            logger.warn("Authenticity token mismatch. Request from {} is forbidden!", context.getRemoteAddr());
            return ninja.getForbiddenResult(context);
        }

        return filterChain.next(context);
    }
}

Use Ninja not NinjaDefault. Log filtered authenticity requests.


package com.thoughtworks.xstream.core.util;

public final class ClassStack {

    private Class[] stack;
    private int pointer;

    public ClassStack(int initialCapacity) {
        stack = new Class[initialCapacity];
    }

    public void push(Class value) {
        if (pointer + 1 >= stack.length) {
            resizeStack(stack.length * 2);
        }
        stack[pointer++] = value;
    }

    public void popSilently() {
        pointer--;
    }

    public Class pop() {
        return stack[--pointer];
    }

    public Class peek() {
        return pointer == 0 ? null : stack[pointer - 1];
    }

    public int size() {
        return pointer;
    }

    public Class get(int i) {
        return stack[i];
    }

    private void resizeStack(int newCapacity) {
        Class[] newStack = new Class[newCapacity];
        System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
        stack = newStack;
    }
}

package com.thoughtworks.xstream.core.util;

public final class ClassStack {

    private Class[] stack;
    private int pointer;

    public ClassStack(int initialCapacity) {
        stack = new Class[initialCapacity];
    }

    public void push(Class value) {
        if (pointer + 1 >= stack.length) {
            resizeStack(stack.length * 2);
        }
        stack[pointer++] = value;
    }

    public void popSilently() {
        stack[--pointer] = null;
    }

    public Class pop() {
        final Class result = stack[--pointer];
        stack[pointer] = null;
        return result;
    }

    public Class peek() {
        return pointer == 0 ? null : stack[pointer - 1];
    }

    public int size() {
        return pointer;
    }

    public Class get(int i) {
        return stack[i];
    }

    private void resizeStack(int newCapacity) {
        Class[] newStack = new Class[newCapacity];
        System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
        stack = newStack;
    }
}

Drop references from popped classes.

Drop references from popped classes.

git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@704 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e


/**
 * This file is part of the Android DependencyManager project hosted at
 * http://code.google.com/p/android-dependencymanager/
 *
 * Copyright (C) 2009 Jens Finkhaeuser <jens@finkhaeuser.de>
 *
 * 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 de.finkhaeuser.dm.testapp;

import android.app.Activity;
import android.os.Bundle;

public class TestApp extends Activity
{
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
}

/**
 * This file is part of the Android DependencyManager project hosted at
 * http://code.google.com/p/android-dependencymanager/
 *
 * Copyright (C) 2009 Jens Finkhaeuser <jens@finkhaeuser.de>
 *
 * 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 de.finkhaeuser.dm.testapp;

import android.app.Activity;
import android.os.Bundle;

import android.database.Cursor;

import android.net.Uri;

import de.finkhaeuser.dm.common.DependencyManagerContract;
import de.finkhaeuser.dm.common.DependencyManagerContract.DependencyColumns;

public class TestApp extends Activity
{
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // XXX This'll need to change. It's just to launch the DpendencyManager
    // right now.
    Cursor managedCursor = managedQuery(
        Uri.parse(String.format("content://%s/%s",
            DependencyManagerContract.CONTENT_AUTHORITY,
            DependencyManagerContract.PATH_LIST_CANDIDATES)),
        DependencyColumns.CANDIDATE_PROJECTION,
        null,          // WHERE clause.
        null,          // WHERE clause value substitution
        null);   // Sort order.
  }
}

Add minimal code necessary to instanciate DependencyManager - will be changed again.


/*
Copyright 2011 Selenium committers

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.openqa.selenium.support;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.openqa.selenium.support.pagefactory.UsingPageFactoryTest;
import org.openqa.selenium.support.ui.SelectLargeTest;

@RunWith(Suite.class)
@Suite.SuiteClasses({
    SelectLargeTest.class,
    UsingPageFactoryTest.class
})
public class LargeTests {}

/*
Copyright 2011 Selenium committers

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.openqa.selenium.support;

import org.junit.AfterClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.openqa.selenium.support.pagefactory.UsingPageFactoryTest;
import org.openqa.selenium.support.ui.SelectLargeTest;
import org.openqa.selenium.testing.JUnit4TestBase;

@RunWith(Suite.class)
@Suite.SuiteClasses({
    SelectLargeTest.class,
    UsingPageFactoryTest.class
})
public class LargeTests {

  @AfterClass
  public static void cleanUpDrivers() {
    JUnit4TestBase.removeDriver();
  }

}

SimonStewart: Clean up the driver instance once the large tests for the support classes are done

r16955


package roart.model;

import java.util.List;

public class LearnTestClassify {
    public Object[][] array;
    public Object[] cat;
    public List<List<Object>> listlist;
    public int modelInt;
    public int size;
    public String period;
    public String mapname;
    public int outcomes;
    public Double prob;
}

package roart.model;

public class LearnTestClassify {
    private Object[][] trainingarray;

    private Object[] trainingcatarray;

    private Object[][] classifyarray;

    private Object[] classifycatarray;

    private int modelInt;

    private int size;

    private String period;

    private String mapname;

    private int outcomes;

    private Double accuracy;

    public LearnTestClassify() {
        super();
    }

    public Object[][] getTrainingarray() {
        return trainingarray;
    }

    public void setTrainingarray(Object[][] trainingarray) {
        this.trainingarray = trainingarray;
    }

    public Object[] getTrainingcatarray() {
        return trainingcatarray;
    }

    public void setTrainingcatarray(Object[] catarray) {
        this.trainingcatarray = catarray;
    }

    public Object[][] getClassifyarray() {
        return classifyarray;
    }

    public void setClassifyarray(Object[][] classifyarray) {
        this.classifyarray = classifyarray;
    }

    public Object[] getClassifycatarray() {
        return classifycatarray;
    }

    public void setClassifycatarray(Object[] classifycatarray) {
        this.classifycatarray = classifycatarray;
    }

    public int getModelInt() {
        return modelInt;
    }

    public void setModelInt(int modelInt) {
        this.modelInt = modelInt;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public String getPeriod() {
        return period;
    }

    public void setPeriod(String period) {
        this.period = period;
    }

    public String getMapname() {
        return mapname;
    }

    public void setMapname(String mapname) {
        this.mapname = mapname;
    }

    public int getOutcomes() {
        return outcomes;
    }

    public void setOutcomes(int outcomes) {
        this.outcomes = outcomes;
    }

    public Double getAccuracy() {
        return accuracy;
    }

    public void setAccuracy(Double accuracy) {
        this.accuracy = accuracy;
    }

}

Use getter/setter. Change field names.

Use getter/setter. Change field names.


package org.jboss.shamrock.example.testutils;

import java.io.InputStream;

import javax.json.JsonReader;

public interface URLResponse {

    int statusCode();

    String asString();

    InputStream asInputStream();

    JsonReader asJsonReader();
}

package org.jboss.shamrock.example.testutils;

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

import javax.json.JsonReader;

public interface URLResponse {

    int statusCode();

    IOException exception();

    String asString();

    InputStream asInputStream();

    JsonReader asJsonReader();
}

Add support for accessing the response exception


package util;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.*;

/**
 * Retrofit interfaces wrapping Filestack API.
 */
public class FilestackService {

    public interface Api {
        String URL = "https://www.filestackapi.com/api/file/";

        @POST("{handle}")
        Call<ResponseBody> overwrite(@Path("handle") String handle, @Query("policy") String policy,
                                     @Query("signature") String signature, @Body RequestBody body);

        @DELETE("{handle}")
        Call<ResponseBody> delete(@Path("handle") String handle, @Query("key") String key,
                                  @Query("policy") String policy, @Query("signature") String signature);
    }

    public interface Cdn {
        String URL = "https://cdn.filestackcontent.com/";

        @GET("{handle}")
        @Streaming
        Call<ResponseBody> get(@Path("handle") String handle, @Query("policy") String policy,
                               @Query("signature") String signature);
    }

    public interface Process {
        String URL = "https://process.filestackapi.com/";

        @Streaming
        @GET("{tasks}/{handle}")
        Call<ResponseBody> get(@Path("tasks") String tasks, @Path("handle") String handle);
    }
}

package util;

import com.google.gson.JsonObject;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.*;

/**
 * Retrofit interfaces wrapping Filestack API.
 */
public class FilestackService {

    public interface Api {
        String URL = "https://www.filestackapi.com/api/file/";

        @POST("{handle}")
        Call<ResponseBody> overwrite(@Path("handle") String handle, @Query("policy") String policy,
                                     @Query("signature") String signature, @Body RequestBody body);

        @DELETE("{handle}")
        Call<ResponseBody> delete(@Path("handle") String handle, @Query("key") String key,
                                  @Query("policy") String policy, @Query("signature") String signature);
    }

    public interface Cdn {
        String URL = "https://cdn.filestackcontent.com/";

        @GET("{handle}")
        @Streaming
        Call<ResponseBody> get(@Path("handle") String handle, @Query("policy") String policy,
                               @Query("signature") String signature);
    }

    public interface Process {
        String URL = "https://process.filestackapi.com/";

        @Streaming
        @GET("{tasks}/{handle}")
        Call<ResponseBody> get(@Path("tasks") String tasks, @Path("handle") String handle);

        @GET("debug/{tasks}/{handle}")
        Call<JsonObject> debug(@Path("tasks") String tasks, @Path("handle") String handle);
    }
}

Add debug method to Retrofit process service


package dmax.dialog;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;

/**
 * Created by Maxim Dybarsky | maxim.dybarskyy@gmail.com
 * on 13.01.15 at 17:34
 */
class ProgressLayout extends FrameLayout {

    private static final int DEFAULT_COUNT = 5;
    private int spotsCount;

    public ProgressLayout(Context context) {
        this(context, null);
    }

    public ProgressLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ProgressLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public ProgressLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        TypedArray a = getContext().getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.Dialog,
                defStyleAttr, defStyleRes);

        spotsCount = a.getInt(R.styleable.Dialog_DialogSpotCount, DEFAULT_COUNT);
        a.recycle();
    }

    public int getSpotsCount() {
        return spotsCount;
    }
}

package dmax.dialog;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.FrameLayout;

/**
 * Created by Maxim Dybarsky | maxim.dybarskyy@gmail.com
 * on 13.01.15 at 17:34
 */
class ProgressLayout extends FrameLayout {

    private static final int DEFAULT_COUNT = 5;
    private int spotsCount;

    public ProgressLayout(Context context) {
        this(context, null);
    }

    public ProgressLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ProgressLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs, defStyleAttr, 0);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ProgressLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs, defStyleAttr, defStyleRes);
    }

    private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        TypedArray a = getContext().getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.Dialog,
                defStyleAttr, defStyleRes);

        spotsCount = a.getInt(R.styleable.Dialog_DialogSpotCount, DEFAULT_COUNT);
        a.recycle();
    }

    public int getSpotsCount() {
        return spotsCount;
    }
}

Fix constructor invokation (pre-lollipop support)


/*
  Suppose you have a lot of files in a directory that contain words
  Exercisei_j, where i and j are digits. Write a program that pads a 0 before
  i if i is a single digit and 0 before j if j is a single digit. For example,
  the word Exercise2_1 in a file will be replaced by Exercise02_01. Use the
  following command to run our program. Use the following command to run your
  program.

  java E12_27 *
*/

import java.io.File;

public class E12_27 {
  public static void main(String[] args) {
    for (String s: args) {
      File file = new File(s);
      if (s.matches(".*Exercise\\d_\\d.*")) {
        StringBuilder sb = new StringBuilder(s);
        int index = sb.indexOf("Exercise");
        sb.insert((index + 8), "0");
        sb.insert((index + 11), "0");
        File newName = new File(sb.toString());
        file.renameTo(newName);
      }
    }
  }
}

/*
  Suppose you have a lot of files in a directory that contain words
  Exercisei_j, where i and j are digits. Write a program that pads a 0 before
  i if i is a single digit and 0 before j if j is a single digit. For example,
  the word Exercise2_1 in a file will be replaced by Exercise02_01. Use the
  following command to run our program. Use the following command to run your
  program.

  java E12_27 *
*/

import java.io.File;

public class E12_27 {
  public static void main(String[] args) {
    for (String s: args) {
      File file = new File(s);
      StringBuilder sb = new StringBuilder(s);
      if (s.matches("Exercise\\d_\\d")) {
        sb.insert(8, "0");
        sb.insert(11, "0");
      } else if (s.matches("Exercise\\d_\\d+")) {
        sb.insert(8, "0");
      } else if (s.matches("Exercise\\d+_\\d")) {
        sb.insert(11, "0");
      }
      File newName = new File(sb.toString());
      file.renameTo(newName);
    }
  }
}

Modify solution to fit the exercise specifications more closely


package com.sanchez.fmf.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.OkHttpClient;

import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;

/**
 * Created by dakota on 9/2/15.
 */
public class RestClient {

    private static final String BASE_URL = "http://10.0.2.2:5000";
    private MarketService marketService;

    public RestClient() {

        Gson gson = new Gson();

        RestAdapter retrofit = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.NONE)
                .setEndpoint(BASE_URL)
                .setClient(new OkClient(new OkHttpClient()))
                .setConverter(new GsonConverter(gson))
                .build();

        marketService = retrofit.create(MarketService.class);
    }

    public MarketService getMarketService() {
        return marketService;
    }
}

package com.sanchez.fmf.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.OkHttpClient;

import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;

/**
 * Created by dakota on 9/2/15.
 */
public class RestClient {

    private static final String BASE_URL = "http://138.197.218.95";
    private MarketService marketService;

    public RestClient() {

        Gson gson = new Gson();

        RestAdapter retrofit = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.NONE)
                .setEndpoint(BASE_URL)
                .setClient(new OkClient(new OkHttpClient()))
                .setConverter(new GsonConverter(gson))
                .build();

        marketService = retrofit.create(MarketService.class);
    }

    public MarketService getMarketService() {
        return marketService;
    }
}

Update endpoint to remote api

Update endpoint to remote api


package org.pdxfinder.repositories;

import org.pdxfinder.dao.Marker;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

import java.util.Collection;
import java.util.List;

/**
 * Interface for Markers
 */
public interface MarkerRepository extends PagingAndSortingRepository<Marker, Long> {

    @Query("MATCH (t:Marker) WHERE t.symbol = {symbol} RETURN t")
    Marker findBySymbol(@Param("symbol") String symbol);

    @Query("MATCH (t:Marker) WHERE t.name = {name} RETURN t")
    Marker findByName(@Param("name") String name);

    @Query("MATCH (m:Marker) RETURN m")
    Collection<Marker> findAllMarkers();

    @Query("MATCH (s:Sample)--(:MolecularCharacterization)--(:MarkerAssociation)--(m:Marker) WHERE s.sourceSampleId = {sampleId}  return m")
    Collection<Marker> findAllBySampleId(@Param("sampleId") String sampleId);

}

package org.pdxfinder.repositories;

import org.pdxfinder.dao.Marker;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

import java.util.Collection;
import java.util.List;

/**
 * Interface for Markers
 */
public interface MarkerRepository extends PagingAndSortingRepository<Marker, Long> {

    @Query("MATCH (t:Marker) WHERE t.symbol = {symbol} RETURN t")
    Marker findBySymbol(@Param("symbol") String symbol);

    @Query("MATCH (t:Marker) WHERE t.name = {name} RETURN t")
    Marker findByName(@Param("name") String name);

    @Query("MATCH (m:Marker) RETURN m")
    Collection<Marker> findAllMarkers();

    @Query("MATCH (s:Sample)--(:MolecularCharacterization)--(:MarkerAssociation)--(m:Marker) RETURN m")
    Collection<Marker> findAllHumanMarkers();

    @Query("MATCH (s:Sample)--(:MolecularCharacterization)--(:MarkerAssociation)--(m:Marker) WHERE s.sourceSampleId = {sampleId}  return m")
    Collection<Marker> findAllBySampleId(@Param("sampleId") String sampleId);

}

Add method for human markers

Add method for human markers


package au.gov.dva.sopapi.sopref.data;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.*;
import java.nio.charset.Charset;

public class Conversions {

    public static String pdfToPlainText(byte[] pdf) throws IOException {

        RandomAccessBuffer randomAccessBuffer = new RandomAccessBuffer(pdf);
        PDFParser pdfParser = new PDFParser(randomAccessBuffer);
        pdfParser.parse();
        COSDocument cosDocument = pdfParser.getDocument();
        PDDocument pdDocument = new PDDocument(cosDocument);
        PDFTextStripper pdfTextStripper = new PDFTextStripper();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        Writer outWriter = new OutputStreamWriter(outStream, Charsets.UTF_8);
        pdfTextStripper.writeText(pdDocument,outWriter);

        String text = outStream.toString("UTF-8");

        pdDocument.close();
        randomAccessBuffer.close();
        cosDocument.close();
        outStream.close();
        return text;
    }

    public static String toString(JsonNode jsonNode) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
    }

}

package au.gov.dva.sopapi.sopref.data;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.IOException;

public class Conversions {

    public static String pdfToPlainText(byte[] pdf) throws IOException {

        RandomAccessBuffer randomAccessBuffer = new RandomAccessBuffer(pdf);
        PDFParser pdfParser = new PDFParser(randomAccessBuffer);
        pdfParser.parse();
        COSDocument cosDocument = pdfParser.getDocument();
        PDDocument pdDocument = new PDDocument(cosDocument);
        PDFTextStripper pdfTextStripper = new PDFTextStripper();
        String text = pdfTextStripper.getText(pdDocument);
        pdDocument.close();
        randomAccessBuffer.close();
        cosDocument.close();

        return text;
    }

    public static String toString(JsonNode jsonNode) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
    }

}

Revert "text conversion changes attempt to fix encoding issue"

This reverts commit eadd90fdaf595936744559c78932204b5554621b.


package com.gitrekt.resort.model.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "resort.packages")
public class Package {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "price_per_person")
    private double pricePerPerson;

    public Package(String name, double pricePerPerson){
        this.name = name;
        this.pricePerPerson = pricePerPerson;
    }

    public String getName(){
        return name;
    }

    //Returns the price rate per person for the package
    public double getPricePerPerson(){
        return pricePerPerson;
    }
}

package com.gitrekt.resort.model.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "resort.packages")
public class Package {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "price_per_person")
    private double pricePerPerson;

    public Package(String name, double pricePerPerson){
        this.name = name;
        this.pricePerPerson = pricePerPerson;
    }

    public String getName(){
        return name;
    }

    public double getPricePerPerson(){
        return pricePerPerson;
    }
}

Fix extra line in package class

Fix extra line in package class


package com.jakewharton.trakt.enumerations;

import java.util.HashMap;
import java.util.Map;
import com.jakewharton.trakt.TraktEnumeration;

public enum Rating implements TraktEnumeration {
    Love("love"),
    Hate("hate"),
    Unrate("unrate");

    private final String value;

    private Rating(String value) {
        this.value = value;
    }

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

    private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>();

    static {
        for (Rating via : Rating.values()) {
            STRING_MAPPING.put(via.toString().toUpperCase(), via);
        }
    }

    public static Rating fromValue(String value) {
        return STRING_MAPPING.get(value.toUpperCase());
    }
}

package com.jakewharton.trakt.enumerations;

import java.util.HashMap;
import java.util.Map;
import com.jakewharton.trakt.TraktEnumeration;

public enum Rating implements TraktEnumeration {
    WeakSauce("1"),
    Terrible("2"),
    Bad("3"),
    Poor("4"),
    Meh("5"),
    Fair("6"),
    Good("7"),
    Great("8"),
    Superb("9"),
    TotallyNinja("10"),
    Unrate("0");

    private final String value;

    private Rating(String value) {
        this.value = value;
    }

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

    private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>();

    static {
        for (Rating via : Rating.values()) {
            STRING_MAPPING.put(via.toString().toUpperCase(), via);
        }
    }

    public static Rating fromValue(String value) {
        return STRING_MAPPING.get(value.toUpperCase());
    }
}

Use new rating values. It is recommended to always send the new ones, so removed Love and Hate and modified Unrate to be 0 instead of 'unrate'.


package fr.masciulli.drinks.activity;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import fr.masciulli.drinks.R;

public class DrinkDetailActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drink);
    }
}

package fr.masciulli.drinks.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;

import fr.masciulli.drinks.R;

public class DrinkDetailActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drink);
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home :
                finish();
                return true;
        }
        return false;
    }
}

Set display home as up

Set display home as up


package basic;

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

    // hello world
    HelloWorld hello = new HelloWorld();
    hello.sayIt();

    // -------------------------------------------------------------------
    System.out.print(String.format("\n\n%60s\n\n", "").replace(' ', '-'));

    Factorial fact = new Factorial();

    long factResult = fact.factorialize(5);
    System.out.println(factResult);

    // -------------------------------------------------------------------
    System.out.print(String.format("\n\n%60s\n\n", "").replace(' ', '-'));

    int[] list = {5, 2, 4, 3, 1};
    SortableList sortList = new SortableList(list);

    int[] sorted = sortList.sort();

    System.out.println(sortList.toString());

  }
}

package basic;

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

    // hello world
    System.out.println("Obligatory 'Hello, world!'");
    HelloWorld hello = new HelloWorld();
    hello.sayIt();

    // -------------------------------------------------------------------
    System.out.print(String.format("\n\n%60s\n\n", "").replace(' ', '-'));

    System.out.println("Factorial");
    Factorial fact = new Factorial();

    for (int i = 0; i < 20; i++) {
      System.out.printf("%2s! = %s\n", i, fact.factorialize(i));
    }

    // -------------------------------------------------------------------
    System.out.print(String.format("\n\n%60s\n\n", "").replace(' ', '-'));

    System.out.println("Merge sort");
    int[] list = {5, 2, 4, 3, 1};
    SortableList sortList = new SortableList(list);

    int[] sorted = sortList.sort();

    System.out.println(sortList.toString());

  }
}

Add some labels to the sections

Add some labels to the sections


package com.samsung.sprc.fileselector;

import java.io.File;

/**
 * A set of tools for file operations
 */
public class FileUtils {

  /** Filter which accepts every file */
  public static final String FILTER_ALLOW_ALL = "*.*";

  /**
   * This method checks that the file is accepted by the filter
   *
   * @param file
   *            - file that will be checked if there is a specific type
   * @param filter
   *            - criterion - the file type(for example ".jpg")
   * @return true - if file meets the criterion - false otherwise.
   */
  public static boolean accept(final File file, final String filter) {
    if (filter.compareTo(FILTER_ALLOW_ALL) == 0) {
      return true;
    }
    if (file.isDirectory()) {
      return true;
    }
    int lastIndexOfPoint = file.getName().lastIndexOf('.');
    if (lastIndexOfPoint == -1) {
      return false;
    }
    String fileType = file.getName().substring(lastIndexOfPoint).toLowerCase();
    return fileType.compareTo(filter) == 0;
  }
}

package com.samsung.sprc.fileselector;

import java.io.File;

/**
 * A set of tools for file operations
 */
public class FileUtils {

  /** Filter which accepts every file */
  public static final String FILTER_ALLOW_ALL = "*.*";

  /**
   * This method checks that the file is accepted by the filter
   *
   * @param file
   *            - file that will be checked if there is a specific type
   * @param filter
   *            - criterion - the file type(for example ".jpg")
   * @return true - if file meets the criterion - false otherwise.
   */
  public static boolean accept(final File file, final String filter) {
    if (filter.compareTo(FILTER_ALLOW_ALL) == 0) {
      return true;
    }
    if (file.isDirectory()) {
      return true;
    }
    int lastIndexOfPoint = file.getName().lastIndexOf('.');
    if (lastIndexOfPoint == -1) {
      return false;
    }
    String fileType = "*" + file.getName().substring(lastIndexOfPoint).toLowerCase();
    return fileType.compareTo(filter) == 0;
  }
}

Allow wildcard star in filter list; "*.txt" instead of ".txt"


package water.runner;

import org.junit.Ignore;
import water.*;

import java.util.Set;

@Ignore
public class CleanNewKeysTask extends KeysMRTask<CleanNewKeysTask> {

    @Override
    protected void setupLocal() {
        final Set<Key> initKeys = LocalTestRuntime.initKeys;
        final Set<Key> actualKeys = H2O.localKeySet();
        for (Key actualKey : actualKeys){

            final Value value = Value.STORE_get(actualKey);
            if (initKeys.contains(actualKey) || isIgnorableKeyLeak(actualKey, value)) continue;
            if (!(value.get() instanceof Keyed)) {
                // Keyed objects might override remove_impl to excerscise their own removal strategy
                // Non-keyed objects should just be removed from the DKV
                DKV.remove(actualKey);
            } else {
                actualKey.remove();
            }
        }

    }

}

package water.runner;

import org.junit.Ignore;
import water.*;

import java.util.Set;

@Ignore
public class CleanNewKeysTask extends KeysMRTask<CleanNewKeysTask> {

    @Override
    protected void setupLocal() {
        DKVManager.retain(LocalTestRuntime.initKeys.toArray(new Key[0]));
    }

}

Use DKVManager to clean newly added keys.


package com.msupplymobile;

import com.facebook.react.ReactActivity;
import com.babisoft.ReactNativeLocalization.ReactNativeLocalizationPackage;
import io.realm.react.RealmReactPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import android.os.Bundle;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

public class MainActivity extends ReactActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    }

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "mSupplyMobile";
    }

    @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
      return new ReactActivityDelegate(this, getMainComponentName()) {
      @Override
      protected ReactRootView createRootView() {
        return new RNGestureHandlerEnabledRootView(MainActivity.this);
      }
    };
  }
}

package com.msupplymobile;

import com.facebook.react.ReactActivity;
import com.babisoft.ReactNativeLocalization.ReactNativeLocalizationPackage;
import io.realm.react.RealmReactPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import android.os.Bundle;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

public class MainActivity extends ReactActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(null);
    }

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "mSupplyMobile";
    }

    @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
      return new ReactActivityDelegate(this, getMainComponentName()) {
      @Override
      protected ReactRootView createRootView() {
        return new RNGestureHandlerEnabledRootView(MainActivity.this);
      }
    };
  }
}

Add use null instead of savedInstanceState in ReactActivity


package br.com.bloder.blorm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import br.com.bloder.blormlib.Blorm;
import br.com.bloder.blormlib.validation.Validate;

import static br.com.bloder.blormlib.validation.Validations.*;

public class MainActivity extends AppCompatActivity {

  private EditText editTextFilled;
  private Button submit;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editTextFilled = (EditText) findViewById(R.id.edit_text_filled);
    submit = (Button) findViewById(R.id.submit);

    new Blorm.Builder().field(editTextFilled).is(filled).onSubmit(submit);

    new Blorm.Builder().field(editTextFilled).is(new Validate() {
      @Override
      public boolean validate() {
        return false;
      }

      @Override
      public void onError() {

      }
    }).onSubmit(submit);
  }
}

package br.com.bloder.blorm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import br.com.bloder.blormlib.Blorm;
import br.com.bloder.blormlib.validation.Action;
import br.com.bloder.blormlib.validation.Validate;

import static br.com.bloder.blormlib.validation.Validations.*;

public class MainActivity extends AppCompatActivity {

  private EditText editTextFilled;
  private Button submit;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editTextFilled = (EditText) findViewById(R.id.edit_text_filled);
    submit = (Button) findViewById(R.id.submit);

    editTextFilled.setText("Hello");

        new Blorm.Builder().field(editTextFilled).is(filled).onSuccess(new Action() {
          @Override
          public void call() {
            onSuccess();
          }}
        ).onSubmit(submit);
  }

  private void onSuccess() {
    editTextFilled.setError(null);
    Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
  }
}

Add validation success example in main activity


/*
 * VowlData.java
 *
 */

package de.uni_stuttgart.vis.vowl.owl2vowl.model;

import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.AbstractNode;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.classes.AbstractClass;

import org.semanticweb.owlapi.model.IRI;

import java.util.HashMap;

/**
 * Contains all data WebVOWL needs.
 */
public class VowlData {

	private HashMap<IRI, AbstractClass> classMap = new HashMap<>();

	public void addClass(AbstractClass vowlClass) {
		classMap.put(vowlClass.getIri(), vowlClass);
	}

	public AbstractNode getNodeForIri(IRI iri) {
		if (classMap.containsKey(iri)) {
			return classMap.get(iri);
		} else {
			throw new IllegalStateException("Can't find node for passed iri: " + iri);
		}
	}
}

/*
 * VowlData.java
 *
 */

package de.uni_stuttgart.vis.vowl.owl2vowl.model;

import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.AbstractNode;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.classes.AbstractClass;
import org.semanticweb.owlapi.model.IRI;

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

/**
 * Contains all data WebVOWL needs.
 */
public class VowlData {

	private HashMap<IRI, AbstractClass> classMap = new HashMap<>();

	public Map<IRI, AbstractClass> getClassMap() {
		return Collections.unmodifiableMap(classMap);
	}

	public void addClass(AbstractClass vowlClass) {
		classMap.put(vowlClass.getIri(), vowlClass);
	}

	public AbstractNode getNodeForIri(IRI iri) {
		if (classMap.containsKey(iri)) {
			return classMap.get(iri);
		} else {
			throw new IllegalStateException("Can't find node for passed iri: " + iri);
		}
	}
}

Add getter for vowl data

Add getter for vowl data


package ml.duncte123.skybot.commands.animals;

import ml.duncte123.skybot.Command;
import ml.duncte123.skybot.utils.AirUtils;
import ml.duncte123.skybot.utils.URLConnectionReader;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import org.json.JSONArray;
import org.json.JSONObject;

public class LlamaCommand extends Command {
    @Override
    public boolean called(String[] args, GuildMessageReceivedEvent event) {
        return true;
    }

    @Override
    public void action(String[] args, GuildMessageReceivedEvent event) {
        try {
            String jsonString = URLConnectionReader.getText("https://lucoa.systemexit.co.uk/animals/api/llama");
            JSONArray jsonArray = new JSONArray(jsonString);
            JSONObject jsonObject = new JSONObject(String.valueOf(jsonArray.get(0)));
            event.getChannel().sendMessage(AirUtils.embedImage(jsonObject.getString("file"))).queue();
        }
        catch (Exception e) {
            e.printStackTrace();
            event.getChannel().sendMessage(AirUtils.embedMessage("ERROR: " + e.getMessage())).queue();
        }
    }

    @Override
    public String help() {
        return "Here is a llama";
    }
}

package ml.duncte123.skybot.commands.animals;

import ml.duncte123.skybot.Command;
import ml.duncte123.skybot.utils.AirUtils;
import ml.duncte123.skybot.utils.URLConnectionReader;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import org.json.JSONArray;
import org.json.JSONObject;

public class LlamaCommand extends Command {
    @Override
    public boolean called(String[] args, GuildMessageReceivedEvent event) {
        return true;
    }

    @Override
    public void action(String[] args, GuildMessageReceivedEvent event) {
        try {
            String jsonString = URLConnectionReader.getText("https://lucoa.systemexit.co.uk/animals/api/llama/random");
            JSONObject jsonObject = new JSONObject(jsonString);
            event.getChannel().sendMessage(AirUtils.embedImage(jsonObject.getString("file"))).queue();
        }
        catch (Exception e) {
            e.printStackTrace();
            event.getChannel().sendMessage(AirUtils.embedMessage("ERROR: " + e.getMessage())).queue();
        }
    }

    @Override
    public String help() {
        return "Here is a llama";
    }
}

Make llama command spit out random llamas


package net.glowstone.entity.ai;

import net.glowstone.entity.GlowLivingEntity;
import org.bukkit.Location;
import org.bukkit.util.Vector;

public class TransportHelper {
    public static void moveTowards(GlowLivingEntity entity, Location direction) {
        moveTowards(entity, direction, 0.3);
    }

    public static void moveTowards(GlowLivingEntity entity, Location direction, double speed) {
        Location location = entity.getLocation();
        double deltaX = (direction.getX() - location.getX());
        double deltaZ = (direction.getZ() - location.getZ());
        Vector vector = new Vector(deltaX, 0, deltaZ).normalize().multiply(speed);
        entity.setVelocity(vector);
    }
}

package net.glowstone.entity.ai;

import net.glowstone.entity.GlowLivingEntity;
import org.bukkit.Location;
import org.bukkit.util.Vector;

public class TransportHelper {
    public static void moveTowards(GlowLivingEntity entity, Location direction) {
        moveTowards(entity, direction, 0.3);
    }

    public static void moveTowards(GlowLivingEntity entity, Location direction, double speed) {
        Location location = entity.getLocation();
        double deltaX = (direction.getX() - location.getX());
        double deltaZ = (direction.getZ() - location.getZ());
        Vector vector = new Vector(deltaX, 0, deltaZ).normalize().multiply(speed);
        entity.setRawLocation(location.add(vector)); // doesn't work on positive X/Z, why??
    }
}

Use setRawLocation instead of velocity (still bugged)


package seedu.tache.logic.commands;

import seedu.tache.model.TaskManager;

/**
 * Clears the task manager.
 */
public class ClearCommand extends Command {

    public static final String COMMAND_WORD = "clear";
    public static final String MESSAGE_SUCCESS = "All tasks has been cleared!";

    @Override
    public CommandResult execute() {
        assert model != null;
        model.resetData(new TaskManager());
        clearUndoHistory();
        return new CommandResult(MESSAGE_SUCCESS);
    }
}

package seedu.tache.logic.commands;

import seedu.tache.model.TaskManager;

/**
 * Clears the task manager.
 */
public class ClearCommand extends Command {

    public static final String COMMAND_WORD = "clear";
    public static final String MESSAGE_SUCCESS = "All tasks has been cleared!";
    //@@author A0150120H
    public static final String MESSAGE_USAGE = COMMAND_WORD + ": deletes all tasks\n"
            + "WARNING: THIS CANNOT BE UNDONE\n"
            + "Example: " + COMMAND_WORD;
    //@@author

    @Override
    public CommandResult execute() {
        assert model != null;
        model.resetData(new TaskManager());
        clearUndoHistory();
        return new CommandResult(MESSAGE_SUCCESS);
    }
}

Add Usage string for clear command

Add Usage string for clear command


package uk.gov.register.db;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import uk.gov.register.core.Entry;
import uk.gov.verifiablelog.store.MerkleLeafStore;

public class EntryMerkleLeafStore implements MerkleLeafStore {

    private final EntryQueryDAO entryDAO;
    private final EntryIteratorDAO entryIteratorDAO;

    public EntryMerkleLeafStore(EntryQueryDAO entryDAO) {
        this.entryDAO = entryDAO;
        this.entryIteratorDAO = new EntryIteratorDAO(entryDAO);
    }

    @Override
    public byte[] getLeafValue(int i) {
        return bytesFromEntry(entryIteratorDAO.findByEntryNumber(i + 1));
    }

    @Override
    public int totalLeaves() {
        return entryDAO.getTotalEntries();
    }

    private byte[] bytesFromEntry(Entry entry) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
            mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false);

            String value = mapper.writeValueAsString(entry);
            return value.getBytes();
        } catch (JsonProcessingException e) {
            // FIXME swallow for now and return null byte
            return new byte[]{0x00};
        }
    }
}

package uk.gov.register.db;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import uk.gov.register.core.Entry;
import uk.gov.verifiablelog.store.MerkleLeafStore;

public class EntryMerkleLeafStore implements MerkleLeafStore {
    private final EntryQueryDAO entryDAO;
    private final EntryIteratorDAO entryIteratorDAO;
    private final boolean hasEntries;

    public EntryMerkleLeafStore(EntryQueryDAO entryDAO) {
        this.entryDAO = entryDAO;
        this.entryIteratorDAO = new EntryIteratorDAO(entryDAO);
        this.hasEntries = totalLeaves() > 0;
    }

    @Override
    public byte[] getLeafValue(int i) {
        return hasEntries ? bytesFromEntry(entryIteratorDAO.findByEntryNumber(i + 1)) : new byte[]{0x00};
    }

    @Override
    public int totalLeaves() {
        return entryDAO.getTotalEntries();
    }

    private byte[] bytesFromEntry(Entry entry) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
            mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false);

            String value = mapper.writeValueAsString(entry);
            return value.getBytes();
        } catch (JsonProcessingException e) {
            // FIXME swallow for now and return null byte
            return new byte[]{0x00};
        }
    }
}

Make EntryMarkleLeafStore cater for empty db


package org.ligoj.bootstrap.model.system;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.springframework.http.HttpMethod;

import org.ligoj.bootstrap.core.model.AbstractAudited;
import lombok.Getter;
import lombok.Setter;

/**
 * A dynamic authorization for a role on a specified module.
 */
@Entity
@Table(name = "S_AUTHORIZATION")
@Getter
@Setter
public class SystemAuthorization extends AbstractAudited<Integer> {

	/**
	 * Authorization type.
	 */
	public enum AuthorizationType {
		/**
		 * Business authorization.
		 */
		BUSINESS,

		/**
		 * UI authorization.
		 */
		UI
	}

	/**
	 * SID
	 */
	private static final long serialVersionUID = 1L;

	@Enumerated(EnumType.ORDINAL)
	@NotNull
	private AuthorizationType type;

	/**
	 * Associated role.
	 */
	@ManyToOne
	@NotNull
	private SystemRole role;

	/**
	 * Authorized URL as pattern.
	 */
	@NotNull
	private String pattern;

	/**
	 * Authorized URL method. Can be <tt>null</tt> for all methods.
	 */
	private HttpMethod method;

}

package org.ligoj.bootstrap.model.system;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.springframework.http.HttpMethod;

import org.ligoj.bootstrap.core.model.AbstractAudited;
import lombok.Getter;
import lombok.Setter;

/**
 * A dynamic authorization for a role on a specified module.
 */
@Entity
@Table(name = "S_AUTHORIZATION")
@Getter
@Setter
public class SystemAuthorization extends AbstractAudited<Integer> {

	/**
	 * Authorization type.
	 */
	public enum AuthorizationType {
		/**
		 * Business authorization.
		 */
		BUSINESS,

		/**
		 * UI authorization.
		 */
		UI
	}

	/**
	 * SID
	 */
	private static final long serialVersionUID = 1L;

	@Enumerated(EnumType.STRING)
	@NotNull
	private AuthorizationType type;

	/**
	 * Associated role.
	 */
	@ManyToOne
	@NotNull
	private SystemRole role;

	/**
	 * Authorized URL as pattern.
	 */
	@NotNull
	private String pattern;

	/**
	 * Authorized URL method. Can be <tt>null</tt> for all methods.
	 */
	@Enumerated(EnumType.STRING)
	private HttpMethod method;

}

Use String instead of ordinal for AuthorizationType


package cl.fatman.capital.fund;

import static org.hamcrest.Matchers.*;

import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

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

public class ControllerTest {

	private static Controller control;
	private static PersistenceData persistence;

	@BeforeClass
	public static void setUp() {
		control = Controller.getInstance();
		control.setUp();
		List<FundType> ftList = new ArrayList<FundType>();
		FundType type = new FundType(1, "Deuda < 90 días");
		ftList.add(type);
		persistence = PersistenceData.getInstance();
		persistence.insertObjectList(ftList);
	}

	@AfterClass
	public static void tearDown() {
		control.tearDown();
	}

	@Test
	public void storeFundDataTest() {
		control.storeFundData();
		List<?> fundList = persistence.selectAllObjects("from Fund", Fund.class);
		List<?> fundRateList = persistence.selectAllObjects("from FundRate", FundRate.class);
		assertThat("Fund rate list should be greater than fund list.", fundRateList.size(), greaterThan(fundList.size()));
	}
}

package cl.fatman.capital.fund;

import static org.hamcrest.Matchers.*;

import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

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

public class ControllerTest {

	private static Controller control;
	private static PersistenceData persistence;

	@BeforeClass
	public static void setUp() {
		control = Controller.getInstance();
		control.setUp();
		persistence = PersistenceData.getInstance();
		//Insert a initial fund type.
		List<FundType> ftList = new ArrayList<FundType>();
		FundType type = new FundType(1, "Deuda < 90 días");
		ftList.add(type);
		persistence.insertObjectList(ftList);
	}

	@AfterClass
	public static void tearDown() {
		control.tearDown();
	}

	@Test
	public void storeFundDataTest() {
		control.storeFundData();
		control.storeFundData();
		List<?> fundList = persistence.selectAllObjects("from Fund", Fund.class);
		List<?> fundRateList = persistence.selectAllObjects("from FundRate", FundRate.class);
		assertThat("Fund rate list should be greater than fund list.", fundRateList.size(), greaterThan(fundList.size()));
	}
}

Update and improve the successful cases for the Controller.


package org.jenkins.ci.plugins.jenkinslint.check;

import hudson.slaves.DumbSlave;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import static org.junit.Assert.assertTrue;

/**
 * SlaveDescriptionChecker Test Case.
 *
 * @author Victor Martinez
 */
public class SlaveVersionCheckerTestCase {
    private SlaveDescriptionChecker checker = new SlaveDescriptionChecker();

    @Rule public JenkinsRule j = new JenkinsRule();
    @Test public void testDefaultSlave() throws Exception {
        DumbSlave slave = j.createSlave();
        assertTrue(checker.executeCheck(slave));
    }
    @Test public void testEmptySlaveName() throws Exception {
        DumbSlave slave = j.createSlave();
        slave.setNodeName("");
        assertTrue(checker.executeCheck(slave));
    }
    @Test public void testSlaveDescription() throws Exception {
        DumbSlave slave = j.createSlave();
        slave.setNodeName("blablabla");
        assertTrue(checker.executeCheck(slave));
    }
    /**
    @Test public void testControlComment() throws Exception {
        DumbSlave slave = j.createSlave();
        assertFalse(checker.isIgnored(project.getDescription()));
        project.setDescription("#lint:ignore:" + checker.getClass().getSimpleName());
        assertTrue(checker.isIgnored(project.getDescription()));
    }*/
}

package org.jenkins.ci.plugins.jenkinslint.check;

import hudson.model.Node;
import hudson.model.Slave;
import hudson.slaves.DumbSlave;
import hudson.slaves.JNLPLauncher;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import java.util.Collections;

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

/**
 * SlaveVersionChecker Test Case.
 *
 * @author Victor Martinez
 */
public class SlaveVersionCheckerTestCase {
    private SlaveVersionChecker checker = new SlaveVersionChecker();

    @Rule public JenkinsRule j = new JenkinsRule();
    @Test public void testDefaultSlave() throws Exception {
        Slave slave = createSlave("default", "", "");
        assertFalse(checker.executeCheck(slave));
    }
    @Test public void testControlComment() throws Exception {
        Slave slave = createSlave("default", "", "");
        assertFalse(checker.isIgnored(slave.getNodeDescription()));
        slave = createSlave("default", "#lint:ignore:" + checker.getClass().getSimpleName(), "");
        assertTrue(checker.isIgnored(slave.getNodeDescription()));
    }

    private Slave createSlave(String name, String description, String label) throws Exception {
        return new DumbSlave(name, description, "/wherever", "1", Node.Mode.NORMAL, label, new JNLPLauncher(), RetentionStrategy.NOOP, Collections.<NodeProperty<?>>emptyList());
    }
}

Test cases for slave version check

Test cases for slave version check


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

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;

public class PhotonLoggerFactory implements ILoggerFactory {

	private final ConcurrentMap<String, Logger> loggerMap = new ConcurrentHashMap<>();

	@Override
	public Logger getLogger(String name) {
		Logger logger = loggerMap.get(name);
		if (logger != null) {
			return logger;
		} else {
			Logger newInstance = new PhotonLogger(name);
			Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
			return oldInstance == null ? newInstance : oldInstance;
		}
	}

}

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

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;

public class PhotonLoggerFactory implements ILoggerFactory {

	private final ConcurrentMap<String, Logger> loggerMap = new ConcurrentHashMap<>();

	@Override
	public Logger getLogger(String name) {
		return loggerMap.computeIfAbsent(name, (k) -> new PhotonLogger(name));
	}

}

Use map.computeIfAbsent to create the logger when needed


package org.gbif.registry.metadata.parse;

import java.util.List;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;

/**
 * Class to temporarily keep paragraph strings before they are used as a single,
 * concatenated string argument in other rules.
 * Digester needs public access to this otherwise package scoped class.
 *

 * Note HTML is used to concatenate paragraphs using break tag
 instead of newline character ("\n"), see POR-3138.
 * @see POR-3138
 */
public class ParagraphContainer {

  private static Joiner PARA_JOIN = Joiner.on("
");
  private List<String> paragraphs = Lists.newArrayList();

  public void appendParagraph(String para) {
    if (!Strings.isNullOrEmpty(para)) {
      paragraphs.add(para.trim());
    }
  }

  public String toString() {
    if (paragraphs.isEmpty()) {
      return null;
    }
    return PARA_JOIN.join(paragraphs);
  }
}

Fix ensures DatasetResource.sanitizeDataset method won't remove HTML line break added during metadata parsing


package com.syncano.library.documentation;

import com.google.gson.JsonArray;
import com.syncano.library.SyncanoApplicationTestCase;
import com.syncano.library.TestSyncanoClass;
import com.syncano.library.api.Response;
import com.syncano.library.data.SyncanoClass;

public class Classes extends SyncanoApplicationTestCase {

    public void testCreateClass() {

        String className = "testsyncanoclass";
        JsonArray schema = TestSyncanoClass.getSchema();
        syncano.deleteSyncanoClass(className);

        // ---------- Creating a Class
        SyncanoClass syncanoClass = new SyncanoClass(className, schema);
        Response<SyncanoClass> response = syncano.createSyncanoClass(syncanoClass).send();
        // -----------------------------

        assertEquals(Response.HTTP_CODE_CREATED, response.getHttpResultCode());
    }
}

package com.syncano.library.documentation;

import com.google.gson.JsonArray;
import com.syncano.library.SyncanoApplicationTestCase;
import com.syncano.library.TestSyncanoClass;
import com.syncano.library.api.Response;
import com.syncano.library.data.SyncanoClass;

public class Classes extends SyncanoApplicationTestCase {

    public void testCreateClass() {

        String className = "testsyncanoclass";
        JsonArray schema = TestSyncanoClass.getSchema();
        syncano.deleteSyncanoClass(className).send();

        // ---------- Creating a Class
        SyncanoClass syncanoClass = new SyncanoClass(className, schema);
        Response<SyncanoClass> response = syncano.createSyncanoClass(syncanoClass).send();
        // -----------------------------

        assertEquals(Response.HTTP_CODE_CREATED, response.getHttpResultCode());
    }
}

Fix in creating class test

Fix in creating class test


package org.cru.godtools.s3;

import com.google.common.base.Strings;

/**
 * Created by ryancarlson on 7/11/15.
 */
public class AmazonS3GodToolsConfig
{
	public static final String BUCKET_NAME = "cru-godtools";

	private static final String META = "meta";
	private static final String PACKAGES = "packages/";
	private static final String LANGUAGES = "languages/";
	private static final String ALL = "all/";
	private static final String CURRENT = "current/";
	private static final String XML = ".XML";
	private static final String ZIP = ".ZIP";

	public static String getMetaKey(String languageCode, String packageCode)
	{
		if(!Strings.isNullOrEmpty(languageCode) && !Strings.isNullOrEmpty(packageCode))
		{
			return META + CURRENT + languageCode + "/" + packageCode + "/" + META + XML;
		}
		if(!Strings.isNullOrEmpty(languageCode))
		{
			return META + CURRENT + languageCode + "/" + META + XML;
		}

		return META + CURRENT + META + XML;
	}

	public static String getPackagesKey(String languageCode, String packageCode)
	{
		return PACKAGES + CURRENT + languageCode + "/" + ALL + languageCode + ZIP;
	}

	public static String getLanguagesKey(String languageCode, String packagesCode)
	{
		return LANGUAGES + CURRENT + languageCode + "/" + ALL + languageCode + ZIP;
	}
}

package org.cru.godtools.s3;

import com.google.common.base.Strings;

/**
 * Created by ryancarlson on 7/11/15.
 */
public class AmazonS3GodToolsConfig
{
	public static final String BUCKET_NAME = "cru-godtools";

	private static final String META = "meta/";
	private static final String PACKAGES = "packages/";
	private static final String LANGUAGES = "languages/";
	private static final String META_FILE = "meta";
	private static final String ALL = "all/";
	private static final String CURRENT = "current/";
	private static final String XML = ".xml";
	private static final String ZIP = ".zip";

	public static String getMetaKey(String languageCode, String packageCode)
	{
		if(!Strings.isNullOrEmpty(languageCode) && !Strings.isNullOrEmpty(packageCode))
		{
			return META + CURRENT + languageCode + "/" + packageCode + "/" + META_FILE + XML;
		}
		if(!Strings.isNullOrEmpty(languageCode))
		{
			return META + CURRENT + languageCode + "/" + META_FILE + XML;
		}

		return META + CURRENT + META_FILE + XML;
	}

	public static String getPackagesKey(String languageCode, String packageCode)
	{
		return PACKAGES + CURRENT + languageCode + "/" + ALL + languageCode + ZIP;
	}

	public static String getLanguagesKey(String languageCode, String packagesCode)
	{
		return LANGUAGES + CURRENT + languageCode + "/" + ALL + languageCode + ZIP;
	}
}

Fix broken key generation code

Fix broken key generation code


/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.intellij.remote;

import com.intellij.openapi.projectRoots.SdkAdditionalData;
import org.jetbrains.annotations.NotNull;

/**
 * @author traff
 */
public interface RemoteSdkAdditionalData<T extends RemoteSdkCredentials>
  extends SdkAdditionalData, RemoteSdkProducer<T>, RemoteSdkProperties {
  void completeInitialization();

  boolean isInitialized();

  void setInitialized(boolean initialized);

  String getFullInterpreterPath();

  void setVagrantConnectionType(@NotNull VagrantBasedCredentialsHolder vagrantBasedCredentials);

  /**
   * This method switches to use of ssh-credentials based data
   * @param credentials credentials that specify connection
   */
  void setSshCredentials(@NotNull RemoteSdkCredentialsHolder credentials);

  void setDeploymentConnectionType(@NotNull WebDeploymentCredentialsHolder credentials);
}

/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.intellij.remote;

import com.intellij.openapi.projectRoots.SdkAdditionalData;
import org.jetbrains.annotations.NotNull;

/**
 * @author traff
 */
public interface RemoteSdkAdditionalData<T extends RemoteSdkCredentials>
  extends SdkAdditionalData, RemoteSdkProducer<T>, RemoteSdkProperties {
  void completeInitialization();

  boolean isInitialized();

  void setInitialized(boolean initialized);

  String getFullInterpreterPath();

  void setVagrantConnectionType(@NotNull VagrantBasedCredentialsHolder vagrantBasedCredentials);

  /**
   * This method switches to use of ssh-credentials based data
   * @param credentials credentials that specify connection
   */
  void setSshCredentials(@NotNull RemoteCredentialsHolder credentials);

  void setDeploymentConnectionType(@NotNull WebDeploymentCredentialsHolder credentials);
}

Fix creation of remote sdk in tests.

Fix creation of remote sdk in tests.


package org.example.prototype.example;

import org.example.domain.Customer;
import org.example.domain.Order;
import org.example.domain.query.QCustomer;
import org.example.domain.query.QOrder;
import org.junit.Test;

import java.util.List;

/**
 */
public class ExampleQuery {

  @Test
  public void test() {

    QCustomer qc = new QCustomer(5);

    Customer rob = new QCustomer(2)
        .select("id, name")
        .status.equalTo(Customer.Status.GOOD)
        .name.ilike("Asd")
        .name.isNull()
        .billingAddress.country.code.equalTo("NZ")
        .contacts.email.endsWith("@foo.com")
        .findUnique();

  }

  @Test
  public void testOrder() {

    List<Order> orders = new QOrder()
        .customer.name.ilike("rob")
        .orderBy()
        .customer.name.asc()
        .orderDate.asc()
        .findList();

//        .shippingAddress.city.ieq("auckla")
//        .shippingAddress.country.code.eq("NZ")
//        .status.equalTo(Order.Status.APPROVED)
//        .orderDate.after(Date.valueOf("2015-01-20"))
//        .findList();
  }

}

package org.example.prototype.example;

import org.example.domain.Customer;
import org.example.domain.Order;
import org.example.domain.query.QCustomer;
import org.example.domain.query.QOrder;
import org.junit.Test;

import java.util.List;

/**
 */
public class ExampleQuery {

  @Test
  public void test() {

    QCustomer qc = new QCustomer(5);

    Customer rob = new QCustomer(2)
        .select("id, name")
        .id.greaterThan(42)
        .status.equalTo(Customer.Status.GOOD)
        .name.ilike("Asd")
        .name.isNull()
        .billingAddress.country.code.equalTo("NZ")
        .contacts.email.endsWith("@foo.com")
        .findUnique();

  }

  @Test
  public void testOrder() {

    List<Order> orders = new QOrder()
        .customer.name.ilike("rob")
        .orderBy()
        .customer.name.asc()
        .orderDate.asc()
        .findList();

//        .shippingAddress.city.ieq("auckla")
//        .shippingAddress.country.code.eq("NZ")
//        .status.equalTo(Order.Status.APPROVED)
//        .orderDate.after(Date.valueOf("2015-01-20"))
//        .findList();
  }

}

Add @TypeQueryBean annotation into generation


package org.folio.okapi.common;

import io.vertx.core.json.JsonObject;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.Base64;

public class OkapiTokenTest {

  @Test
  public void test() {
    OkapiToken t = new OkapiToken();

    JsonObject o = new JsonObject();
    o.put("tenant", "test-lib");
    o.put("foo", "bar");
    String s = o.encodePrettily();
    byte[] encodedBytes = Base64.getEncoder().encode(s.getBytes());
    String e = new String(encodedBytes);
    String tokenStr = "method." + e + ".trail";
    t.setToken(tokenStr);
    assertEquals("test-lib", t.getTenant());
  }
}

package org.folio.okapi.common;

import io.vertx.core.json.JsonObject;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.Base64;

public class OkapiTokenTest {

  @Test
  public void test() {
    OkapiToken t = new OkapiToken();

    JsonObject o = new JsonObject();
    o.put("tenant", "test-lib");
    o.put("foo", "bar");
    String s = o.encodePrettily();
    byte[] encodedBytes = Base64.getEncoder().encode(s.getBytes());
    String e = new String(encodedBytes);
    String tokenStr = "method." + e + ".trail";
    t.setToken(tokenStr);
    assertEquals("test-lib", t.getTenant());
  }

  @Test
  public void test2() {
    String s = "eyJzdWIiOiJfX3VuZGVmaW5lZF9fIiwidXNlcl9pZCI6Ijk5OTk5OTk5L"
      + "Tk5OTktOTk5OS05OTk5LTk5OTk5OTk5OTk5OSIsInRlbmFudCI6InRlc3RsaWIifQ";
    byte[] buf = Base64.getDecoder().decode(s);
    String got = new String(buf);
    String exp = "{\"sub\":\"__undefined__\","
      + "\"user_id\":\"99999999-9999-9999-9999-999999999999\",\"tenant\":\"testlib\"}";
    assertEquals(exp, got);
  }

}

Add test case for MODAT-16

Add test case for MODAT-16


package com.blocksolid.income;

/**
 * Created by Dan Buckland on 16/09/2015.
 */

public class TaxCalculator {

    int MAX_PERSONAL_ALLOWANCE = 1060000;           // £10,600
    int PERSONAL_ALLOWANCE_THRESHOLD = 10000000;    // £100,000
    int BASIC_RATE_THRESHOLD = 3178500;             // £31,785
    int HIGHER_RATE_THRESHOLD = 15000000;           // £150,000

    int annualIncome;
    int personalAllowance;

    public TaxCalculator(int annualIncome) {
        this.annualIncome = annualIncome;
        calculatePersonalAllowance();
        //calculateDeductions(personalAllowance);
    }

    public void setAnnualIncome(int newAnnualIncome) {
        annualIncome = newAnnualIncome;
    }

    public int getAnnualIncome() {
        return annualIncome;
    }

    public int calculatePersonalAllowance() {
        // TODO calculate the personal allowance that's needed to calculate tax deductions
        return personalAllowance;
    }

}

package com.blocksolid.income;

/**
 * Created by Dan Buckland on 16/09/2015.
 */

public class TaxCalculator {

    int MAX_PERSONAL_ALLOWANCE = 1060000;           // £10,600
    int PERSONAL_ALLOWANCE_THRESHOLD = 10000000;    // £100,000
    int BASIC_RATE_THRESHOLD = 3178500;             // £31,785
    int HIGHER_RATE_THRESHOLD = 15000000;           // £150,000

    int annualIncome;
    int personalAllowance;

    public TaxCalculator(int annualIncome) {
        this.annualIncome = annualIncome;
        calculatePersonalAllowance();
        //calculateDeductions(personalAllowance);
    }

    public void setAnnualIncome(int newAnnualIncome) {
        annualIncome = newAnnualIncome;
    }

    public int getAnnualIncome() {
        return annualIncome;
    }

    public int calculatePersonalAllowance() {
        if (annualIncome > PERSONAL_ALLOWANCE_THRESHOLD) {
            int difference = annualIncome - PERSONAL_ALLOWANCE_THRESHOLD;
            if (difference % 200 > 0) {
                difference = difference - 100;
            }
            personalAllowance = MAX_PERSONAL_ALLOWANCE - (difference / 2);
            if (personalAllowance < 0) {
                personalAllowance = 0;
            }
        } else {
            personalAllowance = MAX_PERSONAL_ALLOWANCE;
        }
        return personalAllowance;
    }

}

Add calculatePersonalAllowance method to pass unit tests


package com.redseal.featureset;

public class SomeClass extends SomeAbstractClass {

    public SomeClass() {
        theInt = 42;
        theLong = 0x0123456789abcdefL;
        theString = "Just some class.";
    }

    public SomeClass(int x, long y, String z) {
        theInt = x;
        theLong = y;
        theString = z;
    }

    private int theInt;
    private long theLong;
    private String theString;

    public int getInt() { return theInt; }
    public long getLong() { return theLong; }
    public String getString() { return theString; }

    public void setInt(int x) { theInt = x; }
    public void setLong(long x) { theLong = x; }
    public void setString(String x) { theString = x; }
}

package com.redseal.featureset;

public class SomeClass extends SomeAbstractClass {

    public SomeClass() {
        theInt = 42;
        theLong = java.lang.Long.MAX_VALUE;
        theString = "Just some class.";
    }

    public SomeClass(int x, long y, String z) {
        theInt = x;
        theLong = y;
        theString = z;
    }

    private int theInt;
    private long theLong;
    private String theString;

    public int getInt() { return theInt; }
    public long getLong() { return theLong; }
    public String getString() { return theString; }

    public void setInt(int x) { theInt = x; }
    public void setLong(long x) { theLong = x; }
    public void setString(String x) { theString = x; }
}

Use java.lang.Long.MAX_VALUE as best example of loss of precision.


package space.hideaway.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import space.hideaway.model.SearchModel;
import space.hideaway.services.UserService;

@Controller
public class RouteController
{
    @Autowired
    UserService userService;

    /**
     * The endpoint for the application home page.
     * Secured: No
     * Method: GET
     *

     * Sample URL: / or /home
     *
     * @return The path to the index page template.
     */
    @GetMapping({"/", "/home"})
    public String index(Model model)
    {
        model.addAttribute("searchModel", new SearchModel());
        model.addAttribute("user", userService.getCurrentLoggedInUser());
        return "index";
    }

    /**
     * The endpoint for the application about page.
     * Secured: No
     * Method: GET
     *

     * Sample URL: /about
     *
     * @return The path to the about page template.
     */
    @GetMapping("/about")
    public String about()
    {
        return "about";
    }

    /**
     * The endpoint for the contact page.
     * Secured: No
     * Method: GET
     *

     * Sample URL: /contact
     *
     * @return The name of the contact page template.
     */
    @GetMapping("/contact")
    public String contact()
    {
        return "contact";
    }
}

package space.hideaway.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import space.hideaway.model.SearchModel;
import space.hideaway.services.UserService;

@Controller
public class RouteController
{
    @Autowired
    UserService userService;

    /**
     * The endpoint for the application home page.
     * Secured: No
     * Method: GET
     *

     * Sample URL: / or /home
     *
     * @return The path to the index page template.
     */
    @GetMapping({"/", "/home"})
    public String index(Model model)
    {
        model.addAttribute("searchModel", new SearchModel());
        return "index";
    }

    /**
     * The endpoint for the application about page.
     * Secured: No
     * Method: GET
     *

     * Sample URL: /about
     *
     * @return The path to the about page template.
     */
    @GetMapping("/about")
    public String about()
    {
        return "about";
    }

    /**
     * The endpoint for the contact page.
     * Secured: No
     * Method: GET
     *

     * Sample URL: /contact
     *
     * @return The name of the contact page template.
     */
    @GetMapping("/contact")
    public String contact()
    {
        return "contact";
    }
}

Remove traditional way of getting logged in username.


/**
 *
 */
package com.github.ansell.csvsum;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import joptsimple.OptionException;

/**
 * Tests for {@link CSVSummariser}.
 *
 * @author Peter Ansell p_ansell@yahoo.com
 */
public class CSVSummariserTest {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	/**
	 * Test method for
	 * {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
	 */
	@Test
	public final void testMainNoArgs() throws Exception {
		thrown.expect(OptionException.class);
		CSVSummariser.main();
	}

}

/**
 *
 */
package com.github.ansell.csvsum;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import joptsimple.OptionException;

/**
 * Tests for {@link CSVSummariser}.
 *
 * @author Peter Ansell p_ansell@yahoo.com
 */
public class CSVSummariserTest {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	/**
	 * Test method for
	 * {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
	 */
	@Test
	public final void testMainNoArgs() throws Exception {
		thrown.expect(OptionException.class);
		CSVSummariser.main();
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
	 */
	@Test
	public final void testMainHelp() throws Exception {
		CSVSummariser.main("--help");
	}

}

Add test for CSVSummariser help

Add test for CSVSummariser help


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

/**
 * Interface for subscribing/unsubscribing clients and publishing events to them.
 */
public interface EventBus {

    public interface Subscription {
        void onEvent(String event, String data);
    }

    public Subscription subscribe(String subscriberId, Subscription handler);
    public Subscription unsubscribe(String subscriberId);

    public void broadcast(String event, String data);
    public void send(String subscriberId, String event, String data);
}

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

/**
 * Interface for managing client subscriptions and publishing events to them.
 */
public interface EventBus {

    /**
     * Callback interface clients implement to receive events.
     */
    public interface Subscription {

        /**
         * This method must never block.
         *
         * @param event the type of event being delivered
         * @param data the data associated the the event type
         */
        void onEvent(String event, String data);
    }

    /**
     * Adds a subscription to the event bus.
     *
     * @param subscriberId unique id for the subscription.
     * @param handler the callback that will receive the events.
     * @return the previously registered subscription with that id or null.
     */
    public Subscription subscribe(String subscriberId, Subscription handler);

    /**
     * Removes a subscription from the event bus.
     * @param subscriberId unique id for the subscription.
     * @return the previously registered subscription with that id or null if not registered.
     */
    public Subscription unsubscribe(String subscriberId);

    /**
     * Send an event to all subscribers in a bus.  The event MAY get delivered to the subscriptions
     * after this call returns.
     */
    public void broadcast(String event, String data);

    /**
     * Send an event to a specific subscriber on the bus.  The event MAY get delivered to the subscriptions
     * after this call returns.
     */
    public void send(String subscriberId, String event, String data);
}

Add more javadoc around the event bus.

Add more javadoc around the event bus.


package com.openxc;

import com.openxc.VehicleService;

import android.test.ServiceTestCase;

import android.test.suitebuilder.annotation.SmallTest;

public class VehicleServiceTest extends ServiceTestCase<VehicleService> {
    public VehicleServiceTest() {
        super(VehicleService.class);
    }

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

    @SmallTest
    public void testPreconditions() {
        assertTrue(false);
    }
}

package com.openxc;

import com.openxc.VehicleService;

import android.content.Intent;

import android.os.IBinder;

import android.test.ServiceTestCase;

import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;

public class VehicleServiceTest extends ServiceTestCase<VehicleService> {
    Intent startIntent;

    public VehicleServiceTest() {
        super(VehicleService.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        startIntent = new Intent();
        startIntent.setClass(getContext(), VehicleService.class);
    }

    @SmallTest
    public void testPreconditions() {
    }

    @SmallTest
    public void testStartable() {
        startService(startIntent);
    }

    @MediumTest
    public void testBindable() {
        IBinder service = bindService(startIntent);
    }
}

Test that the VehicleService can be started and bound.


package com.gregory.testing.communication;

import com.gregory.testing.message.TimestampedMessage;
import info.batey.kafka.unit.KafkaUnit;
import kafka.producer.KeyedMessage;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.fest.assertions.Assertions.assertThat;

public final class KafkaConsumerTest {

    private static final String zookeeper = "localhost:5000";
    private static final String broker = "localhost:5001";
    private static final String topic = "test";
    private KafkaUnit kafka;

    @Before
    public void setUp() {
        kafka = new KafkaUnit(zookeeper, broker);
        kafka.startup();
        kafka.createTopic(topic);
    }

    @After
    public void tearDown() {
        kafka.shutdown();
    }

    @Test
    public void it_should_read_messages_from_kafka() {
        long startTimestamp = System.currentTimeMillis();
        KafkaConsumer consumer = new KafkaConsumer(zookeeper, topic);
        KeyedMessage<String, String> keyedMessage = new KeyedMessage<>(topic, "key", "value");
        kafka.sendMessages(keyedMessage);
        TimestampedMessage message = consumer.getMessage();
        assertThat(message.timestamp()).isGreaterThan(startTimestamp);
        assertThat(message.message().data()).isEqualTo("value".getBytes());
    }

}

package com.gregory.testing.communication;

import com.gregory.testing.message.TimestampedMessage;
import info.batey.kafka.unit.KafkaUnit;
import kafka.producer.KeyedMessage;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.fest.assertions.Assertions.assertThat;

public final class KafkaConsumerTest {

    private static final String zookeeper = "localhost:5000";
    private static final String broker = "localhost:5001";
    private static final String topic = "test";
    private KafkaUnit kafka;

    @Before
    public void setUp() {
        kafka = new KafkaUnit(zookeeper, broker);
        kafka.startup();
        kafka.createTopic(topic);
    }

    @After
    public void tearDown() {
        kafka.shutdown();
    }

    @Test
    public void it_should_read_messages_from_kafka() throws InterruptedException {
        long startTimestamp = System.currentTimeMillis();
        KafkaConsumer consumer = new KafkaConsumer(zookeeper, topic);
        Thread.sleep(1000);
        KeyedMessage<String, String> keyedMessage = new KeyedMessage<>(topic, "key", "value");
        kafka.sendMessages(keyedMessage);
        TimestampedMessage message = consumer.getMessage();
        assertThat(message.timestamp()).isGreaterThan(startTimestamp);
        assertThat(message.message().data()).isEqualTo("value".getBytes());
    }

}

Add sleep to let consumer set up

Add sleep to let consumer set up


package me.jesensky.dan.playertracker.net.packets;

import me.jesensky.dan.playertracker.exceptions.InvalidPacketException;

import java.util.Arrays;

public enum PacketType {
    LOGIN(new byte[]{0x1, 0x0, 0x1}),
    LOGIN_RESPONSE(new byte[]{0x1, 0x0, 0x2}),
    FETCH_DATA(new byte[]{0x1, 0x0, 0x3}),
    SEND_DATA(new byte[]{0x1, 0x0, 0x4}),
    ;

    PacketType(byte... data) {
        this.header = data;
    }

    public byte[] getHeader() {
        return this.header;
    }

    public static PacketType getTypeFromHeader(byte... head) throws InvalidPacketException {
        for (PacketType t : PacketType.values()) {
            if (Arrays.equals(t.getHeader(), head))
                return t;
        }
        throw new InvalidPacketException("Header did not match any packet types.");
    }

    private byte[] header;
}

package me.jesensky.dan.playertracker.net.packets;

import me.jesensky.dan.playertracker.exceptions.InvalidPacketException;

import java.util.Arrays;

public enum PacketType {
    LOGIN(new byte[]{0x1, 0x0, 0x1}),
    LOGIN_RESPONSE(new byte[]{0x1, 0x0, 0x2}),
    FETCH_DATA(new byte[]{0x1, 0x0, 0x3}),
    DATA_RESPONSE(new byte[]{0x1, 0x0, 0x4}),
    ;

    PacketType(byte... data) {
        this.header = data;
    }

    public byte[] getHeader() {
        return this.header;
    }

    public static PacketType getTypeFromHeader(byte... head) throws InvalidPacketException {
        for (PacketType t : PacketType.values()) {
            if (Arrays.equals(t.getHeader(), head))
                return t;
        }
        throw new InvalidPacketException("Header did not match any packet types.");
    }

    private byte[] header;
}

Refactor SEND_DATA header to DATA_RESPONSE


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

import net.kuujo.copycat.protocol.Protocol;
import net.kuujo.copycat.test.ProtocolTest;
import org.testng.annotations.Test;

/**
 * Vert.x 3 event bus protocol test.
 *
 * @author Jordan Halterman
 */
@Test
public class VertxEventBusProtocolTest extends ProtocolTest {

  @Override
  protected Protocol createProtocol() {
    return new VertxEventBusProtocol();
  }

  @Override
  protected String createUri() {
    return "eventbus://test";
  }

}

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

import net.kuujo.copycat.protocol.Protocol;
import net.kuujo.copycat.test.ProtocolTest;
import org.testng.annotations.Test;

/**
 * Vert.x 3 event bus protocol test.
 *
 * @author Jordan Halterman
 */
@Test
public class VertxEventBusProtocolTest extends ProtocolTest {

  @Override
  protected Protocol createProtocol() {
    return new VertxEventBusProtocol();
  }

  @Override
  protected String createUri(int id) {
    return String.format("eventbus://test%d", id);
  }

}

Fix compile issue in Vert.x 3 test.

Fix compile issue in Vert.x 3 test.