// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.buildtool.buildevent;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.buildtool.ExecutionTool;

import java.util.Collection;

/**
 * This event is fired from {@link ExecutionTool#executeBuild} to indicate that the execution phase
 * of the build is starting.
 */
public class ExecutionStartingEvent {
  private final Collection<TransitiveInfoCollection> targets;

  /**
   * Construct the event with a set of targets.
   * @param targets Remaining active targets.
   */
  public ExecutionStartingEvent(Collection<? extends TransitiveInfoCollection> targets) {
    this.targets = ImmutableList.copyOf(targets);
  }

  /**
   * @return The set of active targets remaining, which is a subset
   *     of the targets in the user request.
   */
  public Collection<TransitiveInfoCollection> getTargets() {
    return targets;
  }
}

// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.buildtool.buildevent;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import java.util.Collection;

/**
 * This event is fired from {@link com.google.devtools.build.lib.buildtool.ExecutionTool} to
 * indicate that the execution phase of the build is starting.
 */
public class ExecutionStartingEvent {
  private final Collection<TransitiveInfoCollection> targets;

  /**
   * Construct the event with a set of targets.
   * @param targets Remaining active targets.
   */
  public ExecutionStartingEvent(Collection<? extends TransitiveInfoCollection> targets) {
    this.targets = ImmutableList.copyOf(targets);
  }

  /**
   * @return The set of active targets remaining, which is a subset
   *     of the targets in the user request.
   */
  public Collection<TransitiveInfoCollection> getTargets() {
    return targets;
  }
}

Remove dependency on ExecutionTool to break a build cycle.

PiperOrigin-RevId: 304627771


import java.util.List;

/**
 * Created by nate on 4/10/16.
 */
public class Game extends Model {
    public int id;
    public String name;
    public float price;

    public List<Category> categories() {
        return null;
    }

    public List<Review> reviews() {
        return null;
    }
}

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by nate on 4/10/16.
 */
public class Game extends Model {
    public int id;
    public String name;
    public float price;

    public List<Category> categories() {
        try {
            List<Category> categories = new ArrayList<Category>();
            Category cat;

            PreparedStatement s = c.prepareStatement(
                    "SELECT id, name from game_category join category on id=category_id where game_id=?"
            );
            s.setInt(1, id);

            ResultSet rs = s.executeQuery();
            while (rs.next()) {
                cat = new Category();
                cat.id = rs.getInt("id");
                cat.name = rs.getString("name");

                categories.add(cat);
            }

            return categories;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<Review> reviews() {
        try {
            List<Review> reviews = new ArrayList<>();
            UserReview ur;
            CriticReview cr;
            User u;

            PreparedStatement s = c.prepareStatement(
                    "SELECT rating, text, real_name, profile_name, credit_card, level, phone, user.id" +
                            "from user_review" +
                            "join user on user.id=user_review.user_id" +
                            "where game_id=?"
            );
            s.setInt(1, id);

            ResultSet rs = s.executeQuery();
            while (rs.next()) {
                ur = new UserReview();
                ur.rating = rs.getInt("id");
                ur.text = rs.getString("text");
                ur.game = this;

                u = new User();
                ur.user = u;
                u.realName = rs.getString("real_name");
                u.creditCard = rs.getString("credit_card");
                u.level = rs.getInt("level");
                u.phone = rs.getString("phone");
                u.id = rs.getInt("user.id");

                reviews.add(ur);
            }

            s = c.prepareStatement("SELECT rating, text, company, link from critic_review where game_id=?");
            s.setInt(1, id);

            rs = s.executeQuery();
            while (rs.next()) {
                cr = new CriticReview();

                cr.game = this;
                cr.company = rs.getString("company");
                cr.rating = rs.getFloat("rating");
                cr.link = rs.getString("link");

                reviews.add(cr);
            }

            return reviews;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Add query methods to game class

Add query methods to game class


package be.kuleuven.cs.distrinet.jnome.core.type;

import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.generics.FormalParameterType;
import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter;
import org.aikodi.chameleon.oo.type.generics.LazyFormalAlias;

public class JavaLazyFormalAlias extends LazyFormalAlias implements JavaType {

  public JavaLazyFormalAlias(String name, FormalTypeParameter param) {
    super(name, param);
  }

  @Override
  public Type erasure() {
    return this;
  }

  @Override
  public FormalParameterType cloneSelf() {
    return new JavaLazyFormalAlias(name(), parameter());
  }

}

package be.kuleuven.cs.distrinet.jnome.core.type;

import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.TypeFixer;
import org.aikodi.chameleon.oo.type.generics.FormalParameterType;
import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter;
import org.aikodi.chameleon.oo.type.generics.LazyFormalAlias;

public class JavaLazyFormalAlias extends LazyFormalAlias implements JavaType {

  public JavaLazyFormalAlias(String name, FormalTypeParameter param) {
    super(name, param);
  }

  @Override
  public Type erasure() {
    return this;
  }

  @Override
  public FormalParameterType cloneSelf() {
    return new JavaLazyFormalAlias(name(), parameter());
  }

  @Override
  public boolean upperBoundNotHigherThan(Type other, TypeFixer trace) throws LookupException {
    if(trace.contains(other, parameter())) {
      return true;
    }
    if(sameAs(other)) {
      return true;
    }
    trace.add(other, parameter());
    return super.upperBoundNotHigherThan(other, trace);
  }

}

Update the type fixer to avoid an infinite loop for recursively defined captured type parameters


package fr.insee.rmes.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

import org.codehaus.stax2.io.EscapingWriterFactory;

public class CustomXmlEscapingWriterFactory implements EscapingWriterFactory {
public Writer createEscapingWriterFor(final Writer out, String enc) {
    return new Writer(){
        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
            String val = "";
            for (int i = off; i < len; i++) {
                val += cbuf[i];
            }
            String escapedStr = escapeHtml(val); //convert special characters excluding xml tags
            out.write(escapedStr);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public void close() throws IOException {
            out.close();
        }
      };
    }

	private String escapeHtml(String s) {
		 return s.replace("&", "&")
				 .replace(">", ">")
				 .replace("<", "<")
				 .replace("\"", """);
				// .replace("'", "'");
	}

    public Writer createEscapingWriterFor(OutputStream out, String enc) {
        throw new IllegalArgumentException("not supported");
    }
}

package fr.insee.rmes.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

import org.codehaus.stax2.io.EscapingWriterFactory;

public class CustomXmlEscapingWriterFactory implements EscapingWriterFactory {

public Writer createEscapingWriterFor(final Writer out, String enc) {
    return new Writer(){
        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
        	//WARN : the cbuf contains only part of the string = can't validate xml here
            String val = "";
            for (int i = off; i < len; i++) {
                val += cbuf[i];
            }
            String escapedStr = encodeXml(escapeHtml(val)); //encode manually some xml tags
            out.write(escapedStr);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public void close() throws IOException {
            out.close();
        }
      };
    }

	private String escapeHtml(String s) {
		 return s.replace("&", "&")
				 .replace(">", ">")
				 .replace("<", "<")
				 .replace("\"", """);
	}

	private String encodeXml(String s) {
		 return s.replaceAll("<([a-zA-Z]+)>", "<$1>") //xml open tag
				 .replaceAll("</([a-zA-Z]+)>", "</$1>") //xml close tag
				 .replaceAll("<([a-zA-Z]+)/>", "<$1/>") //br
				 .replaceAll("<([a-zA-Z]+) />", "<$1 />"); //br with space
	}

    public Writer createEscapingWriterFor(OutputStream out, String enc) {
        throw new IllegalArgumentException("not supported");
    }
}

Change encoding of xml to encode all except xml tags


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

package org.openmhealth.dsu.repository;

import org.openmhealth.dsu.domain.DataPoint;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

import java.util.Optional;

/**
 * A repository of data points.
 *
 * @see org.springframework.data.repository.CrudRepository
 * @author Emerson Farrugia
 */
@NoRepositoryBean
public interface DataPointRepository extends Repository<DataPoint, String>, CustomDataPointRepository {

    Optional<DataPoint> findOne(String id);

    Iterable<DataPoint> findAll();

    Iterable<DataPoint> save(Iterable<DataPoint> dataPoints);

    void delete(String id);
}

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

package org.openmhealth.dsu.repository;

import org.openmhealth.dsu.domain.DataPoint;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

import java.util.Optional;

/**
 * A repository of data points.
 *
 * @see org.springframework.data.repository.CrudRepository
 * @author Emerson Farrugia
 */
@NoRepositoryBean
public interface DataPointRepository extends Repository<DataPoint, String>, CustomDataPointRepository {

    Optional<DataPoint> findOne(String id);

    Iterable<DataPoint> findAll();

    DataPoint save(DataPoint dataPoint);

    Iterable<DataPoint> save(Iterable<DataPoint> dataPoints);

    Long delete(String id);
}

Add save method and fix delete method in data point repository.


/*
 *  Copyright 2013 Pascal Christoph, hbz
 * Licensed under the Eclipse Public License 1.0 */
package org.culturegraph.mf.util.tries;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 * tests {@link SimpleRegexTrie}
 *
 * @author Pascal Christoph
 *
 */
public final class SimpleRegexTrieTest {
	private static final String SCC = "aacbb|a[ab]bb";
	private static final String AACBB = "aacbb";

	@Test
	public void testWithSimpleCharacterClass() {
		final SimpleRegexTrie<String> trie = new SimpleRegexTrie<String>();
		trie.put(SCC, SCC);
		assertTrue(AACBB, trie.get(AACBB).size() == 1);
	}
}

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

import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 * tests {@link SimpleRegexTrie}
 *
 * @author Pascal Christoph
 *
 */
public final class SimpleRegexTrieTest {
	private static final String SCC = "aacbb|a[ab]bb";
	private static final String AACBB = "aacbb";

	@Test
	public void testWithSimpleCharacterClass() {
		final SimpleRegexTrie<String> trie = new SimpleRegexTrie<String>();
		trie.put(SCC, SCC);
		assertTrue(AACBB, trie.get(AACBB).size() == 1);
	}
}

Change license from epl to apache2

Change license from epl to apache2


package uk.ac.ebi.atlas.profiles.baseline;

import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import uk.ac.ebi.atlas.model.experiment.baseline.BaselineExpression;
import uk.ac.ebi.atlas.model.experiment.baseline.FactorGroup;
import uk.ac.ebi.atlas.profiles.ExpressionsRowRawDeserializer;

import java.util.Iterator;
import java.util.List;
import java.util.Queue;

public class ExpressionsRowRawDeserializerBaseline extends ExpressionsRowRawDeserializer<BaselineExpression> {

    final int expectedNumberOfValues;
    Iterator<FactorGroup> factorGroups;

    public ExpressionsRowRawDeserializerBaseline(List<FactorGroup> orderedFactorGroups) {
        expectedNumberOfValues = orderedFactorGroups.size();
        factorGroups = Iterables.cycle(orderedFactorGroups).iterator();
    }

    @Override
    public ExpressionsRowRawDeserializer<BaselineExpression> reload(BaselineExpression... values) {
        if (values.length != expectedNumberOfValues) {
            throw new IllegalArgumentException(String.format("Expected %s values but got [%s]", expectedNumberOfValues, Joiner.on(",").join(values)));
        }
        return super.reload(values);
    }

    @Override
    public BaselineExpression nextExpression(Queue<BaselineExpression> rawValuesRow) {
        return rawValuesRow.poll();
    }

}

package uk.ac.ebi.atlas.profiles.baseline;

import com.google.common.base.Joiner;
import uk.ac.ebi.atlas.model.experiment.baseline.BaselineExpression;
import uk.ac.ebi.atlas.model.experiment.baseline.FactorGroup;
import uk.ac.ebi.atlas.profiles.ExpressionsRowRawDeserializer;

import java.util.List;
import java.util.Queue;

public class ExpressionsRowRawDeserializerBaseline extends ExpressionsRowRawDeserializer<BaselineExpression> {

    private  int expectedNumberOfValues;

    public ExpressionsRowRawDeserializerBaseline(List<FactorGroup> orderedFactorGroups) {
        expectedNumberOfValues = orderedFactorGroups.size();
    }

    @Override
    public ExpressionsRowRawDeserializer<BaselineExpression> reload(BaselineExpression... values) {
        if (values.length != expectedNumberOfValues) {
            throw new IllegalArgumentException(String.format("Expected %s values but got [%s]", expectedNumberOfValues, Joiner.on(",").join(values)));
        }
        return super.reload(values);
    }

    @Override
    public BaselineExpression nextExpression(Queue<BaselineExpression> rawValuesRow) {
        return rawValuesRow.poll();
    }

}

Remove field which was never accessed

Remove field which was never accessed


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

import org.apache.camel.spring.SpringTestSupport;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringSimpleExpressionTest extends SpringTestSupport {

    @Override
    protected AbstractXmlApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("org/apache/camel/language/SpringSimpleExpressionTest.xml");
    }

    public void testSimpleEmptyString() throws Exception {
        getMockEndpoint("mock:result").expectedBodiesReceived("False");

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

}

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

import org.apache.camel.spring.SpringTestSupport;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringSimpleExpressionTest extends SpringTestSupport {

    @Override
    protected AbstractXmlApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("org/apache/camel/language/SpringSimpleExpressionTest.xml");
    }

    public void testSimpleWhenString() throws Exception {
        getMockEndpoint("mock:result").expectedBodiesReceived("correct");

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    public void testSimpleOtherwiseString() throws Exception {
        getMockEndpoint("mock:result").expectedBodiesReceived("incorrect");

        template.sendBody("direct:start", "Bye World");

        assertMockEndpointsSatisfied();
    }

}

Fix the failing test and add one more test to cover both when/otherwise conditions.


package net.jpountz.util;

/*
 * 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.
 */

import java.nio.ByteOrder;

public enum Utils {
  ;

  public static final ByteOrder NATIVE_BYTE_ORDER = ByteOrder.nativeOrder();

  private static final boolean unalignedAccessAllowed;
  static {
    String arch = System.getProperty("os.arch");
    unalignedAccessAllowed = arch.equals("i386") || arch.equals("x86")
            || arch.equals("amd64") || arch.equals("x86_64");
  }

  public static boolean isUnalignedAccessAllowed() {
    return unalignedAccessAllowed;
  }

}

package net.jpountz.util;

/*
 * 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.
 */

import java.nio.ByteOrder;

public enum Utils {
  ;

  public static final ByteOrder NATIVE_BYTE_ORDER = ByteOrder.nativeOrder();

  private static final boolean unalignedAccessAllowed;
  static {
    String arch = System.getProperty("os.arch");
    unalignedAccessAllowed = arch.equals("i386") || arch.equals("x86")
            || arch.equals("amd64") || arch.equals("x86_64")
            || arch.equals("aarch64");
  }

  public static boolean isUnalignedAccessAllowed() {
    return unalignedAccessAllowed;
  }

}

Add unsafeInstance support for AArch64

Add unsafeInstance support for AArch64


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

import afu.org.checkerframework.checker.nullness.qual.Nullable;

/** Exception thrown when BeamSQL cannot convert sql to BeamRelNode. */
public class SqlConversionException extends RuntimeException {

  public SqlConversionException(@Nullable Throwable cause) {
    super(cause);
  }

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

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

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

import org.checkerframework.checker.nullness.qual.Nullable;

/** Exception thrown when BeamSQL cannot convert sql to BeamRelNode. */
public class SqlConversionException extends RuntimeException {

  public SqlConversionException(@Nullable Throwable cause) {
    super(cause);
  }

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

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

Fix null error in Beam SQL

Fix null error in Beam SQL


/*
 * Copyright 2017 Hewlett Packard Enterprise Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.autonomy.abc.dashboards;

import com.hp.autonomy.frontend.selenium.config.TestConfig;
import org.junit.Before;

public class SunburstWidgetITCase extends ClickableDashboardITCase {
    public SunburstWidgetITCase(final TestConfig config) {
        super(config, 1, "Sunburst Dashboard", "Sunburst", "SunburstSearch");
    }

    @Override
    @Before
    public void setUp() {
        page.waitForSunburstWidgetToRender();
    }

    //TODO once config is set up, test:
    //      * sunburst renders segments
    //      * sunburst resizes
    //      * legend is populated (colours, order by counts)
    //      * segment colours and ordering are correct (give segments data-id for testing?)
    //      * the 'too many entries' legend item is displayed when necessary
    //      * legend changes position with resizing
}

/*
 * Copyright 2017 Hewlett Packard Enterprise Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.autonomy.abc.dashboards;

import com.hp.autonomy.frontend.selenium.config.TestConfig;
import org.junit.Before;

public class SunburstWidgetITCase extends ClickableDashboardITCase {
    public SunburstWidgetITCase(final TestConfig config) {
        super(config, 1, "Sunburst Dashboard", "Sunburst", "SunburstSearch");
    }

    @Override
    @Before
    public void setUp() {
        super.setUp();
        page.waitForSunburstWidgetToRender();
    }

    //TODO once config is set up, test:
    //      * sunburst renders segments
    //      * sunburst resizes
    //      * legend is populated (colours, order by counts)
    //      * segment colours and ordering are correct (give segments data-id for testing?)
    //      * the 'too many entries' legend item is displayed when necessary
    //      * legend changes position with resizing
}

Call super in SunburstWidgetIT setUp method.

Otherwise they fail with NullPointerExceptions.

[rev: ivo.miller]


package com.thinkaurelius.titan.diskstorage.util;

import java.util.concurrent.TimeUnit;

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

public abstract class AbstractTimestampProvider implements TimestampProvider {

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

    @Override
    public long sleepUntil(final long time, final TimeUnit unit, final Logger log) throws InterruptedException {

        // All long variables are times in parameter unit

        long now;

        while ((now = unit.convert(getTime(), getUnit())) <= time) {
            final long delta = time - now;
            /*
             * TimeUnit#sleep(long) internally preserves the nanoseconds parts
             * of the argument, if applicable, and passes both milliseconds and
             * nanoseconds parts into Thread#sleep(long, long)
             */
//            if (log.isDebugEnabled()) {
//                log.error("Sleeping: now={} targettime={} delta={} (unit={})",
//                        new Object[] { now, time, delta, unit });
//            }
            unit.sleep(delta);
        }

        return now;
    }

    @Override
    public long sleepUntil(final long time, final TimeUnit unit) throws InterruptedException {
        return sleepUntil(time, unit, log);
    }

    @Override
    public String toString() {
        return "TimestampProvider[" + getUnit() + "]";
    }
}

package com.thinkaurelius.titan.diskstorage.util;

import java.util.concurrent.TimeUnit;

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

public abstract class AbstractTimestampProvider implements TimestampProvider {

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

    @Override
    public long sleepUntil(final long time, final TimeUnit unit, final Logger log) throws InterruptedException {

        // All long variables are times in parameter unit

        long now;

        while ((now = unit.convert(getTime(), getUnit())) <= time) {
            final long delta = time - now;
            /*
             * TimeUnit#sleep(long) internally preserves the nanoseconds parts
             * of the argument, if applicable, and passes both milliseconds and
             * nanoseconds parts into Thread#sleep(long, long)
             */
            if (log.isDebugEnabled()) {
                log.debug("Sleeping: now={} targettime={} delta={} (unit={})",
                        new Object[] { now, time, delta, unit });
            }
            unit.sleep(delta);
        }

        return now;
    }

    @Override
    public long sleepUntil(final long time, final TimeUnit unit) throws InterruptedException {
        return sleepUntil(time, unit, log);
    }

    @Override
    public String toString() {
        return "TimestampProvider[" + getUnit() + "]";
    }
}

Add a logging statement in TimestampProvider


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// TODO: This implements the old, deprecated document HTTP= API. Remove on Vespa 7
/**
 * Exported not as an API, but specifically for SSBE.
 */
@ExportPackage
package com.yahoo.feedhandler;

import com.yahoo.osgi.annotation.ExportPackage;

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * Exported not as an API, but specifically for SSBE.
 */
@ExportPackage
package com.yahoo.feedhandler;

import com.yahoo.osgi.annotation.ExportPackage;

Remove wrong TODO - this is needed for vespafeeder


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

import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;

import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.SpellResult;

public class AggroAction extends BaseSpellAction
{
    @Override
    public SpellResult perform(CastContext context)
    {
        Entity target = context.getTargetEntity();
        if (!(target instanceof Creature))
        {
            return SpellResult.NO_TARGET;
        }
        LivingEntity source = context.getLivingEntity();
        if (source == null)
        {
            return SpellResult.NO_TARGET;
        }

        Creature creatureTarget = (Creature)target;
        LivingEntity current = creatureTarget.getTarget();
        if (source == current)
        {
            return SpellResult.NO_ACTION;
        }

        ((Creature) target).setTarget(source);
        return SpellResult.CAST;
    }

    @Override
    public boolean isUndoable()
    {
        return false;
    }

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

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

import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;

import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.SpellResult;

public class AggroAction extends BaseSpellAction
{
    private boolean clearTarget;

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

    @Override
    public SpellResult perform(CastContext context)
    {
        Entity target = context.getTargetEntity();
        if (!(target instanceof Creature))
        {
            return SpellResult.NO_TARGET;
        }

        Creature creatureTarget = (Creature)target;
        if (clearTarget) {
            LivingEntity current = creatureTarget.getTarget();
            if (current == null) {
                return SpellResult.NO_TARGET;
            }
            creatureTarget.setTarget(null);
            return SpellResult.CAST;
        }
        LivingEntity source = context.getLivingEntity();
        if (source == null)
        {
            return SpellResult.NO_TARGET;
        }

        LivingEntity current = creatureTarget.getTarget();
        if (source == current)
        {
            return SpellResult.NO_ACTION;
        }

        ((Creature) target).setTarget(source);
        return SpellResult.CAST;
    }

    @Override
    public boolean isUndoable()
    {
        return false;
    }

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

Add clear_target parameter to Aggro action


package jp.ac.nii.prl.mape.autoscaling.analysis.model.dto;

import jp.ac.nii.prl.mape.autoscaling.analysis.model.Adaptation;
import jp.ac.nii.prl.mape.autoscaling.analysis.model.Deployment;
import jp.ac.nii.prl.mape.autoscaling.analysis.model.Instance;
import jp.ac.nii.prl.mape.autoscaling.analysis.model.InstanceType;

public class DeploymentFactory {

	public static Deployment createDeployment(DeploymentDTO dto) {
		return null;
	}

	public static DeploymentDTO createDeploymentDTO(Deployment deployment) {
		return null;
	}

	public static Adaptation createAdaptation(AdaptationDTO dto) {
		return null;
	}

	public static AdaptationDTO createAdaptationDTO(Adaptation adaptation) {
		return null;
	}

	public static Instance createInstance(InstanceDTO dto) {
		return null;
	}

	public static InstanceDTO createInstanceDTO(Instance instance) {
		return null;
	}

	public static InstanceType createInstanceType(InstanceTypeDTO dto) {
		return null;
	}

	public static InstanceTypeDTO createInstanceTypeDTO(InstanceType instanceType) {
		return null;
	}

}

package jp.ac.nii.prl.mape.autoscaling.analysis.model.dto;

import jp.ac.nii.prl.mape.autoscaling.analysis.model.Adaptation;
import jp.ac.nii.prl.mape.autoscaling.analysis.model.Deployment;
import jp.ac.nii.prl.mape.autoscaling.analysis.model.Instance;
import jp.ac.nii.prl.mape.autoscaling.analysis.model.InstanceType;

public class DeploymentFactory {

	public static Deployment createDeployment(DeploymentDTO dto) {
		return null;
	}

	public static DeploymentDTO createDeploymentDTO(Deployment deployment) {
		return null;
	}

	public static Adaptation createAdaptation(AdaptationDTO dto, Deployment deployment) {
		Adaptation adaptation = new Adaptation();

		adaptation.setAdapt(dto.isAdapt());
		adaptation.setCpuCount(dto.getCpuCount());
		adaptation.setScaleUp(dto.isScaleUp());
		adaptation.setDeployment(deployment);

		return adaptation;
	}

	public static AdaptationDTO createAdaptationDTO(Adaptation adaptation) {
		AdaptationDTO dto = new AdaptationDTO();

		dto.setAdapt(adaptation.isAdapt());
		dto.setCpuCount(adaptation.getCpuCount());
		dto.setScaleUp(adaptation.isScaleUp());

		return dto;
	}

	public static Instance createInstance(InstanceDTO dto) {
		return null;
	}

	public static InstanceDTO createInstanceDTO(Instance instance) {
		return null;
	}

	public static InstanceType createInstanceType(InstanceTypeDTO dto) {
		return null;
	}

	public static InstanceTypeDTO createInstanceTypeDTO(InstanceType instanceType) {
		return null;
	}

}

Implement Adaptation to AdaptationDTO and back


package io.georocket.commands;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import de.undercouch.underline.InputReader;
import de.undercouch.underline.OptionParserException;
import de.undercouch.underline.UnknownAttributes;
import io.georocket.GeoRocketCli;
import io.vertx.core.Handler;

/**
 * Displays a command's help
 * @author Michel Kraemer
 */
public class HelpCommand extends AbstractGeoRocketCommand {
  private List<String> commands = new ArrayList<String>();

  /**
   * Sets the commands to display the help for
   * @param commands the commands
   */
  @UnknownAttributes("COMMAND")
  public void setCommands(List<String> commands) {
    this.commands = commands;
  }

  @Override
  public String getUsageName() {
    return "help";
  }

  @Override
  public String getUsageDescription() {
    return "Display a command's help";
  }

  @Override
  public void doRun(String[] remainingArgs, InputReader in, PrintWriter out,
      Handler<Integer> handler) throws OptionParserException, IOException {
    // simply forward commands to GeoRocketCli and append '-h'
    GeoRocketCli cmd = new GeoRocketCli();
    cmd.setup();
    String[] args = commands.toArray(new String[commands.size() + 1]);
    args[args.length - 1] = "-h";
    cmd.setEndHandler(handler);
    cmd.run(args, in, out);
  }
}

package io.georocket.commands;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import de.undercouch.underline.InputReader;
import de.undercouch.underline.OptionParserException;
import de.undercouch.underline.UnknownAttributes;
import io.georocket.GeoRocketCli;
import io.vertx.core.Handler;

/**
 * Displays a command's help
 * @author Michel Kraemer
 */
public class HelpCommand extends AbstractGeoRocketCommand {
  protected List<String> commands = new ArrayList<String>();

  /**
   * Sets the commands to display the help for
   * @param commands the commands
   */
  @UnknownAttributes("COMMAND")
  public void setCommands(List<String> commands) {
    this.commands = commands;
  }

  @Override
  public String getUsageName() {
    return "help";
  }

  @Override
  public String getUsageDescription() {
    return "Display a command's help";
  }

  @Override
  public void doRun(String[] remainingArgs, InputReader in, PrintWriter out,
      Handler<Integer> handler) throws OptionParserException, IOException {
    // simply forward commands to GeoRocketCli and append '-h'
    GeoRocketCli cmd = new GeoRocketCli();
    cmd.setup();
    String[] args = commands.toArray(new String[commands.size() + 1]);
    args[args.length - 1] = "-h";
    cmd.setEndHandler(handler);
    cmd.run(args, in, out);
  }
}

Prepare help command for inheritance

Prepare help command for inheritance


package edu.brown.cs.systems.tracingplane.transit_layer.impl;

import org.junit.Test;
import edu.brown.cs.systems.tracingplane.transit_layer.Baggage;
import junit.framework.TestCase;

public class TestDefaultTransitLayer extends TestCase {

    @Test
    public void testNullTransitLayerImpl() {
        assertNotNull(Baggage.transit);
        assertTrue(Baggage.transit instanceof NullTransitLayer);

        Baggage baggage = Baggage.newInstance();
        assertNotNull(baggage);
        assertEquals(baggage, NullBaggage.INSTANCE);
    }

}

package edu.brown.cs.systems.tracingplane.transit_layer.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import edu.brown.cs.systems.tracingplane.transit_layer.Baggage;

public class TestDefaultTransitLayer {

    @Test
    public void testNullTransitLayerImpl() {
        assertNotNull(Baggage.transit);
        assertTrue(Baggage.transit instanceof NullTransitLayer);

        Baggage baggage = Baggage.newInstance();
        assertNotNull(baggage);
        assertEquals(baggage, NullBaggage.INSTANCE);
    }

}

Convert transit-layer testcases to JUnit 4


package org.metaborg.meta.interpreter.framework;

import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;

public class TermUtils {

	public static boolean boolFromTerm(IStrategoTerm term) {
		if (Tools.isTermAppl(term)) {
			IStrategoAppl tAppl = (IStrategoAppl) term;
			if (Tools.hasConstructor(tAppl, "$__DS_False__$", 0)) {
				return false;
			} else if (Tools.hasConstructor(tAppl, "$__DS_True__$", 0)) {
				return true;
			}
		}
		throw new RuntimeException("Malformed boolean: " + term);
	}

	public static IStrategoTerm termFromBool(boolean bV, ITermFactory factory) {
		return factory.makeAppl(factory.makeConstructor(bV ? "$__DS_True__$"
				: "$__DS_False__$", 0));
	}
}

package org.metaborg.meta.interpreter.framework;

import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;

public class TermUtils {

	public static boolean boolFromTerm(IStrategoTerm term) {
		if (Tools.isTermAppl(term)) {
			IStrategoAppl tAppl = (IStrategoAppl) term;
			if (Tools.hasConstructor(tAppl, "___DS_False___", 0)) {
				return false;
			} else if (Tools.hasConstructor(tAppl, "___DS_True___", 0)) {
				return true;
			}
		}
		throw new RuntimeException("Malformed boolean: " + term);
	}

	public static IStrategoTerm termFromBool(boolean bV, ITermFactory factory) {
		return factory.makeAppl(factory.makeConstructor(bV ? "___DS_True___"
				: "___DS_False___", 0));
	}
}

Fix incorrect ATerms being emitted for booleans


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

public class RestError {

	String developerMsg;
	String userMsg;
	Integer errorCode;

	public RestError() {
		super();
	}

	public RestError(String developerMsg, String userMsg, Integer errorCode) {
		super();
		this.developerMsg = developerMsg;
		this.userMsg = userMsg;
		this.errorCode = errorCode;
	}
	public String getDeveloperMsg() {
		return developerMsg;
	}
	public void setDeveloperMsg(String developerMsg) {
		this.developerMsg = developerMsg;
	}
	public String getUserMsg() {
		return userMsg;
	}
	public void setUserMsg(String userMsg) {
		this.userMsg = userMsg;
	}
	public Integer getErrorCode() {
		return errorCode;
	}
	public void setErrorCode(Integer errorCode) {
		this.errorCode = errorCode;
	}
}

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

public class RestError {

	String developerMsg;
	String userMsg;
	Integer errorCode;

	public RestError() {
	}

	public RestError(String developerMsg, String userMsg, Integer errorCode) {
		this.developerMsg = developerMsg;
		this.userMsg = userMsg;
		this.errorCode = errorCode;
	}
	public String getDeveloperMsg() {
		return developerMsg;
	}
	public void setDeveloperMsg(String developerMsg) {
		this.developerMsg = developerMsg;
	}
	public String getUserMsg() {
		return userMsg;
	}
	public void setUserMsg(String userMsg) {
		this.userMsg = userMsg;
	}
	public Integer getErrorCode() {
		return errorCode;
	}
	public void setErrorCode(Integer errorCode) {
		this.errorCode = errorCode;
	}
}

refactor(exception-mapper): Remove redundant super calls in constructor


package org.madura.mobile.demo;

import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;

/**
 * This UI is served for browsers that don't support TouchKit.
 */
@SuppressWarnings("serial")
//// Disable browser caching the app for running it when offline
//@CacheManifestEnabled(false)
//// Prevent showing OfflineMode client UI if network fails
//@OfflineModeEnabled(false)
public class MaduraMobileDemoFallbackUI extends UI {

    @Override
    protected void init(VaadinRequest request) {
        HorizontalLayout layout = new HorizontalLayout();
        layout.setSpacing(true);
        layout.setMargin(true);

        Button button = new Button("Continue anyway.", new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                getSession().setAttribute("mobile", true);
                getUI().getPage().reload();
            }
        });
        button.addStyleName("link");

        layout.addComponent(new Label("You seem to be using a desktop browser."));
        layout.addComponent(button);

        setContent(layout);
    }

}

package org.madura.mobile.demo;

import com.vaadin.annotations.Theme;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;

/**
 * This UI is served for browsers that don't support TouchKit.
 */
@SuppressWarnings("serial")
@Theme("mytheme")
//// Disable browser caching the app for running it when offline
//@CacheManifestEnabled(false)
//// Prevent showing OfflineMode client UI if network fails
//@OfflineModeEnabled(false)
public class MaduraMobileDemoFallbackUI extends UI {

    @Override
    protected void init(VaadinRequest request) {
        HorizontalLayout layout = new HorizontalLayout();
        layout.setSpacing(true);
        layout.setMargin(true);

        Button button = new Button("Continue anyway.", new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                getSession().setAttribute("mobile", true);
                getUI().getPage().reload();
            }
        });
        button.addStyleName("link");

        layout.addComponent(new Label("You seem to be using a desktop browser."));
        layout.addComponent(button);

        setContent(layout);
    }

}

Set mytheme on fallback UI

Set mytheme on fallback UI


/**
 * Copyright 2014 Flipkart Internet Pvt. Ltd.
 *
 * 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.flipkart.foxtrot.common;

/**
 * Created by rishabh.goyal on 06/05/14.
 */
public enum FieldType {
    STRING,
    INTEGER,
    LONG,
    FLOAT,
    DOUBLE,
    BOOLEAN,
    DATE
}

/**
 * Copyright 2014 Flipkart Internet Pvt. Ltd.
 *
 * 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.flipkart.foxtrot.common;

/**
 * Created by rishabh.goyal on 06/05/14.
 */
public enum FieldType {
    STRING,
    INTEGER,
    LONG,
    FLOAT,
    DOUBLE,
    BOOLEAN,
    DATE,
    OBJECT
}

Fix for elasticsearch object type

Fix for elasticsearch object type


package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_13;

import protocolsupport.protocol.ConnectionImpl;
import protocolsupport.protocol.packet.ClientBoundPacket;
import protocolsupport.protocol.packet.middle.clientbound.play.MiddleCustomPayload;
import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData;
import protocolsupport.protocol.serializer.StringSerializer;
import protocolsupport.utils.recyclable.RecyclableCollection;
import protocolsupport.utils.recyclable.RecyclableSingletonList;

public class CustomPayload extends MiddleCustomPayload {

	public CustomPayload(ConnectionImpl connection) {
		super(connection);
	}

	@Override
	public RecyclableCollection<ClientBoundPacketData> toData() {
		ClientBoundPacketData serializer = ClientBoundPacketData.create(ClientBoundPacket.PLAY_CUSTOM_PAYLOAD_ID);
		StringSerializer.writeString(serializer, connection.getVersion(), tag);
		serializer.writeBytes(data);
		return RecyclableSingletonList.create(serializer);
	}

}

package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_13;

import protocolsupport.protocol.ConnectionImpl;
import protocolsupport.protocol.packet.ClientBoundPacket;
import protocolsupport.protocol.packet.middle.clientbound.play.MiddleCustomPayload;
import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData;
import protocolsupport.protocol.serializer.MerchantDataSerializer;
import protocolsupport.protocol.serializer.StringSerializer;
import protocolsupport.protocol.typeremapper.legacy.LegacyCustomPayloadChannelName;
import protocolsupport.protocol.utils.ProtocolVersionsHelper;
import protocolsupport.utils.recyclable.RecyclableCollection;
import protocolsupport.utils.recyclable.RecyclableSingletonList;

public class CustomPayload extends MiddleCustomPayload {

	public CustomPayload(ConnectionImpl connection) {
		super(connection);
	}

	@Override
	public RecyclableCollection<ClientBoundPacketData> toData() {
		ClientBoundPacketData serializer = ClientBoundPacketData.create(ClientBoundPacket.PLAY_CUSTOM_PAYLOAD_ID);
		StringSerializer.writeString(serializer, connection.getVersion(), tag);
		switch (tag) {
			case (LegacyCustomPayloadChannelName.MODERN_TRADER_LIST): {
				String locale = cache.getAttributesCache().getLocale();
				MerchantDataSerializer.writeMerchantData(
					serializer, connection.getVersion(), locale,
					MerchantDataSerializer.readMerchantData(data, ProtocolVersionsHelper.LATEST_PC, locale)
				);
				break;
			}
			default: {
				serializer.writeBytes(data);
				break;
			}
		}
		return RecyclableSingletonList.create(serializer);
	}

}

Fix traders in 1.13 and 1.13.1

Fix traders in 1.13 and 1.13.1


// BSD License (http://www.galagosearch.org/license)
package org.lemurproject.galago.utility.buffer;

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

/**
 *
 * @author trevor
 */
public abstract class DataStream extends InputStream implements DataInput {
    public abstract DataStream subStream(long start, long length) throws IOException;
    public abstract long getPosition();
    public abstract boolean isDone();
    public abstract long length();

    @Override
    public int read() throws IOException {
      if(isDone()) { return -1; }
      return readUnsignedByte();
    }

    /**
     * Seeks forward into the stream to a particular byte offset (reverse
     * seeks are not allowed).  The offset is relative to the start position of
     * this data stream, not the beginning of the file.
     */
    public abstract void seek(long offset);
}

// BSD License (http://www.galagosearch.org/license)
package org.lemurproject.galago.utility.buffer;

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

/**
 *
 * @author trevor
 */
public abstract class DataStream extends InputStream implements DataInput {
    public abstract DataStream subStream(long start, long length) throws IOException;
    public abstract long getPosition();
    public abstract boolean isDone();
    public abstract long length();

    @Override
    public int read() throws IOException {
      if(isDone()) { return -1; }
      return readUnsignedByte();
    }

    @Override
    public int read(byte[] b) throws IOException {
        return read(b, 0, b.length);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int read;
        for(read=0; read<len && !isDone(); read++) {
            b[off+read] = (byte) readUnsignedByte();
        }
        return read;
    }

    /**
     * Seeks forward into the stream to a particular byte offset (reverse
     * seeks are not allowed).  The offset is relative to the start position of
     * this data stream, not the beginning of the file.
     */
    public abstract void seek(long offset);
}

Speed up the InputStream interface on Galago's cached stream class.


package hello.controllers;

import java.io.IOException;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import models.Greeting;

@RestController
@RequestMapping(value = "/api", produces = { MediaType.APPLICATION_JSON_VALUE })
public class ApiController {

	@RequestMapping(value = "/greeting", method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<Greeting> get() {
		return new ResponseEntity<Greeting>(new Greeting(), HttpStatus.OK);
	}

	@RequestMapping(value = "/greeting", method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<Greeting> post(@RequestBody String body) {
		Greeting greeting = new Greeting(getNameFromJson(body));
		return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
	}

	private String getNameFromJson(String json) {
		ObjectMapper objectMapper = new ObjectMapper();

		JsonNode rootNode;
		String name;

		try {
			rootNode = objectMapper.readTree(json);
			name = rootNode.path("name").textValue();
		} catch (IOException e) {
			name = null;
		}

		return name;
	}

}

package hello.controllers;

import java.io.IOException;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import models.Greeting;

@RestController
@RequestMapping(value = "/api", produces = { MediaType.APPLICATION_JSON_VALUE })
public class ApiController {

	@RequestMapping(value = "/greeting", method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<Greeting> get() {
		return new ResponseEntity<Greeting>(new Greeting(), HttpStatus.OK);
	}

	@RequestMapping(value = "/greeting", method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<Greeting> post(@RequestBody String body) {
		Greeting greeting = new Greeting(getNameFromJson(body));
		return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
	}

	private String getNameFromJson(String json) {
		ObjectMapper objectMapper = new ObjectMapper();

		String name;

		try {
			JsonNode rootNode = objectMapper.readTree(json);
			name = rootNode.path("name").textValue();
		} catch (IOException e) {
			name = null;
		}

		return name;
	}

}

Tidy up scope in API Controller.

Tidy up scope in API Controller.


/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.iod.client.api.textindexing;

import com.hp.autonomy.iod.client.util.MultiMap;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.Collections;
import java.util.Map;
import java.util.Set;

@Setter
@Accessors(chain = true)
public class ListIndexesRequestBuilder {
    /**
     * @param indexTypes The value of the type parameter
     */
    private final Set<IndexType> indexTypes = Collections.emptySet();

    /**
     * @param indexFlavors The value of the flavor parameter
     */
    private final Set<IndexFlavor> indexFlavors = Collections.emptySet();

    /**
     * @return A map of parameters suitable for use with {@link ListIndexesService}.
     */
    public Map<String, Object> build() {
        final Map<String, Object> map = new MultiMap<>();

        for(final IndexType indexType : indexTypes) {
            map.put("type", indexType);
        }

        for (final IndexFlavor indexFlavor : indexFlavors) {
            map.put("flavor", indexFlavor);
        }

        return map;
    }
}

/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.iod.client.api.textindexing;

import com.hp.autonomy.iod.client.util.MultiMap;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Setter
@Accessors(chain = true)
public class ListIndexesRequestBuilder {
    /**
     * @param indexTypes The value of the type parameter
     */
    private Set<IndexType> indexTypes = new HashSet<>();

    /**
     * @param indexFlavors The value of the flavor parameter
     */
    private Set<IndexFlavor> indexFlavors = new HashSet<>();

    /**
     * @return A map of parameters suitable for use with {@link ListIndexesService}.
     */
    public Map<String, Object> build() {
        final Map<String, Object> map = new MultiMap<>();

        for(final IndexType indexType : indexTypes) {
            map.put("type", indexType);
        }

        for (final IndexFlavor indexFlavor : indexFlavors) {
            map.put("flavor", indexFlavor);
        }

        return map;
    }
}

Fix a compilation error in the tests.

Fix a compilation error in the tests.


package com.pixable.pixalytics.google_analytics.platform;

import com.pixable.pixalytics.core.platform.Platform;
import com.pixable.pixalytics.google_analytics.proxy.GoogleAnalyticsProxy;
import com.pixable.pixalytics.google_analytics.R;

import java.util.Map;

public class GoogleAnalyticsPlatform extends Platform {

    public GoogleAnalyticsPlatform(String id, Config config) {
        super(id, R.drawable.pixalytics__tracking_toast_google_analytics, new GoogleAnalyticsProxy(config));
    }

    /**
     * Configuration parameters for a tracking platform. For instance, a project in your Mixpanel
     * account.
     */
    public static class Config extends Platform.Config {
        Map<String, Integer> dimensionsMapping;
        Map<String, Integer>  metricsMapping;

        public Config(String appKey, Map<String, Integer> dimensionsMapping, Map<String, Integer> metricsMapping) {
            super(appKey);
            this.dimensionsMapping = dimensionsMapping;
            this.metricsMapping = metricsMapping;
        }

        public Map<String, Integer> getDimensionsMapping() {
            return dimensionsMapping;
        }

        public Map<String, Integer> getMetricsMapping() {
            return metricsMapping;
        }
    }
}

package com.pixable.pixalytics.google_analytics.platform;

import com.pixable.pixalytics.core.platform.Platform;
import com.pixable.pixalytics.google_analytics.proxy.GoogleAnalyticsProxy;
import com.pixable.pixalytics.google_analytics.R;

import java.util.Map;

public class GoogleAnalyticsPlatform extends Platform {

    public GoogleAnalyticsPlatform(String id, Config config) {
        super(id, R.drawable.pixalytics__tracking_toast_google_analytics, new GoogleAnalyticsProxy(config));
    }

    /**
     * Configuration parameters for a tracking platform. For instance, a project in your Google Analytics
     * account.
     * This configuration consists in:
     * - appKey: Google Analytics Project Id (like 'UA-XXXXXXXX-1')
     * - dimensionsMapping: Mapping of dimensions defined in Google Analytics Admin page to match Properties name and Dimensions Id
     *   Example: ({'view', 1},{'user', 2}...)
     * - metricsMapping: Mapping of metrics defined in Google Analytics Admin page to match Properties name and Metrics Id
     */
    public static class Config extends Platform.Config {
        Map<String, Integer> dimensionsMapping;
        Map<String, Integer>  metricsMapping;

        public Config(String appKey, Map<String, Integer> dimensionsMapping, Map<String, Integer> metricsMapping) {
            super(appKey);
            this.dimensionsMapping = dimensionsMapping;
            this.metricsMapping = metricsMapping;
        }

        public Map<String, Integer> getDimensionsMapping() {
            return dimensionsMapping;
        }

        public Map<String, Integer> getMetricsMapping() {
            return metricsMapping;
        }
    }
}

Add little documentation about Google Analytics Config


package info.u_team.u_team_core.item;

import java.util.function.Supplier;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.Fluid;
import net.minecraft.item.*;
import net.minecraft.util.*;
import net.minecraft.world.World;

public class NoPlaceUBucketItem extends UBucketItem {

	public NoPlaceUBucketItem(String name, ItemGroup group, Properties properties, Supplier<? extends Fluid> fluid) {
		super(name, group, properties, fluid);
	}

	public NoPlaceUBucketItem(String name, Properties properties, Supplier<? extends Fluid> fluid) {
		super(name, properties, fluid);
	}

	@Override
	public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
		return new ActionResult<ItemStack>(ActionResultType.PASS, player.getHeldItem(hand));
	}

}

package info.u_team.u_team_core.item;

import java.util.function.Supplier;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.Fluid;
import net.minecraft.item.*;
import net.minecraft.util.*;
import net.minecraft.world.World;

public class NoPlaceUBucketItem extends UBucketItem {

	public NoPlaceUBucketItem(ItemGroup group, Properties properties, Supplier<? extends Fluid> fluid) {
		super(group, properties, fluid);
	}

	public NoPlaceUBucketItem(Properties properties, Supplier<? extends Fluid> fluid) {
		super(properties, fluid);
	}

	@Override
	public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
		return new ActionResult<ItemStack>(ActionResultType.PASS, player.getHeldItem(hand));
	}

}

Add new no place u bucket item

Add new no place u bucket item


package tars.ui;

import javafx.scene.paint.Color;

/**
 * Manages color for UI parts
 * @@author A0121533W
 *
 */
public class UiColor {

    public static final String STATUS_UNDONE_TEXT_FILL =
            "-fx-text-fill: #212121";
    public static final String STATUS_DONE_TEXT_FILL = "-fx-text-fill: lightgrey";
    public static final String CIRCLE_LABEL_COLOR = "-fx-text-fill: white;";
    public static final String TASK_CARD_NEWLY_ADDED_BORDER = "-fx-border-color: lightblue";
    public static final String TASK_CARD_DEFAULT_BORDER = "-fx-border-color: #455A64";

    public enum CircleColor {
        HIGH(Color.RED), MEDIUM(Color.ORANGE), LOW(Color.GREEN),
        DONE(Color.LIGHTGREY), NONE(Color.TRANSPARENT);
        private Color circleColor;

        CircleColor(Color circleColor) {
            this.circleColor = circleColor;
        }

        Color getCircleColor() {
            return circleColor;
        }
    }
}

package tars.ui;

import javafx.scene.paint.Color;

/**
 * Manages color for UI parts
 * @@author A0121533W
 *
 */
public class UiColor {

    public static final String STATUS_UNDONE_TEXT_FILL_DARK =
            "-fx-text-fill: #212121";
    public static final String STATUS_UNDONE_TEXT_FILL_LIGHT =
            "-fx-text-fill: #757575";
    public static final String STATUS_DONE_TEXT_FILL = "-fx-text-fill: lightgrey";
    public static final String CIRCLE_LABEL_COLOR = "-fx-text-fill: white;";
    public static final String TASK_CARD_NEWLY_ADDED_BORDER = "-fx-border-color: #2E8AF7";
    public static final String TASK_CARD_DEFAULT_BORDER = "-fx-border-color: lightgrey";

    public enum CircleColor {
        HIGH(Color.RED), MEDIUM(Color.ORANGE), LOW(Color.GREEN),
        DONE(Color.LIGHTGREY), NONE(Color.TRANSPARENT);
        private Color circleColor;

        CircleColor(Color circleColor) {
            this.circleColor = circleColor;
        }

        Color getCircleColor() {
            return circleColor;
        }
    }
}

Update colors for task cards

Update colors for task cards


package org.apereo.cas.services;

import org.apereo.cas.util.services.RegisteredServiceJsonSerializer;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.io.ClassPathResource;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

/**
 * Handles test cases for {@link JsonServiceRegistryDao}.
 *
 * @author Misagh Moayyed
 * @since 4.1.0
 */
public class JsonServiceRegistryDaoTests extends AbstractResourceBasedServiceRegistryDaoTests {

    @Before
    public void setUp() {
        try {
            this.dao = new JsonServiceRegistryDao(RESOURCE, false, mock(ApplicationEventPublisher.class));
        } catch (final Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    @Test
    public void verifyLegacyServiceDefn() throws Exception {
        final ClassPathResource resource = new ClassPathResource("Legacy-10000003.json");
        final RegisteredServiceJsonSerializer serializer = new RegisteredServiceJsonSerializer();
        final RegisteredService service = serializer.from(resource.getInputStream());
        assertNotNull(service);
    }
}

package org.apereo.cas.services;

import org.apereo.cas.util.services.RegisteredServiceJsonSerializer;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

/**
 * Handles test cases for {@link JsonServiceRegistryDao}.
 *
 * @author Misagh Moayyed
 * @since 4.1.0
 */
public class JsonServiceRegistryDaoTests extends AbstractResourceBasedServiceRegistryDaoTests {

    @Before
    public void setUp() {
        try {
            this.dao = new JsonServiceRegistryDao(RESOURCE, false, mock(ApplicationEventPublisher.class));
        } catch (final Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    @Test
    public void verifyLegacyServiceDefn() throws Exception {
        final ClassPathResource resource = new ClassPathResource("Legacy-10000003.json");
        final RegisteredServiceJsonSerializer serializer = new RegisteredServiceJsonSerializer();
        final RegisteredService service = serializer.from(resource.getInputStream());
        assertNotNull(service);
    }

    @Test
    public void verifyExistingDefinitionForCompatibility() throws IOException {
        final Resource resource = new ClassPathResource("returnMappedAttributeReleasePolicyTest1.json");
        final RegisteredServiceJsonSerializer serializer = new RegisteredServiceJsonSerializer();
        final RegisteredService service = serializer.from(resource.getInputStream());
        assertNotNull(service);
    }
}

Clean up transformations of multimaps into JSON


package macrobase.analysis.outlier;

import java.util.List;

import macrobase.conf.MacroBaseConf;
import macrobase.conf.MacroBaseDefaults;
import macrobase.datamodel.Datum;

public abstract class TimeSeriesOutlierDetector extends OutlierDetector {
    protected final int tupleWindowSize;
    private int currentTupleWindowSize;

    public TimeSeriesOutlierDetector(MacroBaseConf conf) {
        super(conf);
        this.tupleWindowSize = conf.getInt(MacroBaseConf.TUPLE_WINDOW, MacroBaseDefaults.TUPLE_WINDOW);
        assert tupleWindowSize > 1;
    }

    public abstract void addToWindow(Datum datum);

    public abstract void removeLastFromWindow();

    // Score current window.
    public abstract double scoreWindow();

    @Override
    public void train(List<Datum> data) {
        // Just sanity checks - we don't actually compute anything in train,
        // since we train as we go while scoring.
        assert data.size() >= tupleWindowSize;
        assert data.get(0).getTime() != null;
    }

    @Override
    public double score(Datum datum) {
        /*
         * Note: we assume score is called with data in order - this is true for
         * batch analysis. Somewhat hacky but allows us to maintain
         * compatibility with OutlierDetector.
         */
        if (currentTupleWindowSize == tupleWindowSize) {
            currentTupleWindowSize--;
            removeLastFromWindow();
        }
        currentTupleWindowSize++;
        addToWindow(datum);
        return scoreWindow();
    }

    @Override
    public double getZScoreEquivalent(double zscore) {
        return 0;
    }

}

package macrobase.analysis.outlier;

import java.util.List;

import macrobase.conf.MacroBaseConf;
import macrobase.conf.MacroBaseDefaults;
import macrobase.datamodel.Datum;

public abstract class TimeSeriesOutlierDetector extends OutlierDetector {
    protected final int tupleWindowSize;
    private int currentTupleWindowSize;

    public TimeSeriesOutlierDetector(MacroBaseConf conf) {
        super(conf);
        this.tupleWindowSize = conf.getInt(MacroBaseConf.TUPLE_WINDOW, MacroBaseDefaults.TUPLE_WINDOW);
        assert tupleWindowSize > 1;
    }

    public abstract void addToWindow(Datum datum);

    public abstract void removeLastFromWindow();

    /**
     * Use the current window to build a model and then score the latest datum.
     */
    public abstract double scoreWindow();

    @Override
    public void train(List<Datum> data) {
        // Just sanity checks - we don't actually compute anything in train,
        // since we train as we go while scoring.
        assert data.size() >= tupleWindowSize;
        assert data.get(0).getTime() != null;
    }

    @Override
    public double score(Datum datum) {
        /*
         * Note: we assume score is called with data in order - this is true for
         * batch analysis. Somewhat hacky but allows us to maintain
         * compatibility with OutlierDetector.
         */
        if (currentTupleWindowSize == tupleWindowSize) {
            currentTupleWindowSize--;
            removeLastFromWindow();
        }
        currentTupleWindowSize++;
        addToWindow(datum);
        return scoreWindow();
    }

    @Override
    public double getZScoreEquivalent(double zscore) {
        return 0;
    }

}

Clarify current model of time series scoring


package pro.beam.api.resource.chat.events.data;

import java.util.List;

import pro.beam.api.resource.BeamUser;
import pro.beam.api.resource.chat.AbstractChatEvent;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterators;
import com.google.gson.annotations.SerializedName;

public class IncomingMessageData extends AbstractChatEvent.EventData {
    public int channel;
    public String id;
    public String user_name;
    public String user_id;
    public List<BeamUser.Role> user_roles;
    public List<MessagePart> message;

    public String getMessage() {
        return Joiner.on(' ').join(Iterators.transform(this.message.iterator(), new Function<MessagePart, String>() {
            @Override public String apply(MessagePart part) {
                switch(part.type) {
                    case ME:
                        return part.text;
                    case EMOTICON:
                        return part.path;
                    case LINK:
                        return part.url;
                    case TEXT:
                    default:
                        return part.data;
                }
            }
        }));
    }

    public static class MessagePart {
        public Type type;
        public String url;
        public String data;
        public String path;
        public String text;

        public static enum Type {
            @SerializedName("me") ME,
            @SerializedName("text") TEXT,
            @SerializedName("emoticon") EMOTICON,
            @SerializedName("link") LINK,
        }
    }
}

package pro.beam.api.resource.chat.events.data;

import java.util.List;

import pro.beam.api.resource.BeamUser;
import pro.beam.api.resource.chat.AbstractChatEvent;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterators;
import com.google.gson.annotations.SerializedName;

public class IncomingMessageData extends AbstractChatEvent.EventData {
    public int channel;
    public String id;
    public String user_name;
    public String user_id;
    public List<BeamUser.Role> user_roles;
    public List<MessagePart> message;

    public String getMessage() {
        return Joiner.on(' ').join(Iterators.transform(this.message.iterator(), new Function<MessagePart, String>() {
            @Override public String apply(MessagePart part) {
                switch(part.type) {
                    case ME:
                    case EMOTICON:
                        return part.text;
                    case LINK:
                        return part.url;
                    case TEXT:
                    default:
                        return part.data;
                }
            }
        }));
    }

    public static class MessagePart {
        public Type type;
        public String url;
        public String data;
        public String path;
        public String text;

        // Emoticon-related
        public String source;
        public String pack;
        public Coords coords;

        public static class Coords {
            public int x;
            public int y;
        }

        public static enum Type {
            @SerializedName("me") ME,
            @SerializedName("text") TEXT,
            @SerializedName("emoticon") EMOTICON,
            @SerializedName("link") LINK,
        }
    }
}

Fix emoticon-related parsing issues for chat messages


package com.ggj.game;

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.Array;
import com.ggj.model.Player;
import com.ggj.model.Rock;

public class ObjectController {
  public static synchronized int register(Actor actor) {
    objects.add(actor);

    return ++objectId;
  }

  public static <T> T getObject(Class<T> callee)
  {
    for(Actor actor : objects)
    {
      if(callee.equals(actor.getClass()))
      {
        return (T)actor;
      }
    }

    return null;
  }

  private static int objectId = 0;
  private static Array<Actor> objects = new Array<Actor>();
}

package com.ggj.game;

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

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.Array;
import com.ggj.model.Player;
import com.ggj.model.Rock;

public class ObjectController {
  public static synchronized int register(Actor actor) {
    objects.add(actor);

    return ++objectId;
  }

  public static <T> T getObject(Class<T> callee)
  {
    for(Actor actor : objects)
    {
      if(callee.equals(actor.getClass()))
      {
        return (T)actor;
      }
    }

    return null;
  }

  public static <T> List<T> getList(Class<T> callee)
  {
    List<T> result = new ArrayList<T>();
    for(Actor actor : objects)
    {
      if(callee.equals(actor.getClass()))
      {
        result.add((T)actor);
      }
    }

    return result;
  }

  private static int objectId = 0;
  private static Array<Actor> objects = new Array<Actor>();
}

Add generic way to get a list of objects by class


package uk.ac.ebi.biosamples.utils;

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

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;

public class MailSender {
    private static final String BODY_PART_FAIL = " failed execution on ";
    private static final String MAILX = "mailx";
    private static final String SUBJECT = "-s Email from pipeline ";
    private static final String RECIPIENT = "biosamples-tech@ebi.ac.uk";
    private static final String BODY_PART_SUCCESS = " pipeline execution successful for ";
    public static final String FAILED_FILES_ARE = " Failed files are: ";
    private static Logger log = LoggerFactory.getLogger("MailSender");

    public static void sendEmail(final String pipelineName, final String failures, final boolean isPassed) {
        try {
            final String[] cmd = {MAILX, SUBJECT + pipelineName, RECIPIENT};
            final Process p = Runtime.getRuntime().exec(cmd);
            final OutputStreamWriter osw = new OutputStreamWriter(p.getOutputStream());

            if (isPassed) {
                if (failures != null && !failures.isEmpty())
                    osw.write(pipelineName + BODY_PART_SUCCESS + new Date() + FAILED_FILES_ARE + failures);
                else
                    osw.write(pipelineName + BODY_PART_SUCCESS + new Date());
            } else osw.write(pipelineName + BODY_PART_FAIL + new Date());

            osw.close();
        } catch (final IOException ioe) {
            log.error("Email send failed");
        }
    }
}

package uk.ac.ebi.biosamples.utils;

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

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;

public class MailSender {
    private static final String BODY_PART_FAIL = " failed execution on ";
    private static final String MAILX = "mailx";
    private static final String SUBJECT = "-s Email from pipeline ";
    private static final String RECIPIENT = "biosamples-dev@ebi.ac.uk";
    private static final String BODY_PART_SUCCESS = " pipeline execution successful for ";
    public static final String FAILED_FILES_ARE = " Failed files are: ";
    private static Logger log = LoggerFactory.getLogger("MailSender");

    public static void sendEmail(final String pipelineName, final String failures, final boolean isPassed) {
        try {
            final String[] cmd = {MAILX, SUBJECT + pipelineName, RECIPIENT};
            final Process p = Runtime.getRuntime().exec(cmd);
            final OutputStreamWriter osw = new OutputStreamWriter(p.getOutputStream());

            if (isPassed) {
                if (failures != null && !failures.isEmpty())
                    osw.write(pipelineName + BODY_PART_SUCCESS + new Date() + FAILED_FILES_ARE + failures);
                else
                    osw.write(pipelineName + BODY_PART_SUCCESS + new Date());
            } else osw.write(pipelineName + BODY_PART_FAIL + new Date());

            osw.close();
        } catch (final IOException ioe) {
            log.error("Email send failed");
        }
    }
}

Send emails to biosamples-dev@ebi.ac.uk until we find what is wrong in sending to tech


package pl.brightinventions.slf4android;

import java.text.SimpleDateFormat;

class DateValueSupplier implements LoggerPatternValueSupplier {
    private static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS");
        }
    };

    @Override
    public void append(LogRecord record, StringBuilder builder) {
        String formatted = dateFormat.get().format(record.getDate());
        builder.append(formatted);
    }
}

package pl.brightinventions.slf4android;

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

class DateValueSupplier implements LoggerPatternValueSupplier {
    private static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS", Locale.US);
        }
    };

    @Override
    public void append(LogRecord record, StringBuilder builder) {
        String formatted = dateFormat.get().format(record.getDate());
        builder.append(formatted);
    }
}

Fix lint warning about locale

Fix lint warning about locale


/**
 * Project RSA Algorithm.
 * Copyright Michał Szczygieł.
 * Created at Mar 14, 2014.
 */

package com.m4gik;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Test;

/**
 * This class contains JUnit tests for class {@link SHA1}.
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
public class SHA1Test {

    private static final String EXAMPLE_TEXT = "The quick brown fox jumps over the lazy dog";
    private static final String HASHED_EXAMPLE_TEXT = "2fd4e1c6 7a2d28fc ed849ee1 bb76e739 1b93eb12";

    /**
     * This test method checks SHA1 algorithm for given string, which should be
     * correct with another algorithm based on SHA1.
     *
     * @throws Exception
     */
    @Test
    public void checkCorrectnessOfSHA1() throws Exception {
        // given
        SHA1 sha1 = new SHA1();
        // when
        String result = sha1.hash(EXAMPLE_TEXT);
        // then
        assertThat(result, is(equalTo(HASHED_EXAMPLE_TEXT)));
    }
}

/**
 * Project RSA Algorithm.
 * Copyright Michał Szczygieł.
 * Created at Mar 14, 2014.
 */

package com.m4gik;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.security.spec.InvalidParameterSpecException;

import org.junit.Test;

/**
 * This class contains JUnit tests for class {@link SHA1}.
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
public class SHA1Test {

    private static final String EXAMPLE_TEXT = "The quick brown fox jumps over the lazy dog";
    private static final String HASHED_EXAMPLE_TEXT = "2fd4e1c6 7a2d28fc ed849ee1 bb76e739 1b93eb12";

    /**
     * This test method checks SHA1 algorithm for given string, which should be
     * correct with another algorithm based on SHA1.
     *
     * @throws Exception
     */
    @Test
    public void checkCorrectnessOfSHA1() throws Exception {
        // when
        String result = SHA1.hash(EXAMPLE_TEXT);
        // then
        assertThat(result, is(equalTo(HASHED_EXAMPLE_TEXT)));
    }

    /**
     * This test method checks SHA1 algorithm for given string, and this method
     * shouldn't return exeption
     *
     * @throws Exception
     */
    @Test(
            expected = InvalidParameterSpecException.class)
    public void dataShouldBeMultipleOf64() throws Exception {
        // when
        SHA1.checkData(EXAMPLE_TEXT.getBytes());
        // then ... throw new Exception
    }
}

Add test for checkData() method

Add test for checkData() method


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

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;

/**
 * Generic ResourceNotFoundException corresponding to the {@link RestStatus#NOT_FOUND} status code
 */
public class ResourceNotFoundException extends ElasticsearchException {

    public ResourceNotFoundException(String msg, Object... args) {
        super(msg, args);
    }

    protected ResourceNotFoundException(String msg, Throwable cause, Object... args) {
        super(msg, cause, args);
    }

    public ResourceNotFoundException(StreamInput in) throws IOException {
        super(in);
    }

    @Override
    public final RestStatus status() {
        return RestStatus.NOT_FOUND;
    }
}

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

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;

/**
 * Generic ResourceNotFoundException corresponding to the {@link RestStatus#NOT_FOUND} status code
 */
public class ResourceNotFoundException extends ElasticsearchException {

    public ResourceNotFoundException(String msg, Object... args) {
        super(msg, args);
    }

    public ResourceNotFoundException(String msg, Throwable cause, Object... args) {
        super(msg, cause, args);
    }

    public ResourceNotFoundException(StreamInput in) throws IOException {
        super(in);
    }

    @Override
    public final RestStatus status() {
        return RestStatus.NOT_FOUND;
    }
}

Fix exception on task not found

Fix exception on task not found

Silly protected method....


package stroom.data.store.impl.fs;

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

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

class StreamTypeExtensions {
    private static final Logger LOGGER = LoggerFactory.getLogger(StreamTypeExtensions.class);
    private static final Map<String, String> EXTENSION_MAP = new HashMap<>();

    static {
        EXTENSION_MAP.put("Manifest", "mf");
        EXTENSION_MAP.put("Raw Events", "revt");
        EXTENSION_MAP.put("Raw Reference", "rref");
        EXTENSION_MAP.put("Events", "evt");
        EXTENSION_MAP.put("Reference", "ref");
        EXTENSION_MAP.put("Test Events", "tevt");
        EXTENSION_MAP.put("Test Reference", "tref");
        EXTENSION_MAP.put("Segment Index", "seg");
        EXTENSION_MAP.put("Boundary Index", "bdy");
        EXTENSION_MAP.put("Meta Data", "meta");
        EXTENSION_MAP.put("Error", "err");
        EXTENSION_MAP.put("Context", "ctx");
    }

    static String getExtension(final String streamType) {
        String extension = EXTENSION_MAP.get(streamType);
        if (extension == null) {
            LOGGER.warn("Unknown stream type '" + streamType + "' using extension 'dat'");
            extension = "dat";
        }
        return extension;
    }
}

package stroom.data.store.impl.fs;

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

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

class StreamTypeExtensions {
    private static final Logger LOGGER = LoggerFactory.getLogger(StreamTypeExtensions.class);
    private static final Map<String, String> EXTENSION_MAP = new HashMap<>();

    static {
        EXTENSION_MAP.put("Manifest", "mf");
        EXTENSION_MAP.put("Raw Events", "revt");
        EXTENSION_MAP.put("Raw Reference", "rref");
        EXTENSION_MAP.put("Events", "evt");
        EXTENSION_MAP.put("Reference", "ref");
        EXTENSION_MAP.put("Test Events", "tevt");
        EXTENSION_MAP.put("Test Reference", "tref");
        EXTENSION_MAP.put("Segment Index", "seg");
        EXTENSION_MAP.put("Boundary Index", "bdy");
        EXTENSION_MAP.put("Meta Data", "meta");
        EXTENSION_MAP.put("Error", "err");
        EXTENSION_MAP.put("Context", "ctx");
        EXTENSION_MAP.put("Detections", "dtxn");
    }

    static String getExtension(final String streamType) {
        String extension = EXTENSION_MAP.get(streamType);
        if (extension == null) {
            LOGGER.warn("Unknown stream type '" + streamType + "' using extension 'dat'");
            extension = "dat";
        }
        return extension;
    }
}

Introduce new Detections stream type

Introduce new Detections stream type


package org.springframework.cloud.cloudfoundry;

import java.util.Map;

import org.springframework.cloud.service.common.MongoServiceInfo;

/**
 *
 * @author Ramnivas Laddad
 *
 */
public class MongoServiceInfoCreator extends CloudFoundryServiceInfoCreator<MongoServiceInfo> {

	public MongoServiceInfoCreator() {
		super("mongodb");

	}

	public MongoServiceInfo createServiceInfo(Map<String,Object> serviceData) {
		@SuppressWarnings("unchecked")
		Map<String,Object> credentials = (Map<String, Object>) serviceData.get("credentials");

		String id = (String) serviceData.get("name");

		String uri = (String) credentials.get("uri");

		return new MongoServiceInfo(id, uri);
	}

}

package org.springframework.cloud.cloudfoundry;

import java.util.Map;

import org.springframework.cloud.service.common.MongoServiceInfo;

/**
 *
 * @author Ramnivas Laddad
 *
 */
public class MongoServiceInfoCreator extends CloudFoundryServiceInfoCreator<MongoServiceInfo> {

	public MongoServiceInfoCreator() {
		super("mongodb");

	}

	public MongoServiceInfo createServiceInfo(Map<String,Object> serviceData) {
		@SuppressWarnings("unchecked")
		Map<String,Object> credentials = (Map<String, Object>) serviceData.get("credentials");

		String id = (String) serviceData.get("name");

		String uri = (String) ((credentials.get("uri") == null) ? credentials.get("url") : credentials.get("uri"));

		return new MongoServiceInfo(id, uri);
	}

}

Add fix for MongoDb if url is used instead of uri


package com.vladmihalcea.book.hpjp.hibernate.transaction.spring.routing;

import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Post;
import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Tag;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Arrays;
import java.util.List;

/**
 * @author Vlad Mihalcea
 */
@Service
public class ForumServiceImpl implements ForumService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    public Post newPost(String title, String... tags) {
        Post post = new Post();
        post.setTitle(title);

        post.getTags().addAll(
            entityManager.createQuery("""
                select t
                from Tag t
                where t.name in :tags
                """, Tag.class)
            .setParameter("tags", Arrays.asList(tags))
            .getResultList()
        );

        entityManager.persist(post);

        return post;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Post> findAllPostsByTitle(String title) {
        return entityManager.createQuery("""
            select p
            from Post p
            where p.title = :title
            """, Post.class)
        .setParameter("title", title)
        .getResultList();
    }
}

package com.vladmihalcea.book.hpjp.hibernate.transaction.spring.routing;

import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Post;
import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Tag;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Arrays;
import java.util.List;

/**
 * @author Vlad Mihalcea
 */
@Service
@Transactional(readOnly = true)
public class ForumServiceImpl implements ForumService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    public Post newPost(String title, String... tags) {
        Post post = new Post();
        post.setTitle(title);

        post.getTags().addAll(
            entityManager.createQuery("""
                select t
                from Tag t
                where t.name in :tags
                """, Tag.class)
            .setParameter("tags", Arrays.asList(tags))
            .getResultList()
        );

        entityManager.persist(post);

        return post;
    }

    @Override
    public List<Post> findAllPostsByTitle(String title) {
        return entityManager.createQuery("""
            select p
            from Post p
            where p.title = :title
            """, Post.class)
        .setParameter("title", title)
        .getResultList();
    }
}

Move the @Transactional(readOnly = true) annotation to class level


package org.cyanogenmod.launcher.home.api.sdkexample.receiver;

import android.util.Log;

import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;

/**
 * An extension of CmHomeCardChangeReceiver, that implements the callback for
 * when a card is deleted.
 */
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
    public static final String TAG = "CardDeletedBroadcastReceiver";

    @Override
    protected void onCardDeleted(DataCard.CardDeletedInfo cardDeletedInfo) {
        Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
                   + ", internalID: " + cardDeletedInfo.getInternalId()
                   + ", authority: " + cardDeletedInfo.getAuthority()
                   + ", globalID: " + cardDeletedInfo.getGlobalId());
    }
}

package org.cyanogenmod.launcher.home.api.sdkexample.receiver;

import android.content.Context;
import android.util.Log;

import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;

/**
 * An extension of CmHomeCardChangeReceiver, that implements the callback for
 * when a card is deleted.
 */
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
    public static final String TAG = "CardDeletedBroadcastReceiver";

    @Override
    protected void onCardDeleted(Context context, DataCard.CardDeletedInfo cardDeletedInfo) {
        Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
                   + ", internalID: " + cardDeletedInfo.getInternalId()
                   + ", authority: " + cardDeletedInfo.getAuthority()
                   + ", globalID: " + cardDeletedInfo.getGlobalId());    }
}

Add Context parameter to onCardDelete to match SDK