package com.sangdol.experiment.portableDb;

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

/**
 * @author hugh
 */
public class ViewTable {
    public static final String TABLE_PREFIX = "true_view";
    private static final int TABLE_COUNT = 100;
    private static final List<String> names = new ArrayList<>();

    static {
        for (int i = 0; i < TABLE_COUNT; i++) {
            names.add(TABLE_PREFIX + i);
        }
    }

    public List<String> getAll() {
        return names;
    }

    // TODO throw exception when trying to get a not existing table
    public String get(int userId) {
        final int HOST_COUNT_IN_TABLE = 100;
        int tableNumber = (userId - 1) / HOST_COUNT_IN_TABLE;
        return TABLE_PREFIX + tableNumber;
    }
}

package com.sangdol.experiment.portableDb;

import javax.ws.rs.WebApplicationException;
import java.util.ArrayList;
import java.util.List;

/**
 * Manage horizontally split table names.
 *
 * @author hugh
 */
public class ViewTable {
    public static final String TABLE_PREFIX = "true_view";
    private static final int TABLE_COUNT = 100;
    private static final List<String> names = new ArrayList<>();

    static {
        for (int i = 0; i < TABLE_COUNT; i++) {
            names.add(TABLE_PREFIX + i);
        }
    }

    /**
     * Returns all table names with designated TABLE_PREFIX and TABLE_COUNT.
     */
    public List<String> getAll() {
        return names;
    }

    /**
     * Returns the allocated table name to the userId.
     * The index of table name is 0-based, e.g. true_view0, true_view1...
     */
    public String get(int userId) {
        final int HOST_COUNT_IN_TABLE = 100;
        int tableNumber = (userId - 1) / HOST_COUNT_IN_TABLE;

        if (tableNumber >= TABLE_COUNT)
            throw new WebApplicationException(404);

        return TABLE_PREFIX + tableNumber;
    }
}

Add docs / Throw exception for wrong userId


package invtweaks.forge;

import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.entity.player.EntityPlayer;

public class CommonProxy {
    public void preInit(FMLPreInitializationEvent e) {
    }

    public void init(FMLInitializationEvent e) {
    }

    public void postInit(FMLPostInitializationEvent e) {
    }

    public void setServerAssistEnabled(boolean enabled) {
    }

    public void setServerHasInvTweaks(boolean hasInvTweaks) {
    }

    public void slotClick(PlayerControllerMP playerController,
                          int windowId, int slot, int data,
                          int action, EntityPlayer player) {
    }
}

package invtweaks.forge;

import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.entity.player.EntityPlayer;

public class CommonProxy {
    public void preInit(FMLPreInitializationEvent e) {
    }

    public void init(FMLInitializationEvent e) {
    }

    public void postInit(FMLPostInitializationEvent e) {
    }

    public void setServerAssistEnabled(boolean enabled) {
    }

    public void setServerHasInvTweaks(boolean hasInvTweaks) {
    }

    /* Action values:
     * 0: Standard Click
     * 1: Shift-Click
     * 2: Move item to/from hotbar slot (Depends on current slot and hotbar slot being full or empty)
     * 3: Pick-Block
     * 4: Drop item
     * 5: Spread items (Drag behavior)
     * 6: Merge all valid items with held item
     */
    public void slotClick(PlayerControllerMP playerController,
                          int windowId, int slot, int data,
                          int action, EntityPlayer player) {
    }
}

Comment documenting what the various action values do.


package com.quollwriter.data.comparators;

import java.util.*;

import com.quollwriter.data.*;

public class ChapterItemSorter implements Comparator<ChapterItem>
{

    public int compare (ChapterItem o1,
                        ChapterItem o2)
    {
/*
        if (o1.getKey () == null)
        {

            return 1;

        }

        if (o2.getKey () == null)
        {

            return 1;

        }
  */
        if (o1.getPosition () == o2.getPosition ())
        {

            if ((o1.getKey () == null)
                ||
                (o1.getName () == null)
               )
            {

                return 1;

            }

            if ((o2.getKey () == null)
                ||
                (o2.getName () == null)
               )
            {

                return 1;

            }

            if ((o1 instanceof Scene)
                &&
                (o2 instanceof OutlineItem)
               )
            {

                return -1;

            }

            if ((o2 instanceof Scene)
                &&
                (o1 instanceof OutlineItem)
               )
            {

                return 1;

            }

            return o1.getName ().compareTo (o2.getName ());

            //return (int) (o1.getKey () - o2.getKey ());

        }

        return o1.getPosition () - o2.getPosition ();

    }

    public boolean equals (Object o)
    {

        return this == o;

    }

}

package com.quollwriter.data.comparators;

import java.util.*;

import com.quollwriter.data.*;

public class ChapterItemSorter implements Comparator<ChapterItem>
{

    public int compare (ChapterItem o1,
                        ChapterItem o2)
    {
/*
        if (o1.getKey () == null)
        {

            return 1;

        }

        if (o2.getKey () == null)
        {

            return 1;

        }
  */
        if (o1.getPosition () == o2.getPosition ())
        {

            if ((o1.getKey () == null)
                ||
                (o1.getName () == null)
               )
            {

                return 1;

            }

            if ((o2.getKey () == null)
                ||
                (o2.getName () == null)
               )
            {

                return 1;

            }

            if ((o1 instanceof Scene)
                &&
                (o2 instanceof OutlineItem)
               )
            {

                return -1;

            }

            if ((o2 instanceof Scene)
                &&
                (o1 instanceof OutlineItem)
               )
            {

                return 1;

            }

            int nc = o1.getName ().compareTo (o2.getName ());

            if (nc == 0)
            {

                // Return the one created first.
                return o1.getDateCreated ().compareTo (o2.getDateCreated ());

            }

            return nc;

            //return (int) (o1.getKey () - o2.getKey ());

        }

        return o1.getPosition () - o2.getPosition ();

    }

    public boolean equals (Object o)
    {

        return this == o;

    }

}

Tweak to make sorting work when two objects have same name.


package com.youcruit.billogram.objects.response.billogram;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Callback {

    @Expose
    private String url;
    @SerializedName("sign_key")
    @Expose
    private String signKey;
    @Expose
    private String custom;

    public String getUrl() {
	return url;
    }

    public void setUrl(String url) {
	this.url = url;
    }

    public Callback withUrl(String url) {
	this.url = url;
	return this;
    }

    public String getSignKey() {
	return signKey;
    }

    public void setSignKey(String signKey) {
	this.signKey = signKey;
    }

    public Callback withSignKey(String signKey) {
	this.signKey = signKey;
	return this;
    }

    public String getCustom() {
	return custom;
    }

    public void setCustom(String custom) {
	this.custom = custom;
    }

    public Callback withCustom(String custom) {
	this.custom = custom;
	return this;
    }

}

package com.youcruit.billogram.objects.response.billogram;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.youcruit.billogram.objects.response.event.CallbackEvent;

public class Callback {
    @Expose
    CallbackBillogram billogram;
    @Expose
    CallbackEvent event;
    @Expose
    private String url;
    @SerializedName("sign_key")
    @Expose
    private String signKey;
    @Expose
    private String custom;

    public String getUrl() {
	return url;
    }

    public void setUrl(String url) {
	this.url = url;
    }

    public Callback withUrl(String url) {
	this.url = url;
	return this;
    }

    public String getSignKey() {
	return signKey;
    }

    public void setSignKey(String signKey) {
	this.signKey = signKey;
    }

    public Callback withSignKey(String signKey) {
	this.signKey = signKey;
	return this;
    }

    public String getCustom() {
	return custom;
    }

    public void setCustom(String custom) {
	this.custom = custom;
    }

    public Callback withCustom(String custom) {
	this.custom = custom;
	return this;
    }

}

Add attributes in callback class


package ru.stqa.pft.addressbook.tests;

import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;

import java.util.HashSet;
import java.util.List;

public class GroupCreationTests extends TestBase {

  @Test
  public void testGroupCreation() {
    app.getNavigationHelper().gotoGroupPage();
    List<GroupData> before = app.getGroupHelper().getGroupList();
    GroupData group = new GroupData("test2", null, null);
    app.getGroupHelper().createGroup(group);
    List<GroupData> after = app.getGroupHelper().getGroupList();
    Assert.assertEquals(after.size(), before.size() + 1);

    group.setId(after.stream().max((o1, o2) -> Integer.compare(o1.getId(), o2.getId())).get().getId());
    before.add(group);
    Assert.assertEquals(new HashSet<>(before), new HashSet<>(after));

  }

}

package ru.stqa.pft.addressbook.tests;

import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;

import java.util.HashSet;
import java.util.List;

public class GroupCreationTests extends TestBase {

  @Test
  public void testGroupCreation() {
    app.getNavigationHelper().gotoGroupPage();
    List<GroupData> before = app.getGroupHelper().getGroupList();
    GroupData group = new GroupData("test1", null, null);
    app.getGroupHelper().createGroup(group);
    List<GroupData> after = app.getGroupHelper().getGroupList();
    Assert.assertEquals(after.size(), before.size() + 1);

    before.add(group);
    int max = 0;
    for (GroupData g: after){
      if (g.getId()>max){
        max = g.getId();

      }
    }
    group.setId(max);
    before.add(group);

    Assert.assertEquals(new HashSet<>(before), new HashSet<>(after));

  }

}

Revert "изменение теста создания группы при помощи лямбды (блок лекции 4_9)"


package de.gernd.simplemon.endpoints.dto;

import lombok.Builder;
import lombok.Data;

@Builder
@Data
public class MonitoringResult {
    private boolean isUp;
    private long timeNeededForRequest;
}

package de.gernd.simplemon.endpoints.dto;

import lombok.Builder;
import lombok.Data;

@Builder
@Data
public class MonitoringResult {
    private long timeNeededForRequest;
}

Remove isUp flag from DTO


package remonsinnema.blog.fizzbuzz;

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

public class FizzBuzz {

  private final Collection<Term> terms = Arrays.asList(new Term(3, "Fizz"), new Term(5, "Buzz"));

  public String get(int n) {
    StringBuilder result = new StringBuilder();
    for (Term term : terms) {
      term.textFor(n)
          .ifPresent(t -> result.append(t));
    }
    if (result.length() > 0) {
      return result.toString();
    }
    return Integer.toString(n);
  }

}

package remonsinnema.blog.fizzbuzz;

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

public class FizzBuzz {

  private final Collection<Term> terms = Arrays.asList(new Term(3, "Fizz"), new Term(5, "Buzz"));

  public String get(int n) {
    return terms.stream()
        .map(term -> term.textFor(n))
        .filter(Optional::isPresent)
        .map(o -> o.get())
        .reduce((a, b) -> a + b)
        .orElse(Integer.toString(n));
  }

}

Use streams instead of loops and conditionals


package org.vrjuggler.vrjconfig.ui;

import java.io.File;
import javax.swing.filechooser.*;

/**
 * FileFilter for VR Juggler configuration files.
 */
public class ConfigFileFilter extends FileFilter
{
   /**
    * Verify that the given file is a configuration file.
    */
   public boolean accept(File f)
   {
      String ext = null;
      String s = f.getName();
      int i = s.lastIndexOf('.');

      if (i > 0 &&  i < s.length() - 1)
      {
         ext = s.substring(i+1).toLowerCase();
         if(ext.equals("jconf"))
         {
            return true;
         }
      }
      return false;
   }

   /**
    * Get a description of this filter to display in JFileChooser.
    */
   public String getDescription()
   {
      return("VR Juggler Configuration File (*.jconf)");
   }
}

package org.vrjuggler.vrjconfig.ui;

import java.io.File;
import javax.swing.filechooser.*;

/**
 * FileFilter for VR Juggler configuration files.
 */
public class ConfigFileFilter extends FileFilter
{
   /**
    * Verify that the given file is a configuration file.
    */
   public boolean accept(File f)
   {
      if(f.isDirectory())
      {
         return true;
      }
      String ext = null;
      String s = f.getName();
      int i = s.lastIndexOf('.');

      if (i > 0 &&  i < s.length() - 1)
      {
         ext = s.substring(i+1).toLowerCase();
         if(ext.equals("jconf"))
         {
            return true;
         }
      }
      return false;
   }

   /**
    * Get a description of this filter to display in JFileChooser.
    */
   public String getDescription()
   {
      return("VR Juggler Configuration File (*.jconf)");
   }
}

Allow the user to see directories also.


package org.synyx.urlaubsverwaltung.absence;

import org.springframework.data.repository.CrudRepository;

public interface AbsenceMappingDAO extends CrudRepository<AbsenceMapping, Integer> {

    AbsenceMapping findAbsenceMappingByAbsenceIdAndAbsenceType(Integer id, AbsenceType absenceType);
}

package org.synyx.urlaubsverwaltung.absence;

import org.springframework.data.repository.CrudRepository;

interface AbsenceMappingDAO extends CrudRepository<AbsenceMapping, Integer> {

    AbsenceMapping findAbsenceMappingByAbsenceIdAndAbsenceType(Integer id, AbsenceType absenceType);
}

Reduce scope of absence mapping dao


package quarks.test.svt.apps;

import quarks.topology.Topology;
public class ObdAnalyticsApplication{

    private final FleetManagementAnalyticsClientApplication app;
    private final Topology t;
    private final String sensorId = "obd";

    public ObdAnalyticsApplication(Topology t, FleetManagementAnalyticsClientApplication app) {
        this.t = t;
        this.app = app;
    }

    /**
     * Add the ODB sensor's analytics to the topology.
     */
    public void addAnalytics() {

    }
}

/**
 * GPS analytics
 *

 * Source is a stream of GPS sensor data {@link GpsSensor}
 *

 * Here's an outline of the topology
 *

 *
Log GPS coordinates by publishing to IotF. The data may be used by a
 * server application to display the vehicle on a map.

 *
Filter to detect speeds above a threshold and publish alert IotF

 *
Filter for GPS coordinates that are outside of a defined Geofence
 * boundary

 *
Windowing to detect hard driving: hard braking or hard acceleration and
 * publish alert to IotF

 *

 *

 */
package quarks.test.svt.apps;

import quarks.test.svt.utils.sensor.gps.GpsSensor;
import quarks.topology.Topology;
public class ObdAnalyticsApplication{

    private final FleetManagementAnalyticsClientApplication app;
    private final Topology t;
    private final String sensorId = "obd";

    public ObdAnalyticsApplication(Topology t, FleetManagementAnalyticsClientApplication app) {
        this.t = t;
        this.app = app;
    }

    /**
     * Add the ODB sensor's analytics to the topology.
     */
    public void addAnalytics() {

    }
}

Add Apache header in OdbAnalyticsApplication.java


/*
 * Copyright 2019, 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.server.enrich;

import com.google.protobuf.Message;
import io.spine.base.EventMessage;
import io.spine.core.EventContext;

/**
 * Base interface for event enrichment functions.
 *
 * @param <M> the type of the event message
 * @param <E> the type of the enrichment message
 */
public interface EventEnrichmentFn<M extends EventMessage, E extends Message>
    extends EnrichmentFn<M, EventContext, E> {
}

/*
 * Copyright 2019, 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.server.enrich;

import com.google.protobuf.Message;
import io.spine.base.EventMessage;
import io.spine.core.EventContext;

/**
 * Base interface for event enrichment functions.
 *
 * @param <M> the type of the event message
 * @param <E> the type of the enrichment message
 */
@FunctionalInterface
public interface EventEnrichmentFn<M extends EventMessage, E extends Message>
    extends EnrichmentFn<M, EventContext, E> {
}

Mark event enrichment as func. interface


/*
 * $Id$
 * $Revision$
 * $Date$
 *
 * ====================================================================
 * 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 wicket.examples.signin2;

import wicket.ISessionFactory;
import wicket.Session;
import wicket.examples.WicketExampleApplication;

/**
 * Forms example.
 * @author Jonathan Locke
 */
public final class SignIn2Application extends WicketExampleApplication
{
    /**
     * Constructor.
     */
    public SignIn2Application()
    {
        getPages().setHomePage(Home.class);
    }

    /**
     * @see wicket.protocol.http.WebApplication#getSessionFactory()
     */
    public ISessionFactory getSessionFactory()
    {
        return new ISessionFactory()
        {
            public Session newSession()
            {
                return new SignIn2Session(SignIn2Application.this);
            }
        };
    }
}

/*
 * $Id$
 * $Revision$
 * $Date$
 *
 * ====================================================================
 * 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 wicket.examples.signin2;

import wicket.ISessionFactory;
import wicket.Session;
import wicket.examples.WicketExampleApplication;
import wicket.markup.html.form.encryption.NoCrypt;

/**
 * Forms example.
 * @author Jonathan Locke
 */
public final class SignIn2Application extends WicketExampleApplication
{
    /**
     * Constructor.
     */
    public SignIn2Application()
    {
        getPages().setHomePage(Home.class);

        // WARNING: DO NOT do this on a real world application!!

        // The NoCrypt class is being used here because not everyone
        // has the java security classes required by Crypt installed
        // and we want them to be able to run the examples out of the
        // box.
        getSettings().setCryptClass(NoCrypt.class);
    }

    /**
     * @see wicket.protocol.http.WebApplication#getSessionFactory()
     */
    public ISessionFactory getSessionFactory()
    {
        return new ISessionFactory()
        {
            public Session newSession()
            {
                return new SignIn2Session(SignIn2Application.this);
            }
        };
    }
}

Set Cypt class to NullCrypt for demo purposes


package com.battlelancer.seriesguide.ui;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.actionbarsherlock.app.SherlockFragment;
import com.uwetrottmann.seriesguide.R;

/**
 * Tells about trakt and how it integrates with SeriesGuide, allows to proceed
 * to entering credentials step.
 */
public class ConnectTraktFragment extends SherlockFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.connect_trakt_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // connect button
        getView().findViewById(R.id.buttonConnectTrakt).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ConnectTraktCredentialsFragment f = ConnectTraktCredentialsFragment.newInstance();
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.root_container, f);
                ft.commit();
            }
        });

        // discard button
        getView().findViewById(R.id.buttonDiscard).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }
}

package com.battlelancer.seriesguide.ui;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.uwetrottmann.seriesguide.R;

/**
 * Tells about trakt and how it integrates with SeriesGuide, allows to proceed
 * to entering credentials step.
 */
public class ConnectTraktFragment extends SherlockFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.connect_trakt_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // connect button
        getView().findViewById(R.id.buttonConnectTrakt).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ConnectTraktCredentialsFragment f = ConnectTraktCredentialsFragment.newInstance();
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.root_container, f);
                ft.commit();
            }
        });

        // discard button
        getView().findViewById(R.id.buttonDiscard).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        // make learn more link clickable
        ((TextView) getView().findViewById(R.id.textViewAbout))
                .setMovementMethod(LinkMovementMethod.getInstance());
    }
}

Make learn more link clickable.


package io.dropwizard.logging.layout;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.contrib.jackson.JacksonJsonFormatter;
import ch.qos.logback.contrib.json.JsonLayoutBase;
import ch.qos.logback.core.pattern.PatternLayoutBase;
import io.dropwizard.logging.DropwizardLayout;
import io.dropwizard.logging.JsonStacktraceLayout;

import java.util.TimeZone;

/**
 * Factory that creates a {@link DropwizardLayout}
 */
public class DropwizardLayoutFactory implements LayoutFactory<ILoggingEvent> {
    @Override
    public PatternLayoutBase<ILoggingEvent> buildPatternLayout(LoggerContext context, TimeZone timeZone) {
        return new DropwizardLayout(context, timeZone);
    }

    @Override
    public JsonLayoutBase<ILoggingEvent> buildJsonLayout(LoggerContext context, TimeZone timeZone,
                                                         String timestampFormat, boolean includeStackTrace,
                                                         boolean prettyPrint) {
        JacksonJsonFormatter jsonFormatter = new JacksonJsonFormatter();
        jsonFormatter.setPrettyPrint(prettyPrint);
        JsonStacktraceLayout jsonLayout = new JsonStacktraceLayout();
        jsonLayout.setJsonFormatter(jsonFormatter);
        jsonLayout.setIncludeStacktrace(includeStackTrace);
        jsonLayout.setContext(context);
        jsonLayout.setTimestampFormat(timestampFormat);
        jsonLayout.setTimestampFormatTimezoneId(timeZone.getID());
        return  jsonLayout;
    }
}

package io.dropwizard.logging.layout;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.contrib.jackson.JacksonJsonFormatter;
import ch.qos.logback.contrib.json.JsonLayoutBase;
import ch.qos.logback.core.pattern.PatternLayoutBase;
import io.dropwizard.logging.DropwizardLayout;
import io.dropwizard.logging.JsonStacktraceLayout;

import java.util.TimeZone;

/**
 * Factory that creates a {@link DropwizardLayout}
 */
public class DropwizardLayoutFactory implements LayoutFactory<ILoggingEvent> {
    @Override
    public PatternLayoutBase<ILoggingEvent> buildPatternLayout(LoggerContext context, TimeZone timeZone) {
        return new DropwizardLayout(context, timeZone);
    }

    @Override
    public JsonLayoutBase<ILoggingEvent> buildJsonLayout(LoggerContext context, TimeZone timeZone,
                                                         String timestampFormat, boolean includeStackTrace,
                                                         boolean prettyPrint) {
        JacksonJsonFormatter jsonFormatter = new JacksonJsonFormatter();
        jsonFormatter.setPrettyPrint(prettyPrint);
        JsonStacktraceLayout jsonLayout = new JsonStacktraceLayout();
        jsonLayout.setJsonFormatter(jsonFormatter);
        jsonLayout.setIncludeStacktrace(includeStackTrace);
        jsonLayout.setContext(context);
        jsonLayout.setTimestampFormat(timestampFormat);
        jsonLayout.setTimestampFormatTimezoneId(timeZone.getID());
        jsonLayout.setAppendLineSeparator(true);
        return  jsonLayout;
    }
}

Add line separator in logs from JSON event log to another to facilitate json log parsers


package org.ethereum.config.net;

import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.blockchain.DaoHFConfig;
import org.ethereum.config.blockchain.Eip150HFConfig;
import org.ethereum.config.blockchain.Eip160HFConfig;
import org.ethereum.config.blockchain.MordenConfig;
import org.spongycastle.util.encoders.Hex;

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

/**
 * Created by Anton Nashatyrev on 25.02.2016.
 */
public class MordenNetConfig extends AbstractNetConfig {

    public MordenNetConfig() {
        add(0, new MordenConfig.Frontier());
        add(494_000, new MordenConfig.Homestead());
        add(1_783_000, new Eip150HFConfig(new MordenConfig.Homestead()));
        add(1_885_000, new Eip160HFConfig(new MordenConfig.Homestead()));

    }
}

package org.ethereum.config.net;

import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.blockchain.Eip150HFConfig;
import org.ethereum.config.blockchain.Eip160HFConfig;
import org.ethereum.config.blockchain.MordenConfig;
import org.spongycastle.util.encoders.Hex;

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

/**
 * Created by Anton Nashatyrev on 25.02.2016.
 */
public class MordenNetConfig extends AbstractNetConfig {
    private static final long EIP150_HF_BLOCK = 1_783_000;
    private static final byte[] EIP150_HF_BLOCK_HASH =
            Hex.decode("f376243aeff1f256d970714c3de9fd78fa4e63cf63e32a51fe1169e375d98145");

    public MordenNetConfig() {
        add(0, new MordenConfig.Frontier());
        add(494_000, new MordenConfig.Homestead());
        add(EIP150_HF_BLOCK, new Eip150HFConfig(new MordenConfig.Homestead()) {
            @Override
            public List<Pair<Long, byte[]>> blockHashConstraints() {
                return Collections.singletonList(Pair.of(EIP150_HF_BLOCK, EIP150_HF_BLOCK_HASH));
            }
        });
        add(1_885_000, new Eip160HFConfig(new MordenConfig.Homestead()));

    }
}

Return back separator for Morden since wrong forked peers are still there


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

package com.thanksmister.btcblue;

import android.app.Application;

import timber.log.Timber;

public class BaseApplication extends Application
{
    @Override
    public void onCreate()
    {
        super.onCreate();

        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
            //ButterKnife.setDebug(BuildConfig.DEBUG);
            //LeakCanary.install(this);
            //refWatcher = LeakCanary.install(this);
        } else {
            //Crashlytics.start(this);
            //Timber.plant(new CrashlyticsTree());
        }

        Injector.init(this);
    }
}

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

package com.thanksmister.btcblue;

import android.app.Application;
import android.content.res.Configuration;
import android.content.res.Resources;

import java.util.Locale;

import timber.log.Timber;

public class BaseApplication extends Application
{
    @Override
    public void onCreate()
    {
        super.onCreate();

        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }

        // Force set the default locale to US for conversions
        Locale.setDefault(Locale.US);
        Resources res = getResources();
        Configuration config = res.getConfiguration();
        config.locale = Locale.US;
        res.updateConfiguration(config, res.getDisplayMetrics());

        Injector.init(this);
    }
}

Set default locale to US to use only periods for decimals, this helps with calculations.


package uk.co.alynn.games.ld30.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

import uk.co.alynn.games.ld30.SpaceHams;
import uk.co.alynn.games.ld30.world.Constants;

public class DesktopLauncher {
	public static void main (String[] arg) {
		LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
		config.width = Constants.STANDARD_RES_WIDTH;
		config.height = Constants.STANDARD_RES_HEIGHT;
		config.samples = 2;
		config.vSyncEnabled = true;
		config.title = "Space Hams";
		config.resizable = true;
		config.fullscreen = false;
		new LwjglApplication(new SpaceHams(), config);
	}
}

package uk.co.alynn.games.ld30.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

import uk.co.alynn.games.ld30.SpaceHams;
import uk.co.alynn.games.ld30.world.Constants;

public class DesktopLauncher {
	public static void main (String[] arg) {
		LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
		config.width = Constants.STANDARD_RES_WIDTH;
		config.height = Constants.STANDARD_RES_HEIGHT;
		config.samples = 2;
		config.vSyncEnabled = true;
		config.title = "Border Patrol";
		config.resizable = true;
		config.fullscreen = false;
		new LwjglApplication(new SpaceHams(), config);
	}
}

Use "Border Patrol" in the title


package org.xdi.service.cdi.event;

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

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

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

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

        private static final long serialVersionUID = 4891987789146132930L;

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

}

package org.xdi.service.cdi.event;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Initialized.Literal;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

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

import java.lang.annotation.Annotation;

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

    /**
     * The scope for which to observe initialization
     */
    Class<? extends Annotation> value();

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

        public static final Literal APPLICATION = of(ApplicationScoped.class);

        private static final long serialVersionUID = 1L;

        private final Class<? extends Annotation> value;

        public static Literal of(Class<? extends Annotation> value) {
            return new Literal(value);
        }

        private Literal(Class<? extends Annotation> value) {
            this.value = value;
        }

        @Override
        public Class<? extends Annotation> value() {
            // TODO Auto-generated method stub
            return null;
        }
    }

}

Add event to notify plugins about finish application initialization


package com.yahoo.vespa.hosted.node.admin.task.util.network;

/**
 * Strong type IPv4 and IPv6 with the respective iptables executable.
 *
 * @author smorgrav
 */
public enum IPVersion {

    IPv6("ip6tables"),
    IPv4("iptables");

    IPVersion(String exec) {
        this.exec = exec;
    }

    private String exec;

    String exec() {
        return exec;
    }
}

package com.yahoo.vespa.hosted.node.admin.task.util.network;

/**
 * Strong type IPv4 and IPv6 with common executables for ip related commands.
 *
 * @author smorgrav
 */
public enum IPVersion {

    IPv6("ip6tables", "ip -6"),
    IPv4("iptables", "ip");

    IPVersion(String iptablesCmd, String ipCmd) {
        this.ipCmd = ipCmd;
        this.iptablesCmd = iptablesCmd;
    }

    private String iptablesCmd;
    private String ipCmd;

    public String iptablesCmd() {
        return iptablesCmd;
    }
    public String ipCmd() {
        return ipCmd;
    }
}

Rename exec to iptablesCmd and add ipCmd


package gov.nih.nci.cabig.caaers.service;

import com.semanticbits.aenotification.AENotification;

import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.domain.AdverseEventReport;
import gov.nih.nci.cabig.caaers.esb.client.MessageBroadcastService;
import gov.nih.nci.cabig.caaers.utils.XMLUtil;

/**
 *
 * @author Sujith Vellat Thayyilthodi
 * */
public class InteroperationServiceImpl implements InteroperationService {

	private MessageBroadcastService messageBroadcastService;

	public void pushToStudyCalendar(AdverseEventReport aeReport) throws CaaersSystemException {
		AENotification aeNotification = new AENotification();
		aeNotification.setRegistrationGridId(
				aeReport.getAssignment().getGridId());
		aeNotification.setDetectionDate(
				new java.sql.Date(aeReport.getPrimaryAdverseEvent().getDetectionDate().getTime()));
		aeNotification.setDescription(aeReport.getPrimaryAdverseEvent().getDetailsForOther());
		getMessageBroadcastService().broadcast(XMLUtil.getXML(aeNotification));
	}

	public MessageBroadcastService getMessageBroadcastService() {
		return messageBroadcastService;
	}

	public void setMessageBroadcastService(
			MessageBroadcastService messageBroadcastService) {
		this.messageBroadcastService = messageBroadcastService;
	}

}

package gov.nih.nci.cabig.caaers.service;

import com.semanticbits.aenotification.AENotification;

import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.domain.AdverseEventReport;
import gov.nih.nci.cabig.caaers.esb.client.MessageBroadcastService;
import gov.nih.nci.cabig.caaers.utils.XMLUtil;

/**
 *
 * @author Sujith Vellat Thayyilthodi
 * */
public class InteroperationServiceImpl implements InteroperationService {

	private MessageBroadcastService messageBroadcastService;

	public void pushToStudyCalendar(AdverseEventReport aeReport) throws CaaersSystemException {
		AENotification aeNotification = new AENotification();
		aeNotification.setRegistrationGridId(
				aeReport.getAssignment().getGridId());
		aeNotification.setDetectionDate(
				new java.sql.Date(aeReport.getPrimaryAdverseEvent().getDetectionDate().getTime()));
        // TODO: verify that this is sufficient
        aeNotification.setDescription(aeReport.getPrimaryAdverseEvent().getCtcTerm().getFullName());
		getMessageBroadcastService().broadcast(XMLUtil.getXML(aeNotification));
	}

	public MessageBroadcastService getMessageBroadcastService() {
		return messageBroadcastService;
	}

	public void setMessageBroadcastService(
			MessageBroadcastService messageBroadcastService) {
		this.messageBroadcastService = messageBroadcastService;
	}

}

Use CTC term for notification description


package com.thoughtworks.acceptance;

import com.thoughtworks.acceptance.objects.SampleDynamicProxy;

public class DynamicProxyTest extends AbstractAcceptanceTest {

    public void testDynamicProxy() {
        assertBothWays(SampleDynamicProxy.newInstance(),
                "<dynamic-proxy>\n" +
                "  <interface>com.thoughtworks.acceptance.objects.SampleDynamicProxy$InterfaceOne</interface>\n" +
                "  <interface>com.thoughtworks.acceptance.objects.SampleDynamicProxy$InterfaceTwo</interface>\n" +
                "  <handler class=\"com.thoughtworks.acceptance.objects.SampleDynamicProxy\">\n" +
                "    <aField>hello</aField>\n" +
                "  </handler>\n" +
                "</dynamic-proxy>");
    }

}

package com.thoughtworks.acceptance;

import com.thoughtworks.acceptance.objects.SampleDynamicProxy;

public class DynamicProxyTest extends AbstractAcceptanceTest {
    public static class ClassWithProxyMember {
        SampleDynamicProxy.InterfaceOne one;
        SampleDynamicProxy.InterfaceTwo two;
    };

    public void testDynamicProxy() {
        assertBothWays(SampleDynamicProxy.newInstance(), ""
                + "<dynamic-proxy>\n"
                + "  <interface>com.thoughtworks.acceptance.objects.SampleDynamicProxy$InterfaceOne</interface>\n"
                + "  <interface>com.thoughtworks.acceptance.objects.SampleDynamicProxy$InterfaceTwo</interface>\n"
                + "  <handler class=\"com.thoughtworks.acceptance.objects.SampleDynamicProxy\">\n"
                + "    <aField>hello</aField>\n"
                + "  </handler>\n"
                + "</dynamic-proxy>");
    }

    public void TODOtestDynamicProxyAsFieldMember() {
        ClassWithProxyMember expected = new ClassWithProxyMember();
        expected.one = (SampleDynamicProxy.InterfaceOne)SampleDynamicProxy.newInstance();
        expected.two = (SampleDynamicProxy.InterfaceTwo)expected.one;
        xstream.alias("with-proxy", ClassWithProxyMember.class);
        assertBothWays(expected, ""
                + "<with-proxy>\n"
                + "  <one class=\"dynamic-proxy\">\n"
                + "    <interface>com.thoughtworks.acceptance.objects.SampleDynamicProxy$InterfaceOne</interface>\n"
                + "    <interface>com.thoughtworks.acceptance.objects.SampleDynamicProxy$InterfaceTwo</interface>\n"
                + "    <handler class=\"com.thoughtworks.acceptance.objects.SampleDynamicProxy\">\n"
                + "      <aField>hello</aField>\n"
                + "    </handler>\n"
                + "  </one>\n"
                + "  <two class=\"dynamic-proxy\" reference=\"../one\"/>\n"
                + "</with-proxy>");
    }

}

Add test case for proxy bug.


package org.eobjects.build;

import java.io.File;
import java.util.Map;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Parameter;

public abstract class AbstractDotnetMojo extends AbstractMojo {

    @Parameter(defaultValue = PluginHelper.PROPERTY_BASEDIR, readonly = true)
    private File basedir;

    @Parameter(property = "environment", required = false)
    private Map<String, String> environment;

    @Parameter(required = false, defaultValue = "false")
    private boolean skip;

    @Parameter(property = "dotnet.pack.output", required = false)
    private File packOutput;

    @Parameter(property = "dotnet.configuration", required = false, defaultValue = "Release")
    private String buildConfiguration;

    @Parameter(property = "dotnet.build.framework", required = false, defaultValue = "")
    private String buildTargetFramework;

    public PluginHelper getPluginHelper() {
        return PluginHelper.get(getLog(), basedir, environment, packOutput, buildConfiguration, buildTargetFramework, skip);
    }
}

package org.eobjects.build;

import java.io.File;
import java.util.Map;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Parameter;

public abstract class AbstractDotnetMojo extends AbstractMojo {

    @Parameter(defaultValue = PluginHelper.PROPERTY_BASEDIR, readonly = true)
    private File basedir;

    @Parameter(property = "environment", required = false)
    private Map<String, String> environment;

    @Parameter(required = false, defaultValue = "false")
    private boolean skip;

    @Parameter(property = "dotnet.pack.output", required = false)
    private File packOutput;

    @Parameter(property = "dotnet.configuration", required = false, defaultValue = "Release")
    private String buildConfiguration;

    @Parameter(property = PluginHelper.PROPERTY_TARGET_FRAMEWORK, required = false, defaultValue = "")
    private String buildTargetFramework;

    public PluginHelper getPluginHelper() {
        return PluginHelper.get(getLog(), basedir, environment, packOutput, buildConfiguration, buildTargetFramework, skip);
    }
}

Use central definition of property.


package gov.nasa.arc.mct.scenario;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class Activator implements BundleActivator {

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		// register the service
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
	}

}

package gov.nasa.arc.mct.scenario;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class Activator implements BundleActivator {

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		System.setProperty("mct.menu.this", "File");
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
	}

}

Change 'This' menu to 'File' (depends on platform recognition of System property 'mct.menu.this')


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

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.resources.properties.PackageProperties;

public class DpkgPackageManager implements IPackageManager {

	private PackageProperties properties;

	public DpkgPackageManager() {
		super();
	}

	public CommandResponse install() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public CommandResponse uninstall() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public String latest() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public void setPackageProperties(PackageProperties properties) {
		this.properties = properties;
	}

	public PackageProperties getPackageProperties() {
		return this.properties;
	}
}

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

import com.github.aureliano.achmed.command.CommandFacade;
import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.exception.PackageResourceException;
import com.github.aureliano.achmed.helper.StringHelper;
import com.github.aureliano.achmed.resources.properties.PackageProperties;

public class DpkgPackageManager implements IPackageManager {

	private static final String DPKG_QUERY = "/usr/bin/dpkg-query";
	private static final String QUERY_FORMAT = "'${status} ${version}\\n'";

	private PackageProperties properties;

	public DpkgPackageManager() {
		super();
	}

	public CommandResponse install() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public CommandResponse uninstall() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public String latest() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public boolean isInstalled() {
		final String desiredStatus = "installed";
		CommandResponse res = CommandFacade.executeCommand(
			DPKG_QUERY, "-W", "-f", QUERY_FORMAT, this.properties.getName()
		);

		if (!res.isOK()) {
			throw new PackageResourceException(res);
		}

		String[] match = StringHelper.match("^(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S*)$", res.getOutput());
		if (match == null) {
			throw new PackageResourceException("Failed to match dpkg-query " + res.getCommand());
		}

		return desiredStatus.equalsIgnoreCase(match[3]);
	}

	public void setPackageProperties(PackageProperties properties) {
		this.properties = properties;
	}

	public PackageProperties getPackageProperties() {
		return this.properties;
	}
}

Implement methodo to check wheter package is installed.


package me.williamhester.reddit.ui.activities;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;

import me.williamhester.reddit.R;
import me.williamhester.reddit.models.Submission;
import me.williamhester.reddit.ui.fragments.CommentsFragment;

/** Activity that holds basic content. */
public class ContentActivity extends BaseActivity {

  public static final String TYPE_EXTRA = "type";
  public static final String VOTABLE_EXTRA = "votable";
  public static final String PERMALINK_EXTRA = "permalink";

  public static final String COMMENTS = "comments";

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

    Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
    if (f == null) {
      getSupportFragmentManager().beginTransaction()
          .add(R.id.fragment_container, createContentFragment())
          .commit();
    }

    SharedPreferences prefs = getSharedPreferences("default", MODE_PRIVATE);
    prefs.edit().putBoolean("test", true).apply();
  }

  @Override
  protected int getLayoutId() {
    return R.layout.activity_content;
  }

  protected Fragment createContentFragment() {
    Bundle args = getIntent().getExtras();
    String type = args.getString(TYPE_EXTRA);
    if (type == null) {
      return null;
    }
    switch (type) {
      case COMMENTS:
        String permalink = args.getString(PERMALINK_EXTRA);
        Submission s = args.getParcelable(VOTABLE_EXTRA);
        return CommentsFragment.newInstance(permalink, s);
      default:
        return null;
    }
  }
}

package me.williamhester.reddit.ui.activities;

import android.os.Bundle;
import android.support.v4.app.Fragment;

import me.williamhester.reddit.R;
import me.williamhester.reddit.models.Submission;
import me.williamhester.reddit.ui.fragments.CommentsFragment;

/** Activity that holds basic content. */
public class ContentActivity extends BaseActivity {

  public static final String TYPE_EXTRA = "type";
  public static final String VOTABLE_EXTRA = "votable";
  public static final String PERMALINK_EXTRA = "permalink";

  public static final String COMMENTS = "comments";

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

    Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
    if (f == null) {
      getSupportFragmentManager().beginTransaction()
          .add(R.id.fragment_container, createContentFragment())
          .commit();
    }
  }

  @Override
  protected int getLayoutId() {
    return R.layout.activity_content;
  }

  protected Fragment createContentFragment() {
    Bundle args = getIntent().getExtras();
    String type = args.getString(TYPE_EXTRA);
    if (type == null) {
      return null;
    }
    switch (type) {
      case COMMENTS:
        String permalink = args.getString(PERMALINK_EXTRA);
        Submission s = args.getParcelable(VOTABLE_EXTRA);
        return CommentsFragment.newInstance(permalink, s);
      default:
        return null;
    }
  }
}

Remove accidentally committed test code


package br.com.bloder.blormlib.validation.validations;

import android.widget.EditText;

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

/**
 * Created by bloder on 05/06/16.
 */
public class Filled extends Validation {

  public EditText editText;

  @Override
  public Validate validate() {
    return new Validate() {
      @Override
      public boolean validate() {
        editText = (EditText) field;
        return !String.valueOf(editText.getText()).trim().isEmpty();
      }

      @Override
      public void onError() {
        editText.setError(errorMessage != null && !errorMessage.isEmpty() ? errorMessage : "This field can't be blank");
      }

      @Override public void onSuccess() {
        editText.setError(null);
      }
    };
  }
}

package br.com.bloder.blormlib.validation.validations;

import android.widget.EditText;

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

/**
 * Created by bloder on 05/06/16.
 */
public class Filled extends Validation {

  public EditText editText;
  private int maxSize = -1;
  private int minSize = -1;

  public Filled withMaxSize(int maxSize) {
    this.maxSize = maxSize;
    return this;
  }

  public Filed withMinimumSize(int minSize) {
    this.minSize = minSize;
    return this;
  }

  @Override public Validate validate() {
    return new Validate() {
      @Override public boolean validate() {
        editText = (EditText) field;
        String text = String.valueOf(editText.getText()).trim();
        int textLength = text.length();
        if (!text.isEmpty()) {
          if (maxSize != -1) {
            if (textLength > maxSize) {
              return false;
            }
          }
          if (minSize != -1) {
            if (textLength < minSize) {
              return false;
            }
          }
          return true;
        }
        return false;
      }

      @Override
      public void onError() {
        editText.setError(errorMessage != null && !errorMessage.isEmpty() ? errorMessage : "This field can't be blank");
      }

      @Override public void onSuccess() {
        editText.setError(null);
      }
    };
  }
}

Update with min max for text input validation


package org.robockets.stronghold.robot.commands;

import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.networktables.NetworkTable;

/**
 *
 */
public class MeasureLatency extends Command {

	NetworkTable table;
	double starttime;
	int i = 0;

    public MeasureLatency() {
    }

    protected void initialize() {
    	table = NetworkTable.getTable("vision");
    	starttime = System.nanoTime();
    }

    protected void execute() {
    	if(table.getNumber("heartbeat", 0)==1){
    		System.out.println("i," + (System.nanoTime() - starttime));
    		starttime = System.nanoTime();
    		table.putNumber("heartbeat", 0);
    	}
    }

    protected boolean isFinished() {
        return false;
    }

    protected void end() {
    }

    protected void interrupted() {
    }
}

package org.robockets.stronghold.robot.commands;

import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.networktables.NetworkTable;

/**
 *
 */
public class MeasureLatency extends Command {

	NetworkTable table;
	double starttime;
	int i = 0;

    public MeasureLatency() {
    }

    protected void initialize() {
    	table = NetworkTable.getTable("vision");
    	starttime = System.nanoTime();
    }

    protected void execute() {
    	if (table.getNumber("heartbeat", 0) == 1) {
    		System.out.println("i," + (System.nanoTime() - starttime));
    		starttime = System.nanoTime();
    		table.putNumber("heartbeat", 0);
    	}
    }

    protected boolean isFinished() {
        return false;
    }

    protected void end() {
    }

    protected void interrupted() {
    }
}

Add spaces to an if statement


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

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

/**
 * Base classes and interfaces for Spine Gradle plugins.
 *
 * @author Alex Tymchenko
 */

@ParametersAreNonnullByDefault
package io.spine.gradle;

import javax.annotation.ParametersAreNonnullByDefault;

Add a missing annotation for a package and fix structure of comments


package DataReader;

import DataModel.Attribute;
import DataModel.EntityProfile;
import DataReader.EntityReader.EntityCSVReader;
import java.util.List;

/**
 *
 * @author G.A.P. II
 */

public class TestEntityCSVReader {
    public static void main(String[] args) {
        String filePath = "C:\\Users\\G.A.P. II\\Downloads\\cd.csv";
        EntityCSVReader csvReader = new EntityCSVReader(filePath);
        csvReader.setAttributeNamesInFirstRow(true);
        csvReader.setSeparator(';');
        csvReader.setAttributesToExclude(new int[]{1});
        csvReader.setIdIndex(0);
        List<EntityProfile> profiles = csvReader.getEntityProfiles();
//        for (EntityProfile profile : profiles) {
//            System.out.println("\n\n" + profile.getEntityUrl());
//            for (Attribute attribute : profile.getAttributes()) {
//                System.out.println(attribute.toString());
//            }
//        }
        csvReader.storeSerializedObject(profiles, "C:\\Users\\G.A.P. II\\Downloads\\cddbProfiles");
    }
}

package DataReader;

import DataModel.Attribute;
import DataModel.EntityProfile;
import DataReader.EntityReader.EntityCSVReader;
import java.util.List;

/**
 *
 * @author G.A.P. II
 */

public class TestEntityCSVReader {
    public static void main(String[] args) {
        String filePath = "C:/Users/Manos/workspaceMars/JedAIgitFinal/JedAIgitFinal/datasets/converter/DBLP2.csv";
        EntityCSVReader csvReader = new EntityCSVReader(filePath);
        csvReader.setAttributeNamesInFirstRow(true);
        csvReader.setSeparator(';');
        csvReader.setAttributesToExclude(new int[]{1});
        csvReader.setIdIndex(0);
        List<EntityProfile> profiles = csvReader.getEntityProfiles();
        for (EntityProfile profile : profiles) {
            System.out.println("\n\n" + profile.getEntityUrl());
            for (Attribute attribute : profile.getAttributes()) {
                System.out.println(attribute.toString());
            }
        }
        csvReader.storeSerializedObject(profiles, "C:/Users/Manos/workspaceMars/JedAIgitFinal/JedAIgitFinal/datasets/converter/DBLP2prof");
        csvReader.convertToRDFfile(profiles, "C:/Users/Manos/workspaceMars/JedAIgitFinal/JedAIgitFinal/datasets/converter/DBLP2toRDFxml.xml");

    }
}

Update Test for csv to RDF converter


package com.xamoom.android.mapping;

import com.google.gson.annotations.SerializedName;
import com.xamoom.android.APICallback;
import com.xamoom.android.mapping.ContentBlocks.MenuItem;

import java.util.List;

/**
 * Used for mapping menu responses from the xamoom-cloud-api.
 * Menu will have only a list of MenuItems.
 *
 * @author Raphael Seher
 *
 * @see MenuItem
 * @see com.xamoom.android.XamoomEndUserApi#getContentbyIdFull(String, boolean, boolean, String, boolean, APICallback)
 * @see com.xamoom.android.XamoomEndUserApi#getContentByLocationIdentifier(String, String, boolean, boolean, String, APICallback)
 */
public class Menu {

    private List<MenuItem> items;

    @Override
    public String toString() {
        String output = "items: ";

        for (MenuItem item : items) {
            output += item.toString();
        }

        return output;
    }

    public List<MenuItem> getItems() {
        return items;
    }
}

package com.xamoom.android.mapping;

import com.xamoom.android.APICallback;

import java.util.List;

/**
 * Used for mapping menu responses from the xamoom-cloud-api.
 * Menu will have only a list of MenuItems.
 *
 * @author Raphael Seher
 *
 * @see MenuItem
 * @see com.xamoom.android.XamoomEndUserApi#getContentbyId(String, boolean, boolean, String, boolean, boolean, APICallback)
 * @see com.xamoom.android.XamoomEndUserApi#getContentByLocationIdentifier(String, String, boolean, boolean, String, APICallback)
 */
public class Menu {

    private List<MenuItem> items;

    @Override
    public String toString() {
        String output = "items: ";

        for (MenuItem item : items) {
            output += item.toString();
        }

        return output;
    }

    public List<MenuItem> getItems() {
        return items;
    }
}

Change category from String to int


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

package android.support.v4.view;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.view.PointerIcon;

class PointerIconCompatApi24 {
    public static Object getSystemIcon(Context context, int style) {
        return PointerIcon.getSystemIcon(context, style);
    }

    public static Object createCustomIcon(Bitmap bitmap, float hotSpotX, float hotSpotY) {
        return PointerIcon.createCustomIcon(bitmap, hotSpotX, hotSpotY);
    }

    public static Object loadCustomIcon(Resources resources, int resourceId) {
        return PointerIcon.loadCustomIcon(resources, resourceId);
    }
}

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

package android.support.v4.view;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.view.PointerIcon;

class PointerIconCompatApi24 {
    public static Object getSystemIcon(Context context, int style) {
        return PointerIcon.getSystemIcon(context, style);
    }

    public static Object createCustomIcon(Bitmap bitmap, float hotSpotX, float hotSpotY) {
        return null;
    }

    public static Object loadCustomIcon(Resources resources, int resourceId) {
        return null;
    }
}

Remove references to framework PointerIcon API.


package org.wikipedia.page.gallery;

import android.support.v4.view.ViewPager;
import android.view.View;

public class GalleryPagerTransformer implements ViewPager.PageTransformer {
    private static final float MIN_SCALE = 0.5f;
    private static final float ROTATION_DEGREES = 30.0f;

    @Override
    public void transformPage(View view, float position) {
        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
        } else if (position <= 0) { // [-1,0]
            float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position));
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);
            // fade out
            view.setAlpha(1 + position);
            // give it a bit of a rotation
            view.setRotationY(-position * ROTATION_DEGREES);
        } else if (position <= 1) { // (0,1]
            float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position));
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);
            // fade out
            view.setAlpha(1 - position);
            // give it a bit of a rotation
            view.setRotationY(-position * ROTATION_DEGREES);
        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
        }
    }
}

package org.wikipedia.page.gallery;

import android.support.v4.view.ViewPager;
import android.view.View;

public class GalleryPagerTransformer implements ViewPager.PageTransformer {
    private static final float MIN_SCALE = 0.9f;

    @Override
    public void transformPage(View view, float position) {
        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setTranslationX(0);
        } else if (position <= 0) { // [-1,0]
            float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position));
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);
            // fade out
            view.setAlpha(1 + position);
            // keep it in place (undo the default translation)
            view.setTranslationX(-(view.getWidth() * position));
        } else if (position <= 1) { // (0,1]
            // don't do anything to it when it's sliding in.
        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setTranslationX(0);
        }
    }
}

Improve transition between gallery images.


package com.forerunnergames.tools.common;

public final class DefaultMessage implements Message
{
  private final String text;

  public DefaultMessage (final String text)
  {
    Arguments.checkIsNotNull (text, "text");

    this.text = text;
  }

  // Required for network serialization
  protected DefaultMessage ()
  {
    text = null;
  }

  @Override
  public String getText ()
  {
    return text;
  }

  @Override
  public String toString ()
  {
    return String.format ("%1$s: Text: %2$s", getClass ().getSimpleName (), text);
  }
}

package com.forerunnergames.tools.common;

public final class DefaultMessage implements Message
{
  private final String text;

  public DefaultMessage (final String text)
  {
    Arguments.checkIsNotNull (text, "text");

    this.text = text;
  }

  protected DefaultMessage ()
  {
    text = null;
  }

  @Override
  public String getText ()
  {
    return text;
  }

  @Override
  public String toString ()
  {
    return String.format ("%1$s: Text: %2$s", getClass ().getSimpleName (), text);
  }
}

Remove "Required for network serialization".


package com.marcosbarbero.zuul.filters.pre.ratelimit.config.redis;

import com.marcosbarbero.zuul.filters.pre.ratelimit.config.Policy;
import com.marcosbarbero.zuul.filters.pre.ratelimit.config.Rate;
import com.marcosbarbero.zuul.filters.pre.ratelimit.config.RateLimiter;

import org.springframework.data.redis.core.RedisTemplate;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @author Marcos Barbero
 */
public class RedisRateLimiter implements RateLimiter {
    private RedisTemplate template;

    public RedisRateLimiter(RedisTemplate template) {
        this.template = template;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Rate consume(final Policy policy, final String key) {
        final Long limit = policy.getLimit();
        final Long refreshInterval = policy.getRefreshInterval();
        final Long current = this.template.boundValueOps(key).increment(1L);
        Long expire = this.template.getExpire(key);
        if (expire == null || expire == -1) {
            this.template.expire(key, refreshInterval, SECONDS);
            expire = refreshInterval;
        }
        return new Rate(limit, Math.max(-1, limit - current), SECONDS.toMillis(expire));
    }
}

package com.marcosbarbero.zuul.filters.pre.ratelimit.config.redis;

import com.marcosbarbero.zuul.filters.pre.ratelimit.config.Policy;
import com.marcosbarbero.zuul.filters.pre.ratelimit.config.Rate;
import com.marcosbarbero.zuul.filters.pre.ratelimit.config.RateLimiter;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @author Marcos Barbero
 */
public class RedisRateLimiter implements RateLimiter {
    private final RedisTemplate template;

    public RedisRateLimiter(final RedisTemplate template) {
        Assert.notNull(template, "RedisTemplate cannot be null");
        this.template = template;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Rate consume(final Policy policy, final String key) {
        final Long limit = policy.getLimit();
        final Long refreshInterval = policy.getRefreshInterval();
        final Long current = this.template.boundValueOps(key).increment(1L);
        Long expire = this.template.getExpire(key);
        if (expire == null || expire == -1) {
            this.template.expire(key, refreshInterval, SECONDS);
            expire = refreshInterval;
        }
        return new Rate(limit, Math.max(-1, limit - current), SECONDS.toMillis(expire));
    }
}

Make RedisTemplate final and validate not null construction


// Copyright 2018 Yahoo Holdings. 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.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;

import java.time.Duration;

/**
 * Removes inactive sessions
 * <p>
 * Note: Unit test is in ApplicationRepositoryTest
 *
 * @author hmusum
 */
public class SessionsMaintainer extends ConfigServerMaintainer {
    private final boolean hostedVespa;

    SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
        // Start this maintainer immediately. It frees disk space, so if disk goes full and config server
        // restarts this makes sure that cleanup will happen as early as possible
        super(applicationRepository, curator, Duration.ZERO, interval);
        this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
    }

    @Override
    protected void maintain() {
        applicationRepository.deleteExpiredLocalSessions();

        // Expired remote sessions are not expected to exist, they should have been deleted when
        // a deployment happened or when the application was deleted. We still see them from time to time,
        // probably due to some race or another bug
        if (hostedVespa) {
            Duration expiryTime = Duration.ofDays(30);
            applicationRepository.deleteExpiredRemoteSessions(expiryTime);
        }
    }
}

// Copyright 2018 Yahoo Holdings. 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.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;

import java.time.Duration;

/**
 * Removes inactive sessions
 * <p>
 * Note: Unit test is in ApplicationRepositoryTest
 *
 * @author hmusum
 */
public class SessionsMaintainer extends ConfigServerMaintainer {
    private final boolean hostedVespa;

    SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
        // Start this maintainer immediately. It frees disk space, so if disk goes full and config server
        // restarts this makes sure that cleanup will happen as early as possible
        super(applicationRepository, curator, Duration.ZERO, interval);
        this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
    }

    @Override
    protected void maintain() {
        applicationRepository.deleteExpiredLocalSessions();

        // Expired remote sessions are sessions that belong to an application that have external deployments that
        // are no longer active
        if (hostedVespa) {
            Duration expiryTime = Duration.ofDays(7);
            applicationRepository.deleteExpiredRemoteSessions(expiryTime);
        }
    }
}

Revert "Revert "Reduce the time we keep expired remotes sessions and fix comment""


package net.openhft.chronicle.wire;

import net.openhft.chronicle.bytes.NativeBytes;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

public class LongArrayDirectReferenceTest {

    @Test
    public void getSetValues() throws Exception {
        int length = 1024 + 8;
        try (NativeBytes bytes = NativeBytes.nativeBytes(length + 8)) {
            LongArrayDirectReference.write(bytes, 128);

            LongArrayDirectReference array = new LongArrayDirectReference();
            array.bytesStore(bytes, 0, length);

            assertEquals(128, array.getCapacity());
            for (int i = 0; i < 128; i++)
                array.setValueAt(i, i + 1);

            for (int i = 0; i < 128; i++)
                assertEquals(i + 1, array.getValueAt(i));
        }
    }

}

package net.openhft.chronicle.wire;

import net.openhft.chronicle.bytes.NativeBytes;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class LongArrayDirectReferenceTest {

    @Test
    public void getSetValues() {
        int length = 1024 + 8;
        try (NativeBytes bytes = NativeBytes.nativeBytes(length + 8)) {
            LongArrayDirectReference.write(bytes, 128);

            LongArrayDirectReference array = new LongArrayDirectReference();
            array.bytesStore(bytes, 0, length);

            assertEquals(128, array.getCapacity());
            for (int i = 0; i < 128; i++)
                array.setValueAt(i, i + 1);

            for (int i = 0; i < 128; i++)
                assertEquals(i + 1, array.getValueAt(i));
        }
    }

}

Remove "throws IOException" when "close()" doesn't actually throw it.


package uk.ac.ebi.quickgo.rest.search.filter;

import com.google.common.base.Preconditions;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * Data structure that holds the field name and values of a filter requested by a REST service endpoint.
 *
 * @author Tony Wardell
 * Date: 03/05/2016
 * Time: 10:25
 */
public class RequestFilter {
    private String field;
    private String[] values;

    public RequestFilter(String field, String... values) {
        Preconditions.checkArgument(field != null && !field.trim().isEmpty(), "Filter field cannot be null or empty");
        Preconditions.checkArgument(values != null && values.length > 0, "Filter values cannot be null or empty");

        this.field = field;
        this.values = values;
    }

    /**
     * Provides the field (column) the filter will be applied to.
     *
     * @return the field
     */
    public String getField() {
        return field;
    }

    /**
     * Provides the field (column) the filter will be applied to.
     *
     * @return the field
     */
    public Stream<String> getValues() {
        return Arrays.stream(values);
    }
}

package uk.ac.ebi.quickgo.rest.search.filter;

import com.google.common.base.Preconditions;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * Data structure that holds the field name and values of a filter requested by a REST service endpoint.
 *
 * @author Tony Wardell
 * Date: 03/05/2016
 * Time: 10:25
 */
public class RequestFilter {
    private final String field;
    private final String[] values;

    public RequestFilter(String field, String... values) {
        Preconditions.checkArgument(field != null && !field.trim().isEmpty(), "Filter field cannot be null or empty");
        Preconditions.checkArgument(values != null && values.length > 0, "Filter values cannot be null or empty");

        this.field = field;
        this.values = values;
    }

    /**
     * Provides the field (column) the filter will be applied to.
     *
     * @return the field
     */
    public String getField() {
        return field;
    }

    /**
     * Provides the field (column) the filter will be applied to.
     *
     * @return the field
     */
    public Stream<String> getValues() {
        return Arrays.stream(values);
    }
}

Make state variables final, seeing as these are initialized in the constructor.


package fr.alecharp.picshare.http;

import fr.alecharp.picshare.domain.Event;
import fr.alecharp.picshare.service.EventService;
import net.codestory.http.annotations.Post;
import net.codestory.http.annotations.Prefix;
import net.codestory.http.payload.Payload;

import javax.inject.Inject;
import java.util.Optional;

/**
 * @author Adrien Lecharpentier
 */
@Prefix("/api/event")
public class EventController {
    private final EventService eventService;

    @Inject
    public EventController(EventService eventService) {
        this.eventService = eventService;
    }

    @Post
    public Payload create(Event event) {
        Optional<Event> save = eventService.save(event);
        return save.isPresent() ? Payload.created("/api/event/" + save.get().id()) :
                Payload.badRequest();
    }
}

package fr.alecharp.picshare.http;

import fr.alecharp.picshare.domain.Event;
import fr.alecharp.picshare.domain.Picture;
import fr.alecharp.picshare.service.EventService;
import fr.alecharp.picshare.service.PictureService;
import net.codestory.http.Request;
import net.codestory.http.annotations.Post;
import net.codestory.http.annotations.Prefix;
import net.codestory.http.annotations.Put;
import net.codestory.http.payload.Payload;

import javax.inject.Inject;
import java.util.Optional;
import java.util.Set;

import static java.util.stream.Collectors.toSet;

/**
 * @author Adrien Lecharpentier
 */
@Prefix("/api/event")
public class EventController {
    private final EventService eventService;
    private final PictureService pictureService;

    @Inject
    public EventController(EventService eventService, PictureService pictureService) {
        this.eventService = eventService;
        this.pictureService = pictureService;
    }

    @Post
    public Payload create(Event event) {
        Optional<Event> save = eventService.save(event);
        return save.isPresent() ? Payload.created("/api/event/" + save.get().id()) :
                Payload.badRequest();
    }

    @Put("/:id/pictures")
    public Payload attachPicture(String id, Request req) {
        Set<Picture> pictures = req.parts().stream()
                .filter(part -> part.name().equals("picture"))
                .map(part -> pictureService.upload(id, part))
                .filter(Optional::isPresent).map(Optional::get)
                .collect(toSet());
        Optional<Event> event = eventService.attachPictures(id, pictures);
        if (!event.isPresent()) {
            return Payload.notFound();
        }
        return Payload.ok().withHeader("Location", "/api/event/" + event.get().id());
    }
}

Update even HTTP API to upload images into events


package com.github.legioth.propertysource.rebind;

import com.google.gwt.user.rebind.StringSourceWriter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class StringTypeHandlerTest
{
  @DataProvider( name = "writeValues" )
  public Object[][] actionDescriptions()
  {
    return new Object[][]{
      new Object[]{ "hi", "\"hi\"" },
      new Object[]{ "1\n2", "\"1\\n2\"" },
      new Object[]{ "&", "\"&\"" },
      new Object[]{ "Å", "\"Å\"" },
    };
  }

  @Test( dataProvider = "writeValues" )
  public void writeValues( final String input, final String output )
  {
    final StringSourceWriter writer = new StringSourceWriter();
    StringTypeHandler.INSTANCE.writeValue( null, writer, input );
    assertEquals( writer.toString(), output );
  }
}

package com.github.legioth.propertysource.rebind;

import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.user.rebind.StringSourceWriter;
import java.util.Arrays;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;

public class StringTypeHandlerTest
{
  @DataProvider( name = "writeValues" )
  public Object[][] actionDescriptions()
  {
    return new Object[][]{
      new Object[]{ "hi", "\"hi\"" },
      new Object[]{ "1\n2", "\"1\\n2\"" },
      new Object[]{ "&", "\"&\"" },
      new Object[]{ "Å", "\"Å\"" },
    };
  }

  @Test( dataProvider = "writeValues" )
  public void writeValues( final String input, final String output )
  {
    final StringSourceWriter writer = new StringSourceWriter();
    StringTypeHandler.INSTANCE.writeValue( null, writer, input );
    assertEquals( writer.toString(), output );
  }

  @Test
  public void getStaticReturnValue()
    throws Exception
  {
    final String result =
      StringTypeHandler.INSTANCE.getStaticReturnValue( mock( TreeLogger.class ),
                                                       Arrays.asList( "A" ),
                                                       mock( JMethod.class ) );

    assertEquals( result, "A" );
  }

  @Test
  public void getStaticReturnValue_whenMultipleValues()
    throws Exception
  {
      final TreeLogger logger = mock( TreeLogger.class );
    try
    {
      StringTypeHandler.INSTANCE.getStaticReturnValue( logger,
                                                       Arrays.asList( "A", "B" ),
                                                       mock( JMethod.class ) );
      fail( "Should have raised an exception" );
    }
    catch ( final UnableToCompleteException utce )
    {
      verify( logger ).log( Type.ERROR, "String only supported for properties with only one value" );
    }
  }
}

Add some more basic tests


package de.pentasys.SilverPen.util.test;

import javax.mail.MessagingException;

import org.junit.BeforeClass;
import org.junit.Test;

import de.pentasys.SilverPen.util.Email;

public class EmailTest {
    private static String mailHost = "172.30.2.29";
    private static Email email;

    @BeforeClass
    public static void setUp() throws Exception {
                email = new Email(mailHost, 25, "root", "SilverPen2016");
    }

    @Test
    public void testSendRegistrationConfirmationMail() {
        try {
            email.sendRegistrationConfirmationMail("test", "tobias.johannes.endres@pentasys.de");
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

package de.pentasys.SilverPen.util.test;

import javax.mail.MessagingException;

import org.junit.BeforeClass;
import org.junit.Test;

import de.pentasys.SilverPen.util.Email;

public class EmailTest {
    private static String mailHost = "127.0.0.1";
    private static Email email;

    @BeforeClass
    public static void setUp() throws Exception {
                email = new Email(mailHost, 25, "root", "SilverPen2016");
    }

    @Test
    public void testSendRegistrationConfirmationMail() {
        try {
            email.sendRegistrationConfirmationMail("JUnit-TestMail", "thomas.bankiel@pentasys.de");
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Test für den Email-Versand angepasst


package org.stagemonitor.eum;

import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.stagemonitor.core.Stagemonitor;

@SpringBootApplication
public class EumApplication extends SpringBootServletInitializer {

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		return configureApplication(builder);
	}

	public static void main(String[] args) {
		configureApplication(new SpringApplicationBuilder()).run(args);
	}

	private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) {
		Stagemonitor.init();
		return builder.sources(EumApplication.class).bannerMode(Banner.Mode.OFF);
	}

}

package org.stagemonitor.eum;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.stagemonitor.core.Stagemonitor;

@SpringBootApplication
public class EumApplication extends SpringBootServletInitializer {

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		return configureApplication(builder);
	}

	public static void main(String[] args) {
		configureApplication(new SpringApplicationBuilder()).run(args);
	}

	private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) {
		Stagemonitor.init();
		return builder.sources(EumApplication.class);
	}

}

Enable banner for eum server


package org.buddycloud.channelserver.channel.node.configuration.field;

public class Affiliation extends Field
{
	public static final String FIELD_NAME    = "pubsub#default_affiliation";
	public static final String DEFAULT_VALUE = Affiliation.models.MEMBER.toString();

	public enum models {
		FOLLOWER_AND_POST("publisher"), MEMBER("follower");
		String model = null;
		private models(String model) {
			this.model = model;
		}
		public String toString() {
	        return model;
	    }
	}

	public Affiliation()
	{
		name = FIELD_NAME;
	}

	public boolean isValid()
	{
		return (getValue().equals(Affiliation.models.FOLLOWER_AND_POST.toString())
			|| getValue().equals(Affiliation.models.MEMBER.toString())
		);
	}
}

package org.buddycloud.channelserver.channel.node.configuration.field;

public class Affiliation extends Field {
	public static final String FIELD_NAME = "pubsub#default_affiliation";
	public static final String DEFAULT_VALUE = Affiliation.models.MEMBER
			.toString();

	public enum models {
		FOLLOWER_AND_POST("publisher"), MEMBER("follower"), OWNER("owner"), MODERATOR(
				"moderator");
		String model = null;

		private models(String model) {
			this.model = model;
		}

		public String toString() {
			return model;
		}
	}

	public Affiliation() {
		name = FIELD_NAME;
	}

	public boolean isValid() {
		return (getValue().equals(
				Affiliation.models.FOLLOWER_AND_POST.toString())
		    || getValue().equals(Affiliation.models.MEMBER.toString())
		    || getValue().equals(Affiliation.models.OWNER.toString())
		    || getValue().equals(Affiliation.models.MODERATOR.toString())
	    );
	}
}

Fix for default_affiliation valid values


package org.jetbrains.kotlin.core;

import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace;

import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.jetbrains.kotlin.core.builder.ResourceChangeListener;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class Activator implements BundleActivator {
	private static BundleContext context;

	private final IResourceChangeListener resourceChangeListener = new ResourceChangeListener();

	public static final String PLUGIN_ID = "org.jetbrains.kotlin.core";

	static BundleContext getContext() {
		return context;
	}

	@Override
    public void start(BundleContext bundleContext) throws Exception {
		Activator.context = bundleContext;

		getWorkspace().addResourceChangeListener(resourceChangeListener, IResourceChangeEvent.POST_CHANGE);
	}

	@Override
    public void stop(BundleContext bundleContext) throws Exception {
		Activator.context = null;

		getWorkspace().removeResourceChangeListener(resourceChangeListener);
	}
}

package org.jetbrains.kotlin.core;

import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace;

import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.Plugin;
import org.jetbrains.kotlin.core.builder.ResourceChangeListener;
import org.osgi.framework.BundleContext;

public class Activator extends Plugin {

	private static Activator plugin;

	private final IResourceChangeListener resourceChangeListener = new ResourceChangeListener();

	public static final String PLUGIN_ID = "org.jetbrains.kotlin.core";

	public Activator() {
	    plugin = this;
	}

	public static Activator getDefault() {
		return plugin;
	}

	@Override
    public void start(BundleContext bundleContext) throws Exception {
		getWorkspace().addResourceChangeListener(resourceChangeListener, IResourceChangeEvent.POST_CHANGE);

		super.start(bundleContext);
	}

	@Override
    public void stop(BundleContext bundleContext) throws Exception {
		getWorkspace().removeResourceChangeListener(resourceChangeListener);

		plugin = null;
	}
}

Make core activator extendable of Plugin class


/**
 * Copyright (C) 2014 android10.org. All rights reserved.
 * @author Fernando Cejas (the android10 coder)
 */
package com.fernandocejas.android10.rx.sample;

import java.util.Random;

public class RandomStringGenerator {

  private static final int DEFAULT_STRING_LENGHT = 10;
  private static final char[] symbols;

  static {
    StringBuilder tmpSymbols = new StringBuilder();
    for (char ch = 'a'; ch <= 'z'; ch++) {
      tmpSymbols.append(ch);
    }
    symbols = tmpSymbols.toString().toCharArray();
  }

  private final int stringLenght;
  private final char[] charArray;
  private final Random random;

  public RandomStringGenerator() {
    this(DEFAULT_STRING_LENGHT);
  }

  public RandomStringGenerator(int stringLength) {
    this.stringLenght = stringLength;
    this.charArray = new char[this.stringLenght];
    this.random = new Random();
  }

  public String nextString() {
    for (int i = 0; i < charArray.length; i++) {
      charArray[i] = symbols[random.nextInt(symbols.length)];
    }
    return String.valueOf(charArray);
  }
}

/**
 * Copyright (C) 2014 android10.org. All rights reserved.
 * @author Fernando Cejas (the android10 coder)
 */
package com.fernandocejas.android10.rx.sample;

import java.util.Random;

public class RandomStringGenerator {

  private static final int DEFAULT_STRING_LENGHT = 12;
  private static final char[] symbols;

  static {
    StringBuilder tmpSymbols = new StringBuilder();
    for (char numberChar = '0'; numberChar <= '9'; numberChar++) {
      tmpSymbols.append(numberChar);
    }
    for (char letterChar = 'a'; letterChar <= 'z'; letterChar++) {
      tmpSymbols.append(letterChar);
    }
    symbols = tmpSymbols.toString().toCharArray();
  }

  private final int stringLenght;
  private final char[] charArray;
  private final Random random;

  public RandomStringGenerator() {
    this(DEFAULT_STRING_LENGHT);
  }

  public RandomStringGenerator(int stringLength) {
    this.stringLenght = stringLength;
    this.charArray = new char[this.stringLenght];
    this.random = new Random();
  }

  public String nextString() {
    for (int i = 0; i < charArray.length; i++) {
      charArray[i] = symbols[random.nextInt(symbols.length)];
    }
    return String.valueOf(charArray);
  }
}

Add numeric char to random string generator.


package co.phoenixlab.common.lang;

import java.util.ListIterator;

/**
 * Provides a reversed view of a ListIterator, starting from the last element.
 * @param <E>
 */
public class ReverseListIterator<E> implements ListIterator<E> {

    private final ListIterator<E> parent;

    public ReverseListIterator(ListIterator<E> parent) {
        this.parent = parent;
        //  Wind the iterator to the end
        while (parent.hasNext()) {
            parent.next();
        }
    }

    @Override
    public boolean hasNext() {
        return parent.hasPrevious();
    }

    @Override
    public E next() {
        return parent.previous();
    }

    @Override
    public boolean hasPrevious() {
        return parent.hasNext();
    }

    @Override
    public E previous() {
        return parent.next();
    }

    @Override
    public int nextIndex() {
        return parent.previousIndex();
    }

    @Override
    public int previousIndex() {
        return parent.nextIndex();
    }

    @Override
    public void remove() {
        parent.remove();
    }

    @Override
    public void set(E e) {
        parent.set(e);
    }

    @Override
    public void add(E e) {
        parent.add(e);
    }
}

package co.phoenixlab.common.lang;

import java.util.Iterator;
import java.util.ListIterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;

/**
 * Provides a reversed view of a ListIterator, starting from the last element.
 * @param <E>
 */
public class ReverseListIterator<E> implements ListIterator<E>, Iterable<E> {

    private final ListIterator<E> parent;

    public ReverseListIterator(ListIterator<E> parent) {
        this.parent = parent;
        //  Wind the iterator to the end
        while (parent.hasNext()) {
            parent.next();
        }
    }

    @Override
    public boolean hasNext() {
        return parent.hasPrevious();
    }

    @Override
    public E next() {
        return parent.previous();
    }

    @Override
    public boolean hasPrevious() {
        return parent.hasNext();
    }

    @Override
    public E previous() {
        return parent.next();
    }

    @Override
    public int nextIndex() {
        return parent.previousIndex();
    }

    @Override
    public int previousIndex() {
        return parent.nextIndex();
    }

    @Override
    public void remove() {
        parent.remove();
    }

    @Override
    public void set(E e) {
        parent.set(e);
    }

    @Override
    public void add(E e) {
        parent.add(e);
    }

    @Override
    public Iterator<E> iterator() {
        return this;
    }

    @Override
    public void forEach(Consumer<? super E> action) {
        while (hasNext()) {
            action.accept(next());
        }
    }

    @Override
    public Spliterator<E> spliterator() {
        return Spliterators.spliteratorUnknownSize(this, 0);
    }
}

Implement iterable for use in efor loops