package com.openxc.openxcdiagnostic.diagnostic;

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

import android.widget.LinearLayout;

import com.openxc.messages.DiagnosticRequest;
import com.openxc.messages.DiagnosticResponse;
import com.openxc.openxcdiagnostic.R;

public class DiagnosticOutputTable {

    private DiagnosticActivity mContext;
    private List<DiagnosticOutputRow> rows = new ArrayList<>();
    private LinearLayout mView;
    private int rowNumber = 1;

    public DiagnosticOutputTable(DiagnosticActivity context) {
        mContext = context;
        mView = (LinearLayout) context.findViewById(R.id.outputRows);
    }

    public void addRow(DiagnosticRequest req, DiagnosticResponse resp) {

        DiagnosticOutputRow row = new DiagnosticOutputRow(mContext, this, req, resp, rowNumber++);
        rows.add(0, row);
        mView.addView(row.getView(), 0);
    }

    public void removeRow(DiagnosticOutputRow row) {
        mView.removeView(row.getView());
        rows.remove(row);
    }

    public void deleteAllRows() {
        mView.removeAllViews();
        rows.clear();
    }

}

package com.openxc.openxcdiagnostic.diagnostic;

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

import android.widget.LinearLayout;

import com.openxc.messages.DiagnosticRequest;
import com.openxc.messages.DiagnosticResponse;
import com.openxc.openxcdiagnostic.R;

public class DiagnosticOutputTable {

    private DiagnosticActivity mContext;
    private List<DiagnosticOutputRow> rows = new ArrayList<>();
    private LinearLayout mView;
    private int rowNumber = 1;

    public DiagnosticOutputTable(DiagnosticActivity context) {
        mContext = context;
        mView = (LinearLayout) context.findViewById(R.id.outputRows);
    }

    public void addRow(DiagnosticRequest req, DiagnosticResponse resp) {

        DiagnosticOutputRow row = new DiagnosticOutputRow(mContext, this, req, resp, rowNumber++);
        rows.add(0, row);
        mView.addView(row.getView(), 0);
    }

    public void removeRow(DiagnosticOutputRow row) {
        mView.removeView(row.getView());
        rows.remove(row);
    }

    public void deleteAllRows() {
        mView.removeAllViews();
        rows.clear();
        resetRowCounter();
    }

    private void resetRowCounter() {
        rowNumber = 1;
    }

}

Reset row number after deleting all responses.


package jp.ac.nii.prl.mape.redundancy.model;

import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import org.hibernate.validator.constraints.NotEmpty;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
public class RedundancyView {

	@GeneratedValue
	@Id
	@JsonIgnore
	private Long id;

	@NotEmpty
	@OneToMany(mappedBy="RedundancyView")
	private Collection<Instance> instances;

	public Long getId() {
		return id;
	}

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

	public Collection<Instance> getInstances() {
		return instances;
	}

	public void setInstances(Collection<Instance> instances) {
		this.instances = instances;
	}

	public void addInstance(Instance instance) {
		instances.add(instance);
	}

}

package jp.ac.nii.prl.mape.redundancy.model;

import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import org.hibernate.validator.constraints.NotEmpty;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
public class RedundancyView {

	@GeneratedValue
	@Id
	@JsonIgnore
	private Long id;

	@NotEmpty
	@OneToMany(mappedBy="redundancyView")
	private Collection<Instance> instances;

	public Long getId() {
		return id;
	}

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

	public Collection<Instance> getInstances() {
		return instances;
	}

	public void setInstances(Collection<Instance> instances) {
		this.instances = instances;
	}

	public void addInstance(Instance instance) {
		instances.add(instance);
	}

}

Fix typo in MappedBy annotation

Fix typo in MappedBy annotation


package vg.civcraft.mc.civmodcore.ratelimiting;

public class TokenBucket {

	private int tokens;
	private long lastRefill;

	/**
	 * Local constructor to enforce creation via RateLimiting class
	 *
	 * @param initialCapacity Initial amount of tokens
	 */
	TokenBucket(int initialCapacity) {
		this.tokens = initialCapacity;
		this.lastRefill = System.currentTimeMillis();
	}

	public synchronized void refill(int maxTokens, int toAdd, long minDelay) {
		int refillMultiplier = (int) ((System.currentTimeMillis() - lastRefill) / minDelay);
		if (refillMultiplier >= 1) {
			lastRefill += refillMultiplier * minDelay;
		}
		tokens = Math.max(maxTokens, tokens + toAdd * refillMultiplier);
	}

	public synchronized int getTokensLeft() {
		return tokens;
	}

	public synchronized boolean pullToken() {
		if (tokens <= 0) {
			return false;
		}
		tokens--;
		return true;
	}

}

package vg.civcraft.mc.civmodcore.ratelimiting;

public class TokenBucket {

	private int tokens;
	private long lastRefill;

	/**
	 * Local constructor to enforce creation via RateLimiting class
	 *
	 * @param initialCapacity Initial amount of tokens
	 */
	TokenBucket(int initialCapacity) {
		this.tokens = initialCapacity;
		this.lastRefill = System.currentTimeMillis();
	}

	public synchronized void refill(int maxTokens, int toAdd, long minDelay) {
		int refillMultiplier = (int) ((System.currentTimeMillis() - lastRefill) / minDelay);
		if (refillMultiplier >= 1) {
			lastRefill += refillMultiplier * minDelay;
		}
		tokens = Math.min(maxTokens, tokens + toAdd * refillMultiplier);
	}

	public synchronized int getTokensLeft() {
		return tokens;
	}

	public synchronized boolean pullToken() {
		if (tokens <= 0) {
			return false;
		}
		tokens--;
		return true;
	}

}

Fix bug in tokenbucket refilling

Fix bug in tokenbucket refilling


package com.vikashkothary.life.data.model;

import android.os.Parcelable;

import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import java.util.Date;

@AutoValue
public abstract class Reminder implements Parcelable {
    public static Builder builder() {
        return new AutoValue_Reminder.Builder();
    }

    public static TypeAdapter<Reminder> typeAdapter(Gson gson) {
        return new AutoValue_Reminder.GsonTypeAdapter(gson);
    }

    public abstract long id();

    public abstract String message();

    public abstract Date datetime();

    @AutoValue.Builder
    public abstract static class Builder {
        public abstract Builder setId(long id);

        public abstract Builder setMessage(String message);

        public abstract Builder setDatetime(Date datetime);

        public abstract Reminder build();
    }
}

package com.vikashkothary.life.data.model;

import android.app.Notification;
import android.content.Context;
import android.os.Parcelable;

import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import java.util.Date;

import static com.vikashkothary.life.util.NotificationFactory.createSimpleNotification;

@AutoValue
public abstract class Reminder implements Parcelable {
    public static Builder builder() {
        return new AutoValue_Reminder.Builder();
    }

    public static TypeAdapter<Reminder> typeAdapter(Gson gson) {
        return new AutoValue_Reminder.GsonTypeAdapter(gson);
    }

    public abstract int id();

    public abstract String title();

    public abstract String text();

    public abstract Date datetime();

    public Notification notification(Context context) {
        return createSimpleNotification(context, title(), text());
    }

    @AutoValue.Builder
    public abstract static class Builder {
        public abstract Builder setId(long id);

        public abstract Builder setTitle(String title);

        public abstract Builder setText(String text);

        public abstract Builder setDatetime(Date datetime);

        public abstract Reminder build();
    }
}

Add notification function to reminder model


package com.team254.frc2015.subsystems.controllers;

import com.team254.lib.util.Controller;

public class BangBangFinishLineController extends Controller {

    private double m_position;
    private double m_goal;
    private double m_tolerance;
    private double m_direction = 0.0;

    public BangBangFinishLineController(double tolerance) {
        m_tolerance = tolerance;
    }

    public void setGoal(double goal) {
        m_goal = goal;
    }

    public double getGoal() {
        return m_goal;
    }

    @Override
    public void reset() {
        m_direction = 0.0;
    }

    @Override
    public boolean isOnTarget() {
        return (m_direction > 0 ? m_position > (m_goal - m_tolerance)
                : m_position < (m_goal + m_tolerance));
    }

    public double update(double position) {
        if (m_direction == 0.0) {
            m_direction = (position > m_goal ? -1.0 : 1.0);
        }
        m_position = position;
        if (m_direction > 0) {
            if (position < (m_goal - m_tolerance)) {
                return 1.0;
            } else {
                return 0.0;
            }
        } else {
            if (position > (m_goal + m_tolerance)) {
                return -1.0;
            } else {
                return 0.0;
            }
        }

    }

}

package com.team254.frc2015.subsystems.controllers;

import com.team254.lib.util.Controller;

public class BangBangFinishLineController extends Controller {

    private double m_position;
    private double m_goal;
    private double m_tolerance;
    private double m_direction = 0.0;

    public BangBangFinishLineController(double tolerance) {
        m_tolerance = tolerance;
    }

    public void setGoal(double goal) {
        m_goal = goal;
    }

    public double getGoal() {
        return m_goal;
    }

    @Override
    public void reset() {
        m_direction = 0.0;
    }

    @Override
    public boolean isOnTarget() {
        if (m_direction == 0.0) {
            return false;
        }
        return (m_direction > 0 ? m_position > (m_goal - m_tolerance)
                : m_position < (m_goal + m_tolerance));
    }

    public double update(double position) {
        if (m_direction == 0.0) {
            m_direction = (position > m_goal ? -1.0 : 1.0);
        }
        m_position = position;
        if (m_direction > 0) {
            if (position < (m_goal - m_tolerance)) {
                return 1.0;
            } else {
                return 0.0;
            }
        } else {
            if (position > (m_goal + m_tolerance)) {
                return -1.0;
            } else {
                return 0.0;
            }
        }

    }

}

Fix bug in isOnTarget BandBangController


package com.uber.okbuck.core.model.jvm;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public final class TestOptions {

  private final List<String> jvmArgs;
  private final TreeMap<String, Object> env;

  public TestOptions(List<String> jvmArgs, Map<String, Object> env) {
    this.jvmArgs = jvmArgs;
    this.env = new TreeMap<>(env);
  }

  public List<String> getJvmArgs() {
    return jvmArgs;
  }

  public TreeMap<String, Object> getEnv() {
    return env;
  }
}

package com.uber.okbuck.core.model.jvm;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public final class TestOptions {

  private final List<String> jvmArgs;
  private final TreeMap<String, Object> env;

  public TestOptions(List<String> jvmArgs, Map<String, Object> env) {
    this.jvmArgs = jvmArgs;
    this.env = new TreeMap<>(env);
  }

  public List<String> getJvmArgs() {
    return jvmArgs;
  }

  public Map<String, Object> getEnv() {
    return env;
  }
}

Use Map in getter instead of TreeMap

Use Map in getter instead of TreeMap


package org.valid4j.impl;

import org.valid4j.UnreachablePolicy;
import org.valid4j.exceptions.ContractViolation;
import org.valid4j.exceptions.NeverGetHereViolation;

import java.util.Queue;

import static org.valid4j.Message.withFormattedMessage;

/**
 * Policy for handling unreachable code by throwing an unrecoverable exception.
 */
public class NeverGetHerePolicy implements UnreachablePolicy {

  private final Queue<ContractViolation> violations;

  public NeverGetHerePolicy(Queue<ContractViolation> violations) {
    this.violations = violations;
  }

  @Override
  public void neverGetHere(Throwable cause, String msg, Object... values) {
    throw tracked(new NeverGetHereViolation(cause, withFormattedMessage(msg, values)));
  }

  private NeverGetHereViolation tracked(NeverGetHereViolation neverGetHereViolation) {
    violations.offer(neverGetHereViolation);
    return neverGetHereViolation;
  }
}

package org.valid4j.impl;

import org.valid4j.UnreachablePolicy;
import org.valid4j.exceptions.ContractViolation;
import org.valid4j.exceptions.NeverGetHereViolation;

import java.util.Queue;

import static org.valid4j.Message.withFormattedMessage;

/**
 * Policy for handling unreachable code by throwing an unrecoverable exception.
 */
public class NeverGetHerePolicy extends TrackingViolationPolicy implements UnreachablePolicy {

  public NeverGetHerePolicy(Queue<ContractViolation> violations) {
    super(violations);
  }

  @Override
  public void neverGetHere(Throwable cause, String msg, Object... values) {
    throw tracked(new NeverGetHereViolation(cause, withFormattedMessage(msg, values)));
  }
}

Use the tracking policy to track thrown never-get-here errors


package utils;

public class Parser {

	public static int parseScore(String s) {
		String[] parse = s.split(",");
		int i;
		for (i = 0; i < parse.length; i++) {
			System.out.println("Parsed : " + parse[i]);
		}
		System.out.println("Score : " + parse[2]);
		return Integer.parseInt(parse[2]);
	}
}

package utils;

public class Parser {

	public static int parseScore(String s) {
		String[] parse = s.split(",");
		int i;
		return Integer.parseInt(parse[2]);
	}
}

Remove printing of some lines

Remove printing of some lines


package com.alsash.reciper.logic.event;

import com.alsash.reciper.logic.action.RecipeAction;

public class RecipeEvent {

    public final RecipeAction action;
    public final String uuid;

    public RecipeEvent(RecipeAction action, String uuid) {
        this.action = action;
        this.uuid = uuid;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof RecipeEvent)) return false;

        RecipeEvent event = (RecipeEvent) o;

        if (action != event.action) return false;
        return uuid != null ? uuid.equals(event.uuid) : event.uuid == null;
    }

    @Override
    public int hashCode() {
        int result = action != null ? action.hashCode() : 0;
        result = 31 * result + (uuid != null ? uuid.hashCode() : 0);
        return result;
    }
}

Update ui - favorite button

Update ui - favorite button


package org.robotninjas.barge;

import com.google.common.collect.Maps;
import org.jetlang.core.BatchExecutorImpl;
import org.jetlang.core.EventReader;
import org.slf4j.MDC;

import java.util.Map;

class BatchExecutor extends BatchExecutorImpl {

  Map contextMap = Maps.newHashMap();

  @Override
  public void execute(EventReader toExecute) {

    Map oldContext = MDC.getCopyOfContextMap();
    MDC.setContextMap(contextMap);

    super.execute(toExecute);

    contextMap = MDC.getCopyOfContextMap();
    MDC.setContextMap(oldContext);

  }

}

package org.robotninjas.barge;

import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import org.jetlang.core.BatchExecutorImpl;
import org.jetlang.core.EventReader;
import org.slf4j.MDC;

import java.util.Map;

class BatchExecutor extends BatchExecutorImpl {

  Map contextMap = Maps.newHashMap();

  @Override
  public void execute(EventReader toExecute) {

    Optional<Map> oldContext = Optional.fromNullable(MDC.getCopyOfContextMap());
    MDC.setContextMap(contextMap);

    super.execute(toExecute);

    contextMap = MDC.getCopyOfContextMap();
    if (oldContext.isPresent()) {
      MDC.setContextMap(oldContext.get());
    }

  }

}

Handle case where MDC is null

Handle case where MDC is null


package org.jvirtanen.nassau;

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

/**
 * MessageListener is the interface for inbound messages.
 */
public interface MessageListener {

    /**
     * Receive a message. The message is contained in the buffer between the
     * current position and the limit.
     *
     * @param buffer a buffer
     * @throws IOException if an I/O error occurs
     */
    void message(ByteBuffer buffer) throws IOException;

}

package org.jvirtanen.nassau;

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

/**
 * The interface for inbound messages.
 */
public interface MessageListener {

    /**
     * Receive a message. The message is contained in the buffer between the
     * current position and the limit.
     *
     * @param buffer a buffer
     * @throws IOException if an I/O error occurs
     */
    void message(ByteBuffer buffer) throws IOException;

}

Tweak documentation for message listener


package eu.nerro.wolappla.provider;

/**
 * Contract class for interacting with {@link DeviceProvider}.
 */
public class DeviceContract {
}

package eu.nerro.wolappla.provider;

import android.net.Uri;

/**
 * Contract class for interacting with {@link DeviceProvider}.
 */
public class DeviceContract {
  public static final String CONTENT_AUTHORITY = "eu.nerro.wolappla";
  public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);

  interface DevicesColumns {
    /** Name describing this device. */
    String DEVICE_NAME = "device_name";
    /** MAC address of the network card of this device. */
    String DEVICE_MAC_ADDRESS = "device_mac_address";
    /** Network broadcast IP. */
    String DEVICE_IP_ADDRESS = "device_ip_address";
    /** Port on which this device is listening for magic packets. */
    String DEVICE_PORT = "device_port";
  }
}

Add column description for device SQLite table


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

package com.google.sps.servlets;

public final class BlogConstants {
  public static String MESSAGE_PARAMETER = "text-input";
  public static String SENDER_PARAMETER = "sender";
  public static String TAG_PARAMETER = "tags";
  public static String PARENTID_PARAMETER = "parentID";
  public static String BLOG_ENTITY_KIND = "blogMessage";
  public static String ID_PARAMETER = "messageId";
  public static String TAG_QUERY = "followedTag";
  public static String NICKNAME = "nickname";
}

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

package com.google.sps.servlets;

public final class BlogConstants {
  public static String MESSAGE_PARAMETER = "text-input";
  public static String SENDER_PARAMETER = "sender";
  public static String TAG_PARAMETER = "tags";
  public static String PARENTID_PARAMETER = "parentID";
  public static String BLOG_ENTITY_KIND = "blogMessage";
  public static String ID_PARAMETER = "messageId";
  public static String TAG_QUERY = "followedTag";
  public static String NICKNAME = "nickname";
  public static String BLOG_USER = "BlogUser";
  public static String ID = "id";
  public static String EMAIL = "email";
  public static String TIME = "time";
}

Add new constants that are used throughout servlets.


package com.thoughtworks.xstream.core;

import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;

public class TreeMarshallerTest extends AbstractAcceptanceTest {

    class Thing {
        Thing thing;
    }

    protected void setUp() throws Exception {
        super.setUp();
        xstream.setMode(XStream.NO_REFERENCES);
    }

    public void testThrowsExceptionWhenDetectingCircularReferences() {
        Thing a = new Thing();
        Thing b = new Thing();
        a.thing = b;
        b.thing = a;

        try {
            xstream.toXML(a);
            fail("expected exception");
        } catch (TreeMarshaller.CircularReferenceException expected) {
            // good
        }
    }
}

package com.thoughtworks.xstream.core;

import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;

public class TreeMarshallerTest extends AbstractAcceptanceTest {

    static class Thing {
        Thing thing;
    }

    protected void setUp() throws Exception {
        super.setUp();
        xstream.setMode(XStream.NO_REFERENCES);
    }

    public void testThrowsExceptionWhenDetectingCircularReferences() {
        Thing a = new Thing();
        Thing b = new Thing();
        a.thing = b;
        b.thing = a;

        try {
            xstream.toXML(a);
            fail("expected exception");
        } catch (TreeMarshaller.CircularReferenceException expected) {
            // good
        }
    }
}

Fix unit test for JDK 1.3.

Fix unit test for JDK 1.3.


package com.bjorn;

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

import javax.xml.bind.annotation.XmlAttribute;
import java.util.HashMap;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class GameTest {
    UI mockUI;
    Board mockBoard;
    Game newGame;

    @Before
    public void setUp() {
        mockUI = Mockito.mock(UI.class);
        mockBoard = Mockito.mock(Board.class);
        newGame = new Game(mockUI, mockBoard);
        newGame.startGame();

    }

    @Test
    public void checkIfWelcomeIsCalled() {
        verify(mockUI, times(1)).printWelcome();
    }

    @Test
    public void checkIfPrintBoardIsCalled() {
        verify(mockUI, atLeastOnce()).printBoard(mockBoard);
    }

    @Test
    public void checkIfPromptForXCoordinateIsCalled() {
        verify(mockUI, atLeastOnce()).promptForXCoordinate();
    }

    @Test
    public void checkIfPromptForYCoordinateIsCalled() {
        verify(mockUI, atLeastOnce()).promptForYCoordinate();
    }

    @Test
    public void checkIfGetUserInputIsCalled() {
        verify(mockUI, atLeastOnce()).getUserInput();
    }

    @Test
    public void checkIfUpdateBoardStateIsCalled() {
        verify(mockBoard, atLeastOnce()).upDateBoardState(0, 0, "H");
    }

}

package com.bjorn;

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

import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class GameTest {
    UI mockUI;
    Board mockBoard;
    Game newGame;

    @Before
    public void setUp() {
        mockUI = Mockito.mock(UI.class);
        mockBoard = Mockito.mock(Board.class);
        newGame = new Game(mockUI, mockBoard);
        newGame.startGame();

    }

    @Test
    public void checkIfWelcomeIsCalled() {
        verify(mockUI, times(1)).printWelcome();
    }

    @Test
    public void checkIfPrintBoardIsCalled() {
        verify(mockUI, atLeastOnce()).printBoard(mockBoard);
    }

    @Test
    public void checkIfPromptForXCoordinateIsCalled() {
        verify(mockUI, atLeastOnce()).promptForXCoordinate();
    }

    @Test
    public void checkIfPromptForYCoordinateIsCalled() {
        verify(mockUI, atLeastOnce()).promptForYCoordinate();
    }

    @Test
    public void checkIfGetUserInputIsCalled() {
        verify(mockUI, atLeastOnce()).getUserInput();
    }

    @Test
    public void checkIfUpdateBoardStateIsCalled() {
        verify(mockBoard, atLeastOnce()).upDateBoardState(0, 0, "H");
    }

}

Remove unused imports in game tests

Remove unused imports in game tests


package org.motechproject.server.pillreminder.util;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Util {

    public static DateTime currentDateTime() {
        return new DateTime(DateTimeZone.UTC);
    }

    public static Date newDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        return cal.getTime();
    }

    public static boolean areDatesSame(Date date1, Date date2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        return dateFormat.format(date1).equals(dateFormat.format(date2));
    }

    public static Date getDateAfter(Date date, int numOfMonth) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, numOfMonth);
        return cal.getTime();
    }
}

package org.motechproject.server.pillreminder.util;

import org.joda.time.DateTime;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Util {

    public static DateTime currentDateTime() {
        return new DateTime();
    }

    public static Date newDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        return cal.getTime();
    }

    public static boolean areDatesSame(Date date1, Date date2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        return dateFormat.format(date1).equals(dateFormat.format(date2));
    }

    public static Date getDateAfter(Date date, int numOfMonth) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, numOfMonth);
        return cal.getTime();
    }
}

Remove UTC from time util<Manohar/Shruthi>


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

package org.osgi.test.cases.jndi.provider;

import java.util.Hashtable;

import javax.naming.NamingException;
import javax.naming.spi.ObjectFactory;

import org.osgi.test.cases.jndi.provider.CTObjectFactory;

/**
 * @version $Revision$ $Date$
 */
public class CTObjectFactoryBuilder implements javax.naming.spi.ObjectFactoryBuilder {

	public ObjectFactory createObjectFactory(Object obj, Hashtable var1)
			throws NamingException {
		if (obj instanceof CTReference) {
		return new CTObjectFactory();
		} else {
			return null;
		}
	}

}

Fix formatting of if statement

Fix formatting of if statement


package org.datavaultplatform.common.metadata.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.datavaultplatform.common.model.Dataset;
import org.datavaultplatform.common.metadata.Provider;

// This mock metadata provider is for testing purposes only

public class MockProvider implements Provider {

    List<Dataset> datasets = new ArrayList<>();
    Map<String, String> projectIds = new HashMap<>();

    public MockProvider() {
        for (int i = 1; i < 6; i++) {
            Dataset d = new Dataset();
            d.setID("MOCK-DATASET-" + i);
            d.setName("Sample dataset " + i);
            d.setContent("Mock Metadata");
            d.setVisible(true);
            datasets.add(d);
            projectIds.put(d.getID(), "MOCK-PROJECTID-" + i);
        }
    }

    @Override
    public List<Dataset> getDatasetsForUser(String userID) {
        return datasets;
    }

    @Override
    public Dataset getDataset(String id) {
        for (Dataset d : datasets) {
            if (d.getID().equals(id)) {
                return d;
            }
        }
        return null;
    }

	@Override
	public Map<String, String> getPureProjectIds() {
		return projectIds;
	}

	@Override
	public String getPureProjectId(String datasetId) {
		return projectIds.get(datasetId);
	}
}

package org.datavaultplatform.common.metadata.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.datavaultplatform.common.model.Dataset;
import org.datavaultplatform.common.metadata.Provider;

// This mock metadata provider is for testing purposes only

public class MockProvider implements Provider {

    List<Dataset> datasets = new ArrayList<>();
    Map<String, String> projectIds = new HashMap<>();

    public MockProvider() {
        for (int i = 1; i < 6; i++) {
            Dataset d = new Dataset();
            d.setID("MOCK-DATASET-" + i);
            d.setName("Sample dataset " + i);
            d.setContent("Mock Metadata");
            d.setVisible(true);
            d.setCrisId("CRIS01");
            datasets.add(d);
            projectIds.put(d.getID(), "MOCK-PROJECTID-" + i);
        }
    }

    @Override
    public List<Dataset> getDatasetsForUser(String userID) {
        return datasets;
    }

    @Override
    public Dataset getDataset(String id) {
        for (Dataset d : datasets) {
            if (d.getID().equals(id)) {
                return d;
            }
        }
        return null;
    }

	@Override
	public Map<String, String> getPureProjectIds() {
		return projectIds;
	}

	@Override
	public String getPureProjectId(String datasetId) {
		return projectIds.get(datasetId);
	}
}

Fix Mocked Datsetws missing the CrisId field


package study.hard.javalib.file;

import java.io.File;
import java.io.IOException;

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

public class FileTest {

	FileHandler fileHandler;
	File tempFile;

	@Before
	public void setUp() {
		fileHandler = new FileHandler();
	}

	@Test
	public void testCreateTempFile() throws IOException {
		tempFile = fileHandler.getTempFile("TEST_TEMP_FILE.txt");
		System.out.println("Absolute path of temporary file: " + tempFile.getAbsolutePath());
	}

	@After
	public void clean() {
		tempFile.delete();
	}
}

package study.hard.javalib.file;

import java.io.File;
import java.io.IOException;

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

public class FileTest {

	FileHandler fileHandler;
	File tempFile;

	@Before
	public void setUp() {
		fileHandler = new FileHandler();
	}

	@Test
	public void testCreateTempFile() throws IOException {
		tempFile = fileHandler.getTempFile("TEST_TEMP_FILE.txt");
		System.out.println("Absolute path of temporary file: " + tempFile.getAbsolutePath());
	}

	@Test
	public void testGetTempDirectoryPath() {
		File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
		System.out.println(tempDirectory);
	}

	@After
	public void clean() {
		if (tempFile != null) {
			tempFile.delete();
		}
	}
}

Add a test case to get temp directory.

Add a test case to get temp directory.


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

import aQute.bnd.annotation.Version;
import aQute.bnd.annotation.Export;

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

import aQute.bnd.annotation.Version;
import aQute.bnd.annotation.Export;

OAK-3749: Implement tooling for tracing a node through the revision history
Bump package export version

git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1718630 13f79535-47bb-0310-9956-ffa450edef68


package net.onrc.onos.core.newintent;

import com.google.common.collect.ImmutableList;
import net.onrc.onos.api.newintent.InstallableIntent;

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

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

/**
 * A class representing a result of intent compilation.
 */
public class IntentCompilationResult {
    private final List<InstallableIntent> result;

    /**
     * Constructs an instance containing the specified list of installable intents.
     *
     * @param result installable intents
     */
    public IntentCompilationResult(List<InstallableIntent> result) {
        checkNotNull(result);
        checkArgument(result.size() > 0,
                "result of intent compilation should be " +
                "more than 1 installable intents or more, but %s", result.size());

        this.result = new ArrayList<>(checkNotNull(result));
    }

    /**
     * Constructor for serializer.
     */
    protected IntentCompilationResult() {
        this.result = null;
    }

    /**
     * Returns list of installable intents that this object contains.
     *
     * @return installable intents
     */
    public List<InstallableIntent> getResult() {
        return ImmutableList.copyOf(result);
    }
}

package net.onrc.onos.core.newintent;

import com.google.common.collect.ImmutableList;
import net.onrc.onos.api.newintent.InstallableIntent;

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

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

/**
 * A class representing a result of intent compilation.
 */
public class IntentCompilationResult {
    private final List<InstallableIntent> result;

    /**
     * Constructs an instance containing the specified list of installable intents.
     *
     * @param result installable intents
     */
    public IntentCompilationResult(List<InstallableIntent> result) {
        checkNotNull(result);
        checkArgument(result.size() > 0,
                "result of intent compilation should be " +
                "at least one installable intent, but %s", result.size());

        this.result = new ArrayList<>(checkNotNull(result));
    }

    /**
     * Constructor for serializer.
     */
    protected IntentCompilationResult() {
        this.result = null;
    }

    /**
     * Returns list of installable intents that this object contains.
     *
     * @return installable intents
     */
    public List<InstallableIntent> getResult() {
        return ImmutableList.copyOf(result);
    }
}

Revise message explaining the cause of exception

Change-Id: Ic6c6048f3e04d99c55b8de08ec4be1370139a549


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

import java.io.IOException;
import java.util.Set;

/**
 * Reads class dependencies from bytecode
 *
 * @param data
 *            bytecode of a class
 * @throws IOException
 *             if bytecode is invalid or other error occurred during processing
 * @return list of classes on which given class depends
 */
public interface DependencyReader {
    public Set<String> getDependencies(byte[] data) throws IOException;
}

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

import java.io.IOException;
import java.util.Set;

public interface DependencyReader {

    /**
     * Read class dependencies from bytecode
     *
     * @param data
     *            bytecode of a class
     * @throws IOException
     *             if bytecode is invalid or other error occurred during
     *             processing
     * @return list of classes on which given class depends
     */
    public Set<String> getDependencies(byte[] data) throws IOException;
}

Move javadoc comment where it belongs

Move javadoc comment where it belongs


package io.github.jordao76.quotes.filters;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.slf4j.*;
import org.springframework.stereotype.*;
import org.springframework.web.filter.*;

@Component
public class RequestLoggingFilter extends OncePerRequestFilter {

  private static final Logger LOGGER = LoggerFactory.getLogger(RequestLoggingFilter.class);

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

    filterChain.doFilter(request, response);

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("HTTP {} for {} {}",
        value("status", response.getStatus()),
        value("method", request.getMethod()),
        value("endpoint", request.getRequestURI()));
    }

  }

  // note: later to be replaced,
  // see https://github.com/logstash/logstash-logback-encoder/tree/logstash-logback-encoder-4.7#loggingevent_custom_event
  private Object value(String key, Object value) {
    return value;
  }

}

package io.github.jordao76.quotes.filters;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.slf4j.*;
import org.springframework.stereotype.*;
import org.springframework.web.filter.*;

@Component
public class RequestLoggingFilter extends OncePerRequestFilter {

  private final Logger logger = LoggerFactory.getLogger(getClass());

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

    filterChain.doFilter(request, response);

    if (logger.isDebugEnabled()) {
      logger.debug("HTTP {} for {} {}",
        value("status", response.getStatus()),
        value("method", request.getMethod()),
        value("endpoint", request.getRequestURI()));
    }

  }

  // note: later to be replaced,
  // see https://github.com/logstash/logstash-logback-encoder/tree/logstash-logback-encoder-4.7#loggingevent_custom_event
  private Object value(String key, Object value) {
    return value;
  }

}

Change filter logger to instance field

Change filter logger to instance field


// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.identity;

import com.yahoo.vespa.athenz.api.AthenzService;

import javax.net.ssl.SSLContext;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * A helper class managing {@link ServiceIdentityProvider.Listener} instances for implementations of {@link ServiceIdentityProvider}.
 *
 * @author bjorncs
 */
public class ServiceIdentityProviderListenerHelper {

    private final Set<ServiceIdentityProvider.Listener> listeners = new ConcurrentSkipListSet<>();
    private final AthenzService identity;

    public ServiceIdentityProviderListenerHelper(AthenzService identity) {
        this.identity = identity;
    }

    public void addIdentityListener(ServiceIdentityProvider.Listener listener) {
        listeners.add(listener);
    }

    public void removeIdentityListener(ServiceIdentityProvider.Listener listener) {
        listeners.remove(listener);
    }

    public void onCredentialsUpdate(SSLContext sslContext) {
        listeners.forEach(l -> l.onCredentialsUpdate(sslContext, identity));
    }

    public void clearListeners() {
        listeners.clear();
    }

}

// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.identity;

import com.yahoo.vespa.athenz.api.AthenzService;

import javax.net.ssl.SSLContext;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * A helper class managing {@link ServiceIdentityProvider.Listener} instances for implementations of {@link ServiceIdentityProvider}.
 *
 * @author bjorncs
 */
public class ServiceIdentityProviderListenerHelper {

    private final Set<ServiceIdentityProvider.Listener> listeners = new CopyOnWriteArraySet<>();
    private final AthenzService identity;

    public ServiceIdentityProviderListenerHelper(AthenzService identity) {
        this.identity = identity;
    }

    public void addIdentityListener(ServiceIdentityProvider.Listener listener) {
        listeners.add(listener);
    }

    public void removeIdentityListener(ServiceIdentityProvider.Listener listener) {
        listeners.remove(listener);
    }

    public void onCredentialsUpdate(SSLContext sslContext) {
        listeners.forEach(l -> l.onCredentialsUpdate(sslContext, identity));
    }

    public void clearListeners() {
        listeners.clear();
    }

}

Use ConcurrentCopyOnWriteArraySet -- could alternatively provide a Comparator


package etomica.simulation;

import etomica.modules.catalysis.Catalysis;
import etomica.space3d.Space3D;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.profile.StackProfiler;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

@State(Scope.Benchmark)
@Fork(1)
public class BenchSimCatalysis {
    private Catalysis sim;

    @Param("20")
    private int nCellsZ;

    @Setup
    public void setup() {
        sim = new Catalysis(Space3D.getInstance(), nCellsZ);
        sim.integrator.reset();
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    @Warmup(time = 3, iterations = 5)
    @Measurement(time = 10, timeUnit = TimeUnit.SECONDS, iterations = 3)
    public long integratorStep() {
        sim.integrator.doStep();
        return sim.integrator.getStepCount();
    }

    public static void main(String[] args) throws RunnerException {
        Options opts = new OptionsBuilder()
                .include(BenchSimCatalysis.class.getSimpleName())
                .addProfiler(StackProfiler.class)
                .build();

        new Runner(opts).run();
    }
}

package etomica.simulation;

import etomica.modules.catalysis.Catalysis;
import etomica.space3d.Space3D;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.profile.StackProfiler;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

@State(Scope.Benchmark)
@Fork(1)
public class BenchSimCatalysis {
    private Catalysis sim;

    @Param("20")
    private int nCellsZ;

    @Setup(Level.Iteration)
    public void setup() {
        sim = new Catalysis(Space3D.getInstance(), nCellsZ);
        sim.integrator.reset();
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    @Warmup(time = 3, iterations = 5)
    @Measurement(time = 10, timeUnit = TimeUnit.SECONDS, iterations = 3)
    public long integratorStep() {
        sim.integrator.doStep();
        return sim.integrator.getStepCount();
    }

    public static void main(String[] args) throws RunnerException {
        Options opts = new OptionsBuilder()
                .include(BenchSimCatalysis.class.getSimpleName())
                .addProfiler(StackProfiler.class)
                .build();

        new Runner(opts).run();
    }
}

Make sure Catalysis benchmark sets up between each iteration

Probably why it was so erratic.


package org.apache.maven.cli;

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

import java.io.File;

/**
 * Resolve relative file path against the given base directory
 */
public class ResolveFile
{
    public static File resolveFile( File file, String baseDirectory )
    {
        if ( file == null )
        {
            return null;
        }
        else if ( file.isAbsolute() )
        {
            return file;
        }
        else if ( file.getPath().startsWith( File.separator ) )
        {
            // drive-relative Windows path
            return file.getAbsoluteFile();
        }
        else
        {
            return new File( baseDirectory, file.getPath() ).getAbsoluteFile();
        }
    }
}

package org.apache.maven.cli;

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

import java.io.File;
import java.nio.file.Paths;

/**
 * Resolve relative file path against the given base directory
 */
public class ResolveFile
{
    public static File resolveFile( File file, String baseDirectory )
    {
        if ( file == null )
        {
            return null;
        }
        else if ( file.isAbsolute() )
        {
            return file;
        }
        else if ( file.getPath().startsWith( File.separator ) )
        {
            // drive-relative Windows path
            return file.getAbsoluteFile();
        }
        else
        {
            return Paths.get( baseDirectory, file.getPath() ).normalize().toFile();
        }
    }
}

[MNG-6071] Normalize relative paths for working directory


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

import org.junit.Test;

import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;

/**
 * {@link CereebroServerProperties} unit tests.
 *
 * @author michaeltecourt
 */
public class CereebroServerPropertiesTest {

    @Test
    public void verifyEqualsAndHashcode() {
        EqualsVerifier.forClass(CereebroServerProperties.class).suppress(Warning.NONFINAL_FIELDS).verify();
    }

}

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

import java.util.Arrays;

import org.assertj.core.api.Assertions;
import org.junit.Test;

import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;

/**
 * {@link CereebroServerProperties} unit tests.
 *
 * @author michaeltecourt
 */
public class CereebroServerPropertiesTest {

    @Test
    public void verifyEqualsAndHashcode() {
        EqualsVerifier.forClass(CereebroServerProperties.class).suppress(Warning.NONFINAL_FIELDS).verify();
    }

    @Test
    public void testToString() {
        CereebroServerProperties server = new CereebroServerProperties();
        SystemProperties system = new SystemProperties();
        system.setName("alpha");
        system.setPath("/nope");
        SnitchProperties snitch = new SnitchProperties();
        snitch.setResources(Arrays.asList());
        system.setSnitch(snitch);
        server.setSystem(system);
        Assertions.assertThat(server.toString()).isNotEmpty();
    }

}

Improve test coverage one last time

Improve test coverage one last time


/*
 *  Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
 *
 *  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 es.bsc.compss.agent;

public class AgentException extends Exception {

    public AgentException(String message) {
        super(message);
    }

    public AgentException(Throwable cnfe) {
        super(cnfe);
    }

    public AgentException(String message, Throwable cause) {
        super(message, cause);
    }

}

/*
 *  Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
 *
 *  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 es.bsc.compss.agent;

public class AgentException extends Exception {

    /**
     * Exceptions Version UID are 2L in all Runtime.
     */
    private static final long serialVersionUID = 2L;

    public AgentException(String message) {
        super(message);
    }

    public AgentException(Throwable cnfe) {
        super(cnfe);
    }

    public AgentException(String message, Throwable cause) {
        super(message, cause);
    }

}

Add serialization number to agent exception


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

package alluxio.worker.netty;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * Closes the channel if it has been idle for too long.
 */
public class IdleReadHandler extends ChannelDuplexHandler {
  /**
   * Creates a new idle read handler.
   */
  public IdleReadHandler() {}

  @Override
  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
      if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
        ctx.close();
      }
    }
  }
}

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

package alluxio.worker.netty;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Closes the channel if it has been idle for too long.
 */
public class IdleReadHandler extends ChannelDuplexHandler {
  private static final Logger LOG = LoggerFactory.getLogger(IdleReadHandler.class);

  /**
   * Creates a new idle read handler.
   */
  public IdleReadHandler() {}

  @Override
  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
      if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
        LOG.warn("Closing netty channel to {} due to inactivity.", ctx.channel().remoteAddress());
        ctx.close();
      }
    }
  }
}

Add logging when netty channels are closed due to inactivity.


package com.ippon.jug.slip;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;

@RestController
public class SlipController {

    @RequestMapping(value = "/request")
    public String getRequest() throws InterruptedException, UnknownHostException {
        this.doSlip();
        return "Hello I'm " + InetAddress.getLocalHost().getHostName();
    }

    private static final int SLEEP_MILLIS = 50;

    private synchronized void doSlip() throws InterruptedException {
        Thread.sleep(SLEEP_MILLIS);
    }

    @RequestMapping(value = "/dockerHealth")
    public ResponseEntity<Void> getHealth() {
        return new ResponseEntity<Void>(HttpStatus.OK);
    }
}

package com.ippon.jug.slip;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;

@RestController
public class SlipController {

    @RequestMapping(value = "/request")
    public String getRequest() throws InterruptedException, UnknownHostException {
        this.doSlip();
        return "Hello I'm " + InetAddress.getLocalHost().getHostName();
    }

    private static final int SLEEP_MILLIS = 50;

    private synchronized void doSlip() throws InterruptedException {
        Thread.sleep(SLEEP_MILLIS);
    }

    @RequestMapping(value = "/dockerHealth")
    public ResponseEntity<Void> getHealth() {
        return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Set to InternalServerError the slip healthcheck


package org.terasology.logic.jedit;

import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.entitySystem.event.ReceiveEvent;
import org.terasology.entitySystem.systems.BaseComponentSystem;
import org.terasology.entitySystem.systems.RegisterSystem;
import org.terasology.input.ButtonState;
import org.terasology.input.binds.general.JeditButton;
import org.terasology.network.ClientComponent;
import org.terasology.utilities.jedit.JeditManager;

/**
 * Open Jedit
 * @author Patricio Huepe
 */
@RegisterSystem
public class JeditSystem extends BaseComponentSystem {
	 @ReceiveEvent(components = ClientComponent.class)
	 public void onToggleChat(JeditButton event, EntityRef entity) {
		 if (event.getState() == ButtonState.DOWN) {
			 JeditManager.openJedit("test.java");
	         event.consume();
	    }
	 }
}

package org.terasology.logic.jedit;

import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.entitySystem.event.ReceiveEvent;
import org.terasology.entitySystem.systems.BaseComponentSystem;
import org.terasology.entitySystem.systems.RegisterSystem;
import org.terasology.input.ButtonState;
import org.terasology.input.binds.general.JeditButton;
import org.terasology.network.ClientComponent;
import org.terasology.utilities.jedit.JeditManager;

/**
 * Open Jedit
 * @author Patricio Huepe
 */
@RegisterSystem
public class JeditSystem extends BaseComponentSystem {
	 @ReceiveEvent(components = ClientComponent.class)
	 public void openJedit(JeditButton event, EntityRef entity) {
		 if (event.getState() == ButtonState.DOWN) {
			 JeditManager.openJedit("test.java");
	         event.consume();
	    }
	 }
}

Change of a method name

Change of a method name


package org.subethamail.smtp.command;

import java.io.IOException;

import org.subethamail.smtp.server.BaseCommand;
import org.subethamail.smtp.server.ConnectionContext;

/**
 * @author Ian McFarland <ian@neo.com>
 * @author Jon Stevens
 */
public class QuitCommand extends BaseCommand
{
	public QuitCommand()
	{
		super("QUIT", "Exit the SMTP session.");
	}

	@Override
	public void execute(String commandString, ConnectionContext context) throws IOException
	{
		context.sendResponse("221 Bye");
		context.getSession().quit();
	}
}

package org.subethamail.smtp.command;

import java.io.IOException;

import org.subethamail.smtp.server.BaseCommand;
import org.subethamail.smtp.server.ConnectionContext;

/**
 * @author Ian McFarland <ian@neo.com>
 * @author Jon Stevens
 */
public class QuitCommand extends BaseCommand
{
	public QuitCommand()
	{
		super("QUIT", "Exit the SMTP session.");
	}

	@Override
	public void execute(String commandString, ConnectionContext context) throws IOException
	{
		context.getSession().quit();
		context.sendResponse("221 Bye");
	}
}

Fix to ensure session is closed on QUIT command response

git-svn-id: 22ec8cfea0672d04b2346d96717164b900bedbad@212 d4f6eda6-38e6-11de-8fef-1f5ae417a2df


package org.atlasapi.output.annotation;

import org.atlasapi.content.Content;
import org.atlasapi.content.Episode;
import org.atlasapi.output.FieldWriter;
import org.atlasapi.output.OutputContext;
import org.atlasapi.output.writers.SeriesSummaryWriter;

import java.io.IOException;

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

public class SeriesSummaryAnnotation extends OutputAnnotation<Content> {

    public static final String SERIES_FIELD = "series";

    private final SeriesSummaryWriter summaryWriter;

    public SeriesSummaryAnnotation(SeriesSummaryWriter summaryWriter) {
        this.summaryWriter = checkNotNull(summaryWriter);
    }

    @Override
    public void write(Content entity, FieldWriter writer, OutputContext ctxt) throws IOException {
        if (entity instanceof Episode) {
            Episode episode = (Episode) entity;
            if(episode.getSeriesRef() == null) {
                writer.writeField(SERIES_FIELD, null);
            } else {
                summaryWriter.write(episode, writer, ctxt);
            }
        }
    }
}

package org.atlasapi.output.annotation;

import org.atlasapi.content.Content;
import org.atlasapi.content.Episode;
import org.atlasapi.output.FieldWriter;
import org.atlasapi.output.OutputContext;
import org.atlasapi.output.writers.SeriesSummaryWriter;

import java.io.IOException;

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

public class SeriesSummaryAnnotation extends OutputAnnotation<Content> {

    public static final String SERIES_FIELD = "series";

    private final SeriesSummaryWriter summaryWriter;

    public SeriesSummaryAnnotation(SeriesSummaryWriter summaryWriter) {
        this.summaryWriter = checkNotNull(summaryWriter);
    }

    @Override
    public void write(Content entity, FieldWriter writer, OutputContext ctxt) throws IOException {
        if (entity instanceof Episode) {
            Episode episode = (Episode) entity;
            if(episode.getSeriesRef() == null) {
                writer.writeField(SERIES_FIELD, null);
            } else {
                writer.writeObject(summaryWriter, episode, ctxt);
            }
        }
    }
}

Write series summary in correct field.

Write series summary in correct field.


package net.shadowfacts.foodies.item;

import cpw.mods.fml.common.registry.GameRegistry;

/**
 * Helper class for registering items.
 * @author shadowfacts
 */
public class FItems {
	// Foods
	public static Food toast;
	public static Food tomato;
	public static Food beefPattie;
	public static Food hamburger;

	public static void preInit() {
		// Create Items
		toast = new Food(5, 0.3f).setUnlocalizedName("foodToast").setTextureName("foodToast");
		tomato = new Food(1, 0.1f).setUnlocalizedName("fruitTomato").setTextureName("fruitTomato");
		beefPattie = new Food(7, 0.4f).setUnlocalizedName("foodBeefPattie").setTextureName("foodBeefPattie");
		hamburger = new Food(5, 0.7f).setUnlocalizedName("foodHamburger").setTextureName("foodHamburger");

		// Register items
		GameRegistry.registerItem(toast, "foodToast");
		GameRegistry.registerItem(tomato, "fruitTomato");
		GameRegistry.registerItem(beefPattie, "foodBeefPattie");
		GameRegistry.registerItem(hamburger, "foodHamburger");
	}

	public static void load() {

	}

	public static void postInit() {

	}
}

package net.shadowfacts.foodies.item;

import cpw.mods.fml.common.registry.GameRegistry;

/**
 * Helper class for registering items.
 * @author shadowfacts
 */
public class FItems {
	// Foods
	public static Food toast;
	public static Food tomato;
	public static Food beefPattie;
	public static Food hamburger;

	public static void preInit() {
		// Create Items
		toast = new Food(3, 0.3f).setUnlocalizedName("foodToast").setTextureName("foodToast");
		tomato = new Food(1, 0.1f).setUnlocalizedName("fruitTomato").setTextureName("fruitTomato");
		beefPattie = new Food(7, 0.4f).setUnlocalizedName("foodBeefPattie").setTextureName("foodBeefPattie");
		hamburger = new Food(5, 0.7f).setUnlocalizedName("foodHamburger").setTextureName("foodHamburger");

		// Register items
		GameRegistry.registerItem(toast, "foodToast");
		GameRegistry.registerItem(tomato, "fruitTomato");
		GameRegistry.registerItem(beefPattie, "foodBeefPattie");
		GameRegistry.registerItem(hamburger, "foodHamburger");
	}

	public static void load() {

	}

	public static void postInit() {

	}
}

Change hunger values for toast AGAIN

Change hunger values for toast AGAIN


package at.medunigraz.imi.abbres.model.mapper;

import java.util.Map;
import java.util.TreeMap;

import at.medunigraz.imi.abbres.model.NGramMap;
import junit.framework.TestCase;

public class UnigramMapperTest extends TestCase {

	public void testMap() {
		Map<String, Integer> map = new TreeMap<>();
		map.put("To", 10);
		map.put("A", 1000);
		map.put("Kill", 1);
		map.put("Pride", 100);
		map.put("Prejudice", 100);

		UnigramMapper unigramMapper = new UnigramMapper(new NGramMap(map));

		Map<String, Integer> unigrams = unigramMapper.map("Pr.", "", "");
		assertEquals(2, unigrams.size());
	}
}

package at.medunigraz.imi.abbres.model.mapper;

import java.util.Map;
import java.util.TreeMap;

import at.medunigraz.imi.abbres.model.NGramMap;
import junit.framework.TestCase;

public class UnigramMapperTest extends TestCase {

	public void testMap() {
		Map<String, Integer> map = new TreeMap<>();
		map.put("To", 10);
		map.put("A", 1000);
		map.put("Kill", 1);
		map.put("Pride", 100);
		map.put("Prejudice", 100);

		Mapper unigramMapper = new UnigramMapper(new NGramMap(map));

		Map<String, Integer> unigrams = unigramMapper.map("Pr.", "", "");
		assertEquals(2, unigrams.size());
	}
}

Change from testing implementation to interface


/*
 * Copyright 2013-2020 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 org.cloudfoundry.client.v3;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.AllowNulls;
import org.cloudfoundry.Nullable;
import org.immutables.value.Value;

import java.util.Map;

/**
 * The metadata payload for a resource
 */
@JsonDeserialize
@Value.Immutable
abstract class _Metadata {

    /**
     * The metadata annotations
     */
    @JsonProperty("annotations")
    @AllowNulls
    @Nullable
    abstract Map<String, String> getAnnotations();

    /**
     * The metadata labels
     */
    @JsonProperty("labels")
    @AllowNulls
    @Nullable
    abstract Map<String, String> getLabels();

}

/*
 * Copyright 2013-2020 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 org.cloudfoundry.client.v3;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.AllowNulls;
import org.cloudfoundry.Nullable;
import org.immutables.value.Value;

import java.util.Map;

/**
 * The metadata payload for a resource
 */
@JsonDeserialize
@Value.Immutable
abstract class _Metadata {

    /**
     * The metadata annotations
     */
    @JsonProperty("annotations")
    @JsonInclude
    @AllowNulls
    @Nullable
    abstract Map<String, String> getAnnotations();

    /**
     * The metadata labels
     */
    @JsonProperty("labels")
    @JsonInclude
    @AllowNulls
    @Nullable
    abstract Map<String, String> getLabels();

}

Fix Metadata serialization (serialize null values)


package hu.elte.txtuml.examples.validation;
import hu.elte.txtuml.api.model.ModelClass;
import hu.elte.txtuml.api.model.Signal;

public class InvalidModifier extends ModelClass {

	synchronized void f() {}

	final void g() {}

	static int i;

}

package hu.elte.txtuml.examples.validation;
import hu.elte.txtuml.api.model.ModelClass;
import hu.elte.txtuml.api.model.Signal;

public class InvalidModifier extends ModelClass {

	synchronized void f() {}

	static final void g() {}

	static int i;

}

Extend validation tests to check if static methods are allowed


package io.sitoolkit.wt.gui.domain.sample;

import java.io.File;

import io.sitoolkit.util.buidtoolhelper.maven.MavenProject;
import io.sitoolkit.util.buidtoolhelper.process.ProcessCommand;
import io.sitoolkit.util.buidtoolhelper.process.ProcessExitCallback;
import io.sitoolkit.wt.util.infra.concurrent.ExecutorContainer;

public class SampleProcessClient {

    public SampleProcessClient() {
    }

    /**
     * 次のコマンドを実行します。
     *
     *

     * mvn
     *

     *
     */
    public void start(File sampleDir, SampleStartedCallback callback) {

        JettyMavenPluginStdoutListener listener = new JettyMavenPluginStdoutListener();
        MavenProject
            .load(sampleDir.toPath())
            .mvnw("")
            .stdout(listener)
            .executeAsync();

        ExecutorContainer.get().execute(() -> {
            callback.onStarted(listener.isSuccess());
        });
    }

    /**
     * 次のコマンドを実行します。
     *
     *

     * mvn jetty:stop
     *

     *
     */
    public void stop(File sampleDir, ProcessExitCallback callback) {

        ProcessCommand cmd = MavenProject
            .load(sampleDir.toPath())
            .mvnw("jetty:stop");
        if (callback != null)
            cmd.getExitCallbacks().add(callback);
        cmd.executeAsync();
    }
}

package io.sitoolkit.wt.gui.domain.sample;

import java.io.File;

import io.sitoolkit.util.buidtoolhelper.maven.MavenProject;
import io.sitoolkit.util.buidtoolhelper.process.ProcessCommand;
import io.sitoolkit.util.buidtoolhelper.process.ProcessExitCallback;
import io.sitoolkit.wt.util.infra.concurrent.ExecutorContainer;

public class SampleProcessClient {

    public SampleProcessClient() {
    }

    /**
     * 次のコマンドを実行します。
     *
     *

     * mvn
     *

     *
     */
    public void start(File sampleDir, SampleStartedCallback callback) {

        JettyMavenPluginStdoutListener listener = new JettyMavenPluginStdoutListener();
        MavenProject.load(sampleDir.toPath()).mvnw().stdout(listener).executeAsync();

        ExecutorContainer.get().execute(() -> {
            callback.onStarted(listener.isSuccess());
        });
    }

    /**
     * 次のコマンドを実行します。
     *
     *

     * mvn jetty:stop
     *

     *
     */
    public void stop(File sampleDir, ProcessExitCallback callback) {

        ProcessCommand cmd = MavenProject.load(sampleDir.toPath()).mvnw("jetty:stop");
        if (callback != null)
            cmd.getExitCallbacks().add(callback);
        cmd.executeAsync();
    }
}

Fix error on starting sample site

Fix error on starting sample site


package ca.corefacility.bioinformatics.irida.model.sample;

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

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

/**
 * Stores unstructured metadata for a given {@link Sample}.
 */
@Document
public class SampleMetadata {

	@Field(value = "metadata")
	Map<String, Object> metadata;

	@Id
	Long sampleId;

	public SampleMetadata() {
		metadata = new HashMap<>();
	}

	public Map<String, Object> getMetadata() {
		if (this.metadata == null) {
			this.metadata = new HashMap<>();
		}
		return metadata;
	}

	public void setMetadata(Map<String, Object> metadata) {
		this.metadata = metadata;
	}

	public Long getSampleId() {
		return sampleId;
	}

	public void setSampleId(Long sampleId) {
		this.sampleId = sampleId;
	}
}

package ca.corefacility.bioinformatics.irida.model.sample;

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

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

/**
 * Stores unstructured metadata for a given {@link Sample}.
 */
@Document
public class SampleMetadata {

	@Field(value = "metadata")
	Map<String, Object> metadata;

	@Id
	Long sampleId;

	public SampleMetadata() {
		metadata = new HashMap<>();
	}

	public Map<String, Object> getMetadata() {
		return metadata;
	}

	public void setMetadata(Map<String, Object> metadata) {
		this.metadata = metadata;
	}

	public Long getSampleId() {
		return sampleId;
	}

	public void setSampleId(Long sampleId) {
		this.sampleId = sampleId;
	}
}

Revert "Need a check for an emtpy hash"

Revert "Need a check for an emtpy hash"

This reverts commit 07100389c363710260f4c0f5799da548672ad06a.


/*
 * Copyright (C) 2013 Conductor, 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 net.opentsdb.contrib.tsquare.support;

import java.util.Iterator;

import net.opentsdb.core.Aggregator.Doubles;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;

/**
 * Wraps a {@link DataPoints} object and exposes the data consistent
 * with the {@link Doubles} interface.
 *
 * @author James Royalty (jroyalty) <i>[Jul 12, 2013]</i>
 */
public class DataPointsAsDoubles implements Doubles {
    private final Iterator<DataPoint> iterator;

    public DataPointsAsDoubles(final DataPoints points) {
        this.iterator = points.iterator();
    }

    @Override
    public boolean hasNextValue() {
        return iterator.hasNext();
    }

    @Override
    public double nextDoubleValue() {
        return iterator.next().toDouble();
    }
}

/*
 * Copyright (C) 2013 Conductor, 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 net.opentsdb.contrib.tsquare.support;

import java.util.Iterator;

import net.opentsdb.core.Aggregator.Doubles;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;

/**
 * Wraps a {@link DataPoints} object and exposes the data consistent
 * with the {@link Doubles} interface.
 *
 * @author James Royalty (jroyalty) <i>[Jul 12, 2013]</i>
 */
public class DataPointsAsDoubles implements Doubles {
    private final Iterator<DataPoint> iterator;

    public DataPointsAsDoubles(final DataPoints points) {
        this.iterator = points.iterator();
    }

    @Override
    public boolean hasNextValue() {
        return iterator.hasNext();
    }

    @Override
    public double nextDoubleValue() {
        final DataPoint point = iterator.next();
        return TsWebUtils.asDouble(point);
    }
}

Use conversion methods in utils class.

Use conversion methods in utils class.


package de.uni_tuebingen.ub.ixTheo.conditionalInsertField;

import java.io.IOException;

import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.processor.UpdateRequestProcessor;
import org.apache.solr.update.processor.UpdateRequestProcessorFactory;

public class ConditionalInsertFieldProcessorFactory extends UpdateRequestProcessorFactory
{
    @Override
    public UpdateRequestProcessor getInstance(SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) {
         return new ConditionalInsertProcessor(next);
    }
}

class ConditionalInsertProcessor extends UpdateRequestProcessor
{
    public ConditionalInsertProcessor(UpdateRequestProcessor next) {
        super(next);
    }

    @Override
    public void processAdd(AddUpdateCommand cmd) throws IOException {
        addHasFulltext(cmd);
        // pass it up the chain
        super.processAdd(cmd);
    }

    // Add has_fulltext flag if fulltext is present
    protected void addHasFulltext(AddUpdateCommand cmd) throws IOException {
        SolrInputDocument doc = cmd.getSolrInputDocument();
        String fulltext = (String) doc.getFieldValue("fulltext");
        if (fulltext != null && !fulltext.isEmpty())
            doc.addField("has_fulltext", "true");
    }
}

package de.uni_tuebingen.ub.ixTheo.conditionalInsertField;

import java.io.IOException;

import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.processor.UpdateRequestProcessor;
import org.apache.solr.update.processor.UpdateRequestProcessorFactory;

public class ConditionalInsertFieldProcessorFactory extends UpdateRequestProcessorFactory
{
    @Override
    public UpdateRequestProcessor getInstance(SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) {
         return new ConditionalInsertProcessor(next);
    }
}

class ConditionalInsertProcessor extends UpdateRequestProcessor
{
    public ConditionalInsertProcessor(UpdateRequestProcessor next) {
        super(next);
    }

    @Override
    public void processAdd(AddUpdateCommand cmd) throws IOException {
        addHasFulltext(cmd);
        // pass it up the chain
        super.processAdd(cmd);
    }

    // Add has_fulltext flag if fulltext is present
    protected void addHasFulltext(AddUpdateCommand cmd) throws IOException {
        SolrInputDocument doc = cmd.getSolrInputDocument();
        boolean fulltext_exists = doc.getField("fulltext").getValueCount() > 0;
        boolean fulltext_toc_exists = doc.getField("fulltext_toc").getValueCount() > 0;
        boolean fulltext_abstract_exists = doc.getField("fulltext_abstract").getValueCount() > 0;
        if (fulltext_exists || fulltext_toc_exists || fulltext_abstract_exists)
            doc.addField("has_fulltext", "true");
    }
}

Extend has fulltext to new scopes

Extend has fulltext to new scopes


package com.github.ignition.support.http.gzip;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.protocol.HttpContext;

import com.github.ignition.support.http.IgnitedHttp;

/**
 * Simple {@link HttpResponseInterceptor} that inflates response if GZIP encoding header.
 */
public class GzipHttpResponseInterceptor implements HttpResponseInterceptor {

    @Override
    public void process(final HttpResponse response, final HttpContext context) {
        // Inflate any responses compressed with gzip
        final HttpEntity entity = response.getEntity();
        final Header encoding = entity.getContentEncoding();
        if (encoding != null) {
            for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(IgnitedHttp.ENCODING_GZIP)) {
                    response.setEntity(new GzipInflatingEntity(response.getEntity()));
                    break;
                }
            }
        }
    }

}

package com.github.ignition.support.http.gzip;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.protocol.HttpContext;

import com.github.ignition.support.http.IgnitedHttp;

/**
 * Simple {@link HttpResponseInterceptor} that inflates response if GZIP encoding header.
 */
public class GzipHttpResponseInterceptor implements HttpResponseInterceptor {

    @Override
    public void process(final HttpResponse response, final HttpContext context) {
        // Inflate any responses compressed with gzip
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(IgnitedHttp.ENCODING_GZIP)) {
                        response.setEntity(new GzipInflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    }

}

Check if http entity is null and don't do anything if it is.


/*
 * Copyright 2015-2017 OpenCB
 *
 * 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.opencb.opencga.storage.core.variant.io.json.mixin;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * Created by jacobo on 2/02/15.
 */

@JsonIgnoreProperties({"proteinSubstitutionScores", "variantTraitAssociation"})
public abstract class VariantAnnotationMixin {
}

/*
 * Copyright 2015-2017 OpenCB
 *
 * 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.opencb.opencga.storage.core.variant.io.json.mixin;

import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.opencb.biodata.models.variant.avro.GeneCancerAssociation;

import java.util.List;

/**
 * Created by jacobo on 2/02/15.
 */

@JsonIgnoreProperties({"proteinSubstitutionScores", "variantTraitAssociation"})
public abstract class VariantAnnotationMixin {

    @JsonAlias("cancerGeneAssociations")
    public abstract List<GeneCancerAssociation> getGeneCancerAssociations();

}

storage: Add alias for VariantAnnotation.geneCancerAssociations to handle property renaming


package org.apache.mesos.logstash.common;

public interface LogstashConstants {
    String FRAMEWORK_NAME = "logstash";
    int FAILOVER_TIMEOUT = 300000;
    String EXECUTOR_IMAGE_NAME = "mesos/logstash-executor";
    String EXECUTOR_IMAGE_TAG = "latest";
    String EXECUTOR_IMAGE_NAME_WITH_TAG = EXECUTOR_IMAGE_NAME + ":" + EXECUTOR_IMAGE_TAG;
    String NODE_NAME = "logstash.node";
    String TASK_NAME = "logstash.task";
    String TASK_DATE_FORMAT = "yyyyMMdd'T'HHmmss.SSS'Z'";
}

package org.apache.mesos.logstash.common;

public interface LogstashConstants {
    String FRAMEWORK_NAME = "logstash";
    int FAILOVER_TIMEOUT = 300000;
    String EXECUTOR_IMAGE_NAME = "mesos/logstash-executor";
    String EXECUTOR_IMAGE_TAG = "0.0.3";
    String EXECUTOR_IMAGE_NAME_WITH_TAG = EXECUTOR_IMAGE_NAME + ":" + EXECUTOR_IMAGE_TAG;
    String NODE_NAME = "logstash.node";
    String TASK_NAME = "logstash.task";
    String TASK_DATE_FORMAT = "yyyyMMdd'T'HHmmss.SSS'Z'";
}

Set executor container to 0.0.3

Set executor container to 0.0.3


/*
 * Copyright 2012-2020 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
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure.data.neo4j.scan;

import org.springframework.data.neo4j.core.schema.RelationshipProperties;

@RelationshipProperties
public class TestRelationshipProperties {

}

/*
 * Copyright 2012-2021 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
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure.data.neo4j.scan;

import org.springframework.data.neo4j.core.schema.GeneratedValue;
import org.springframework.data.neo4j.core.schema.Id;
import org.springframework.data.neo4j.core.schema.RelationshipProperties;

@RelationshipProperties
public class TestRelationshipProperties {

	@Id
	@GeneratedValue
	Long id;

}

Add required id field to Spring Data Neo4j test class

Fixes gh-28303


package defaultPackage;

public class TryArrays {

	public static void main(String[] args) {
		int[] numbers = new int[5];
		double[] squares = new double[5];
		for (int i = 0; i < numbers.length; i++)
		{
			numbers[i] = i + 1;
			squares[i] = Math.pow(i + 1, 2);
		}
		for (int i = 0; i < 5; i++)
		{
			System.out.println("number: " + numbers[i] + " square: " + squares[i]);
		}
	}

}

package defaultPackage;

public class TryArrays {

	public static void main(String[] args) {
		int[] numbers = new int[5];
		double[] squares = new double[5];
		int[] smallPrimes = {2, 3, 5, 7};
		for (int i = 0; i < numbers.length; i++)
		{
			numbers[i] = i + 1;
			squares[i] = Math.pow(i + 1, 2);
		}
		for (int i = 0; i < 5; i++)
		{
			System.out.println("number: " + numbers[i] + " square: " + squares[i]);
		}

		for (int number: numbers)
		{
			System.out.println("number using foreach: " + number);
		}

		for (int prime: smallPrimes)
		{
			System.out.println("small prime using foreach: " + prime);
		}
	}

}

Create array with shorthand notation

Create array with shorthand notation


package com.learnium.RNDeviceInfo;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;

public class RNDeviceInfo implements ReactPackage {

  @Override
  public List<NativeModule> createNativeModules(
                              ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();

    modules.add(new RNDeviceModule(reactContext));

    return modules;
  }

  @Override
  public List<Class<? extends JavaScriptModule>> createJSModules() {
  	return Collections.emptyList();
  }

  @Override
  public List<ViewManager> createViewManagers(
                            ReactApplicationContext reactContext) {
  	return Collections.emptyList();
  }

}

package com.learnium.RNDeviceInfo;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;

public class RNDeviceInfo implements ReactPackage {

  @Override
  public List<NativeModule> createNativeModules(
                              ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();

    modules.add(new RNDeviceModule(reactContext));

    return modules;
  }

  // Deprecated RN 0.47
  public List<Class<? extends JavaScriptModule>> createJSModules() {
  	return Collections.emptyList();
  }

  @Override
  public List<ViewManager> createViewManagers(
                            ReactApplicationContext reactContext) {
  	return Collections.emptyList();
  }

}

Handle Android RN 0.47 breaking change

Handle Android RN 0.47 breaking change


package com.github.atomfrede.jadenticon;

import org.apache.commons.io.FileUtils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;

public class JdenticonWrapper {

    private Object jdenticon;
    private Invocable invocable;

    public JdenticonWrapper() {

        try {
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

            invocable = (Invocable) nashorn;

            String script = FileUtils.readFileToString(new File(getClass().getResource("/jdenticon.js").toURI()));
            nashorn.eval(script);

            jdenticon = nashorn.eval("jdenticon");
        } catch (Exception e) {

            throw new RuntimeException("Unable to setup nashorn and jdenticon script.", e);
        }

    }

    public String getSvg(Jadenticon jadenticon) {

        try {
            return (String) invocable.invokeMethod(jdenticon, "toSvg", jadenticon.hash, jadenticon.size, jadenticon.padding);
        } catch (ScriptException | NoSuchMethodException e) {

            throw new RuntimeException("Unable to create jdenticon svg.", e);
        }

    }
}

package com.github.atomfrede.jadenticon;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.InputStream;

public class JdenticonWrapper {

    private Object jdenticon;
    private Invocable invocable;

    public JdenticonWrapper() {

        try {
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

            invocable = (Invocable) nashorn;

            InputStream scriptStream = getClass().getResourceAsStream("/jdenticon.js");
            String script = IOUtils.toString(scriptStream);
            nashorn.eval(script);

            jdenticon = nashorn.eval("jdenticon");
        } catch (Exception e) {

            throw new RuntimeException("Unable to setup nashorn and jdenticon script.", e);
        }

    }

    public String getSvg(Jadenticon jadenticon) {

        try {
            return (String) invocable.invokeMethod(jdenticon, "toSvg", jadenticon.hash, jadenticon.size, jadenticon.padding);
        } catch (ScriptException | NoSuchMethodException e) {

            throw new RuntimeException("Unable to create jdenticon svg.", e);
        }

    }
}

Use getResourceAsStream as getResource won't work


package info.u_team.u_team_core.data;

import java.nio.file.Path;

import net.minecraft.entity.EntityType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;

public abstract class CommonEntityTypeTagsProvider extends CommonTagsProvider<EntityType<?>> {

	@SuppressWarnings("deprecation")
	public CommonEntityTypeTagsProvider(GenerationData data) {
		super(data, Registry.ENTITY_TYPE);
	}

	@Override
	protected Path makePath(ResourceLocation location) {
		return resolveData(location).resolve("tags").resolve("entity_types").resolve(location.getPath() + ".json");
	}

	@Override
	public String getName() {
		return "Entity-Type-Tags";
	}
}

package info.u_team.u_team_core.data;

import java.nio.file.Path;

import net.minecraft.entity.EntityType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;

public abstract class CommonEntityTypeTagsProvider extends CommonTagsProvider<EntityType<?>> {

	@SuppressWarnings("deprecation")
	public CommonEntityTypeTagsProvider(GenerationData data) {
		super(data, Registry.ENTITY_TYPE);
	}

	@Override
	protected String getTagFolder() {
		return "entity_types";
	}

	@Override
	protected Path makePath(ResourceLocation location) {
		return resolveData(location).resolve("tags").resolve(getTagFolder()).resolve(location.getPath() + ".json");
	}

	@Override
	public String getName() {
		return "Entity-Type-Tags";
	}
}

Implement in the entity type tags provider


package org.bricolages.streaming.preproc;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.dao.DataIntegrityViolationException;

public interface PreprocMessageRepository extends JpaRepository<PreprocMessage, Long> {
    PreprocMessage findByMessageId(String msgid);

    default public PreprocMessage upsert(PreprocMessage msg) {
        try {
            return save(msg);
        }
        catch (DataIntegrityViolationException ex) {
            // no need to update
            return findByMessageId(msg.getMessageId());
        }
    }
}

package org.bricolages.streaming.preproc;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.dao.DataIntegrityViolationException;
import lombok.*;

public interface PreprocMessageRepository extends JpaRepository<PreprocMessage, Long> {
    PreprocMessage findByMessageId(String msgid);

    default public PreprocMessage upsert(PreprocMessage msg) {
        // to reduce duplicated rows error
        val curr = findByMessageId(msg.getMessageId());
        if (curr != null) return curr;
        try {
            return save(msg);
        }
        catch (DataIntegrityViolationException ex) {
            // no need to update
            return findByMessageId(msg.getMessageId());
        }
    }
}

fix: Select PreprocMessage first to reduce duplicated rows error