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

package org.gradle.api.internal.changedetection.state;

import org.gradle.api.internal.changedetection.state.mirror.PhysicalSnapshot;
import org.gradle.internal.file.FileType;
import org.gradle.internal.hash.HashCode;

public class DefaultNormalizedFileSnapshot extends AbstractNormalizedFileSnapshot {
    private final String normalizedPath;

    public DefaultNormalizedFileSnapshot(String normalizedPath, FileType type, HashCode contentHash) {
        super(type, contentHash);
        this.normalizedPath = normalizedPath;
    }

    public DefaultNormalizedFileSnapshot(String normalizedPath, PhysicalSnapshot snapshot) {
        this(normalizedPath, snapshot.getType(), snapshot.getType() == FileType.Directory ? DIR_SIGNATURE : snapshot.getHash());
    }

    @Override
    public String getNormalizedPath() {
        return normalizedPath;
    }
}

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

package org.gradle.api.internal.changedetection.state;

import org.gradle.api.internal.changedetection.state.mirror.PhysicalSnapshot;
import org.gradle.internal.file.FileType;
import org.gradle.internal.hash.HashCode;

public class DefaultNormalizedFileSnapshot extends AbstractNormalizedFileSnapshot {
    private final String normalizedPath;

    public DefaultNormalizedFileSnapshot(String normalizedPath, FileType type, HashCode contentHash) {
        super(type, hashForType(type, contentHash));
        this.normalizedPath = normalizedPath;
    }

    public DefaultNormalizedFileSnapshot(String normalizedPath, PhysicalSnapshot snapshot) {
        this(normalizedPath, snapshot.getType(), snapshot.getHash());
    }

    private static HashCode hashForType(FileType fileType, HashCode hash) {
        switch (fileType) {
            case Directory:
                return DIR_SIGNATURE;
            case Missing:
                return MISSING_FILE_SIGNATURE;
            case RegularFile:
                return hash;
            default:
                throw new IllegalStateException("Unknown file type: " + fileType);
        }
    }

    @Override
    public String getNormalizedPath() {
        return normalizedPath;
    }
}

Use correct hash for missing files

Use correct hash for missing files


package com.amee.domain;

import java.util.Date;

public class ProfileItemsFilter extends LimitFilter {

    private Date startDate = new Date();
    private Date endDate = null;

    @Override
    public int getResultLimitDefault() {
        return 50;
    }

    @Override
    public int getResultLimitMax() {
        return 100;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        if (startDate != null) {
            this.startDate = startDate;
        }
    }
}

package com.amee.domain;

import java.util.Date;

public class ProfileItemsFilter extends LimitFilter {

    private Date startDate = new Date();
    private Date endDate = null;

    /**
     * Setting this to 'start' will only include items which start during the query window.
     * Setting 'end' will include only items which end during the window.
     * The default behaviour is to include any item that intersects the query window.
     */
    private String selectBy;

    // TODO: Handle mode (prorata)

    @Override
    public int getResultLimitDefault() {
        return 50;
    }

    @Override
    public int getResultLimitMax() {
        return 100;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        if (startDate != null) {
            this.startDate = startDate;
        }
    }

    public String getSelectBy() {
        return selectBy;
    }

    public void setSelectBy(String selectBy) {
        this.selectBy = selectBy;
    }
}

Handle selectBy for profile items. PL-11101.


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

import playn.core.PlayN;
import playn.java.JavaPlatform;
import playn.showcase.core.Showcase;

public class ShowcaseJava {

  public static void main(String[] args) {
    JavaPlatform platform = JavaPlatform.register();
    platform.assets().setPathPrefix("playn/showcase/resources");
    platform.graphics().registerFont("Museo-300", "text/Museo.otf");
    PlayN.run(new Showcase());
  }
}

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

import playn.core.PlayN;
import playn.java.JavaPlatform;
import playn.showcase.core.Showcase;

public class ShowcaseJava {

  public static void main(String[] args) {
    JavaPlatform platform = JavaPlatform.register();
    platform.assets().setPathPrefix("playn/showcase/resources");
    platform.graphics().registerFont("Museo-300", "text/Museo.ttf");
    PlayN.run(new Showcase());
  }
}

Use the TTF version of the font in Java.

Windows (XP anyway) seems not to support OpenType fonts. Yay!


/*
 * History
 * Created on Nov 23, 2004 by kofke
 */
package etomica.nbr.cell;

import etomica.atom.Atom;
import etomica.atom.AtomArrayList;
import etomica.atom.AtomList;
import etomica.lattice.AbstractLattice;
import etomica.lattice.RectangularLattice;
import etomica.lattice.SiteFactory;

/**
 * Site used to form array of cells for cell-based neighbor listing.  Each
 * cell is capable of holding lists of atoms that are in them.
 */

public class Cell implements java.io.Serializable {

    public Cell(int latticeArrayIndex) {
        this.latticeArrayIndex = latticeArrayIndex;
    }

    public AtomArrayList occupants() {return occupants;}

    public void addAtom(Atom atom) {
        occupants.add(atom);
    }

    public void removeAtom(Atom atom) {
        occupants.removeAndReplace(occupants.indexOf(atom));
    }

    public int getLatticeArrayIndex() {
        return latticeArrayIndex;
    }

    private final AtomArrayList occupants = new AtomArrayList();
    final int latticeArrayIndex;//identifies site in lattice

    public static final SiteFactory FACTORY = new CellFactory();

    public static class CellFactory implements SiteFactory, java.io.Serializable {
        public Object makeSite(AbstractLattice lattice, int[] coord) {
            return new Cell(((RectangularLattice)lattice).arrayIndex(coord));
        }
    };
}

/*
 * History
 * Created on Nov 23, 2004 by kofke
 */
package etomica.nbr.cell;

import etomica.atom.Atom;
import etomica.atom.AtomArrayList;
import etomica.atom.AtomList;
import etomica.lattice.AbstractLattice;
import etomica.lattice.RectangularLattice;
import etomica.lattice.SiteFactory;

/**
 * Site used to form array of cells for cell-based neighbor listing.  Each
 * cell is capable of holding lists of atoms that are in them.
 */

public class Cell implements java.io.Serializable {

    public Cell(int latticeArrayIndex) {
        this.latticeArrayIndex = latticeArrayIndex;
    }

    public AtomArrayList occupants() {return occupants;}

    public void addAtom(Atom atom) {
        occupants.add(atom);
    }

    public void removeAtom(Atom atom) {
        occupants.removeAndReplace(occupants.indexOf(atom));
    }

    public int getLatticeArrayIndex() {
        return latticeArrayIndex;
    }

    private final AtomArrayList occupants = new AtomArrayList(1);
    final int latticeArrayIndex;//identifies site in lattice

    public static final SiteFactory FACTORY = new CellFactory();

    public static class CellFactory implements SiteFactory, java.io.Serializable {
        public Object makeSite(AbstractLattice lattice, int[] coord) {
            return new Cell(((RectangularLattice)lattice).arrayIndex(coord));
        }
    };
}

Use initial capacity of 1. Max is often just 1 or maybe 2. LJMC might get slower, but everyone should use less RAM and some might get faster. Any slowdown should only affect startup, not long-term performance of a simulation.


package de.otto.edison.metricsconfiguration;

import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcTagsProvider;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.servlet.DispatcherType;

@Component
public class WebMvcMetricsFilterWorkaroundForBugInSpringBoot2_7_0 {

    @Bean
    public FilterRegistrationBean<WebMvcMetricsFilter> webMvcMetricsFilter(MetricsProperties properties,
                                                                           MeterRegistry registry, WebMvcTagsProvider tagsProvider) {
        MetricsProperties.Web.Server.ServerRequest request = properties.getWeb().getServer().getRequest();
        WebMvcMetricsFilter filter = new WebMvcMetricsFilter(registry, tagsProvider, request.getMetricName(),
                request.getAutotime());
        FilterRegistrationBean<WebMvcMetricsFilter> registration = new FilterRegistrationBean<>(filter);
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
        registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
        return registration;
    }

}

package de.otto.edison.metricsconfiguration;

import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcTagsProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.servlet.DispatcherType;

/* TODO: Remove this when Spring Boot 2.7.1 is there */
@Component
public class WebMvcMetricsFilterWorkaroundForBugInSpringBoot2_7_0 {

    @Bean
    @ConditionalOnMissingBean
    public FilterRegistrationBean<WebMvcMetricsFilter> webMvcMetricsFilter(MetricsProperties properties,
                                                                           MeterRegistry registry, WebMvcTagsProvider tagsProvider) {
        MetricsProperties.Web.Server.ServerRequest request = properties.getWeb().getServer().getRequest();
        WebMvcMetricsFilter filter = new WebMvcMetricsFilter(registry, tagsProvider, request.getMetricName(),
                request.getAutotime());
        FilterRegistrationBean<WebMvcMetricsFilter> registration = new FilterRegistrationBean<>(filter);
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
        registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
        return registration;
    }

}

Add condition to webMvcMetricsFilter bean

Co-authored-by: Marco Geweke <8bae85dbfa00ce59d1b81e4121747343f331087b@otto.de>


package signature;

import java.util.Arrays;

public class CanonicalLabellingVisitor implements DAGVisitor {

    private int[] labelling;

    private int currentLabel;

    public CanonicalLabellingVisitor(int vertexCount) {
        this.labelling = new int[vertexCount];
        Arrays.fill(this.labelling, -1);
        this.currentLabel = 0;
    }

    public void visit(DAG.Node node) {
        // only label if this vertex has not yet been labeled
        if (this.labelling[node.vertexIndex] == -1) {
            this.labelling[node.vertexIndex] = this.currentLabel;
            this.currentLabel++;
        }
        for (DAG.Node child : node.children) {
            child.accept(this);
        }
    }

    public int[] getLabelling() {
        return this.labelling;
    }

}

package signature;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

public class CanonicalLabellingVisitor implements DAGVisitor {

    private int[] labelling;

    private int currentLabel;

    private Comparator<DAG.Node> comparator;

    public CanonicalLabellingVisitor(
            int vertexCount, Comparator<DAG.Node> comparator) {
        labelling = new int[vertexCount];
        Arrays.fill(labelling, -1);
        currentLabel = 0;
    }

    public void visit(DAG.Node node) {
        // only label if this vertex has not yet been labeled
        if (this.labelling[node.vertexIndex] == -1) {
            this.labelling[node.vertexIndex] = this.currentLabel;
            this.currentLabel++;
        }
        Collections.sort(node.children, comparator);
        for (DAG.Node child : node.children) {
            child.accept(this);
        }
    }

    public int[] getLabelling() {
        return this.labelling;
    }

}

Sort the child nodes in the labelling visitor, to make sure that they are sorted


package com.young.simpledict.dict;

import com.young.simpledict.dict.model.DictDetail;

/**
 * Author: taylorcyang
 * Date:   2014-10-21
 * Time:   19:00
 * Life with passion. Code with creativity!
 */
public interface DictAdapter {
    public static final int DICT_YOUDAO_BRIEF = 0;
    public static final int DICT_YOUDAO_DETAIL = 1;

    public String getSearchUri(String mWordToSearch);

    public DictDetail parseDict(String response);
}

package com.young.simpledict.dict;

import com.young.simpledict.dict.model.DictDetail;

/**
 * Author: taylorcyang
 * Date:   2014-10-21
 * Time:   19:00
 * Life with passion. Code with creativity!
 */
public interface DictAdapter {
    int DICT_YOUDAO_BRIEF = 0;
    int DICT_YOUDAO_DETAIL = 1;

    String getSearchUri(String mWordToSearch);

    DictDetail parseDict(String response);
}

Remove redundant modifier from interface fields and method


package org.kohsuke.github;

import java.io.IOException;
import org.junit.Test;

/**
 * @author Martin van Zijl
 */
public class GHIssueEventTest extends AbstractGitHubApiTestBase {

    @Test
    public void testEventsForSingleIssue() throws Exception {
        GHRepository repo = getRepository();
        GHIssue issue = repo.getIssue(1);

        for (GHIssueEvent event : issue.listEvents()) {
            System.out.println(event);
        }

        //TODO: Use the following...
        //GHIssueBuilder builder = repo.createIssue("test from the api");
        //GHIssue issue = builder.create();
    }

    @Test
    public void testRepositoryEvents() throws Exception {
        GHRepository repo = getRepository();
        PagedIterable<GHIssueEvent> list = repo.listIssueEvents();

        for (GHIssueEvent event : list) {
            System.out.println(event);
        }
    }

    @Test
    public void testRepositorySingleEvent() throws Exception {
        GHRepository repo = getRepository();
        GHIssueEvent event = repo.getIssueEvent(2615868520L);

        System.out.println(event);
    }

    protected GHRepository getRepository() throws IOException {
        return getRepository(gitHub);
    }

    private GHRepository getRepository(GitHub gitHub) throws IOException {
        return gitHub.getOrganization("github-api-test-org").getRepository("github-api");
    }
}

package org.kohsuke.github;

import java.io.IOException;
import org.junit.Test;

/**
 * @author Martin van Zijl
 */
public class GHIssueEventTest extends AbstractGitHubApiTestBase {

    @Test
    public void testEventsForSingleIssue() throws Exception {
        GHRepository repo = getRepository();
        GHIssue issue = repo.getIssue(1);

        System.out.println("Single issue:");
        for (GHIssueEvent event : issue.listEvents()) {
            System.out.println(event);
        }

        //TODO: Use the following...
        //GHIssueBuilder builder = repo.createIssue("test from the api");
        //GHIssue issue = builder.create();
    }

    @Test
    public void testRepositoryEvents() throws Exception {
        GHRepository repo = getRepository();
        PagedIterable<GHIssueEvent> list = repo.listIssueEvents();

        System.out.println("Repository (all):");
        int i = 0;
        for (GHIssueEvent event : list.asList()) {
            System.out.println(event);
            if (i++ > 10) break;
        }
    }

    @Test
    public void testRepositorySingleEvent() throws Exception {
        GHRepository repo = getRepository();
        GHIssueEvent event = repo.getIssueEvent(2615868520L);

        System.out.println("Repository (single event):");
        System.out.println(event);
    }

    protected GHRepository getRepository() throws IOException {
        return getRepository(gitHub);
    }

    private GHRepository getRepository(GitHub gitHub) throws IOException {
        return gitHub.getOrganization("github-api-test-org").getRepository("github-api");
    }
}

Make unit test output neater.

Make unit test output neater.


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

package bisq.asset.coins;

import bisq.asset.Base58BitcoinAddressValidator;
import bisq.asset.Coin;
import bisq.asset.NetworkParametersAdapter;

public class KnowYourDeveloper extends Coin {
    public KnowYourDeveloper() {
        super("Know Your Developer", "KYD", new Base58BitcoinAddressValidator(new KydMainNetParams()));
    }

    public static class KydMainNetParams extends NetworkParametersAdapter {
        public KydMainNetParams() {
            this.addressHeader = 78;
            this.p2shHeader = 85;
            this.acceptableAddressCodes = new int[]{this.addressHeader, this.p2shHeader};
        }
    }
}

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

package bisq.asset.coins;

import bisq.asset.Base58BitcoinAddressValidator;
import bisq.asset.Coin;
import bisq.asset.NetworkParametersAdapter;

public class KnowYourDeveloper extends Coin {
    public KnowYourDeveloper() {
        super("Know Your Developer", "KYDC", new Base58BitcoinAddressValidator(new KydMainNetParams()));
    }

    public static class KydMainNetParams extends NetworkParametersAdapter {
        public KydMainNetParams() {
            this.addressHeader = 78;
            this.p2shHeader = 85;
            this.acceptableAddressCodes = new int[]{this.addressHeader, this.p2shHeader};
        }
    }
}

Update KYD to KYDC listing to be conform ISO_4217


package com.bendoerr.saltedmocha;

import static com.bendoerr.saltedmocha.CryptoException.exceptionOf;

public class Util {

    public static final int MAX_ARRAY_SIZE;

    static {
        int max = Integer.MAX_VALUE - 2;
        try {
            byte[] bytes = new byte[max];
        } catch (java.lang.OutOfMemoryError oom) {
            // Probably OK. Need to test on 32bit JVM.
            // Reports say it's somewhere around 1.1 billion.
            max = Integer.MAX_VALUE / 2;
        }
        MAX_ARRAY_SIZE = max;
    }

    public static void checkedArrayCopy(Object src, int srcPos, Object dst, int dstPos, int len) throws CryptoException {
        try {
            System.arraycopy(src, srcPos, dst, dstPos, len);
        } catch (RuntimeException re) {
            throw exceptionOf(re);
        }
    }

    public static void validateLength(byte[] a, int expected, String what, String expectedWhat) throws CryptoException {
        if (a.length != expected)
            throw exceptionOf(new IllegalArgumentException(
                    what + " length(" + a.length + ") is not " + expectedWhat + "(" + expected + ")"));
    }

}

package com.bendoerr.saltedmocha;

import static com.bendoerr.saltedmocha.CryptoException.exceptionOf;

public class Util {

    public static final int MAX_ARRAY_SIZE;

    static {
        int max = Integer.MAX_VALUE - 2;
        try {
            byte[] bytes = new byte[max];
        } catch (java.lang.OutOfMemoryError oom) {
            // Probably OK. Need to test on 32bit JVM.
            // Reports say it's somewhere around 1.1 billion.
            max = Integer.MAX_VALUE / 2;
        }
        MAX_ARRAY_SIZE = max;
    }

    public static void checkedArrayCopy(Object src, int srcPos, Object dst, int dstPos, int len) throws CryptoException {
        try {
            System.arraycopy(src, srcPos, dst, dstPos, len);
        } catch (RuntimeException re) {
            throw exceptionOf(re);
        }
    }

    public static void validateLength(byte[] a, int expected, String what, String expectedWhat) throws CryptoException {
        if (a.length != expected)
            throw exceptionOf(new IllegalArgumentException(
                    what + " length(" + a.length + ") is not " + expectedWhat + "(" + expected + ")"));
    }

    /**
     * Approximation of libsodium's sodium_memzero. For us in
     * Javaland it looks like fill(array, (byte) 0)
     *
     * @param array to zero out.
     *
     * @see Libsodium Zeroing Memory
     */
    public static void java_memzero(byte[] array) {
        fill(array, (byte) 0);
    }

}

Add approximation of libsodium's sodium_memzero.


/*
 * Copyright (c) 2010 Célio Cidral Junior
 *
 *    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.tomighty.sound.timer;

import org.tomighty.config.Options.SoundConfig;
import org.tomighty.sound.SoundSupport;

public class Ding extends SoundSupport {

	@Override
	protected SoundConfig configuration() {
		return options().sound().ding();
	}

	@Override
	protected String defaultSoundResource() {
		return "/ding.wav";
	}

}

/*
 * Copyright (c) 2010 Célio Cidral Junior
 *
 *    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.tomighty.sound.timer;

import org.tomighty.config.Options.SoundConfig;
import org.tomighty.sound.SoundSupport;

public class Ding extends SoundSupport {

	@Override
	protected SoundConfig configuration() {
		return options().sound().ding();
	}

	@Override
	protected String defaultSoundResource() {
		return "/deskbell.wav";
	}

}

Fix ding sound's resource name

Fix ding sound's resource name


package invtweaks.forge.asm;

import cpw.mods.fml.relauncher.IFMLLoadingPlugin;

import java.util.Map;

@IFMLLoadingPlugin.MCVersion("1.5.2")
@IFMLLoadingPlugin.TransformerExclusions({"invtweaks.forge.asm.ITAccessTransformer"})
public class FMLPlugin implements IFMLLoadingPlugin {
    @Override
    public String[] getLibraryRequestClass() {
        return new String[0];
    }

    @Override
    public String[] getASMTransformerClass() {
        return new String[] { "invtweaks.forge.asm.ITAccessTransformer" };
    }

    @Override
    public String getModContainerClass() {
        return null;
    }

    @Override
    public String getSetupClass() {
        return null;
    }

    @Override
    public void injectData(Map<String, Object> data) {
    }
}

package invtweaks.forge.asm;

import cpw.mods.fml.relauncher.IFMLLoadingPlugin;

import java.util.Map;

@IFMLLoadingPlugin.MCVersion("@MCVERSION@")
@IFMLLoadingPlugin.TransformerExclusions({"invtweaks.forge.asm.ITAccessTransformer"})
public class FMLPlugin implements IFMLLoadingPlugin {
    @Override
    public String[] getLibraryRequestClass() {
        return new String[0];
    }

    @Override
    public String[] getASMTransformerClass() {
        return new String[] { "invtweaks.forge.asm.ITAccessTransformer" };
    }

    @Override
    public String getModContainerClass() {
        return null;
    }

    @Override
    public String getSetupClass() {
        return null;
    }

    @Override
    public void injectData(Map<String, Object> data) {
    }
}

Use ant filtering for MC version number.


package nl.github.martijn9612.fishy;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;

public class Main extends BasicGame
{
	public Main(String gamename)
	{
		super(gamename);
	}

	@Override
	public void init(GameContainer gc) throws SlickException {}

	@Override
	public void update(GameContainer gc, int i) throws SlickException {}

	@Override
	public void render(GameContainer gc, Graphics g) throws SlickException
	{
		g.drawString("Hello World!", 100, 100);
	}

	public static void main(String[] args)
	{
		try
		{
			AppGameContainer appgc;
			appgc = new AppGameContainer(new Main("Simple Slick Game"));
			appgc.setDisplayMode(640, 480, false);
			appgc.start();
		}
		catch (SlickException ex)
		{
			Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
}

package nl.github.martijn9612.fishy;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;

public class Main extends BasicGame
{
	public Main(String gamename)
	{
		super(gamename);
	}

	@Override
	public void init(GameContainer gc) throws SlickException {}

	@Override
	public void update(GameContainer gc, int i) throws SlickException {}

	@Override
	public void render(GameContainer gc, Graphics g) throws SlickException
	{
		g.drawString("Hello World!", 100, 100);
	}

	public static void main(String[] args)
	{
		try
		{
			AppGameContainer appgc;
			appgc = new AppGameContainer(new Main("Fishy"));
			appgc.setDisplayMode(640, 480, false);
			appgc.start();
		}
		catch (SlickException ex)
		{
			Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
}

Change game name to Fishy

Change game name to Fishy


package com.varunvats.practice.sorting;

public class MergeTopDown extends MergeBase {

    public static <T extends Comparable<T>> void sort(T[] a) {
        final int N = a.length;
        aux = new Comparable[N];
        sort(a, 0, N - 1);
    }

    private static <T extends Comparable<T>> void sort(T[] a, int low, int high) {
        if (low >= high)
            return;
        final int mid = (low + high) / 2;
        sort(a, low, mid);
        sort(a, mid + 1, high);
        merge(a, low, mid, high);
    }

}

package com.varunvats.practice.sorting;

public class MergeTopDown extends MergeBase {

    public static <T extends Comparable<T>> void sort(T[] a) {
        final int N = a.length;
        aux = new Comparable[N];
        sort(a, 0, N - 1);
    }

    private static <T extends Comparable<T>> void sort(T[] a, int low, int high) {
        if (low >= high)
            return;
        final int mid = (low + high) / 2;
        sort(a, low, mid);
        sort(a, mid + 1, high);
        if (!less(a[mid], a[mid + 1]))
            merge(a, low, mid, high);
    }

}

Optimize merge step of Merge sort.

Optimize merge step of Merge sort.

A merge is necessary only when the last element of the sorted left
sub-array is greater than or equal to the first element of the sorted
right sub-array.


package x1125io.initdlight;

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

public class BootReceiver extends BroadcastReceiver {

    final String TAG = "initdlight";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {

            for (String file: context.getFilesDir().list()) {

                ProcessRunner pr = new ProcessRunner();
                String fullFilePath = context.getFilesDir().toString() + "/" + file;
                int exitCode = pr.Run(new String[] { "su", "-c", "sh " + fullFilePath });

                if (exitCode == 0) {
                    Log.d(TAG, "started " + file);
                } else {
                    Log.d(TAG, String.format(
                            "error starting %s; exit code: %d; stdout: %s; stderr: %s",
                            file,
                            exitCode,
                            pr.getStdout(),
                            pr.getStderr()
                    ));
                }
            }

        }
    }
}

package x1125io.initdlight;

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

public class BootReceiver extends BroadcastReceiver {

    final String TAG = "initdlight";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {

            for (String file: context.getFilesDir().list()) {

                ProcessRunner pr = new ProcessRunner();
                String fullFilePath = context.getFilesDir().toString() + "/" + file;
                int exitCode = pr.Run(new String[] { "su", "-c", fullFilePath });

                if (exitCode == 0) {
                    Log.d(TAG, "started " + file);
                } else {
                    Log.d(TAG, String.format(
                            "error starting %s; exit code: %d; stdout: %s; stderr: %s",
                            file,
                            exitCode,
                            pr.getStdout(),
                            pr.getStderr()
                    ));
                }
            }

        }
    }
}

Remove "sh" command from script execution


package dk.statsbiblioteket.demo;

public class Main {

    public static void main(String[] args) {
        System.out.println("This is the Demo of the Git");
        System.out.println("This is now real");
    }
}

package dk.statsbiblioteket.demo;

public class Main {

    public static void main(String[] args) {
        System.out.println("This is the Demo of the Git");
        System.out.println("This is now real");
        System.out.println("Print all the lines!!!");
    }
}

Print the most AMAZING text ever!!!!1!

Print the most AMAZING text ever!!!!1!


/*
 * Copyright (C) 2008 XStream Committers.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 *
 * Created on 13. October 2008 by Joerg Schaible
 */
package com.thoughtworks.xstream.core.util;

public final class FastField {
    private final String name;
    private final Class declaringClass;

    public FastField(Class definedIn, String name) {
        this.name = name;
        this.declaringClass = definedIn;
    }

    public String getName() {
        return this.name;
    }

    public Class getDeclaringClass() {
        return this.declaringClass;
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (this == null) {
            return false;
        }
        if (obj.getClass() == FastField.class) {
            final FastField field = (FastField)obj;
            return name.equals(field.getName())
                && declaringClass.equals(field.getDeclaringClass());
        }
        return false;
    }

    public int hashCode() {
        return name.hashCode() ^ declaringClass.hashCode();
    }

    public String toString() {
        return declaringClass.getName() + "[" + name + "]";
    }
}

/*
 * Copyright (C) 2008, 2010 XStream Committers.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 *
 * Created on 13. October 2008 by Joerg Schaible
 */
package com.thoughtworks.xstream.core.util;

public final class FastField {
    private final String name;
    private final Class declaringClass;

    public FastField(Class definedIn, String name) {
        this.name = name;
        this.declaringClass = definedIn;
    }

    public String getName() {
        return this.name;
    }

    public Class getDeclaringClass() {
        return this.declaringClass;
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (this == null) {
            return false;
        }
        if (obj.getClass() == FastField.class) {
            final FastField field = (FastField)obj;
            if ((declaringClass == null && field.declaringClass != null)
                || (declaringClass != null && field.declaringClass == null)) {
                return false;
            }
            return name.equals(field.getName())
                && (declaringClass == null || declaringClass.equals(field.getDeclaringClass()));
        }
        return false;
    }

    public int hashCode() {
        return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode());
    }

    public String toString() {
        return (declaringClass == null ? "" : declaringClass.getName() + ".") + name;
    }
}

Allow null as defining class.

Allow null as defining class.


package com.mssngvwls;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class PhaseRespacerTests {

    @Mock
    private RandomNumberGenerator randomNumberGenerator;

    @InjectMocks
    private PhraseRespacer phraseRespacer;

    @Test
    public void phrase_is_respaced() {
        final String input = "Manchester United";
        when(randomNumberGenerator.between(1, 4)).thenReturn(1);
        final String expectedOutput = "M a n c h e s t e r U n i t e d";
        final String actualOutput = phraseRespacer.respace(input);
        assertThat(actualOutput).isEqualTo(expectedOutput);
    }
}

package com.mssngvwls;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class PhaseRespacerTests {

    @Mock
    private RandomNumberGenerator randomNumberGenerator;

    @InjectMocks
    private PhraseRespacer phraseRespacer;

    @Test
    public void phrase_is_respaced_with_equal_spacings() {
        final String input = "Manchester United";
        when(randomNumberGenerator.between(1, 4)).thenReturn(1);
        final String expectedOutput = "M a n c h e s t e r U n i t e d";
        final String actualOutput = phraseRespacer.respace(input);
        assertThat(actualOutput).isEqualTo(expectedOutput);
    }

    @Test
    public void phrase_is_respaced_with_different_spacings() {
        final String input = "Manchester United";
        when(randomNumberGenerator.between(1, 4)).thenReturn(3, 2, 4, 3, 1, 3);
        final String expectedOutput = "Man ch este rUn i ted";
        final String actualOutput = phraseRespacer.respace(input);
        assertThat(actualOutput).isEqualTo(expectedOutput);
    }
}

Add respacing test with varying group sizes


package de.fau.cs.mad.fablab.android.model;

import de.fau.cs.mad.fablab.rest.core.MailAddresses;
import de.fau.cs.mad.fablab.rest.myapi.DataApi;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MailModel {
    private String mFeedbackMailAddress;
    private String mFablabMailAddress;

    public MailModel(DataApi dataApi) {
        dataApi.getMailAddresses(new Callback<MailAddresses>() {
            @Override
            public void success(MailAddresses mailAddresses, Response response) {
                mFeedbackMailAddress = mailAddresses.getFeedbackMail();
                mFablabMailAddress = mailAddresses.getFabLabMail();
            }

            @Override
            public void failure(RetrofitError error) {
                mFeedbackMailAddress = "";
                mFablabMailAddress = "";
            }
        });
    }

    public String getFeedbackMailAddress() {
        return mFeedbackMailAddress;
    }

    public String getFablabMailAddress() {
        return mFablabMailAddress;
    }
}

package de.fau.cs.mad.fablab.android.model;

import de.fau.cs.mad.fablab.rest.core.MailAddresses;
import de.fau.cs.mad.fablab.rest.myapi.DataApi;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MailModel {
    private String mFeedbackMailAddress = "";
    private String mFablabMailAddress = "";

    public MailModel(DataApi dataApi) {
        dataApi.getMailAddresses(new Callback<MailAddresses>() {
            @Override
            public void success(MailAddresses mailAddresses, Response response) {
                mFeedbackMailAddress = mailAddresses.getFeedbackMail();
                mFablabMailAddress = mailAddresses.getFabLabMail();
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    public String getFeedbackMailAddress() {
        return mFeedbackMailAddress;
    }

    public String getFablabMailAddress() {
        return mFablabMailAddress;
    }
}

Initialize mail addresses to prevent crashes


package com.epam.ta.reportportal.ws.model.integration;

import com.epam.ta.reportportal.ws.annotations.NotEmpty;
import com.fasterxml.jackson.annotation.JsonInclude;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * @author Ivan Budayeu
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UpdatePluginStateRQ implements Serializable {

	@NotNull
	@NotEmpty
	private String name;

	@NotNull
	private Boolean isEnabled;

	public UpdatePluginStateRQ() {
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Boolean getEnabled() {
		return isEnabled;
	}

	public void setEnabled(Boolean enabled) {
		isEnabled = enabled;
	}

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

		UpdatePluginStateRQ that = (UpdatePluginStateRQ) o;

		if (name != null ? !name.equals(that.name) : that.name != null) {
			return false;
		}
		return isEnabled != null ? isEnabled.equals(that.isEnabled) : that.isEnabled == null;
	}

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

package com.epam.ta.reportportal.ws.model.integration;

import com.fasterxml.jackson.annotation.JsonInclude;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * @author Ivan Budayeu
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UpdatePluginStateRQ implements Serializable {

	@NotNull
	private Boolean isEnabled;

	public UpdatePluginStateRQ() {
	}

	public Boolean getEnabled() {
		return isEnabled;
	}

	public void setEnabled(Boolean enabled) {
		isEnabled = enabled;
	}

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

		UpdatePluginStateRQ that = (UpdatePluginStateRQ) o;

		return isEnabled != null ? isEnabled.equals(that.isEnabled) : that.isEnabled == null;
	}

	@Override
	public int hashCode() {
		return isEnabled != null ? isEnabled.hashCode() : 0;
	}
}

Update Plugin state entity refactoring

Update Plugin state entity refactoring


package com.github.aureliano.achmed.resources.types;

public enum OperatingSystemFamily {

	DEBIAN,
	UBUNTU,
	RPM,
	APP
}

package com.github.aureliano.achmed.resources.types;

public enum OperatingSystemFamily {

	DEBIAN(null),
	UBUNTU(DEBIAN),
	RPM(null),
	APP(null);

	private OperatingSystemFamily ancestor;

	private OperatingSystemFamily(OperatingSystemFamily ancestor) {
		this.ancestor = ancestor;
	}

	public OperatingSystemFamily getAncestor() {
		return ancestor;
	}
}

Add attribute ancestor to operating system type.


package com.cube.storm.ui.lib.factory;

import com.cube.storm.ui.view.View;
import com.cube.storm.ui.view.holder.Holder;

/**
 * This is the factory class which is used by Storm to help with getting the correct view holder/controller
 * for a specific view class name.
 *
 * @author Callum Taylor
 * @project StormUI
 */
public abstract class ViewFactory
{
	/**
	 * Gets the view holder class for a specific view name
	 *
	 * @param viewName The name of the view to lookup
	 *
	 * @return The view holder class or null if one was not found.
	 */
	public Class<? extends Holder> getHolderForView(String viewName)
	{
		return View.valueOf(viewName).getHolderClass();
	}
}

package com.cube.storm.ui.lib.factory;

import com.cube.storm.ui.view.View;
import com.cube.storm.ui.view.holder.Holder;

/**
 * This is the factory class which is used by Storm to help with getting the correct view holder/controller
 * for a specific view class name.
 *
 * @author Callum Taylor
 * @project StormUI
 */
public abstract class ViewFactory
{
	/**
	 * Gets the view holder class for a specific view name
	 *
	 * @param viewName The name of the view to lookup
	 *
	 * @return The view holder class or null if one was not found.
	 */
	public Class<? extends Holder> getHolderForView(String viewName)
	{
		try
		{
			return View.valueOf(viewName).getHolderClass();
		}
		catch (IllegalArgumentException e)
		{
			e.printStackTrace();
		}

		return null;
	}
}

Return null in view factory if the view enum was not found


package nanomsg;

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.PointerByReference;
import com.sun.jna.ptr.IntByReference;

public class NativeLibrary {
  public static native int nn_socket (int domain, int protocol);
  public static native int nn_close (int s);
  public static native int nn_bind (int s, String addr);
  public static native int nn_connect (int s, String addr);
  public static native int nn_send (int s, byte[] buff, int len, int flags);
  public static native int nn_recv (int s, PointerByReference buff, int len, int flags);
  public static native int nn_setsockopt (int s, int level, int option, Pointer optval, int optvallen);
  public static native int nn_getsockopt (int s, int level, int option, Pointer optval, Pointer optvallen);
  public static native int nn_freemsg (Pointer msg);
  public static native int nn_errno ();
  public static native int nn_device (int s1, int s2);
  public static native void nn_term();

  public static native String nn_strerror (int errnum);
  public static native Pointer nn_symbol (int i, IntByReference value);

  static {
    Native.register("nanomsg");
  }
}

package nanomsg;

import java.nio.ByteBuffer;

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.PointerByReference;
import com.sun.jna.ptr.IntByReference;

public class NativeLibrary {
  public static native int nn_socket (int domain, int protocol);
  public static native int nn_close (int s);
  public static native int nn_bind (int s, String addr);
  public static native int nn_connect (int s, String addr);
  public static native int nn_send (int s, byte[] buff, int len, int flags);
  public static native int nn_send (int s, ByteBuffer buff, int len, int flags);
  public static native int nn_recv (int s, PointerByReference buff, int len, int flags);
  public static native int nn_setsockopt (int s, int level, int option, Pointer optval, int optvallen);
  public static native int nn_getsockopt (int s, int level, int option, Pointer optval, Pointer optvallen);
  public static native int nn_freemsg (Pointer msg);
  public static native int nn_errno ();
  public static native int nn_device (int s1, int s2);
  public static native void nn_term();

  public static native String nn_strerror (int errnum);
  public static native Pointer nn_symbol (int i, IntByReference value);

  static {
    Native.register("nanomsg");
  }
}

Add bytebuffer overload to native library.


package stexfires.io;

import stexfires.core.Record;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.util.Objects;

/**
 * @author Mathias Kalb
 * @since 0.1
 */
public class BaseRecordFile<W extends Record, R extends W> implements ReadableRecordFile<R>, WritableRecordFile<W> {

    protected final Path path;

    public BaseRecordFile(final Path path) {
        Objects.requireNonNull(path);
        this.path = path;
    }

    @Override
    public final Path getPath() {
        return path;
    }

    @Override
    public ReadableRecordProducer<R> openProducer() throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public WritableRecordConsumer<W> openConsumer() throws IOException {
        throw new UnsupportedOperationException();
    }

    protected BufferedWriter newBufferedWriter(Charset charset, OpenOption... options) throws IOException {
        return Files.newBufferedWriter(path, charset, options);
    }

    protected BufferedReader newBufferedReader(Charset charset) throws IOException {
        return Files.newBufferedReader(path, charset);
    }

}

package stexfires.io;

import stexfires.core.Record;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.util.Objects;

/**
 * @author Mathias Kalb
 * @since 0.1
 */
public class BaseRecordFile<W extends Record, R extends W> implements ReadableRecordFile<R>, WritableRecordFile<W> {

    protected final Path path;

    public BaseRecordFile(final Path path) {
        Objects.requireNonNull(path);
        this.path = path;
    }

    @Override
    public final Path getPath() {
        return path;
    }

    @Override
    public ReadableRecordProducer<R> openProducer() throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public WritableRecordConsumer<W> openConsumer() throws IOException {
        throw new UnsupportedOperationException();
    }

    protected BufferedWriter newBufferedWriter(Charset charset, OpenOption... options) throws IOException {
        return Files.newBufferedWriter(path, charset, options);
    }

    protected BufferedWriter newBufferedWriter(CharsetEncoder charsetEncoder, OpenOption... options) throws IOException {
        return new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(path, options), charsetEncoder));
    }

    protected BufferedReader newBufferedReader(Charset charset) throws IOException {
        return Files.newBufferedReader(path, charset);
    }

}

Add new method newBufferedWriter with a CharsetEncoder


package edu.asu.scrapbook.digital.util;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import edu.asu.scrapbook.digital.dao.UserDAO;
import edu.asu.scrapbook.digital.dao.UserDAOFactory;

public class UserUtil {
	public static String getRequestUsername() {
		UserService userService = UserServiceFactory.getUserService();
		return userService.getCurrentUser().getEmail();
	}

	public static boolean userExists(String username) throws Exception {
		UserDAO dao = UserDAOFactory.getInstance();
		return dao.findById(username) != null;
	}
}

package edu.asu.scrapbook.digital.util;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import edu.asu.scrapbook.digital.dao.UserDAO;
import edu.asu.scrapbook.digital.dao.UserDAOFactory;

public class UserUtil {
	public static String getRequestUsername() {
		UserService userService = UserServiceFactory.getUserService();
		User authUser = userService.getCurrentUser();
		return (authUser != null) ? authUser.getEmail() : null;
	}

	public static boolean userExists(String username) throws Exception {
		UserDAO dao = UserDAOFactory.getInstance();
		return dao.findById(username) != null;
	}
}

Add null check in case user isn't logged in


package brooklyn.cli;

import brooklyn.rest.BrooklynService;
import org.junit.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class ClientTest {

    BrooklynService brooklynServer;
    Client brooklynClient;

    @BeforeClass
    public void testSetUp() throws Exception {
        // Start the REST server
        brooklynServer = BrooklynService.newBrooklynService();
        String[] args = {"server","config.sample.yml"};
        brooklynServer.runAsync(args);
    }

    @AfterClass
    public void testTearDown() {
        // Kill the REST server
        brooklynServer = null;
    }

    @Test(enabled = true)
    public void testCatalogEntitiesCommand() {
        System.out.println("testCatalogEntitiesCommand");
        String[] args = {"catalog-entities"};
        Client.main(args);
        //TODO: check that client output matches what we expect (need to make the client more testable)
    }

}

package brooklyn.cli;

import brooklyn.rest.BrooklynService;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;

public class ClientTest {

    BrooklynService brooklynServer;
    Client brooklynClient;

    private ByteArrayOutputStream outBytes;
    private PrintStream out;
    private ByteArrayOutputStream errBytes;
    private PrintStream err;

    protected String standardOut() {
        return outBytes.toString();
    }

    protected String standardErr() {
        return errBytes.toString();
    }

    @BeforeClass
    public void testSetUp() throws Exception {
        // Start the REST server
        brooklynServer = BrooklynService.newBrooklynService();
        String[] args = {"server","config.sample.yml"};
        brooklynServer.runAsync(args);
        // Rewire the output/error stream of the client
        outBytes = new ByteArrayOutputStream();
        out = new PrintStream(outBytes);
        errBytes = new ByteArrayOutputStream();
        err = new PrintStream(errBytes);
        brooklynClient = new Client(out,err);
    }

    @AfterClass
    public void testTearDown() {
        // Kill the REST server and client instance
        brooklynServer = null;
        brooklynClient = null;
        // Reset i/o streams
        outBytes = null;
        out = null;
        errBytes = null;
        err = null;
    }

    @Test(enabled = true)
    public void testCatalogEntitiesCommand() throws Exception {
        // Run the catalog-entities command
        String[] args = {"catalog-entities"};
        brooklynClient.run(args);
        // Check that output matches what we expect
        assertThat(standardOut(), containsString("brooklyn.entity.webapp.jboss.JBoss6Server"));

    }

}

Implement assert statement for catalog-entities command


package com.github.couchmove.pojo;

import com.couchbase.client.java.Bucket;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.jetbrains.annotations.NotNull;

import java.util.Date;

/**
 * a {@link CouchbaseEntity} representing a change in Couchbase {@link Bucket}
 *
 * @author ctayeb
 * Created on 27/05/2017
 */
@EqualsAndHashCode(callSuper = false)
@Builder(toBuilder = true)
@Data
public class ChangeLog extends CouchbaseEntity implements Comparable<ChangeLog> {

    /**
     * The version of the change
     */
    private String version;

    /**
     * The execution order of the change
     */
    private Integer order;

    /**
     * The description of the change
     */
    private String description;

    /**
     * The {@link Type} of the change
     */
    private Type type;

    /**
     * The script file or folder that was executed in the change
     */
    private String script;

    /**
     * A unique identifier of the file or folder of the change
     */
    private String checksum;

    /**
     * The OS username of the process that executed the change
     */
    private String runner;

    /**
     * Date of execution of the change
     */
    private Date timestamp;

    /**
     * The duration of the execution of the change in milliseconds
     */
    private Long duration;

    /**
     * The {@link Status} of the change
     */
    private Status status;

    @Override
    public int compareTo(@NotNull ChangeLog o) {
        return version == null ? 0 : version.compareTo(o.version);
    }
}

package com.github.couchmove.pojo;

import com.couchbase.client.java.Bucket;
import lombok.*;
import org.jetbrains.annotations.NotNull;

import java.util.Date;

import static lombok.AccessLevel.PRIVATE;

/**
 * a {@link CouchbaseEntity} representing a change in Couchbase {@link Bucket}
 *
 * @author ctayeb
 *         Created on 27/05/2017
 */
@AllArgsConstructor
@NoArgsConstructor(access = PRIVATE)
@EqualsAndHashCode(callSuper = false)
@Builder(toBuilder = true)
@Data
public class ChangeLog extends CouchbaseEntity implements Comparable<ChangeLog> {

    /**
     * The version of the change
     */
    private String version;

    /**
     * The execution order of the change
     */
    private Integer order;

    /**
     * The description of the change
     */
    private String description;

    /**
     * The {@link Type} of the change
     */
    private Type type;

    /**
     * The script file or folder that was executed in the change
     */
    private String script;

    /**
     * A unique identifier of the file or folder of the change
     */
    private String checksum;

    /**
     * The OS username of the process that executed the change
     */
    private String runner;

    /**
     * Date of execution of the change
     */
    private Date timestamp;

    /**
     * The duration of the execution of the change in milliseconds
     */
    private Long duration;

    /**
     * The {@link Status} of the change
     */
    private Status status;

    @Override
    public int compareTo(@NotNull ChangeLog o) {
        return version == null ? 0 : version.compareTo(o.version);
    }
}

Fix Jackson no suitable constructor found


package kawa.standard;
import gnu.expr.*;
import gnu.lists.*;
import kawa.lang.*;

public class thisRef extends Syntax
{
  public Expression rewriteForm (Pair form, Translator tr)
  {
    if (form.cdr == LList.Empty)
      {
	ScopeExp sc = tr.currentScope();
	while (sc != null && ! (sc instanceof ClassExp))
	  sc = sc.outer;
	if (sc == null)
	  tr.error('w', "use fo this not inside a class");
	return new ThisExp(sc);
      }
    else
      return tr.syntaxError("this with paramater not implemented");
  }
}

package kawa.standard;
import gnu.expr.*;
import gnu.lists.*;
import kawa.lang.*;

public class thisRef extends Syntax
{
  public Expression rewriteForm (Pair form, Translator tr)
  {
    if (form.cdr == LList.Empty)
      {
	ScopeExp sc = tr.currentScope();
	while (sc != null && ! (sc instanceof ClassExp))
	  sc = sc.outer;
	if (sc == null)
	  tr.error('w', "use of 'this' not inside a class");
	return new ThisExp(sc);
      }
    else
      return tr.syntaxError("this with paramater not implemented");
  }
}

Fix typo in error message.

Fix typo in error message.

git-svn-id: 169764d5f12c41a1cff66b81d896619f3ce5473d@2638 5e0a886f-7f45-49c5-bc19-40643649e37f


package net.kencochrane.raven.marshaller.json;

import com.fasterxml.jackson.core.JsonGenerator;
import net.kencochrane.raven.event.interfaces.MessageInterface;

import java.io.IOException;

public class MessageInterfaceBinding implements InterfaceBinding<MessageInterface> {
    private static final String MESSAGE_PARAMETER = "message";
    private static final String PARAMS_PARAMETER = "params";

    @Override
    public void writeInterface(JsonGenerator generator, MessageInterface messageInterface) throws IOException {
        generator.writeStartObject();
        generator.writeStringField(MESSAGE_PARAMETER, messageInterface.getMessage());
        generator.writeArrayFieldStart(PARAMS_PARAMETER);
        for (String parameter : messageInterface.getParams()) {
            generator.writeString(parameter);
        }
        generator.writeEndArray();
        generator.writeEndObject();
    }
}

package net.kencochrane.raven.marshaller.json;

import com.fasterxml.jackson.core.JsonGenerator;
import net.kencochrane.raven.event.interfaces.MessageInterface;

import java.io.IOException;

public class MessageInterfaceBinding implements InterfaceBinding<MessageInterface> {
    /**
     * Maximum length for a message.
     */
    public static final int MAX_MESSAGE_LENGTH = 1000;
    private static final String MESSAGE_PARAMETER = "message";
    private static final String PARAMS_PARAMETER = "params";

    /**
     * Formats a message, ensuring that the maximum length {@link #MAX_MESSAGE_LENGTH} isn't reached.
     *
     * @param message message to format.
     * @return formatted message (shortened if necessary).
     */
    private String formatMessage(String message) {
        if (message == null)
            return null;
        else if (message.length() > MAX_MESSAGE_LENGTH)
            return message.substring(0, MAX_MESSAGE_LENGTH);
        else return message;
    }

    @Override
    public void writeInterface(JsonGenerator generator, MessageInterface messageInterface) throws IOException {
        generator.writeStartObject();
        generator.writeStringField(MESSAGE_PARAMETER, formatMessage(messageInterface.getMessage()));
        generator.writeArrayFieldStart(PARAMS_PARAMETER);
        for (String parameter : messageInterface.getParams()) {
            generator.writeString(parameter);
        }
        generator.writeEndArray();
        generator.writeEndObject();
    }
}

Set a maximum size for the Message interface


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

package co.phoenixlab.discord.api.request;

import co.phoenixlab.discord.api.entities.PresenceGame;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Builder;

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class UpdateStatusRequest {

    private PresenceGame game;
    private long idleSince;

}

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

package co.phoenixlab.discord.api.request;

import co.phoenixlab.discord.api.entities.PresenceGame;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Builder;

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class UpdateStatusRequest {

    private PresenceGame game;
    private Long idleSince;

}

Switch to obj long for nullable field

Switch to obj long for nullable field


package domain;

public class Contact {

	private long id;
	private String firstName;
	private String lastName;
	private String email;

	/**
	 * @return Email
	 */
	public String getEmail() {
	    return email;
	}

	/**
	 * @return First Name
	 */
	public String getFirstName() {
	  return firstName;
	}

	/**
     * @return Last name
     */
    public String getLastName() {
    	return lastName;
    }

    /**
     * @param string Sets the Email
     */
    public void setEmail(String string) {
    	email = string;
    }

    /**
     * @param string Sets the First Name
     */
    public void setFirstName(String string) {
    	firstName = string;
    }

    /**
     * @param string sets the Last Name
     */
    public void setLastName(String string) {
    	lastName = string;
    }

    /**
     * @return ID Returns ID
     */
    public long getId() {
    	return id;
    }

    /**
     * @param l Sets the ID
     */
    public void setId(long l) {
    	id = l;
    }
}

package domain;

import java.util.Set;

public class Contact {

	private long id;
	private String firstName;
	private String lastName;
	private String email;
	private Set<PhoneNumber> phones;
	private Address address;

	public Contact() {
		// TODO Auto-generated constructor stub
	}

	public Contact(long id, String firstName, String lastName, String email,
			Set<PhoneNumber> phones, Address address) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
		this.phones = phones;
		this.address = address;
	}

	public String getFullName() {
		return String.format("%s %s", firstName, lastName);
	}

	/**
	 * @return Email
	 */
	public String getEmail() {
	    return email;
	}

	/**
	 * @return First Name
	 */
	public String getFirstName() {
	  return firstName;
	}

	/**
     * @return Last name
     */
    public String getLastName() {
    	return lastName;
    }

    /**
     * @param string Sets the Email
     */
    public void setEmail(String string) {
    	email = string;
    }

    /**
     * @param string Sets the First Name
     */
    public void setFirstName(String string) {
    	firstName = string;
    }

    /**
     * @param string sets the Last Name
     */
    public void setLastName(String string) {
    	lastName = string;
    }

    /**
     * @return ID Returns ID
     */
    public long getId() {
    	return id;
    }

    /**
     * @param l Sets the ID
     */
    public void setId(long l) {
    	id = l;
    }
}

Add defautl constructor and getFullName method


/*
 * Copyright 2015 Michael Rozumyanskiy
 *
 * 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.michaelrocks.lightsaber.processor;

import com.beust.jcommander.Parameter;

public class LightsaberParameters {
    @Parameter(names = "--jar", description = "Jar file to process")
    public String jar;

    @Parameter(names = "--classes", description = "Classes directory to process")
    public String classes;

    @Parameter(names = "--stacktrace", description = "Print stack traces")
    public boolean printStacktrace = false;
}

/*
 * Copyright 2015 Michael Rozumyanskiy
 *
 * 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.michaelrocks.lightsaber.processor;

import com.beust.jcommander.Parameter;

public class LightsaberParameters {
    @Parameter(names = "--jar", description = "Jar file to process")
    public String jar;

    @Parameter(names = "--classes", description = "Classes directory to process")
    public String classes;

    @Parameter(names = { "-v", "--verbose" }, description = "Use verbose output")
    public boolean verbose = false;

    @Parameter(names = "--stacktrace", description = "Print stack traces")
    public boolean printStacktrace = false;
}

Add verbose flag to processor parameters


package seedu.address.storage;

import java.io.File;
import java.io.FileNotFoundException;

import javax.xml.bind.JAXBException;

import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.commons.util.XmlUtil;

/**
 * Stores taskmanager data in an XML file
 */
public class XmlFileStorage {
    /**
     * Saves the given taskmanager data to the specified file.
     */
    public static void saveDataToFile(File file, XmlSerializableTaskManager addressBook)
            throws FileNotFoundException {
        try {
            XmlUtil.saveDataToFile(file, addressBook);
        } catch (JAXBException e) {
            assert false : "Unexpected exception " + e.getMessage();
        }
    }

    /**
     * Returns task manager in the file or an empty task manager
     */
    public static XmlSerializableTaskManager loadDataFromSaveFile(File file) throws DataConversionException,
                                                                            FileNotFoundException {
        try {
            return XmlUtil.getDataFromFile(file, XmlSerializableTaskManager.class);
        } catch (JAXBException e) {
            throw new DataConversionException(e);
        }
    }

}

package seedu.address.storage;

import java.io.File;
import java.io.FileNotFoundException;

import javax.xml.bind.JAXBException;

import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.commons.util.XmlUtil;

/**
 * Stores taskmanager data in an XML file
 */
public class XmlFileStorage {
    /**
     * Saves the given taskmanager data to the specified file.
     */
    public static void saveDataToFile(File file, XmlSerializableTaskManager taskManager)
            throws FileNotFoundException {
        try {
            XmlUtil.saveDataToFile(file, taskManager);
        } catch (JAXBException e) {
            assert false : "Unexpected exception " + e.getMessage();
        }
    }

    /**
     * Returns task manager in the file or an empty task manager
     */
    public static XmlSerializableTaskManager loadDataFromSaveFile(File file) throws DataConversionException,
                                                                            FileNotFoundException {
        try {
            return XmlUtil.getDataFromFile(file, XmlSerializableTaskManager.class);
        } catch (JAXBException e) {
            throw new DataConversionException(e);
        }
    }

}

Rename Address Book to Task Manager

Rename Address Book to Task Manager


package utask.model.task;

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

import org.junit.Test;

public class DeadlineTest {

    @Test
    public void isValidDeadline() {
        // invalid Deadline
        assertFalse(Deadline.isValidDeadline("")); // empty string
        assertFalse(Deadline.isValidDeadline(" ")); // spaces only
        assertFalse(Deadline.isValidDeadline("jan")); // non-numeric
        assertFalse(Deadline.isValidDeadline("13jan17")); // alphabets within digits
        assertFalse(Deadline.isValidDeadline("13 01 17")); // spaces within digits
        assertFalse(Deadline.isValidDeadline("310417")); // no 31st day in April
        // valid phone numbers
        assertTrue(Deadline.isValidDeadline("300406"));  // support backdated
        assertTrue(Deadline.isValidDeadline("130117"));
        assertTrue(Deadline.isValidDeadline("090820"));
    }
}

package utask.model.task;

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

import org.junit.Test;

import utask.commons.exceptions.IllegalValueException;

public class DeadlineTest {

    @Test
    public void isValidDeadline() {
        // invalid Deadline
        assertFalse(Deadline.isValidDeadline("")); // empty string
        assertFalse(Deadline.isValidDeadline(" ")); // spaces only
        assertFalse(Deadline.isValidDeadline("jan")); // non-numeric
        assertFalse(Deadline.isValidDeadline("13jan17")); // alphabets within digits
        assertFalse(Deadline.isValidDeadline("13 01 17")); // spaces within digits
        assertFalse(Deadline.isValidDeadline("310417")); // no 31st day in April
        // valid phone numbers
        assertTrue(Deadline.isValidDeadline("300406"));  // support backdated
        assertTrue(Deadline.isValidDeadline("130117"));
        assertTrue(Deadline.isValidDeadline("090820"));
    }

    @Test
    public void testConstructor() {
        Deadline d;
        try {
            d = new Deadline("-"); // constructor with dash only
            assertEquals(d, null);

            d = Deadline.getEmptyDeadline(); // empty constructor
            assertEquals(d, null);

            assertEquals(d.toString(), ""); //checking toString() value when Deadline is Null
            assertEquals(d.hashCode(), "".hashCode()); //checking hashCode when Deadline is Null
        } catch (IllegalValueException e) {
            e.printStackTrace();
        }

    }
}

Add more test cases for Deadline

Add more test cases for Deadline


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        printTitle();
        titleWait();
        System.out.println("You wake up on a beach.");
    }

    private static void printTitle() {
        String banner = "___________      .__     ___________              __   \n" +
                "\\_   _____/_____ |__| ___\\__    ___/___ ___  ____/  |_ \n" +
                " |    __)_\\____ \\|  |/ ___\\|    |_/ __ \\\\  \\/  /\\   __\\\n" +
                " |        \\  |_> >  \\  \\___|    |\\  ___/ >    <  |  |  \n" +
                "/_______  /   __/|__|\\___  >____| \\___  >__/\\_ \\ |__|  \n" +
                "        \\/|__|           \\/           \\/      \\/       ";
        System.out.println(banner);
    }

    private static void titleWait() {
        System.out.println("Press \"ENTER\" to continue...");
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
        clearScreen();
    }

    private static void clearScreen() {

    }
}

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        printTitle();
        titleWait();
        System.out.println("You wake up on a beach.");
    }

    private static void printTitle() {
        String banner = "___________      .__     ___________              __   \n" +
                "\\_   _____/_____ |__| ___\\__    ___/___ ___  ____/  |_ \n" +
                " |    __)_\\____ \\|  |/ ___\\|    |_/ __ \\\\  \\/  /\\   __\\\n" +
                " |        \\  |_> >  \\  \\___|    |\\  ___/ >    <  |  |  \n" +
                "/_______  /   __/|__|\\___  >____| \\___  >__/\\_ \\ |__|  \n" +
                "        \\/|__|           \\/           \\/      \\/       ";
        System.out.println(banner);
    }

    private static void titleWait() {
        System.out.println("Press \"ENTER\" to continue...");
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
        clearScreen();
    }

    private static void clearScreen() {
        System.out.println("\n\n\n\n\n\n\n\n\n\n");
    }
}

Add new line print to clearScreen()

Add new line print to clearScreen()


/*
 * 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.hadoop.hbase.client;

import static org.apache.hadoop.hbase.HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.util.ReflectionUtils;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * Factory class to get the instance of configured connection registry.
 */
@InterfaceAudience.Private
final class ConnectionRegistryFactory {

  private ConnectionRegistryFactory() {
  }

  /**
   * @return The connection registry implementation to use.
   */
  static ConnectionRegistry getRegistry(Configuration conf) {
    Class<? extends ConnectionRegistry> clazz = conf.getClass(
        CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY, MasterRegistry.class,
        ConnectionRegistry.class);
    return ReflectionUtils.newInstance(clazz, conf);
  }
}

/*
 * 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.hadoop.hbase.client;

import static org.apache.hadoop.hbase.HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.util.ReflectionUtils;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * Factory class to get the instance of configured connection registry.
 */
@InterfaceAudience.Private
final class ConnectionRegistryFactory {

  private ConnectionRegistryFactory() {
  }

  /**
   * @return The connection registry implementation to use.
   */
  static ConnectionRegistry getRegistry(Configuration conf) {
    Class<? extends ConnectionRegistry> clazz = conf.getClass(
        CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY, ZKConnectionRegistry.class,
        ConnectionRegistry.class);
    return ReflectionUtils.newInstance(clazz, conf);
  }
}

Switch the default registry to ZK based

Switch the default registry to ZK based

In branch-2 we want to retain the ZK based registry as the default.


package org.qfox.jestful.client.nio.timeout;

import java.net.SocketTimeoutException;
import java.nio.channels.SelectionKey;

/**
 * Created by yangchangpei on 17/3/27.
 */
public abstract class TimeoutHandler implements Comparable<TimeoutHandler> {
    protected final SelectionKey key;
    protected final long timeInvalid;

    protected TimeoutHandler(SelectionKey key, long timeout) {
        this.key = key;
        this.timeInvalid = System.currentTimeMillis() + timeout;
    }

    public boolean isInvalid(long time) {
        return time > timeInvalid;
    }

    protected SocketTimeoutException wrapSocketTimeoutException() {
        return wrapSocketTimeoutException(null);
    }

    protected SocketTimeoutException wrapSocketTimeoutException(String msg) {
        try {
            throw msg == null ? new SocketTimeoutException() : new SocketTimeoutException(msg);
        } catch (SocketTimeoutException ste) {
            return ste;
        }
    }

    public abstract void doInvalid();

    public SelectionKey getKey() {
        return key;
    }

    public long getTimeInvalid() {
        return timeInvalid;
    }

    @Override
    public int compareTo(TimeoutHandler o) {
        return timeInvalid < o.timeInvalid ? -1 : 1;
    }
}

package org.qfox.jestful.client.nio.timeout;

import java.net.SocketTimeoutException;
import java.nio.channels.SelectionKey;

/**
 * Created by yangchangpei on 17/3/27.
 */
public abstract class TimeoutHandler implements Comparable<TimeoutHandler> {
    protected final SelectionKey key;
    protected final long timeInvalid;

    protected TimeoutHandler(SelectionKey key, long timeout) {
        this.key = key;
        this.timeInvalid = System.currentTimeMillis() + timeout;
    }

    public boolean isInvalid(long time) {
        return time > timeInvalid;
    }

    protected SocketTimeoutException wrapSocketTimeoutException(String msg) {
        try {
            throw msg == null ? new SocketTimeoutException() : new SocketTimeoutException(msg);
        } catch (SocketTimeoutException ste) {
            return ste;
        }
    }

    public abstract void doInvalid();

    public SelectionKey getKey() {
        return key;
    }

    public long getTimeInvalid() {
        return timeInvalid;
    }

    @Override
    public int compareTo(TimeoutHandler o) {
        return timeInvalid < o.timeInvalid ? -1 : 1;
    }
}

Set Default Timeouts For NIO Builder While Creation


package org.jenkinsci.plugins.gitclient;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

/**
 * Recording log handler to allow assertions on logging. Not intended for use
 * outside this package. Not intended for use outside tests.
 *
 * @author Mark Waite
 */
public class LogHandler extends Handler {

    private List<String> messages = new ArrayList<>();

    @Override
    public void publish(LogRecord lr) {
        messages.add(lr.getMessage());
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
        messages = new ArrayList<>();
    }

    /* package */ List<String> getMessages() {
        return messages;
    }

    /* package */ boolean containsMessageSubstring(String messageSubstring) {
        for (String message : messages) {
            if (message.indexOf(messageSubstring) >= 0) {
                return true;
            }
        }
        return false;
    }

    /* package */ List<Integer> getTimeouts() {
        List<Integer> timeouts = new ArrayList<>();
        for (String message : getMessages()) {
            int start = message.indexOf(CliGitAPIImpl.TIMEOUT_LOG_PREFIX);
            if (start >= 0) {
                String timeoutStr = message.substring(start + CliGitAPIImpl.TIMEOUT_LOG_PREFIX.length());
                timeouts.add(Integer.parseInt(timeoutStr));
            }
        }
        return timeouts;
    }
}

package org.jenkinsci.plugins.gitclient;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

/**
 * Recording log handler to allow assertions on logging. Not intended for use
 * outside this package. Not intended for use outside tests.
 *
 * @author Mark Waite
 */
public class LogHandler extends Handler {

    private List<String> messages = new ArrayList<>();

    @Override
    public void publish(LogRecord lr) {
        messages.add(lr.getMessage());
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
        messages = new ArrayList<>();
    }

    /* package */ List<String> getMessages() {
        return messages;
    }

    /* package */ boolean containsMessageSubstring(String messageSubstring) {
        for (String message : messages) {
            if (message.contains(messageSubstring)) {
                return true;
            }
        }
        return false;
    }

    /* package */ List<Integer> getTimeouts() {
        List<Integer> timeouts = new ArrayList<>();
        for (String message : getMessages()) {
            int start = message.indexOf(CliGitAPIImpl.TIMEOUT_LOG_PREFIX);
            if (start >= 0) {
                String timeoutStr = message.substring(start + CliGitAPIImpl.TIMEOUT_LOG_PREFIX.length());
                timeouts.add(Integer.parseInt(timeoutStr));
            }
        }
        return timeouts;
    }
}

Use 'contains' instead of indexOf to find substrings


package com.growingwiththeweb.algorithms.interviewquestions.dividewithoutdivide;

public class Program {
    public static void main(String[] args) {
        assert divide(10,4) == 2;
        assert divide(11,4) == 2;
        assert divide(12,4) == 3;
        assert divide(13,4) == 3;
        assert divide(130,3) == 43;

        System.out.println("Tests passed");
    }

    public static double divide(double a, double b) {
        int sign = 1;
        if (a < 0) {
            a = -a;
            sign = -sign;
        }
        if (b < 0) {
            b = -b;
            sign = -sign;
        }
        double result = 0;
        while (a >= 0) {
            a -= b;
            result++;
        }
        return (result - 1) * sign;
    }
}

package com.growingwiththeweb.algorithms.interviewquestions.dividewithoutdivide;

import java.lang.ArithmeticException;

public class Program {
    public static void main(String[] args) {
        assert divide(10, 4) == 2;
        assert divide(11, 4) == 2;
        assert divide(12, 4) == 3;
        assert divide(13, 4) == 3;
        assert divide(130,3 ) == 43;

        boolean threw = false;
        try {
            divide(1, 0);
        } catch (ArithmeticException ex) {
            threw = true;
        }
        assert threw;

        System.out.println("Tests passed");
    }

    public static double divide(double a, double b) {
        if (b == 0) {
            throw new ArithmeticException(
                    "Division by 0 is undefined: " + a + "/" + b);
        }
        int sign = 1;
        if (a < 0) {
            a = -a;
            sign = -sign;
        }
        if (b < 0) {
            b = -b;
            sign = -sign;
        }
        double result = 0;
        while (a >= 0) {
            a -= b;
            result++;
        }
        return (result - 1) * sign;
    }
}

Add exception for division by zero

Add exception for division by zero


package org.hcjf.layers;

import java.lang.reflect.InvocationHandler;

/**
 * @author javaito
 *
 */
public interface LayerInterface extends InvocationHandler {

    /**
     * Return the layer implementation name.
     * @return Layer implementation name.
     */
    String getImplName();

    /**
     * Returns true if the layer is stateful or false in the otherwise.
     * @return Stateful
     */
    boolean isStateful();

    /**
     * Returns true if the layer is a plugin or false in the otherwise.
     * @return Plugin status.
     */
    boolean isPlugin();

}

package org.hcjf.layers;

import org.hcjf.layers.distributed.DistributedLayer;

import java.lang.reflect.InvocationHandler;

/**
 * @author javaito
 *
 */
public interface LayerInterface extends InvocationHandler {

    /**
     * Return the layer implementation name.
     * @return Layer implementation name.
     */
    String getImplName();

    /**
     * Returns true if the layer is stateful or false in the otherwise.
     * @return Stateful
     */
    boolean isStateful();

    /**
     * Returns true if the layer is a plugin or false in the otherwise.
     * @return Plugin status.
     */
    boolean isPlugin();

    /**
     * Returns true if the layer implementation is instance of {@link DistributedLayer}.
     * @return True if the layer implementation is instance of {@link DistributedLayer} and false in the otherwise.
     */
    default boolean isDistributed() {
        return this instanceof DistributedLayer;
    }

}

Add in the layer interface the capability of knows if the implementation is distributed or not.


package src;

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

import org.ini4j.Wini;

public class Tournament {
    String _userName;
    String _game;

    //много параметров, может, их в отдельный класс?
    String _fullPath;
    String _tempPath;
    String _tableCaption;
    String _judgePath;

    public Tournament(String userName, String game){
        _userName = _userName;
        _game = game;

        try {
            LoadIni();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void LoadIni() throws IOException {
        Wini ini = new Wini(new File("tournamentset.ini"));
        _fullPath = ini.get("Paths", "FullPath");
        _tempPath = ini.get("Paths", "TempPath");
        _tableCaption = ini.get("DBSettings", "TableCaption");
        _judgePath = ini.get("ExternalLinks", "JudgePath");
    }
}

package src;

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

import org.ini4j.Wini;

public class Tournament {
    String _userName;
    String _game;

    public Tournament(String userName, String game){
        _userName = _userName;
        _game = game;
    }
}

Remove old unnesessary code (load ini file). Now this operations is in FileWorker.


package config;

import android.content.Context;

import cl_toolkit.Logger;
import cl_toolkit.Storage;

/**
 * Run-time data
 * @author Chris Lewis
 */
public class Runtime {

	private static Logger getLogger(Context context) {
		return new Logger(Storage.getStorage() + "/" + Build.DEBUG_LOG_NAME, Build.DEBUG_LOG_MAX_SIZE_BYTES);
	}

    public static void log(Context context, String TAG, String message, String level) {
        getLogger(context).log(TAG, message, level);
    }

    public static void logStackTrace(Context context, Exception e) {
        getLogger(context).logStackTrace(e);
    }

    public static void startNewSession(Context context) {
        getLogger(context).startNewSession();
    }

}

package config;

import android.content.Context;

import cl_toolkit.Logger;
import cl_toolkit.Storage;

/**
 * Run-time data
 * @author Chris Lewis
 */
public class Runtime {

	private static Logger getLogger(Context context) {
		return new Logger(Storage.getAppStorage(context) + "/" + Build.DEBUG_LOG_NAME, Build.DEBUG_LOG_MAX_SIZE_BYTES);
	}

    public static void log(Context context, String TAG, String message, String level) {
        getLogger(context).log(TAG, message, level);
    }

    public static void logStackTrace(Context context, Exception e) {
        getLogger(context).logStackTrace(e);
    }

    public static void startNewSession(Context context) {
        getLogger(context).startNewSession();
    }

}

Write logs to Application Storage to avoid permission problem on Android 6+


package com.gentics.mesh.core.data.group;

import com.gentics.mesh.core.data.HibCoreElement;
import com.gentics.mesh.core.data.HibNamedElement;
import com.gentics.mesh.core.data.user.HibUserTracking;
import com.gentics.mesh.core.rest.group.GroupReference;

public interface HibGroup extends HibCoreElement, HibUserTracking, HibNamedElement {

	GroupReference transformToReference();

	void removeElement();

	String getElementVersion();

}

package com.gentics.mesh.core.data.group;

import static com.gentics.mesh.core.rest.MeshEvent.GROUP_CREATED;
import static com.gentics.mesh.core.rest.MeshEvent.GROUP_DELETED;
import static com.gentics.mesh.core.rest.MeshEvent.GROUP_UPDATED;

import com.gentics.mesh.ElementType;
import com.gentics.mesh.core.TypeInfo;
import com.gentics.mesh.core.data.HibCoreElement;
import com.gentics.mesh.core.data.HibNamedElement;
import com.gentics.mesh.core.data.user.HibUserTracking;
import com.gentics.mesh.core.rest.group.GroupReference;

public interface HibGroup extends HibCoreElement, HibUserTracking, HibNamedElement {

	TypeInfo TYPE_INFO = new TypeInfo(ElementType.GROUP, GROUP_CREATED, GROUP_UPDATED, GROUP_DELETED);

	@Override
	default TypeInfo getTypeInfo() {
		return TYPE_INFO;
	}

	GroupReference transformToReference();

	void removeElement();

	String getElementVersion();

}

Move group type info to interface

Move group type info to interface


// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttp;

import java.nio.channels.Selector;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Executor;

/**
 * A SelectTaskQueue is meant to be used with a Selector.  Submitted
 * tasks will wake up the associated Selector for immediate execution.
 * Because of this, all tasks should be short and non-blocking.
 *
 * This is intended for waking up (i.e., rescheduling select operations)
 * a sleeping connection.
 *
 * All tasks are placed in an unbounded queue.  Thus, it is best to schedule
 * just O(1) tasks per connection.
 */
class SelectTaskQueue implements Executor {
    private Selector mSelector;

    private BlockingQueue<Runnable> mTaskQueue;

    public SelectTaskQueue(Selector selector) {
        mSelector = selector;
        // We want an unbounded queue, since we never want a task to block.
        mTaskQueue = new LinkedBlockingQueue<Runnable>();
    }

    public void execute(final Runnable r) {
        mTaskQueue.offer(r);

        mSelector.wakeup();
    }

    /**
     * @return the head of the queue or null if empty.  This is thread-safe.
     */
    public Runnable poll() {
        return mTaskQueue.poll();
    }
}

// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttp;

import java.nio.channels.Selector;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Executor;

/**
 * A SelectTaskQueue is meant to be used with a Selector.  Submitted
 * tasks will wake up the associated Selector for immediate execution.
 * Because of this, all tasks should be short and non-blocking.
 *
 * This is intended for waking up (i.e., rescheduling select operations)
 * a sleeping connection.
 *
 * All tasks are placed in an unbounded queue.  Thus, it is best to schedule
 * just O(1) tasks per connection.
 */
class SelectTaskQueue implements Executor {
    private Selector mSelector;

    private BlockingQueue<Runnable> mTaskQueue;

    public SelectTaskQueue(Selector selector) {
        mSelector = selector;
        // We want an unbounded queue, since we never want a task to block.
        mTaskQueue = new LinkedBlockingQueue<Runnable>();
    }

    public void execute(final Runnable r) {
        mTaskQueue.add(r);

        mSelector.wakeup();
    }

    /**
     * @return the head of the queue or null if empty.  This is thread-safe.
     */
    public Runnable poll() {
        return mTaskQueue.poll();
    }
}

Use add instead of offer with the unbounded blocking queue to guarantee successful add.


package info.u_team.u_team_test;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.integration.IntegrationManager;
import info.u_team.u_team_core.util.verify.JarSignVerifier;
import info.u_team.u_team_test.init.*;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.common.Mod;

@Mod(TestMod.MODID)
public class TestMod {

	public static final String MODID = "uteamtest";
	public static final Logger LOGGER = LogManager.getLogger("UTeamTest");

	public TestMod() {
		JarSignVerifier.checkSigned(MODID);

		LOGGER.info("--------------------------------------- LOADING TEST MOD ---------------------------------------");

		TestCommonBusRegister.register();
		DistExecutor.safeRunWhenOn(Dist.CLIENT, () -> TestClientBusRegister::register);

		IntegrationManager.constructIntegrations(MODID);
	}
}

package info.u_team.u_team_test;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.construct.ConstructManager;
import info.u_team.u_team_core.integration.IntegrationManager;
import info.u_team.u_team_core.util.verify.JarSignVerifier;
import net.minecraftforge.fml.common.Mod;

@Mod(TestMod.MODID)
public class TestMod {

	public static final String MODID = "uteamtest";
	public static final Logger LOGGER = LogManager.getLogger("UTeamTest");

	public TestMod() {
		JarSignVerifier.checkSigned(MODID);

		LOGGER.info("--------------------------------------- LOADING TEST MOD ---------------------------------------");

//		TestCommonBusRegister.register();
//		DistExecutor.safeRunWhenOn(Dist.CLIENT, () -> TestClientBusRegister::register);

		ConstructManager.constructConstructs(MODID);

		IntegrationManager.constructIntegrations(MODID);
	}
}

Add call to construct manager in test mod