package me.nallar.tickthreading.minecraft.commands;

import java.util.List;

import me.nallar.tickthreading.minecraft.TickManager;
import me.nallar.tickthreading.minecraft.TickThreading;
import net.minecraft.command.ICommandSender;

public class TPSCommand extends Command {
	public static String name = "tps";

	@Override
	public String getCommandName() {
		return name;
	}

	@Override
	public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender) {
		return true;
	}

	@Override
	public void processCommand(ICommandSender commandSender, List<String> arguments) {
		StringBuilder tpsReport = new StringBuilder();
		tpsReport.append("---- TPS Report ----\n");
		long usedTime = 0;
		for (TickManager tickManager : TickThreading.instance().getManagers()) {
			tpsReport.append(tickManager.getBasicStats());
			usedTime += tickManager.lastTickLength;
		}
		tpsReport.append("\nOverall TPS: ").append(Math.min(20, 1000 / usedTime))
				.append("\nOverall load: ").append(usedTime / 0.5).append('%');
		sendChat(commandSender, tpsReport.toString());
	}
}

package me.nallar.tickthreading.minecraft.commands;

import java.util.List;

import me.nallar.tickthreading.minecraft.TickManager;
import me.nallar.tickthreading.minecraft.TickThreading;
import net.minecraft.command.ICommandSender;

public class TPSCommand extends Command {
	public static String name = "tps";

	@Override
	public String getCommandName() {
		return name;
	}

	@Override
	public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender) {
		return true;
	}

	@Override
	public void processCommand(ICommandSender commandSender, List<String> arguments) {
		StringBuilder tpsReport = new StringBuilder();
		tpsReport.append("---- TPS Report ----\n");
		long usedTime = 0;
		for (TickManager tickManager : TickThreading.instance().getManagers()) {
			tpsReport.append(tickManager.getBasicStats());
			usedTime += tickManager.lastTickLength;
		}
		tpsReport.append("\nOverall TPS: ").append(Math.min(20, 1000 / (usedTime == 0 ? 1 : usedTime)))
				.append("\nOverall load: ").append(usedTime * 2).append('%');
		sendChat(commandSender, tpsReport.toString());
	}
}

Fix for / by 0 in /tps

Fix for / by 0 in /tps

Signed-off-by: Ross Allan <ca2c77e14df1e7ee673215c1ef658354e220f471@gmail.com>


package com.elmakers.mine.bukkit.action.builtin;

import com.elmakers.mine.bukkit.action.CompoundAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;

public class CoverAction extends CompoundAction
{
	@Override
	public SpellResult step(CastContext context) {
        Block targetBlock = context.getTargetBlock();
        targetBlock = context.findSpaceAbove(targetBlock);
        targetBlock = context.findBlockUnder(targetBlock);
        Block coveringBlock = targetBlock.getRelative(BlockFace.UP);
        if (context.isTransparent(targetBlock.getType()) || !context.isTransparent(coveringBlock.getType())) {
            skippedActions(context);
            return SpellResult.NO_TARGET;
        }
        actionContext.setTargetLocation(targetBlock.getLocation());
        return startActions();
	}

    @Override
    public boolean requiresTarget() {
        return true;
    }
}

package com.elmakers.mine.bukkit.action.builtin;

import com.elmakers.mine.bukkit.action.CompoundAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.configuration.ConfigurationSection;

public class CoverAction extends CompoundAction
{
    protected boolean targetAbove = false;

    @Override
    public void prepare(CastContext context, ConfigurationSection parameters) {
        super.prepare(context, parameters);
        targetAbove = parameters.getBoolean("target_above", false);
    }

	@Override
	public SpellResult step(CastContext context) {
        Block targetBlock = context.getTargetBlock();
        targetBlock = context.findSpaceAbove(targetBlock);
        targetBlock = context.findBlockUnder(targetBlock);
        Block coveringBlock = targetBlock.getRelative(BlockFace.UP);
        if (context.isTransparent(targetBlock.getType()) || !context.isTransparent(coveringBlock.getType())) {
            skippedActions(context);
            return SpellResult.NO_TARGET;
        }
        if (targetAbove) {
            actionContext.setTargetLocation(coveringBlock.getLocation());
        } else {
            actionContext.setTargetLocation(targetBlock.getLocation());
        }
        return startActions();
	}

    @Override
    public boolean requiresTarget() {
        return true;
    }
}

Add target_above option to Cover action

Add target_above option to Cover action


package com.kantenkugel.discordbot.versioncheck;

import org.apache.commons.lang3.tuple.Pair;

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

public enum RepoType
{
    JCENTER("http://jcenter.bintray.com/", Pair.of("jcenter()", null), "bintray"),
    MAVENCENTRAL("https://repo.maven.apache.org/maven2/", null, "central", "maven");

    private final String repoBase;
    private final Pair<String, String> gradleImport;
    private final List<String> aliases;

    RepoType(String repoBase, Pair<String, String> gradleImport, String... aliases)
    {
        this.repoBase = repoBase;
        this.gradleImport = gradleImport;
        this.aliases = Arrays.asList(aliases);
    }

    public String getRepoBase()
    {
        return repoBase;
    }

    public Pair<String, String> getGradleImport()
    {
        return gradleImport;
    }

    public List<String> getAliases()
    {
        return Collections.unmodifiableList(aliases);
    }

    public static RepoType fromString(String value)
    {
        value = value.toLowerCase();
        for (RepoType repoType : RepoType.values())
        {
            if (repoType.toString().equals(value) || repoType.aliases.contains(value))
            {
                return repoType;
            }
        }
        return null;
    }

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

package com.kantenkugel.discordbot.versioncheck;

import org.apache.commons.lang3.tuple.Pair;

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

public enum RepoType
{
    JCENTER("https://jcenter.bintray.com/", Pair.of("jcenter()", null), "bintray"),
    MAVENCENTRAL("https://repo.maven.apache.org/maven2/", null, "central", "maven");

    private final String repoBase;
    private final Pair<String, String> gradleImport;
    private final List<String> aliases;

    RepoType(String repoBase, Pair<String, String> gradleImport, String... aliases)
    {
        this.repoBase = repoBase;
        this.gradleImport = gradleImport;
        this.aliases = Arrays.asList(aliases);
    }

    public String getRepoBase()
    {
        return repoBase;
    }

    public Pair<String, String> getGradleImport()
    {
        return gradleImport;
    }

    public List<String> getAliases()
    {
        return Collections.unmodifiableList(aliases);
    }

    public static RepoType fromString(String value)
    {
        value = value.toLowerCase();
        for (RepoType repoType : RepoType.values())
        {
            if (repoType.toString().equals(value) || repoType.aliases.contains(value))
            {
                return repoType;
            }
        }
        return null;
    }

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

Use HTTPS for JCenter repository

Use HTTPS for JCenter repository


package io.parsingdata.metal.expression.value.reference;

import static io.parsingdata.metal.Util.checkNotNull;

import io.parsingdata.metal.data.Environment;
import io.parsingdata.metal.data.ParseValue;
import io.parsingdata.metal.encoding.Encoding;
import io.parsingdata.metal.expression.value.ConstantFactory;
import io.parsingdata.metal.expression.value.OptionalValue;
import io.parsingdata.metal.expression.value.ValueExpression;

public class Len implements ValueExpression {

    private final String _name;

    public Len(final String name) {
        _name = checkNotNull(name, "name");
    }

    @Override
    public OptionalValue eval(final Environment env, final Encoding enc) {
        final ParseValue value = env.order.get(_name);
        return OptionalValue.of(value == null || value.getValue() == null ? null : ConstantFactory.createFromNumeric(value.getValue().length, new Encoding(true)));
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "(" + _name + ")";
    }

}

package io.parsingdata.metal.expression.value.reference;

import static io.parsingdata.metal.Util.checkNotNull;

import io.parsingdata.metal.data.Environment;
import io.parsingdata.metal.data.ParseValue;
import io.parsingdata.metal.encoding.Encoding;
import io.parsingdata.metal.expression.value.ConstantFactory;
import io.parsingdata.metal.expression.value.OptionalValue;
import io.parsingdata.metal.expression.value.Value;
import io.parsingdata.metal.expression.value.ValueExpression;

public class Len implements ValueExpression {

    private final String _name;

    public Len(final String name) {
        _name = checkNotNull(name, "name");
    }

    @Override
    public OptionalValue eval(final Environment env, final Encoding enc) {
        final ParseValue value = env.order.get(_name);
        return OptionalValue.of(value == null || value.getValue() == null ? num(0) : num(value.getValue().length));
    }

    private static Value num(final long length) {
        return ConstantFactory.createFromNumeric(length, new Encoding(true));
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "(" + _name + ")";
    }
}

Return zero length when value is null

Return zero length when value is null


package org.commonwl.view.workflow;

import org.commonwl.view.git.GitDetails;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 * Stores workflows in the queue waiting for cwltool
 */
public interface QueuedWorkflowRepository extends PagingAndSortingRepository<QueuedWorkflow, String> {

    /**
     * Finds a queued workflow based on where it was retrieved from
     * @param retrievedFrom Details of where the queued workflow is from
     * @return The queued workflow
     */
    @Query("{tempRepresentation.retrievedFrom: ?0}")
    QueuedWorkflow findByRetrievedFrom(GitDetails retrievedFrom);

    /**
     * Deletes a queued workflow based on where it was retrieved from
     * @param retrievedFrom Details of where the queued workflow is from
     */
    @Query("{tempRepresentation.retrievedFrom: ?0}")
    void deleteByRetrievedFrom(GitDetails retrievedFrom);

}

package org.commonwl.view.workflow;

import org.commonwl.view.git.GitDetails;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

import java.util.Date;
import java.util.List;

/**
 * Stores workflows in the queue waiting for cwltool
 */
public interface QueuedWorkflowRepository extends PagingAndSortingRepository<QueuedWorkflow, String> {

    /**
     * Finds a queued workflow based on where it was retrieved from
     * @param retrievedFrom Details of where the queued workflow is from
     * @return The queued workflow
     */
    @Query("{tempRepresentation.retrievedFrom: ?0}")
    QueuedWorkflow findByRetrievedFrom(GitDetails retrievedFrom);

    /**
     * Deletes a queued workflow based on where it was retrieved from
     * @param retrievedFrom Details of where the queued workflow is from
     */
    @Query("{tempRepresentation.retrievedFrom: ?0}")
    void deleteByRetrievedFrom(GitDetails retrievedFrom);

    /**
     * Deletes all queued workflows with date retrieved on older or equal to the Date argument passed.
     * @param retrievedOn Date of when the queued workflow was retrieved
     * @return The number of queued workflows deleted
     */
    Long deleteByTempRepresentation_RetrievedOnLessThanEqual(Date retrievedOn);

    /**
     * Finds and returns all queued workflows with date retrieved on older or equal to the Date argument passed.
     * @param retrievedOn Details of where the queued workflow is from
     * @return A list of queued workflows
     */
    List<QueuedWorkflow> findByTempRepresentation_RetrievedOnLessThanEqual(Date retrievedOn);

}

Add delete by date retrieved on method to queued workflow repository


package me.prettyprint.cassandra.service;

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

import me.prettyprint.cassandra.service.CassandraHostConfigurator;

public class ClusterFactory {

  private static Map<String, Cluster> clusters = new HashMap<String, Cluster>();

  public static Cluster get(String clusterName) {
    return clusters.get(clusterName);
  }
  /**
   *
   * @param clusterName The cluster name. This is an identifying string for the cluster, e.g.
   * "production" or "test" etc. Clusters will be created on demand per each unique clusterName key.
   * @param hostIp host:ip format string
   * @return
   */
  public static Cluster getOrCreate(String clusterName, String hostIp) {
    /*
     I would like to move off of string literals for hosts, perhaps
     providing them for convinience, and used specific types

     */
    return getOrCreate(clusterName, new CassandraHostConfigurator(hostIp));
  }

  public static Cluster getOrCreate(String clusterName,
      CassandraHostConfigurator cassandraHostConfigurator) {
    Cluster c = clusters.get(clusterName);
    if (c == null) {
      synchronized (clusters) {
        c = clusters.get(clusterName);
        if (c == null) {
          c = create(clusterName, cassandraHostConfigurator);
          clusters.put(clusterName, c);
        }
      }
    }
    return c;
  }

  public static Cluster create(String clusterName, CassandraHostConfigurator cassandraHostConfigurator) {
    return new ClusterImpl(clusterName, cassandraHostConfigurator);
  }
}

package me.prettyprint.cassandra.service;

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

import me.prettyprint.cassandra.service.CassandraHostConfigurator;

public class ClusterFactory {

  private static final Map<String, Cluster> clusters = new HashMap<String, Cluster>();

  public static Cluster get(String clusterName) {
    return clusters.get(clusterName);
  }
  /**
   *
   * @param clusterName The cluster name. This is an identifying string for the cluster, e.g.
   * "production" or "test" etc. Clusters will be created on demand per each unique clusterName key.
   * @param hostIp host:ip format string
   * @return
   */
  public static Cluster getOrCreate(String clusterName, String hostIp) {
    /*
     I would like to move off of string literals for hosts, perhaps
     providing them for convinience, and used specific types

     */
    return getOrCreate(clusterName, new CassandraHostConfigurator(hostIp));
  }

  public static Cluster getOrCreate(String clusterName,
      CassandraHostConfigurator cassandraHostConfigurator) {
    Cluster c = clusters.get(clusterName);
    if (c == null) {
      synchronized (clusters) {
        c = clusters.get(clusterName);
        if (c == null) {
          c = create(clusterName, cassandraHostConfigurator);
          clusters.put(clusterName, c);
        }
      }
    }
    return c;
  }

  public static Cluster create(String clusterName, CassandraHostConfigurator cassandraHostConfigurator) {
    return new ClusterImpl(clusterName, cassandraHostConfigurator);
  }
}

Make the clusters member final

Make the clusters member final


package com.aspectran.with.jetty;

import com.aspectran.core.component.bean.ablility.DisposableBean;
import com.aspectran.core.component.bean.ablility.InitializableBean;
import com.aspectran.core.util.logging.Log;
import com.aspectran.core.util.logging.LogFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.thread.ThreadPool;

/**
 *
Created: 2016. 12. 22.

 */
public class JettyServer extends Server implements InitializableBean, DisposableBean {

    private static final Log log = LogFactory.getLog(JettyServer.class);

    public JettyServer() {
        super();
    }

    public JettyServer(int port) {
        super(port);
    }

    public JettyServer(ThreadPool pool) {
        super(pool);
    }

    @Override
    public void initialize() throws Exception {
        System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");
    }

    @Override
    public void destroy() {
        try {
            stop();
        } catch (Exception e) {
            log.error("JettyServer shutdown failed", e);
        }
    }

}

package com.aspectran.with.jetty;

import com.aspectran.core.component.bean.ablility.DisposableBean;
import com.aspectran.core.component.bean.ablility.InitializableBean;
import com.aspectran.core.util.logging.Log;
import com.aspectran.core.util.logging.LogFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.thread.ThreadPool;

/**
 *
Created: 2016. 12. 22.

 */
public class JettyServer extends Server implements InitializableBean, DisposableBean {

    private static final Log log = LogFactory.getLog(JettyServer.class);

    private boolean autoStart;

    public JettyServer() {
        super();
    }

    public JettyServer(int port) {
        super(port);
    }

    public JettyServer(ThreadPool pool) {
        super(pool);
    }

    public void setAutoStart(boolean autoStart) {
        this.autoStart = autoStart;
    }

    @Override
    public void initialize() throws Exception {
        System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

        if (autoStart) {
            start();
        }
    }

    @Override
    public void destroy() {
        try {
            stop();
        } catch (Exception e) {
            log.error("JettyServer shutdown failed", e);
        }
    }

}

Add a property that allows the web server to start automatically during initialization


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

import java.util.Date;

import lombok.Data;

import com.ajah.user.UserId;
import com.ajah.util.Identifiable;

@Data
public class UserFollow implements Identifiable<UserFollowId> {

	private UserFollowId id;
	private UserId userId;
	private UserId followedUserId;
	private UserFollowStatus status;
	private UserFollowType type;
	private Date created;

}

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

import java.util.Date;

import javax.persistence.Transient;

import lombok.Data;

import com.ajah.user.User;
import com.ajah.user.UserId;
import com.ajah.util.Identifiable;

@Data
public class UserFollow implements Identifiable<UserFollowId> {

	private UserFollowId id;
	private UserId userId;
	private UserId followedUserId;
	private UserFollowStatus status;
	private UserFollowType type;
	private Date created;
	private String comment;

	@Transient
	User user;

	@Transient
	User followedUser;

}

Add comment field and some transient helpers


package edu.northwestern.bioinformatics.studycalendar.web.template;

import edu.northwestern.bioinformatics.studycalendar.web.ReturnSingleObjectController;
import edu.northwestern.bioinformatics.studycalendar.domain.Arm;
import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.AccessControl;
import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.StudyCalendarProtectionGroup;

/**
 * @author Rhett Sutphin
 */
@AccessControl(protectionGroups = StudyCalendarProtectionGroup.STUDY_COORDINATOR)
public class SelectArmController extends ReturnSingleObjectController<Arm> {
    public SelectArmController() {
        setParameterName("arm");
        setViewName("template/ajax/selectArm");
    }

    @Override
    protected Object wrapObject(Arm loaded) {
        return new ArmTemplate(loaded);
    }
}

package edu.northwestern.bioinformatics.studycalendar.web.template;

import edu.northwestern.bioinformatics.studycalendar.web.ReturnSingleObjectController;
import edu.northwestern.bioinformatics.studycalendar.domain.Arm;
import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.AccessControl;
import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.StudyCalendarProtectionGroup;

/**
 * @author Rhett Sutphin
 */
@AccessControl(protectionGroups = StudyCalendarProtectionGroup.BASE)
public class SelectArmController extends ReturnSingleObjectController<Arm> {
    public SelectArmController() {
        setParameterName("arm");
        setViewName("template/ajax/selectArm");
    }

    @Override
    protected Object wrapObject(Arm loaded) {
        return new ArmTemplate(loaded);
    }
}

Use base because everyone can use the template view


package org.edx.mobile.view.custom;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebSettings;
import android.webkit.WebView;

import org.edx.mobile.BuildConfig;
import org.edx.mobile.R;

public class EdxWebView extends WebView {
    @SuppressLint("SetJavaScriptEnabled")
    public EdxWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        final WebSettings settings = getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setBuiltInZoomControls(false);
        settings.setSupportZoom(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setDomStorageEnabled(true);
        settings.setUserAgentString(
                settings.getUserAgentString() + " " +
                        context.getString(R.string.app_name) + "/" +
                        BuildConfig.APPLICATION_ID + "/" +
                        BuildConfig.VERSION_NAME
        );
    }
}

package org.edx.mobile.view.custom;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebSettings;
import android.webkit.WebView;

import org.edx.mobile.BuildConfig;
import org.edx.mobile.R;

public class EdxWebView extends WebView {
    @SuppressLint("SetJavaScriptEnabled")
    public EdxWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        final WebSettings settings = getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setBuiltInZoomControls(false);
        settings.setSupportZoom(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setDomStorageEnabled(true);
        settings.setUserAgentString(
                settings.getUserAgentString() + " " +
                        context.getString(R.string.app_name) + "/" +
                        BuildConfig.APPLICATION_ID + "/" +
                        BuildConfig.VERSION_NAME
        );
        setLayerType(LAYER_TYPE_HARDWARE, null);
    }
}

Enable hardware acceleration for all WebView

- LEARNER-7224


package uk.ac.ic.wlgitbridge.writelatex.api.request.getsavedvers;

import uk.ac.ic.wlgitbridge.util.Util;

/**
 * Created by Winston on 06/11/14.
 */
public class SnapshotInfo implements Comparable<SnapshotInfo> {

    private int versionId;
    private String comment;
    private WLUser user;
    private String createdAt;

    public SnapshotInfo(int versionID, String createdAt, String name, String email) {
        this(versionID, "Update on " + Util.getServiceName() + ".", name, email, createdAt);
    }

    public SnapshotInfo(int versionID, String comment, String email, String name, String createdAt) {
        versionId = versionID;
        this.comment = comment;
        user = new WLUser(name, email);
        this.createdAt = createdAt;
    }

    public int getVersionId() {
        return versionId;
    }

    public String getComment() {
        return comment;
    }

    public WLUser getUser() {
        return user;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof SnapshotInfo)) {
            return false;
        }
        SnapshotInfo that = (SnapshotInfo) obj;
        return versionId == that.versionId;
    }

    @Override
    public int compareTo(SnapshotInfo o) {
        return Integer.compare(versionId, o.versionId);
    }
}

package uk.ac.ic.wlgitbridge.writelatex.api.request.getsavedvers;

import uk.ac.ic.wlgitbridge.util.Util;

/**
 * Created by Winston on 06/11/14.
 */
public class SnapshotInfo implements Comparable<SnapshotInfo> {

    private int versionId;
    private String comment;
    private WLUser user;
    private String createdAt;

    public SnapshotInfo(int versionID, String createdAt, String name, String email) {
        this(versionID, "Update on " + Util.getServiceName() + ".", email, name, createdAt);
    }

    public SnapshotInfo(int versionID, String comment, String email, String name, String createdAt) {
        versionId = versionID;
        this.comment = comment;
        user = new WLUser(name, email);
        this.createdAt = createdAt;
    }

    public int getVersionId() {
        return versionId;
    }

    public String getComment() {
        return comment;
    }

    public WLUser getUser() {
        return user;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof SnapshotInfo)) {
            return false;
        }
        SnapshotInfo that = (SnapshotInfo) obj;
        return versionId == that.versionId;
    }

    @Override
    public int compareTo(SnapshotInfo o) {
        return Integer.compare(versionId, o.versionId);
    }
}

Fix bug with Overleaf commits swapping name and email.


if (message.hasMedia()) {
    Message.Media media = message.getMedia();

    String sid = media.getSid();
    String type = media.getType();
    String fn = media.getFileName();
    long size = media.getSize();

    Timber.d("This is a media message with SID "+sid+", type "+type+", name "+fn+", and size "+size);

    if (type.contentEquals("text/plain")) {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        media.download(out, new StatusListener() {
            @Override
            public void onSuccess() {
                String content = out.toString();
                Timber.d("Downloaded media "+content);
            }

            @Override
            public void onError(ErrorInfo error) {
                Timber.e("Error downloading media");
            }
        }, new ProgressListener() {
            @Override
            public void onStarted() {
                Timber.d("Download started");
            }

            @Override
            public void onProgress(long bytes) {
                Timber.d("Downloaded "+bytes+" bytes");
            }

            @Override
            public void onCompleted(String mediaSid) {
                Timber.d("Download completed");
            }
        });
    }
}

if (message.hasMedia()) {
    message.getMediaContentTemporaryUrl(new CallbackListener<String>() {
        @Override
        public void onSuccess(String mediaContentUrl) {
            Log.d("TAG", mediaContentUrl);
        }
    });
}

Update Android retrieve conversations media example


package fi.nls.oskari.routing;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import java.io.Reader;

public class RoutingService {
    private SqlMapClient client = null;
    private static String SQL_MAP_LOCATION = "META-INF/SqlMapConfig.xml";

    protected SqlMapClient getSqlMapClient() {
        if (client != null) {
            return client;
        }

        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(SQL_MAP_LOCATION);
            client = SqlMapClientBuilder.buildSqlMapClient(reader);
            return client;
        } catch (Exception e) {
            throw new RuntimeException("Failed to retrieve SQL client", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public Long hevonen() {
        try {
            client = getSqlMapClient();
            Long results = (Long)client.queryForObject("Routing.foo");
            return results;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("Failed to query", e);
        }
    }
}

package fi.nls.oskari.routing;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import java.io.Reader;

public class RoutingService {
    private SqlMapClient client = null;
    private static String SQL_MAP_LOCATION = "META-INF/SqlMapConfig.xml";

    private SqlMapClient getSqlMapClient() {
        if (client != null) { return client; }

        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(SQL_MAP_LOCATION);
            client = SqlMapClientBuilder.buildSqlMapClient(reader);
            return client;
        } catch (Exception e) {
            throw new RuntimeException("Failed to retrieve SQL client", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public Long hevonen() {
        try {
            SqlMapClient client = getSqlMapClient();
            Long results = (Long)client.queryForObject("Routing.foo");
            return results;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("Failed to query", e);
        }
    }
}

Use local variable instead of member variable


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;

import com.yahoo.log.LogLevel;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;

import java.time.Duration;

/**
 * Removes expired sessions and locks
 * <p>
 * Note: Unit test is in ApplicationRepositoryTest
 *
 * @author hmusum
 */
public class SessionsMaintainer extends ConfigServerMaintainer {
    private final boolean hostedVespa;
    private int iteration = 0;

    SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
        super(applicationRepository, curator, flagSource, Duration.ofMinutes(1), interval);
        this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
    }

    @Override
    protected boolean maintain() {
        if (iteration % 10 == 0)
            log.log(LogLevel.INFO, () -> "Running " + SessionsMaintainer.class.getSimpleName());

        applicationRepository.deleteExpiredLocalSessions();

        if (hostedVespa) {
            Duration expiryTime = Duration.ofMinutes(90);
            int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
            log.log(LogLevel.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
        }

        iteration++;
        return true;
    }

}

// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;

import com.yahoo.log.LogLevel;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;

import java.time.Duration;

/**
 * Removes expired sessions and locks
 * <p>
 * Note: Unit test is in ApplicationRepositoryTest
 *
 * @author hmusum
 */
public class SessionsMaintainer extends ConfigServerMaintainer {
    private final boolean hostedVespa;
    private int iteration = 0;

    SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
        super(applicationRepository, curator, flagSource, Duration.ofMinutes(1), interval);
        this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
    }

    @Override
    protected boolean maintain() {
        if (iteration % 10 == 0)
            log.log(LogLevel.INFO, () -> "Running " + SessionsMaintainer.class.getSimpleName() + ", iteration "  + iteration);

        applicationRepository.deleteExpiredLocalSessions();

        if (hostedVespa) {
            Duration expiryTime = Duration.ofMinutes(90);
            int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
            log.log(LogLevel.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
        }

        iteration++;
        return true;
    }

}

Add iteration to log message

Add iteration to log message


package io.github.lukehutch.fastclasspathscanner.utils;

import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner;

public class Log {
    public static void log(final String msg) {
        System.out.println(FastClasspathScanner.class.getSimpleName() + ": " + msg);
    }
}

package io.github.lukehutch.fastclasspathscanner.utils;

import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner;

public class Log {
    public static void log(final String msg) {
        System.err.println(FastClasspathScanner.class.getSimpleName() + ": " + msg);
    }
}

Switch logging from stdout to stderr

Switch logging from stdout to stderr


package org.fluentd.logger.sender;

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

import java.util.Deque;
import java.util.LinkedList;

/**
 * Calculate exponential delay for reconnecting
 */
public class ConstantDelayReconnector implements Reconnector {
    private static final Logger LOG = LoggerFactory.getLogger(ConstantDelayReconnector.class);

    private double wait = 50; // Default wait to 50 ms

    private int maxErrorHistorySize = 100;

    private Deque<Long> errorHistory = new LinkedList<Long>();

    public ConstantDelayReconnector() {
        errorHistory = new LinkedList<Long>();
    }

    public ConstantDelayReconnector(int wait) {
        this.wait = wait;
        errorHistory = new LinkedList<Long>();
    }

    public void addErrorHistory(long timestamp) {
        errorHistory.addLast(timestamp);
        if (errorHistory.size() > maxErrorHistorySize) {
            errorHistory.removeFirst();
        }
    }

    public boolean isErrorHistoryEmpty() {
        return errorHistory.isEmpty();
    }

    public void clearErrorHistory() {
        errorHistory.clear();
    }

    public boolean enableReconnection(long timestamp) {
        int size = errorHistory.size();
        if (size == 0) {
            return true;
        }

        return (!(timestamp - errorHistory.getLast() < wait));
    }

}

package org.fluentd.logger.sender;

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

import java.util.Deque;
import java.util.LinkedList;

/**
 * Calculate exponential delay for reconnecting
 */
public class ConstantDelayReconnector implements Reconnector {
    private static final Logger LOG = LoggerFactory.getLogger(ConstantDelayReconnector.class);

    private double wait = 50; // Default wait to 50 ms

    private static final int MAX_ERROR_HISTORY_SIZE = 100;

    private Deque<Long> errorHistory = new LinkedList<Long>();

    public ConstantDelayReconnector() {
        errorHistory = new LinkedList<Long>();
    }

    public ConstantDelayReconnector(int wait) {
        this.wait = wait;
        errorHistory = new LinkedList<Long>();
    }

    public void addErrorHistory(long timestamp) {
        errorHistory.addLast(timestamp);
        if (errorHistory.size() > MAX_ERROR_HISTORY_SIZE) {
            errorHistory.removeFirst();
        }
    }

    public boolean isErrorHistoryEmpty() {
        return errorHistory.isEmpty();
    }

    public void clearErrorHistory() {
        errorHistory.clear();
    }

    public boolean enableReconnection(long timestamp) {
        int size = errorHistory.size();
        if (size == 0) {
            return true;
        }

        return (!(timestamp - errorHistory.getLast() < wait));
    }

}

Use constants if the variable can't be modified


package valandur.webapi.serialize.view.data;

import org.spongepowered.api.data.manipulator.mutable.entity.FlyingData;
import valandur.webapi.api.serialize.BaseView;

public class FlyingDataView extends BaseView<FlyingData> {

    public boolean flying;

    public FlyingDataView(FlyingData value) {
        super(value);

        this.flying = value.flying().get();
    }
}

package valandur.webapi.serialize.view.data;

import com.fasterxml.jackson.annotation.JsonValue;
import org.spongepowered.api.data.manipulator.mutable.entity.FlyingData;
import valandur.webapi.api.serialize.BaseView;

public class FlyingDataView extends BaseView<FlyingData> {

    @JsonValue
    public boolean flying;

    public FlyingDataView(FlyingData value) {
        super(value);

        this.flying = value.flying().get();
    }
}

fix(view): Remove wrapping element from flying data


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

import java.util.ArrayList;

public class KeywordCampaign {

    public int keywordCampaignId;
    public int userId;
    public int impressions;
    public int clicks;
    public int cost;
    public ArrayList<Integer> DSACampaignIds;

    // TODO: add the keyword campaign input settings

    public KeywordCampaign(int keywordCampaignId, int userId, int impressions, int clicks, int cost, ArrayList<Integer> DSACampaignIds) {
        this.keywordCampaignId = keywordCampaignId;
        this.userId = userId;
        this.impressions = impressions;
        this.clicks = clicks;
        this.DSACampaignIds = DSACampaignIds;
    }
}

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

import java.util.ArrayList;

// contains all the necessary information about a keyword campaign, including id, input settings, and statistics
public class KeywordCampaign {

    public int keywordCampaignId;
    public int userId;
    public int impressions;
    public int clicks;
    public int cost;
    public ArrayList<Integer> DSACampaignIds;

    // TODO: add the keyword campaign input settings

    public KeywordCampaign(int keywordCampaignId, int userId, int impressions, int clicks, int cost, ArrayList<Integer> DSACampaignIds) {
        this.keywordCampaignId = keywordCampaignId;
        this.userId = userId;
        this.impressions = impressions;
        this.clicks = clicks;
        this.DSACampaignIds = DSACampaignIds;
    }
}

Add comment explaining keyword campaign class.


package com.epam.rft.atsy.cucumber.util;

import static com.epam.rft.atsy.cucumber.util.DriverProvider.getDriver;

import org.openqa.selenium.By;

import cucumber.api.java.en.Given;

public class CommonStepDefs {

  @Given("The user signed in")
  public void loggedIn() {
    getDriver().get("http://localhost:8080/atsy/login?locale=hu");
    getDriver().findElement(By.id("name")).sendKeys("test");
    getDriver().findElement(By.id("password")).sendKeys("pass3");
    getDriver().findElement(By.id("loginButton")).click();
  }
}

package com.epam.rft.atsy.cucumber.util;

import static com.epam.rft.atsy.cucumber.util.DriverProvider.getDriver;
import static com.epam.rft.atsy.cucumber.util.DriverProvider.waitForPageLoadAfter;

import org.openqa.selenium.By;

import cucumber.api.java.en.Given;

public class CommonStepDefs {

  @Given("The user signed in")
  public void loggedIn() {
    getDriver().get("http://localhost:8080/atsy/login?locale=hu");
    getDriver().findElement(By.id("name")).sendKeys("test");
    getDriver().findElement(By.id("password")).sendKeys("pass3");
    waitForPageLoadAfter(event -> getDriver().findElement(By.id("loginButton")).click());
  }
}

Add wait for page load condition when user signs in


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

public class Constants {

    public static final String PACKAGE_NAME =
            Constants.class.getPackage().getName();

}

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

public class Constants {

    public static final String PACKAGE_NAME =
            Constants.class.getPackage().getName();

    public static final boolean IS_SECURITY_ENABLED = (System.getSecurityManager() != null);
}

Add new constant missed in previous commit

git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1589992 13f79535-47bb-0310-9956-ffa450edef68


package fi.mml.portti.service.search;

import fi.nls.oskari.search.channel.SearchableChannel;
import fi.nls.oskari.service.OskariComponent;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.PropertyUtil;
import org.json.JSONObject;

import java.util.Map;

/**
 * Interface to service that searches all the channels.
 */
public abstract class SearchService extends OskariComponent {

	private int maxCount = -1;

	@Override
	public void init() {
		super.init();
	}

	/**
	 * Makes a search with given criteria
	 *
	 * @param searchCriteria
	 * @return Query
	 */
	public abstract Query doSearch(SearchCriteria searchCriteria);
	public abstract JSONObject doSearchAutocomplete(SearchCriteria searchCriteria);
	public abstract void addChannel(String channelId, SearchableChannel searchableChannel);
    public abstract Map<String, SearchableChannel> getAvailableChannels();

	/**
	 * Returns a generic maximum results instruction for search functions.
	 * SearchChannels/implementations may opt to use this to
	 * @return maxCount  - Search results max count
     */
	public int getMaxResultsCount() {
		if (maxCount == -1) {
			maxCount = ConversionHelper.getInt(PropertyUtil.getOptional("search.max.results"), maxCount);
		}
		return maxCount;
	}
}

package fi.mml.portti.service.search;

import fi.nls.oskari.search.channel.SearchableChannel;
import fi.nls.oskari.service.OskariComponent;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.PropertyUtil;
import org.json.JSONObject;

import java.util.Map;

/**
 * Interface to service that searches all the channels.
 */
public abstract class SearchService extends OskariComponent {

	private int maxCount = -1;

	@Override
	public void init() {
		super.init();
	}

	/**
	 * Makes a search with given criteria
	 *
	 * @param searchCriteria
	 * @return Query
	 */
	public abstract Query doSearch(SearchCriteria searchCriteria);
	public abstract JSONObject doSearchAutocomplete(SearchCriteria searchCriteria);
	public abstract void addChannel(String channelId, SearchableChannel searchableChannel);
    public abstract Map<String, SearchableChannel> getAvailableChannels();

	/**
	 * Returns a generic maximum results instruction for search functions.
	 * SearchChannels/implementations may opt to use this to
	 * @return maxCount  - Search results max count
     */
	public int getMaxResultsCount() {
		if (maxCount == -1) {
			maxCount = ConversionHelper.getInt(PropertyUtil.getOptional("search.max.results"), 100);
		}
		return maxCount;
	}
}

Fix maxCount defaultting to 100

Fix maxCount defaultting to 100


package behave.tools;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

//TODO use some proper logging framework
public class Log {
    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss:SSS");

    public static void debug(String msg) {
        print("debug", msg);
    }

    public static void info(String msg) {
        print("info", msg);
    }

    public static void warning(String msg) {
        print("warning", msg);
    }

    public static void error(String msg) {
        print("error", msg);
    }

    private static void print(String level, String msg) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(dtf.format(now) + " [" + level + "] : " + msg);
    }
}

package behave.tools;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

//TODO use some proper logging framework
public class Log {
    private static boolean m_logDebug = false;
    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss:SSS");

    public static void debug(String msg) {
        if (m_logDebug)
            print("debug", msg);
    }

    public static void info(String msg) {
        print("info", msg);
    }

    public static void warning(String msg) {
        print("warning", msg);
    }

    public static void error(String msg) {
        print("error", msg);
    }

    private static void print(String level, String msg) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(dtf.format(now) + " [" + level + "] : " + msg);
    }
}

Hide debug logs by default

Hide debug logs by default


package me.hugmanrique.pokedata.sprites.signs;

import me.hugmanrique.pokedata.sprites.Sprite;
import me.hugmanrique.pokedata.utils.ROM;

/**
 * @author Hugmanrique
 * @since 02/05/2017
 */
public class SpriteSign extends Sprite {
    private byte b2;
    private byte b4;
    private byte b5;
    private byte b6;
    private byte b7;
    private byte b8;
    private long scriptPtr;

    public SpriteSign(ROM rom) {
        x = rom.readByte();
        b2 = rom.readByte();
        y = rom.readByte();
        b4 = rom.readByte();
        b5 = rom.readByte();
        b6 = rom.readByte();
        b7 = rom.readByte();
        b8 = rom.readByte();
        scriptPtr = rom.getPointer();
    }

    @Override
    public int getSize() {
        return 12;
    }
}

package me.hugmanrique.pokedata.sprites.signs;

import me.hugmanrique.pokedata.sprites.Sprite;
import me.hugmanrique.pokedata.utils.ROM;

/**
 * @author Hugmanrique
 * @since 02/05/2017
 */
public class SpriteSign extends Sprite {
    // TODO Check if some of these bytes are words values
    private byte b2;
    private byte b4;
    private byte b5;
    private byte b6;
    private byte b7;
    private byte b8;
    private long scriptPtr;

    public SpriteSign(ROM rom) {
        x = rom.readByte();
        b2 = rom.readByte();
        y = rom.readByte();
        b4 = rom.readByte();
        b5 = rom.readByte();
        b6 = rom.readByte();
        b7 = rom.readByte();
        b8 = rom.readByte();
        scriptPtr = rom.getPointer();
    }

    @Override
    public int getSize() {
        return 12;
    }
}

Add TODO, sign bytes may be words

Add TODO, sign bytes may be words


/*
 * Copyright 2014 Red Hat, Inc, and individual contributors.
 *
 * 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.projectodd.wunderboss.codecs;

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

public class Codecs {

    public Codecs add(Codec codec) {
        codecs.put(codec.name(), codec);
        codecs.put(codec.contentType(), codec);

        return this;
    }

    public Codec forName(String name) {
        return codecs.get(name);
    }

    public Codec forContentType(String contentType) {
        return codecs.get(contentType);
    }

    public Collection<Codec> codecs() {
        return Collections.unmodifiableCollection(codecs.values());
    }

    private final Map<String, Codec> codecs = new HashMap<>();
}

/*
 * Copyright 2014 Red Hat, Inc, and individual contributors.
 *
 * 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.projectodd.wunderboss.codecs;

import java.util.*;

public class Codecs {

    public Codecs add(Codec codec) {
        codecs.put(codec.name(), codec);
        codecs.put(codec.contentType(), codec);

        return this;
    }

    public Codec forName(String name) {
        return codecs.get(name);
    }

    public Codec forContentType(String contentType) {
        return codecs.get(contentType);
    }

    public Set<Codec> codecs() {
        return Collections.unmodifiableSet(new HashSet<>(codecs.values()));
    }

    private final Map<String, Codec> codecs = new HashMap<>();
}

Return a set of codecs instead of a collection to strip the duplicates.

Each codec is in the map twice, once for name and once for
content-type. We don't need both copies returned.


package com.redpois0n.gitj;

import java.io.File;

import javax.swing.UIManager;

import com.redpois0n.git.Repository;
import com.redpois0n.gitj.ui.MainFrame;

public class Main {

	public static void main(String[] args) throws Exception {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

			MainFrame frame = new MainFrame();
			frame.setVisible(true);

			if (argsContains("--debug", args)) {
				File dir = new File(System.getProperty("user.dir"));
				Repository repository = new Repository(dir);

				frame.loadRepository(repository);
				frame.addBookmark(repository);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static boolean argsContains(String s, String[] args) {
		for (String arg : args) {
			if (arg.equalsIgnoreCase(s)) {
				return true;
			}
		}

		return false;
	}

	public static void displayError(Exception e) {

	}

	public static void print(String s) {
		System.out.println(s);
	}
}

package com.redpois0n.gitj;

import java.io.File;

import javax.swing.UIManager;

import com.redpois0n.git.Repository;
import com.redpois0n.gitj.ui.MainFrame;

public class Main {

	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

			MainFrame frame = new MainFrame();
			frame.setVisible(true);

			if (argsContains("--debug", args)) {
				File dir = new File(System.getProperty("user.dir"));
				Repository repository = new Repository(dir);

				frame.loadRepository(repository);
				frame.addBookmark(repository);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static boolean argsContains(String s, String[] args) {
		for (String arg : args) {
			if (arg.equalsIgnoreCase(s)) {
				return true;
			}
		}

		return false;
	}

	public static void displayError(Exception e) {

	}

	public static void print(String s) {
		System.out.println(s);
	}
}

Remove throws exception on main()

Remove throws exception on main()


package com.google.sampling.experiential.server.stats.usage;

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

public class UsageStatsBlobWriter {

  private static final Logger log = Logger.getLogger(UsageStatsBlobWriter.class.getName());

  public UsageStatsBlobWriter() {
  }

  public String writeStatsAsJson(String jobId, String timeZone, String requestorEmail) {
    log.info("writing usage stats report");
//    UsageStatsBackfillJob job = new UsageStatsBackfillJob();
    UsageStatsCreatorStatsJob job = new UsageStatsCreatorStatsJob();
    try {
      job.run();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "it doesn't do that anymore :-)";
  }

}

package com.google.sampling.experiential.server.stats.usage;

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

public class UsageStatsBlobWriter {

  private static final Logger log = Logger.getLogger(UsageStatsBlobWriter.class.getName());

  public UsageStatsBlobWriter() {
  }

  public String writeStatsAsJson(String jobId, String timeZone, String requestorEmail) {
    log.info("writing usage stats report");
//    UsageStatsBackfillJob job = new UsageStatsBackfillJob();
//    UsageStatsCreatorStatsJob job = new UsageStatsCreatorStatsJob();
    UsageStatsCronJob job = new UsageStatsCronJob();
    try {
      job.run();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "no job id reported for this type of job";
  }

}

Switch back to usage stas cronjob

Switch back to usage stas cronjob


package ch.difty.sipamato.persistance.jooq;

public final class TestDbConstants {

    public static final int RECORD_COUNT_PREPOPULATED = 36;
    public static final Long MAX_ID_PREPOPULATED = 41l;

    private TestDbConstants() {
    }

}

package ch.difty.sipamato.persistance.jooq;

public final class TestDbConstants {

    public static final int RECORD_COUNT_PREPOPULATED = 76;
    public static final Long MAX_ID_PREPOPULATED = 81l;

    private TestDbConstants() {
    }

}

Adjust integration tests to match new number of papers


package io.syndesis.qe.steps.other;

import com.dropbox.core.DbxException;
import cucumber.api.java.en.When;
import io.syndesis.qe.utils.DropBoxUtils;
import org.assertj.core.api.Assertions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

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

public class DropBoxSteps {
    @Lazy
    @Autowired
    private DropBoxUtils dropBoxUtils;

    @When("^.*uploads? file with path \"([^\"]*)\" and content \"([^\"]*)\" on Dropbox$")
    public void uploadFile(String filePath, String content) throws IOException, DbxException, TimeoutException, InterruptedException {
        dropBoxUtils.uploadFile(filePath, content);
    }

    @When("^.*checks? that file with path \"([^\"]*)\" exists? on Dropbox$")
    public void checkThatFileExists(String filePath) throws IOException, DbxException, TimeoutException, InterruptedException {
        Assertions.assertThat(dropBoxUtils.checkIfFileExists(filePath)).isTrue();
    }

    @When("^.*deletes? file with path \"([^\"]*)\" from Dropbox$")
    public void deleteFile(String filePath) throws DbxException {
        dropBoxUtils.deleteFile(filePath);
        Assertions.assertThat(dropBoxUtils.checkIfFileExists(filePath)).isFalse();
    }
}

package io.syndesis.qe.steps.other;

import com.dropbox.core.DbxException;
import cucumber.api.java.en.When;
import io.syndesis.qe.utils.DropBoxUtils;
import io.syndesis.qe.utils.TestUtils;
import org.assertj.core.api.Assertions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

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

public class DropBoxSteps {
    @Lazy
    @Autowired
    private DropBoxUtils dropBoxUtils;

    @When("^.*uploads? file with path \"([^\"]*)\" and content \"([^\"]*)\" on Dropbox$")
    public void uploadFile(String filePath, String content) throws IOException, DbxException, TimeoutException, InterruptedException {
        dropBoxUtils.uploadFile(filePath, content);
    }

    @When("^.*checks? that file with path \"([^\"]*)\" exists? on Dropbox$")
    public void checkThatFileExists(String filePath) throws IOException, DbxException, TimeoutException, InterruptedException {
        boolean fileExists = TestUtils.waitForEvent(r -> r, () -> dropBoxUtils.checkIfFileExists(filePath), TimeUnit.MINUTES, 2, TimeUnit.SECONDS, 15);
        Assertions.assertThat(fileExists).isTrue();
    }

    @When("^.*deletes? file with path \"([^\"]*)\" from Dropbox$")
    public void deleteFile(String filePath) throws DbxException {
        dropBoxUtils.deleteFile(filePath);
        Assertions.assertThat(dropBoxUtils.checkIfFileExists(filePath)).isFalse();
    }
}

Add wait for file to appear in Dropbox

fix(ui): Add wait for file to appear in Dropbox


package edu.northwestern.bioinformatics.studycalendar.xml.writers;

import edu.northwestern.bioinformatics.studycalendar.domain.delta.Add;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Change;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;
import org.dom4j.Element;

public class AddXmlSerializer extends AbstractChangeXmlSerializer {
    private static final String ADD = "add";
    private static final String INDEX = "index";

    public AddXmlSerializer(Study study) {
        super(study);
    }

    protected Change changeInstance() {
        return new Add();
    }

    protected String elementName() {
        return ADD;
    }

    protected void addAdditionalAttributes(final Change change, Element element) {
        element.addAttribute(INDEX, ((Add)change).getIndex().toString());
        PlanTreeNode<?> planTreeNode = ((Add)change).getChild();
        AbstractPlanTreeNodeXmlSerializer serializer = getPlanTreeNodeSerializerFactory().createPlanTreeNodeXmlSerializer(planTreeNode);
        Element ePlanTreeNode = serializer.createElement(planTreeNode);
        element.add(ePlanTreeNode);
    }

    protected void setAdditionalProperties(final Element element, Change change) {
        ((Add)change).setIndex(new Integer(element.attributeValue(INDEX)));
        // TODO: Call PlanTreeNodeXmlSerializer
    }
}

package edu.northwestern.bioinformatics.studycalendar.xml.writers;

import edu.northwestern.bioinformatics.studycalendar.domain.delta.Add;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Change;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;
import org.dom4j.Element;

import java.util.List;

public class AddXmlSerializer extends AbstractChangeXmlSerializer {
    private static final String ADD = "add";
    private static final String INDEX = "index";

    public AddXmlSerializer(Study study) {
        super(study);
    }

    protected Change changeInstance() {
        return new Add();
    }

    protected String elementName() {
        return ADD;
    }

    protected void addAdditionalAttributes(final Change change, Element element) {
        element.addAttribute(INDEX, ((Add)change).getIndex().toString());
        PlanTreeNode<?> planTreeNode = ((Add)change).getChild();
        AbstractPlanTreeNodeXmlSerializer serializer = getPlanTreeNodeSerializerFactory().createPlanTreeNodeXmlSerializer(planTreeNode);
        Element ePlanTreeNode = serializer.createElement(planTreeNode);
        element.add(ePlanTreeNode);
    }

    protected void setAdditionalProperties(final Element element, Change add) {
        ((Add)add).setIndex(new Integer(element.attributeValue(INDEX)));
        List<Element> ePlanTreeNodes = element.elements();
        Element ePlanTreeNode = ePlanTreeNodes.get(0);
        AbstractPlanTreeNodeXmlSerializer serializer = getPlanTreeNodeSerializerFactory().createPlanTreeNodeXmlSerializer(ePlanTreeNode);
        PlanTreeNode<?> planTreeNode = serializer.readElement(ePlanTreeNode);
        ((Add)add).setChild(planTreeNode);
    }
}

Add change will now de-serialize a PlanTreeNode children when readElement is called.

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@2230 0d517254-b314-0410-acde-c619094fa49f


/*
 * Copyright 2017 anand.
 *
 * 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 sshd.shell.springboot.console;

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

/**
 *
 * @author anand
 */
public class ConsoleIOTest {

    @Test
    public void testConsoleIOAsJsonException() {
        assertTrue(ConsoleIO.asJson(new X("x")).startsWith("Error processing json output"));
    }

    @lombok.AllArgsConstructor
    private static class X {
        private final String x;
    }
}

/*
 * Copyright 2017 anand.
 *
 * 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 sshd.shell.springboot.console;

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

/**
 *
 * @author anand
 */
public class ConsoleIOTest {

    @Test
    public void testConsoleIOAsJsonException() {
        assertTrue(ConsoleIO.asJson(new X("x")).startsWith("Error processing json output"));
    }

    @lombok.AllArgsConstructor
    private static class X {
        final String x;
    }
}

Fix for broken unit test in Linux

Fix for broken unit test in Linux


package org.workcraft.presets;

import org.workcraft.gui.dialogs.ModalDialog;
import org.workcraft.utils.DesktopApi;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.io.File;

public abstract class PresetDialog<T> extends ModalDialog<PresetManager<T>> {

    public PresetDialog(Window owner, String title, PresetManager<T> presetManager) {
        super(owner, title, presetManager);
    }

    public JButton addCheckerButton(ActionListener action) {
        return addButton("Check syntax", action, false);
    }

    public JButton addHelpButton(File helpFile) {
        return addButton("Help", event -> DesktopApi.open(helpFile), true);
    }

    public abstract T getPresetData();

}

package org.workcraft.presets;

import org.workcraft.gui.dialogs.ModalDialog;
import org.workcraft.utils.DesktopApi;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URI;

public abstract class PresetDialog<T> extends ModalDialog<PresetManager<T>> {

    public PresetDialog(Window owner, String title, PresetManager<T> presetManager) {
        super(owner, title, presetManager);
    }

    public JButton addCheckerButton(ActionListener action) {
        return addButton("Check syntax", action, false);
    }

    public JButton addHelpButton(File file) {
        return addButton("Help", event -> DesktopApi.open(file), true);
    }

    public JButton addHelpButton(URI uri) {
        return addButton("Help", event -> DesktopApi.browse(uri), true);
    }

    public abstract T getPresetData();

}

Enable linking external URI to Help button


package com.github.aleksandermielczarek.napkin;

import android.content.Context;

/**
 * Created by Aleksander Mielczarek on 14.05.2016.
 */
public class Napkin {

    private Napkin() {

    }

    public static <T> T provideComponent(Context context) {
        Context applicationContext = context.getApplicationContext();
        ComponentProvider<T> componentProvider = (ComponentProvider<T>) applicationContext;
        return componentProvider.provideComponent();
    }
}

package com.github.aleksandermielczarek.napkin;

import android.content.Context;

/**
 * Created by Aleksander Mielczarek on 14.05.2016.
 */
public class Napkin {

    private Napkin() {

    }

    public static <T> T provideComponent(Context context) {
        Context applicationContext = context.getApplicationContext();
        ComponentProvider<T> componentProvider = (ComponentProvider<T>) applicationContext;
        return componentProvider.provideComponent();
    }

    public static <T> T provideComponent(Context context, Class<T> componentClass) {
        Context applicationContext = context.getApplicationContext();
        ComponentProvider<T> componentProvider = (ComponentProvider<T>) applicationContext;
        return componentProvider.provideComponent();
    }
}

Add new method for component retrieve

Add new method for component retrieve


package com.lenguyenthanh.nimble.view;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;

public class ViewHelper {
  private ViewHelper() {
  }

  private static ViewHelper instance;

  public synchronized static ViewHelper getInstance() {
    if(instance == null){
      instance = new ViewHelper();
    }
    return instance;
  }

  public Activity getActivity(Context context) {
    while (!(context instanceof Activity) && context instanceof ContextWrapper) {
      context = ((ContextWrapper) context).getBaseContext();
    }
    if (!(context instanceof Activity)) {
      throw new IllegalStateException(
          "Expected an activity context, got " + context.getClass().getSimpleName());
    }
    return (Activity) context;
  }
}

package com.lenguyenthanh.nimble.view;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;

public final class ViewHelper {

  private static ViewHelper instance;

  private ViewHelper() {
  }

  public static ViewHelper getInstance() {
    synchronized (ViewHelper.class) {
      if (instance == null) {
        instance = new ViewHelper();
      }
    }
    return instance;
  }

  public Activity getActivity(final Context viewContext) {
    Context context = viewContext;
    while (!(context instanceof Activity) && context instanceof ContextWrapper) {
      context = ((ContextWrapper) context).getBaseContext();
    }
    if (!(context instanceof Activity)) {
      throw new IllegalStateException(
          "Expected an activity context, got " + context.getClass().getSimpleName());
    }
    return (Activity) context;
  }
}

Fix potential bugs follow PMD

Fix potential bugs follow PMD


package org.realityforge.replicant.server;

import javax.annotation.Nonnull;

/**
 * A representation indicating that an entity message will cause another channel to be subscribed.
 */
public final class ChannelLink
{
  @Nonnull
  private final ChannelDescriptor _sourceChannel;
  @Nonnull
  private final ChannelDescriptor _targetChannel;

  public ChannelLink( @Nonnull final ChannelDescriptor sourceChannel,
                      @Nonnull final ChannelDescriptor targetChannel )
  {
    if ( null == sourceChannel.getSubChannelID() )
    {
      throw new IllegalArgumentException( "Channel Link source sub-channel id should not be null" );
    }
    if ( null == targetChannel.getSubChannelID() )
    {
      throw new IllegalArgumentException( "Channel Link target sub-channel id should not be null" );
    }
    _sourceChannel = sourceChannel;
    _targetChannel = targetChannel;
  }

  @Nonnull
  public ChannelDescriptor getSourceChannel()
  {
    return _sourceChannel;
  }

  @Nonnull
  public ChannelDescriptor getTargetChannel()
  {
    return _targetChannel;
  }

  @Override
  public boolean equals( final Object o )
  {
    if ( this == o )
    {
      return true;
    }
    if ( o == null || getClass() != o.getClass() )
    {
      return false;
    }

    final ChannelLink that = (ChannelLink) o;
    return _targetChannel.equals( that._targetChannel );
  }

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

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

package org.realityforge.replicant.server;

import javax.annotation.Nonnull;

/**
 * A representation indicating that an entity message will cause another channel to be subscribed.
 */
public final class ChannelLink
{
  @Nonnull
  private final ChannelDescriptor _sourceChannel;
  @Nonnull
  private final ChannelDescriptor _targetChannel;

  public ChannelLink( @Nonnull final ChannelDescriptor sourceChannel,
                      @Nonnull final ChannelDescriptor targetChannel )
  {
    _sourceChannel = sourceChannel;
    _targetChannel = targetChannel;
  }

  @Nonnull
  public ChannelDescriptor getSourceChannel()
  {
    return _sourceChannel;
  }

  @Nonnull
  public ChannelDescriptor getTargetChannel()
  {
    return _targetChannel;
  }

  @Override
  public boolean equals( final Object o )
  {
    if ( this == o )
    {
      return true;
    }
    if ( o == null || getClass() != o.getClass() )
    {
      return false;
    }

    final ChannelLink that = (ChannelLink) o;
    return _targetChannel.equals( that._targetChannel );
  }

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

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

Remove checks that are not valid as we already have graph links between typed graphs and instanced graphs and will probably have links between type graphs sooner rather than later


/*
 * Cuelib library for manipulating cue sheets.
 * Copyright (C) 2007-2009 Jan-Willem van den Broek
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package jwbroek.id3.v2;

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

import jwbroek.id3.ID3Frame;

public interface FrameReader
{
  public ID3Frame readFrameBody(final int size, final InputStream input)
    throws IOException, UnsupportedEncodingException, MalformedFrameException;
}

/*
 * Cuelib library for manipulating cue sheets.
 * Copyright (C) 2007-2009 Jan-Willem van den Broek
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package jwbroek.id3.v2;

import jwbroek.id3.ID3Frame;

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

public interface FrameReader {

    public ID3Frame readFrameBody(final int size, final InputStream input) throws IOException, UnsupportedEncodingException, MalformedFrameException;
}

Reformat code, remove hardcoded path.

Reformat code, remove hardcoded path.


package com.ezardlabs.lostsector.objects.weapons;

import com.ezardlabs.dethsquare.Animation;
import com.ezardlabs.dethsquare.Collider;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.TextureAtlas;
import com.ezardlabs.lostsector.Game;
import com.ezardlabs.lostsector.objects.enemies.Enemy;

public abstract class MeleeWeapon extends Weapon {
	private final Game.DamageType damageType;
	private final GameObject wielder;
	protected String currentAnimation = null;

	public MeleeWeapon(String name, Game.DamageType damageType, GameObject wielder) {
		super(name);
		this.damageType = damageType;
		this.wielder = wielder;
	}

	public abstract Animation[] getAnimations(TextureAtlas ta);

	public abstract String getNextAnimation(int direction);

	public final void reset() {
		currentAnimation = null;
	}

	protected void damageEnemies(int damage, float left, float top, float right, float bottom) {
		Collider c;
		for (GameObject go : GameObject.findAllWithTag("enemy")) {
			if ((c = go.getComponent(Collider.class)) != null && c.bounds.intersects(left, top, right, bottom)) {
				//noinspection ConstantConditions
				go.getComponentOfType(Enemy.class).applyDamage(damage, damageType, wielder.transform.position);
			}
		}
	}
}

package com.ezardlabs.lostsector.objects.weapons;

import com.ezardlabs.dethsquare.Animation;
import com.ezardlabs.dethsquare.Collider;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.TextureAtlas;
import com.ezardlabs.lostsector.Game;
import com.ezardlabs.lostsector.objects.enemies.Enemy;

public abstract class MeleeWeapon extends Weapon {
	private final Game.DamageType damageType;
	private final GameObject wielder;
	protected String currentAnimation = null;

	public MeleeWeapon(String name, Game.DamageType damageType, GameObject wielder) {
		super(name);
		this.damageType = damageType;
		this.wielder = wielder;
	}

	public abstract Animation[] getAnimations(TextureAtlas ta);

	public abstract String getNextAnimation(int direction);

	public final void reset() {
		currentAnimation = null;
	}

	protected void damageEnemies(float damage, float left, float top, float right, float bottom) {
		Collider c;
		for (GameObject go : GameObject.findAllWithTag("enemy")) {
			if ((c = go.getComponent(Collider.class)) != null && c.bounds.intersects(left, top, right, bottom)) {
				//noinspection ConstantConditions
				go.getComponentOfType(Enemy.class).applyDamage(damage, damageType, wielder.transform.position);
			}
		}
	}
}

Allow damage to be a float

Allow damage to be a float


package org.metaborg.spoofax.core.shell;

import javax.annotation.Nullable;

import org.metaborg.spoofax.core.esv.ESVReader;
import org.spoofax.interpreter.terms.IStrategoAppl;

public class ShellFacetFromESV {

    public static @Nullable ShellFacet create(IStrategoAppl esv) {
        IStrategoAppl shellTerm = ESVReader.findTerm(esv, "Shell");
        if (shellTerm == null) {
            return null;
        }
        String commandPrefix = commandPrefix(shellTerm);
        String evaluationMethod = evaluationMethod(shellTerm);
        return new ShellFacet(commandPrefix, evaluationMethod);
    }

    private static @Nullable String commandPrefix(IStrategoAppl term) {
        return ESVReader.getProperty(term, "CommandPrefix");
    }

    private static @Nullable String evaluationMethod(IStrategoAppl term) {
        return ESVReader.getProperty(term, "EvaluationMethod");
    }
}

package org.metaborg.spoofax.core.shell;

import javax.annotation.Nullable;

import org.metaborg.spoofax.core.esv.ESVReader;
import org.spoofax.interpreter.terms.IStrategoAppl;

public class ShellFacetFromESV {

    public static @Nullable ShellFacet create(IStrategoAppl esv) {
        IStrategoAppl shellTerm = ESVReader.findTerm(esv, "Shell");
        if (shellTerm == null) {
            return null;
        }
        String commandPrefix = commandPrefix(shellTerm);
        String evaluationMethod = evaluationMethod(shellTerm);
        return new ShellFacet(commandPrefix, evaluationMethod);
    }

    private static String commandPrefix(IStrategoAppl term) {
        // Default is ":"
        return ESVReader.getProperty(term, "CommandPrefix", ":");
    }

    private static String evaluationMethod(IStrategoAppl term) {
        // Default is "dynsem"
        return ESVReader.getProperty(term, "EvaluationMethod", "dynsem");
    }
}

Add default values for command prefix and evaluation method


package com.averi.worldscribe.activities;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import com.averi.worldscribe.R;

public class SettingsActivity extends AppCompatActivity {

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

        setAppBar();
    }

    /**
     * Setup this Activity's app bar.
     */
    private void setAppBar() {
        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        assert myToolbar != null;
        myToolbar.setTitle(R.string.settingsTitle);
        setSupportActionBar(myToolbar);
    }

}

package com.averi.worldscribe.activities;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.Spinner;

import com.averi.worldscribe.R;
import com.averi.worldscribe.adapters.AppThemeArrayAdapter;

public class SettingsActivity extends AppCompatActivity {

    private Spinner appThemeSpinner;

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

        appThemeSpinner = (Spinner) findViewById(R.id.themeSelector);

        setAppBar();
        populateAppThemeSpinner();
    }

    /**
     * Setup this Activity's app bar.
     */
    private void setAppBar() {
        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        assert myToolbar != null;
        myToolbar.setTitle(R.string.settingsTitle);
        setSupportActionBar(myToolbar);
    }

    /**
     * Populate the App Theme spinner with all available app themes.
     */
    private void populateAppThemeSpinner() {
        Integer allThemes[] = {R.style.AppTheme, R.style.SunsetOrange, R.style.EnchantedGreen,
            R.style.UbePurple, R.style.LovelyRed};
        AppThemeArrayAdapter adapter = new AppThemeArrayAdapter(this, allThemes);
        appThemeSpinner.setAdapter(adapter);
    }

}

Set adapter for select app theme spinner


/*
 * #%L
 * ACS AEM Commons Bundle
 * %%
 * Copyright (C) 2016 Adobe
 * %%
 * 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.
 * #L%
 */
@aQute.bnd.annotation.Version("1.0.0")
package com.adobe.acs.commons.fam.actions;

/*
 * #%L
 * ACS AEM Commons Bundle
 * %%
 * Copyright (C) 2016 Adobe
 * %%
 * 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.
 * #L%
 */
@aQute.bnd.annotation.Version("1.1.0")
package com.adobe.acs.commons.fam.actions;

Increase package version for ActionBatch addition


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

package io.spine.system.server;

import com.google.protobuf.Message;
import io.spine.annotation.Internal;

/**
 * A gateway for sending messages into a system bounded context.
 *
 * @author Dmytro Dashenkov
 */
@Internal
public interface SystemGateway {

    /**
     * Posts a system command.
     *
     * <p>In a multitenant environment, the command is posted for
     * the {@linkplain io.spine.server.tenant.TenantAwareOperation current tenant}.
     *
     * @param systemCommand command message
     */
    void postCommand(Message systemCommand);
}

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

package io.spine.system.server;

import com.google.protobuf.Message;
import io.spine.annotation.Internal;

/**
 * A gateway for sending messages into a system bounded context.
 *
 * @author Dmytro Dashenkov
 */
@Internal
public interface SystemGateway {

    /**
     * Posts a system command.
     *
     * <p>If the associated bounded context is
     * {@linkplain io.spine.server.BoundedContext#isMultitenant() multitenant}, the command is
     * posted for the {@linkplain io.spine.server.tenant.TenantAwareOperation current tenant}.
     *
     * @param systemCommand command message
     */
    void postCommand(Message systemCommand);
}

Make doc more strictly correct.

Make doc more strictly correct.


package com.avairebot.orion.commands.interaction;

import com.avairebot.orion.Orion;
import com.avairebot.orion.contracts.commands.InteractionCommand;

import java.util.Arrays;
import java.util.List;

public class HugCommand extends InteractionCommand {

    public HugCommand(Orion orion) {
        super(orion, "hugs");
    }

    @Override
    public List<String> getInteractionImages() {
        return Arrays.asList(
            "https://i.imgur.com/aBdIEEu.gif",
            "https://i.imgur.com/03grRGj.gif",
            "https://i.imgur.com/EuIBiLi.gif",
            "https://i.imgur.com/8KgVR9j.gif"
        );
    }

    @Override
    public String getName() {
        return "Hug Command";
    }

    @Override
    public List<String> getTriggers() {
        return Arrays.asList("hug", "hugs");
    }
}

package com.avairebot.orion.commands.interaction;

import com.avairebot.orion.Orion;
import com.avairebot.orion.contracts.commands.InteractionCommand;

import java.util.Arrays;
import java.util.List;

public class HugCommand extends InteractionCommand {

    public HugCommand(Orion orion) {
        super(orion, "hugs");
    }

    @Override
    public List<String> getInteractionImages() {
        return Arrays.asList(
            "https://i.imgur.com/aBdIEEu.gif",
            "https://i.imgur.com/03grRGj.gif",
            "https://i.imgur.com/EuIBiLi.gif",
            "https://i.imgur.com/8KgVR9j.gif",
            "https://i.imgur.com/ZepPo0t.gif"
        );
    }

    @Override
    public String getName() {
        return "Hug Command";
    }

    @Override
    public List<String> getTriggers() {
        return Arrays.asList("hug", "hugs");
    }
}

Add new image to hug interaction

Add new image to hug interaction


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

package ml.duncte123.skybot.unstable.utils;

import ml.duncte123.skybot.Author;

@Author(nickname = "Sanduhr32", author = "Maurice R S")
public class ComparatingUtils {
    // Needs to be fixed
    public static void execCheck(Throwable t) {
        t.printStackTrace();
        Throwable cause = t.getCause();
        while (cause != null) {
            cause.printStackTrace();
            cause = cause.getCause();
        }
    }
}

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

package ml.duncte123.skybot.unstable.utils;

import ml.duncte123.skybot.Author;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Author(nickname = "Sanduhr32", author = "Maurice R S")
public class ComparatingUtils {

    private static final Logger logger = LoggerFactory.getLogger(ComparatingUtils.class);

    // Needs to be fixed
    public static void execCheck(Throwable t) {
        logger.error("An error occurred", t);
        t.printStackTrace();
        Throwable cause = t.getCause();
        while (cause != null) {
            cause.printStackTrace();
            cause = cause.getCause();
        }
    }
}

Add error log for execCheck

Add error log for execCheck


package simplemods.cheesemod.blocks;

import java.util.Random;

import simplemods.cheesemod.BaseMod;
import simplemods.cheesemod.CommonProxy;
import simplemods.cheesemod.inventory.CCreativeTabs;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
/**
 * No, this is not a hopper...
 */
public class BlockHotPepperCheeseOre extends Block{

	public BlockHotPepperCheeseOre(Material p_i45394_1_) {
		super(Material.rock);
		setCreativeTab(CCreativeTabs.tabBlock);
		setBlockName("pepper_cheese_ore");
		setBlockTextureName("cheesemod:pepper_cheese_ore");
		setLightLevel(0.325F);
	}

	@Override
	public Item getItemDropped(int p_149650_1_, Random p_149650_2_,
			int p_149650_3_) {
		return CommonProxy.hot_pepper_cheese;
	}

}

package simplemods.cheesemod.blocks;

import java.util.Random;

import simplemods.cheesemod.BaseMod;
import simplemods.cheesemod.CommonProxy;
import simplemods.cheesemod.inventory.CCreativeTabs;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import net.minecraft.item.ItemPickaxe;
/**
 * No, this is not a hopper...
 */
public class BlockHotPepperCheeseOre extends Block{

	public BlockHotPepperCheeseOre(Material p_i45394_1_) {
		super(Material.rock);
		setCreativeTab(CCreativeTabs.tabBlock);
		setBlockName("pepper_cheese_ore");
		setBlockTextureName("cheesemod:pepper_cheese_ore");
		setLightLevel(0.325F);
		setHardness(0.4F);
		setHarvestLevel("pickaxe", 0);
	}

	@Override
	public Item getItemDropped(int p_149650_1_, Random p_149650_2_,
			int p_149650_3_) {
		return CommonProxy.hot_pepper_cheese;
	}

}

Fix hot pepper cheese hardness bug

Fix hot pepper cheese hardness bug


/*
 * $HeadURL$
 * $Id$
 * Copyright (c) 2006-2013 by Public Library of Science http://plos.org http://ambraproject.org
 * 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.0Unless 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.ambraproject.wombat.controller;

import org.ambraproject.wombat.config.site.Site;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

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

/**
 * Controller intended to serve static pages
 */
@Controller
public class StaticContentController extends WombatController {

  @RequestMapping(value = {"/s", "/{site}/s"})
  public String renderStaticContent(Model model, @SiteParam Site site)
          throws IOException {

    return site + "/ftl/static/container";
  }

}

/*
 * $HeadURL$
 * $Id$
 * Copyright (c) 2006-2013 by Public Library of Science http://plos.org http://ambraproject.org
 * 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.0Unless 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.ambraproject.wombat.controller;

import org.ambraproject.wombat.config.site.Site;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.HandlerMapping;

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

/**
 * Controller intended to serve static pages
 */
@Controller
public class StaticContentController extends WombatController {

  @RequestMapping(value = {"/s/*", "/{site}/s/*"})
  public String renderStaticContent(Model model, @SiteParam Site site)
          throws IOException {

    return site + "/ftl/static/container";
  }

}

DPRO-769: Use wild card for static content controller to support multiple pages


package com.openxc.measurements;

import java.util.Locale;

import com.openxc.units.State;

/**
 * The ClimateMode measurement is used to start the AC/Heater/Fan
 */
public class ClimateMode extends BaseMeasurement<State<ClimateMode.ClimateControls>> {
	public final static String ID = "climate_mode";

	public enum ClimateControls {
		UNUSED(0),
		PANEL_VENT(1),
		PANEL_FLOOR(2),
		FLOOR(3),
		FAN_SPEED_INCREMENT(11),
		FAN_SPEED_DECREMENT(12),
		AUTO(13),
		MAX_AC(14),
		RECIRCULATION(15),
		FRONT_DEFROST(16),
		REAR_DEFROST(17),
		MAX_DEFROTS(22)
	}

	public ClimateMode(State<ClimateControls> value) {
		super(value);
	}

	public ClimateMode(ClimateControls value) {
		this(new State<ClimateControls>(value));
	}
    public ClimateMode(String value) {
        this(ClimateControls.valueOf(value.toUpperCase(Locale.US)));
    }

    @Override
    public String getGenericName() {
        return ID;
    }
}

package com.openxc.measurements;

import java.util.Locale;

import com.openxc.units.State;

/**
 * The ClimateMode measurement is used to start the AC/Heater/Fan
 */
public class ClimateMode extends BaseMeasurement<State<ClimateMode.ClimateControls>> {
	public final static String ID = "climate_mode";

	public enum ClimateControls {
		OFF,
		PANEL_VENT,
		PANEL_FLOOR,
		FLOOR,
		FAN_SPEED_INCREMENT,
		FAN_SPEED_DECREMENT,
		AUTO,
		MAX_AC,
		RECIRCULATION,
		FRONT_DEFROST,
		REAR_DEFROST,
		MAX_DEFROST
	}

	public ClimateMode(State<ClimateControls> value) {
		super(value);
	}

	public ClimateMode(ClimateControls value) {
		this(new State<ClimateControls>(value));
	}
    public ClimateMode(String value) {
        this(ClimateControls.valueOf(value.toUpperCase(Locale.US)));
    }

    @Override
    public String getGenericName() {
        return ID;
    }
}

Remove int enum values, as they are unneeded