package org.jboss.reddeer.eclipse.jface.wizard;

import org.apache.log4j.Logger;
import org.jboss.reddeer.swt.api.Menu;
import org.jboss.reddeer.swt.impl.menu.DefaultMenu;
import org.jboss.reddeer.swt.impl.shell.ActiveShell;
import org.jboss.reddeer.swt.impl.tree.DefaultTreeItem;

/**
 * Abstract class to manage new wizard dialog
 * @author vpakan
 *
 */
public abstract class NewWizardDialog extends WizardDialog{
	public static final String DIALOG_TITLE = "New";
	private String[] path;
	protected final Logger log = Logger.getLogger(this.getClass());
	/**
	 * @param path - path to new object to be created within tree widget
	 * inside New wizard dialog
	 */
	public NewWizardDialog(String... path) {
		this.path = path;
	}
	/**
	 * Opens wizard for new object to be created
	 */
	public void open(){
		log.info("Open New Wizard");
		super.open();
		Menu menu = new DefaultMenu("File","New","Other...");
		menu.select();
		new ActiveShell(DIALOG_TITLE);
		if (path.length > 0){
		  new DefaultTreeItem(path).select();
	    next();
		}

	}
}

package org.jboss.reddeer.eclipse.jface.wizard;

import org.apache.log4j.Logger;
import org.jboss.reddeer.swt.api.Menu;
import org.jboss.reddeer.swt.impl.menu.ShellMenu;
import org.jboss.reddeer.swt.impl.shell.ActiveShell;
import org.jboss.reddeer.swt.impl.tree.DefaultTreeItem;

/**
 * Abstract class to manage new wizard dialog
 * @author vpakan
 *
 */
public abstract class NewWizardDialog extends WizardDialog{
	public static final String DIALOG_TITLE = "New";
	private String[] path;
	protected final Logger log = Logger.getLogger(this.getClass());
	/**
	 * @param path - path to new object to be created within tree widget
	 * inside New wizard dialog
	 */
	public NewWizardDialog(String... path) {
		this.path = path;
	}
	/**
	 * Opens wizard for new object to be created
	 */
	public void open(){
		log.info("Open New Wizard");
		super.open();
		Menu menu = new ShellMenu("File","New","Other...");
		menu.select();
		new ActiveShell(DIALOG_TITLE);
		if (path.length > 0){
		  new DefaultTreeItem(path).select();
	    next();
		}

	}
}

Use ShellMenu instead of DefaultMenu

Use ShellMenu instead of DefaultMenu


package org.helioviewer.jhv.threads;

import java.util.concurrent.FutureTask;

public class CancelTask extends FutureTask<Void> {

    public CancelTask(FutureTask<?> abolishTask) {
        super(new Runnable() {
                private FutureTask<?> abolishTask;

                public Runnable init(FutureTask<?> abolishTask) {
                    this.abolishTask = abolishTask;
                    return this;
                }

                @Override
                public void run() {
                    abolishTask.cancel(true);
                }
            }.init(abolishTask), null);
    }

}

package org.helioviewer.jhv.threads;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class CancelTask extends FutureTask<Boolean> {

    public CancelTask(FutureTask<?> cancelTask) {
        super(new Callable<Boolean>() {
                private FutureTask<?> _cancelTask;

                public Callable init(FutureTask<?> _cancelTask) {
                    this._cancelTask = _cancelTask;
                    return this;
                }

                @Override
                public Boolean call() {
                    return _cancelTask.cancel(true);
                }
            }.init(cancelTask));
    }

}

Use Callable to be able to retrieve the result of cancel

git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@5095 b4e469a2-07ce-4b26-9273-4d7d95a670c7


package org.sql2o.converters;

/**
 * Default implementation of {@link EnumConverterFactory},
 * used by sql2o to convert a value from the database into an {@link Enum}.
 */
public class DefaultEnumConverterFactory implements EnumConverterFactory {
    public <E extends Enum> Converter<E> newConverter(final Class<E> enumType) {
        return new Converter<E>() {
            @SuppressWarnings("unchecked")
            public E convert(Object val) throws ConverterException {
                if (val == null) {
                    return null;
                }
                try {
                    if (val instanceof String){
                        return (E)Enum.valueOf(enumType, val.toString());
                    } else if (val instanceof Number){
                        return enumType.getEnumConstants()[((Number)val).intValue()];
                    }
                } catch (Throwable t) {
                    throw new ConverterException("Error converting value '" + val.toString() + "' to " + enumType.getName(), t);
                }
                throw new ConverterException("Cannot convert type '" + val.getClass().getName() + "' to an Enum");
            }

            public Object toDatabaseParam(Enum val) {
                return val.toString();
            }
        };
    }
}

package org.sql2o.converters;

/**
 * Default implementation of {@link EnumConverterFactory},
 * used by sql2o to convert a value from the database into an {@link Enum}.
 */
public class DefaultEnumConverterFactory implements EnumConverterFactory {
    public <E extends Enum> Converter<E> newConverter(final Class<E> enumType) {
        return new Converter<E>() {
            @SuppressWarnings("unchecked")
            public E convert(Object val) throws ConverterException {
                if (val == null) {
                    return null;
                }
                try {
                    if (val instanceof String){
                        return (E)Enum.valueOf(enumType, val.toString());
                    } else if (val instanceof Number){
                        return enumType.getEnumConstants()[((Number)val).intValue()];
                    }
                } catch (Throwable t) {
                    throw new ConverterException("Error converting value '" + val.toString() + "' to " + enumType.getName(), t);
                }
                throw new ConverterException("Cannot convert type '" + val.getClass().getName() + "' to an Enum");
            }

            public Object toDatabaseParam(Enum val) {
                return val.name();
            }
        };
    }
}

Use name() instead of toString() for enum value.

The javadoc for Enum notes that name() should be used when
correctness depends on getting the exact name of the enum
constant which will not vary from release to release. The
javadoc further encourages overriding the toString() method
when appropriate to provide a more user-friendly name. This
commit fixes the DefaultEnumConverterFactory in cases where
the toString() method is overridden to return something other
than the enum constant.


/*
 *
 *
 * Copyright (C) 2004 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2004 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.site.phone.polycom;

import junit.framework.Test;
import net.sourceforge.jwebunit.WebTestCase;

import org.sipfoundry.sipxconfig.site.SiteTestHelper;
import org.sipfoundry.sipxconfig.site.phone.PhoneTestHelper;
import org.w3c.dom.Element;

public class PasswordSettingTestUi extends WebTestCase {

    private PhoneTestHelper m_helper;

    public static Test suite() throws Exception {
        return SiteTestHelper.webTestSuite(PasswordSettingTestUi.class);
    }

    protected void setUp() throws Exception {
        super.setUp();
        getTestContext().setBaseUrl(SiteTestHelper.getBaseUrl());
        m_helper = new PhoneTestHelper(tester);
        m_helper.reset();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

    public void testEditSipSetttings() {
        m_helper.seedLine(1);
        clickLink("ManagePhones");
        clickLinkWithText(SiteTestHelper.TEST_USER);
        clickLinkWithText("Registration");
        Element passwordField = getDialog().getElement("setting:auth.password");
        assertEquals("password", passwordField.getAttribute("type"));
    }
}

/*
 *
 *
 * Copyright (C) 2004 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2004 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.site.phone.polycom;

import junit.framework.Test;
import net.sourceforge.jwebunit.WebTestCase;

import org.sipfoundry.sipxconfig.site.SiteTestHelper;
import org.sipfoundry.sipxconfig.site.phone.PhoneTestHelper;
import org.w3c.dom.Element;

public class PasswordSettingTestUi extends WebTestCase {

    private PhoneTestHelper m_helper;

    public static Test suite() throws Exception {
        return SiteTestHelper.webTestSuite(PasswordSettingTestUi.class);
    }

    protected void setUp() throws Exception {
        super.setUp();
        getTestContext().setBaseUrl(SiteTestHelper.getBaseUrl());
        m_helper = new PhoneTestHelper(tester);
        m_helper.reset();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

    public void testEditSipSetttings() {
        m_helper.seedLine(1);
        SiteTestHelper.setScriptingEnabled(true);
        clickLink("ManagePhones");
        clickLinkWithText(SiteTestHelper.TEST_USER);
        clickLinkWithText("Registration");
        clickLink("setting:toggle");
        Element passwordField = getDialog().getElement("setting:auth.password");
        assertEquals("password", passwordField.getAttribute("type"));
    }
}

FIX BUILD: Unit test assumed polycom authid was first visible on page

git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@7583 a612230a-c5fa-0310-af8b-88eea846685b


/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

import static org.fest.assertions.api.Assertions.*;

import org.junit.Test;

public class RemoveUnreachableTest {
  private static boolean classExists(String s) {
    try {
      Class.forName(s);
    } catch (ClassNotFoundException e) {
      return false;
    }
    return true;
  }

  @Test
  public void testSeeds() {
    assertThat(classExists("A")).isFalse();
  }

  /**
   * Inheritance test from Guava.
   */
  @Test
  public void testHasher() {
    TestHasher h = new TestHasher();
    UseHasher.use(h);
  }
}

class A {
}

// This example is distilled from Guava
interface Hasher {
  void putBytes();
  void putString();
}

abstract class AbstractHasher implements Hasher {
  public void putString() {
    putBytes();
  }
}

class TestHasher extends AbstractHasher {
  public void putBytes() {
  }
}

class UseHasher {
  public static void use(AbstractHasher ah) {
    ah.putString();
  }
}

/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

import static org.fest.assertions.api.Assertions.*;

import org.junit.Test;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;

public class RemoveUnreachableTest {
  volatile long counter;

  private static boolean classExists(String s) {
    try {
      Class.forName(s);
    } catch (ClassNotFoundException e) {
      return false;
    }
    return true;
  }

  @Test
  public void testSeeds() {
    assertThat(classExists("A")).isFalse();
  }

  /**
   * Inheritance test from Guava.
   */
  @Test
  public void testHasher() {
    TestHasher h = new TestHasher();
    UseHasher.use(h);
  }

  @Test
  public void testAtomicUpdater() {
    AtomicLongFieldUpdater<RemoveUnreachableTest> up
      = AtomicLongFieldUpdater.newUpdater(
          RemoveUnreachableTest.class,
          "counter");
  }
}

class A {
}

// This example is distilled from Guava
interface Hasher {
  void putBytes();
  void putString();
}

abstract class AbstractHasher implements Hasher {
  public void putString() {
    putBytes();
  }
}

class TestHasher extends AbstractHasher {
  public void putBytes() {
  }
}

class UseHasher {
  public static void use(AbstractHasher ah) {
    ah.putString();
  }
}

Test for volatile fields in RemoveUnreachable

Summary: Add a test for non-removal of volatile fields.

Reviewed By: satnam6502

Differential Revision: D3874792

fbshipit-source-id: 5344fc03173cefb283b726ff7f8f8dd634d14061


package ca.corefacility.bioinformatics.irida.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.Tag;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import ca.corefacility.bioinformatics.irida.config.IridaApiGalaxyTestConfig;
import ca.corefacility.bioinformatics.irida.config.data.IridaApiTestFilesystemConfig;
import ca.corefacility.bioinformatics.irida.config.services.IridaApiServicesConfig;

/**
 * Annotation that is to be specified on Galaxy integration tests. Simplifies the configuration of tests by
 * automatically adding a number of necessary annotations.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Inherited

@Tag("IntegrationTest")
@Tag("Galaxy")
@ActiveProfiles("test")
@SpringBootTest(classes = {
		DataSourceAutoConfiguration.class,
		IridaApiTestFilesystemConfig.class,
		IridaApiServicesConfig.class,
		IridaApiGalaxyTestConfig.class })
public @interface GalaxyIntegrationTest {

}

package ca.corefacility.bioinformatics.irida.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.Tag;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import ca.corefacility.bioinformatics.irida.config.IridaApiGalaxyTestConfig;
import ca.corefacility.bioinformatics.irida.config.data.IridaApiTestFilesystemConfig;
import ca.corefacility.bioinformatics.irida.config.services.IridaApiServicesConfig;

/**
 * Annotation that is to be specified on Galaxy integration tests. Simplifies the configuration of tests by
 * automatically adding a number of necessary annotations.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Inherited

@Tag("IntegrationTest")
@Tag("Galaxy")
@ActiveProfiles("test")
@SpringBootTest(classes = {
		DataSourceAutoConfiguration.class,
		HibernateJpaAutoConfiguration.class,
		IridaApiTestFilesystemConfig.class,
		IridaApiServicesConfig.class,
		IridaApiGalaxyTestConfig.class })
public @interface GalaxyIntegrationTest {

}

Add back in missing auto config for galaxy integration tests.


package org.tigris.subversion.svnclientadapter.javahl;

import org.tigris.subversion.javahl.ConflictDescriptor;
import org.tigris.subversion.javahl.ConflictResolverCallback;
import org.tigris.subversion.javahl.SubversionException;
import org.tigris.subversion.svnclientadapter.ISVNConflictResolver;
import org.tigris.subversion.svnclientadapter.SVNClientException;

public class JhlConflictResolver implements ConflictResolverCallback {

	ISVNConflictResolver worker;

	public JhlConflictResolver(ISVNConflictResolver worker) {
		super();
		this.worker = worker;
	}

	public int resolve(ConflictDescriptor descrip)
			throws SubversionException {
		try {
			return worker.resolve(JhlConverter.convertConflictDescriptor(descrip));
		} catch (SVNClientException e) {
			throw new JhlException(e);
		}
	}

}

package org.tigris.subversion.svnclientadapter.javahl;

import org.tigris.subversion.javahl.ConflictDescriptor;
import org.tigris.subversion.javahl.ConflictResolverCallback;
import org.tigris.subversion.javahl.ConflictResult;
import org.tigris.subversion.javahl.SubversionException;
import org.tigris.subversion.svnclientadapter.ISVNConflictResolver;
import org.tigris.subversion.svnclientadapter.SVNClientException;

public class JhlConflictResolver implements ConflictResolverCallback {

	ISVNConflictResolver worker;

	public JhlConflictResolver(ISVNConflictResolver worker) {
		super();
		this.worker = worker;
	}

	public ConflictResult resolve(ConflictDescriptor descrip)
			throws SubversionException {
		try {
			return new ConflictResult(worker.resolve(JhlConverter.convertConflictDescriptor(descrip)), null);
		} catch (SVNClientException e) {
			throw new JhlException(e);
		}
	}

}

Update for changes in JavaHL conflict resolution callback


/*
  Copyright 2016, Google, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package com.example.storage;

// [START storage_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Storage storage = StorageOptions.defaultInstance().service();

    // The name for the new bucket
    String bucketName = "my-new-bucket";

    // Creates the new bucket
    Bucket bucket = storage.create(BucketInfo.of(bucketName));

    System.out.printf("Bucket %s created.%n", bucket.name());
  }
}
// [END storage_quickstart]

/*
  Copyright 2016, Google, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package com.example.storage;

// [START storage_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Storage storage = StorageOptions.defaultInstance().service();

    // The name for the new bucket
    String bucketName = "my-new-bucket";

    // Creates the new bucket
    Bucket bucket = storage.create(BucketInfo.of(bucketName));

    System.out.printf("Bucket %s created.%n", bucket.name());
  }
}
// [END storage_quickstart]

Add quickstarts to root module.

Add quickstarts to root module.

Fixes checkstyle errors in samples.


package study.hard.javalib.nativelib;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MathTest {

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

	private Double amount;
	private Double ratio;
	private Double result;

	@Before
	public void setUp() {
		amount = 0D;
		ratio = 0D;
		result = 0D;
		logger.debug("amount: {} / ratio: {} / result: {}", new Object[] {amount, ratio, result});
	}

	@Test
	public void floor() {
		amount = 39000.000D;
		ratio = 0.020D;
		result = Math.floor(amount * ratio);

		logger.debug("result: {}", result);

		assertEquals(new Double(780D), result);
	}

}

package study.hard.javalib.nativelib;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MathTest {

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

	private Double amount;
	private Double ratio;
	private Double result;

	@Before
	public void setUp() {
		amount = 0D;
		ratio = 0D;
		result = 0D;
		logger.debug("amount: {} / ratio: {} / result: {}", new Object[] {amount, ratio, result});
	}

	@Test
	public void floor() {
		amount = 39000.000D;
		ratio = 0.020D;
		result = Math.floor(amount * ratio);

		logger.debug("result: {}", result);

		assertEquals(new Double(780D), result);
	}

	@Test
	public void ceil() {
		logger.debug("(3 / 7): " + (3 / 7));
		logger.debug("(3D / 7D): " + (3D / 7D));
		logger.debug("Math.ceil(3 / 7): " + Math.ceil(3 / 7));
		logger.debug("Math.ceil(3D / 7D): " + Math.ceil(3D / 7D));
		logger.debug("(int)Math.ceil(3 / 7): " + (int)Math.ceil(3 / 7));
		logger.debug("(int)Math.ceil(3D / 7D): " + (int)Math.ceil(3D / 7D));
		logger.debug("(int)Math.ceil((double)3 / (double)7): " + (int)Math.ceil((double)3 / (double)7));
	}

}

Add test case related to devide numbers.


package us.kbase.workspace.test;

import static us.kbase.common.test.TestCommon.getTestProperty;
import static us.kbase.common.test.TestCommon.destroyDB;

import com.mongodb.DB;

public class WorkspaceTestCommon {

	public static final String PLACKUPEXE = "test.plackup.exe";
	public static final String HANDLE_SRV_PSGI = "test.handle.service.psgi";
	public static final String HANDLE_MGR_PSGI = "test.handle.manager.psgi";
	public static final String HANDLE_PERL5LIB = "test.handle.PERL5LIB";

	public static final String GRIDFS = "gridFS";
	public static final String SHOCK = "shock";

	public static String getPlackupExe() {
		return getTestProperty(PLACKUPEXE);
	}

	public static String getHandleServicePSGI() {
		return getTestProperty(HANDLE_SRV_PSGI);
	}

	public static String getHandleManagerPSGI() {
		return getTestProperty(HANDLE_MGR_PSGI);
	}

	public static String getHandlePERL5LIB() {
		return getTestProperty(HANDLE_PERL5LIB);
	}

	public static void destroyWSandTypeDBs(DB mdb, String typedb) {
		destroyDB(mdb);
		destroyDB(mdb.getSisterDB(typedb));
	}
}

package us.kbase.workspace.test;

import static us.kbase.common.test.TestCommon.destroyDB;

import com.mongodb.DB;

public class WorkspaceTestCommon {

	public static void destroyWSandTypeDBs(DB mdb, String typedb) {
		destroyDB(mdb);
		destroyDB(mdb.getSisterDB(typedb));
	}
}

Remove more handle service cruft

Remove more handle service cruft


package fr.alecharp.picshare;

import fr.alecharp.picshare.config.PicShareModule;
import fr.alecharp.picshare.http.EventController;
import net.codestory.http.WebServer;
import net.codestory.http.injection.GuiceAdapter;

/**
 * @author Adrien Lecharpentier
 */
public class App {
    public static void main(String[] args) {
        new WebServer()
            .configure(r -> r
                .setIocAdapter(new GuiceAdapter(new PicShareModule()))
                .get("/ping", "pong")
                .add(EventController.class)
            ).start(8080);
    }
}

package fr.alecharp.picshare;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.name.Names;
import fr.alecharp.picshare.config.PicShareModule;
import fr.alecharp.picshare.http.EventController;
import net.codestory.http.WebServer;
import net.codestory.http.injection.GuiceAdapter;

import java.nio.file.Paths;

/**
 * @author Adrien Lecharpentier
 */
public class App {
    public static void main(String[] args) {
        new WebServer()
            .configure(r -> {
                Injector injector = Guice.createInjector(new PicShareModule());
                String storageLocation = injector.getInstance(Key.get(String.class, Names.named("storageLocation")));
                r
                    .setIocAdapter(new GuiceAdapter(injector))
                    .get("/ping", "pong")
                    .add(EventController.class)
                    .bind(String.format("/%s/", storageLocation), Paths.get(storageLocation).toFile());
            }).start(8080);
    }
}

Configure server to serve picture directly


package com.secdec.codedx.util;

/**************************************************************************
 * Copyright (c) 2014 Applied Visions, Inc. All Rights Reserved.
 * Author: Applied Visions, Inc. - Chris Ellsworth
 * Project: Code Dx
 * SubSystem: com.secdec.codedx.util
 * FileName: HashUtil.java
 *************************************************************************/

        import java.security.MessageDigest;
        import java.security.NoSuchAlgorithmException;
        import java.util.Formatter;

/**
 * @author Chris Ellsworth
 *
 */
public class HashUtil {
//    public static String toMd5(String input) {
//        String toReturn = null;
//        try {
//            byte[] digest = MessageDigest.getInstance("MD5").digest(input.getBytes());
//            StringBuilder hashBuilder = new StringBuilder();
//            for (byte b : digest) {
//                hashBuilder.append(String.format("%x", b));
//            }
//            toReturn = hashBuilder.toString();
//        } catch (NoSuchAlgorithmException exc) {
//            throw new CodeDxException(exc);
//        }
//        return toReturn;
//    }

    public static byte[] getSHA1(byte[] input) {

        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.reset();
            return md.digest(input);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String toHexString(byte[] bytes) {
        return toHexString(bytes, "");
    }

    public static String toHexString(byte[] bytes, String sep) {
        Formatter f = new Formatter();
        for (int i = 0; i < bytes.length; i++) {
            f.format("%02x", bytes[i]);
            if (i < bytes.length - 1) {
                f.format(sep);
            }
        }
        String result = f.toString();
        f.close();
        return result;
    }
}

package com.secdec.codedx.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

/**
 * Contains utilities for dealing with Hashes
 *
 * @author Samuel Johnson
 *
 */
public class HashUtil {

	public static byte[] getSHA1(byte[] input) {

		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.reset();
			return md.digest(input);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

	public static String toHexString(byte[] bytes) {
		return toHexString(bytes, "");
	}

	public static String toHexString(byte[] bytes, String sep) {
		Formatter f = new Formatter();
		for (int i = 0; i < bytes.length; i++) {
			f.format("%02x", bytes[i]);
			if (i < bytes.length - 1) {
				f.format(sep);
			}
		}
		String result = f.toString();
		f.close();
		return result;
	}
}

Clean up code and documentation

Clean up code and documentation

This file contained JavaDoc and unused code that wasn't cleaned up when I borrowed it from elsewhere in our codebase.


package org.tt.core.dm;

import org.tt.core.fetch.AbstractDataFetcher;
import org.tt.core.sql.AbstractQueries;
import org.tt.core.sql.AbstractSQLManager;

public class TTFactory {
    private static AbstractSQLManager sqlm;
    private static AbstractQueries qrs;
    private static AbstractDataFetcher df;
    private static TTFactory ttf;

    private TTFactory() {
    }

    public static TTFactory getInstance() {
        if (ttf == null) {
            ttf = new TTFactory();
        }

        return ttf;
    }

    public void setSQLManager(AbstractSQLManager sqlm) {
        this.sqlm = sqlm;
    }

    public void setSQLQueries(AbstractQueries qrs) {
        this.qrs = qrs;
    }

    public void setDataFetcher(AbstractDataFetcher df) {
        this.df = df;
    }

    public TTUpdateManager produceUpdateManager() {
        return new TTUpdateManager(sqlm, df);
    }

    public TTDeliveryManager produceDeliveryManager() {
        return new TTDeliveryManager(sqlm);
    }

}

package org.tt.core.dm;

import org.tt.core.fetch.AbstractDataFetcher;
import org.tt.core.sql.AbstractQueries;
import org.tt.core.sql.AbstractSQLManager;

public class TTFactory {
    private static AbstractSQLManager sqlm;
    private static AbstractDataFetcher df;
    private static TTFactory ttf;

    private TTFactory() {
    }

    public static TTFactory getInstance() {
        if (ttf == null) {
            ttf = new TTFactory();
        }

        return ttf;
    }

    public void setSQLManager(AbstractSQLManager sqlm, AbstractQueries qrs) {
        this.sqlm = sqlm;
        this.sqlm.setQueries(qrs);
    }

    public void setDataFetcher(AbstractDataFetcher df) {
        this.df = df;
    }

    public TTUpdateManager produceUpdateManager() {
        return new TTUpdateManager(sqlm, df);
    }

    public TTDeliveryManager produceDeliveryManager() {
        return new TTDeliveryManager(sqlm);
    }

}

Make setSQLManager forced to load queries to avoid NPE and misunderstanding


package org.exist.storage.index;

import org.exist.storage.BrokerPool;
import org.exist.storage.DefaultCacheManager;
import org.exist.storage.btree.BTree;
import org.exist.storage.btree.DBException;
import org.exist.storage.lock.Lock;
import org.exist.storage.lock.MultiReadReentrantLock;
import org.exist.util.FileUtils;

import java.nio.file.Path;

public class BTreeStore extends BTree {

    public final static short FILE_FORMAT_VERSION_ID = 2;

    protected Lock lock = null;

    public BTreeStore(BrokerPool pool, byte fileId, boolean transactional, final Path file, DefaultCacheManager cacheManager) throws DBException {
        super(pool, fileId, transactional, cacheManager, file);
        lock = new MultiReadReentrantLock(FileUtils.fileName(file));

        if(exists()) {
            open(FILE_FORMAT_VERSION_ID);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Creating data file: " + FileUtils.fileName(getFile()));
            }
            create((short)-1);
        }
        setSplitFactor(0.7);
    }

    @Override
    public Lock getLock() {
        return lock;
    }

    public short getFileVersion() {
        return FILE_FORMAT_VERSION_ID;
    }
}

package org.exist.storage.index;

import org.exist.storage.BrokerPool;
import org.exist.storage.DefaultCacheManager;
import org.exist.storage.btree.BTree;
import org.exist.storage.btree.DBException;
import org.exist.storage.lock.Lock;
import org.exist.storage.lock.ReentrantReadWriteLock;
import org.exist.util.FileUtils;

import java.nio.file.Path;

public class BTreeStore extends BTree {

    public final static short FILE_FORMAT_VERSION_ID = 2;

    protected Lock lock = null;

    public BTreeStore(BrokerPool pool, byte fileId, boolean transactional, final Path file, DefaultCacheManager cacheManager) throws DBException {
        super(pool, fileId, transactional, cacheManager, file);
        lock = new ReentrantReadWriteLock(FileUtils.fileName(file));

        if(exists()) {
            open(FILE_FORMAT_VERSION_ID);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Creating data file: " + FileUtils.fileName(getFile()));
            }
            create((short)-1);
        }
        setSplitFactor(0.7);
    }

    @Override
    public Lock getLock() {
        return lock;
    }

    public short getFileVersion() {
        return FILE_FORMAT_VERSION_ID;
    }
}

Revert "Structure index: change lock to MultiReadReentrantLock"


package me.izstas.rfs.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import me.izstas.rfs.server.config.web.PathWithinPattern;
import me.izstas.rfs.server.model.Metadata;
import me.izstas.rfs.server.service.MetadataService;

@RestController
@RequestMapping("/metadata/**")
public class MetadataController {
    @Autowired
    private MetadataService metadataService;

    @RequestMapping(method = RequestMethod.GET)
    public Metadata getMetadata(@PathWithinPattern String path) {
        return metadataService.getMetadataFromUserPath(path);
    }

    @RequestMapping(method = RequestMethod.POST)
    public void applyMetadata(@PathWithinPattern String path, @RequestBody Metadata metadata) {
        metadataService.applyMetadataToUserPath(path, metadata);
    }
}

package me.izstas.rfs.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import me.izstas.rfs.server.config.web.PathWithinPattern;
import me.izstas.rfs.server.model.Metadata;
import me.izstas.rfs.server.service.MetadataService;

@RestController
@RequestMapping("/metadata/**")
public class MetadataController {
    @Autowired
    private MetadataService metadataService;

    @RequestMapping(method = RequestMethod.GET)
    public Metadata getMetadata(@PathWithinPattern String path) {
        return metadataService.getMetadataFromUserPath(path);
    }

    @RequestMapping(method = RequestMethod.POST)
    public Metadata applyMetadata(@PathWithinPattern String path, @RequestBody Metadata metadata) {
        metadataService.applyMetadataToUserPath(path, metadata);
        return metadataService.getMetadataFromUserPath(path);
    }
}

Make POST request to /metadata/** return the new metadata instead of giving empty response


package com.zephir.psi;

import com.intellij.psi.tree.IElementType;
import com.zephir.ZephirLanguage;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

/**
 * @author Nikita Gusakov
 */
public class ZephirTokenType extends IElementType {

    public ZephirTokenType(@NotNull @NonNls String debugName) {
        super(debugName, ZephirLanguage.INSTANCE);
    }

    @Override
    public String toString() {
        return "ZephirTokenType." + super.toString();
    }
}

package com.zephir.psi;

import com.intellij.psi.tree.IElementType;
import com.zephir.ZephirLanguage;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

/**
 * @author Nikita Gusakov
 */
public class ZephirTokenType extends IElementType {

    public ZephirTokenType(@NotNull @NonNls String debugName) {
        super(debugName, ZephirLanguage.INSTANCE);
    }
}

Remove token to string override

Remove token to string override


/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.core;

public class ContextAgentRunnable
  implements Runnable
{
  final X            x_;
  final ContextAgent agent_;
  final String description_;

  public ContextAgentRunnable(X x, ContextAgent agent, String description) {
    x_     = x;
    agent_ = agent;
    description_ = description;
  }

  public String toString() {
    return description_;
  }

  public void run() {
    agent_.execute(x_);
  }
}

/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.core;

public class ContextAgentRunnable
  implements Runnable
{
  final X            x_;
  final ContextAgent agent_;
  final String description_;

  public ContextAgentRunnable(X x, ContextAgent agent, String description) {
    x_     = x;
    agent_ = agent;
    description_ = description;
  }

  public String toString() {
    return description_;
  }

  public void run() {
    XLocator.set(x_);
    try {
      agent_.execute(x_);
    } finally {
      XLocator.set(null);
    }
  }
}

Fix XLocator when from from AssemblyLine.


package main.java.engine.objects;

import main.java.engine.objects.TDObject;

public class Tower extends TDObject {

	public Tower(String name, boolean unique_id, double x, double y,
			int collisionid, String gfxname) {
		super(name, unique_id, x, y, collisionid, gfxname);
		// TODO Auto-generated constructor stub
	}
}

package main.java.engine.objects;

import jgame.JGObject;
import ProjectPoseidon.Constants;
import main.java.engine.objects.TDObject;

public class Tower extends TDObject {

    public static final String TOWER_GFX = "tower";
    public static final int TOWER_CID = 0;

    private double health;
    private double damage;
    private double range;

    /**
     * Create a tower at the specified x,y coordinate.
     * @param x
     * @param y
     */
    public Tower (double x, double y) {
        super("tower", x, y, TOWER_CID, TOWER_GFX);
    }

    /**
     * Shoot a projectile in the direction of the specified x,y target coordinates
     *
     * @param targetX
     * @param targetY
     */
    public void fireProjectile (double targetX, double targetY) {
        /* trigonometry from Guardian JGame example */
        double angle = Math.atan2(targetX - this.x, targetY - this.y);
        new Projectile(this.x, this.y, angle);
    }

}

Update tower constructor and add fireProjectile()


package talkhouse;

public class Segmenter {
  private double[] buf=null;
  int winsz;
  int winshift;
  static final int MIN_SEGMENTS = 3;

  public Segmenter(int winsz, int winshift) {
    this.winsz = winsz;
    this.winshift = winshift;
  }

  public double[][] apply(double[] data) {
    double[] combo;
    if (buf != null) {
        combo = new double[buf.length + data.length];
        System.arraycopy(buf, 0, combo, 0, buf.length);
        System.arraycopy(data, 0, combo, buf.length, data.length);
    } else {
        combo = data;
    }
    if (combo.length < winsz + winshift * MIN_SEGMENTS){
        buf = combo;
        return null;
    } else {
        buf = null;
    }
    double[][] result = new double[(combo.length-winsz)/winshift+1][];
    int i = 0;
    int j=0;
    while (i+winsz <= combo.length) {
      double[] seg = new double[winsz];
      System.arraycopy(combo, i, seg, 0, winsz);
      result[j++] = seg;
      i+=winshift;
    }

    int bufsize = combo.length - i;
    if (bufsize > 0) {
        if (buf == null || buf.length != bufsize) {
          buf = new double[bufsize];
        }
        System.arraycopy(combo, combo.length - bufsize, buf, 0, bufsize);
    } else {
        buf = null;
    }
    return result;
  }
};

package talkhouse;

public class Segmenter {
  private double[] buf=null;
  int winsz;
  int winshift;
  static final int MIN_SEGMENTS = 3;

  public Segmenter(int winsz, int winshift) {
    this.winsz = winsz;
    this.winshift = winshift;
  }

  public double[][] apply(double[] data) {
    double[] combo;
    if (buf != null) {
        combo = new double[buf.length + data.length];
        System.arraycopy(buf, 0, combo, 0, buf.length);
        System.arraycopy(data, 0, combo, buf.length, data.length);
    } else {
        combo = data;
    }
    if (combo.length < winsz + winshift * MIN_SEGMENTS){
        buf = combo;
        return null;
    } else {
        buf = null;
    }
    int rows = (combo.length - combo.length % winshift - winsz +
          winshift)/ winshift;
    double[][] result = new double[rows][];

    for (int i=0;i<rows;++i) {
      double[] seg = new double[winsz];
      System.arraycopy(combo, i*winshift, seg, 0, winsz);
      result[i] = seg;
    }

    int bufsize = combo.length - rows * winshift;
    if (bufsize > 0) {
        if (buf == null || buf.length != bufsize) {
          buf = new double[bufsize];
        }
        System.arraycopy(combo, combo.length - bufsize, buf, 0, bufsize);
    } else {
        buf = null;
    }
    return result;
  }
};

Update Java segmenter to use the same formula as the C version.


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

import org.traccar.helper.Log;
import org.traccar.model.Position;

public class DefaultDataHandler extends BaseDataHandler {

    @Override
    protected Position handlePosition(Position position) {

        try {
            Context.getDataManager().addPosition(position);
            Context.getDataManager().updateLatestPosition(position);
        } catch (Exception error) {
            Log.warning(error);
        }

        return position;
    }

}

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

import org.traccar.helper.Log;
import org.traccar.model.Position;

public class DefaultDataHandler extends BaseDataHandler {

    @Override
    protected Position handlePosition(Position position) {

        try {
            Context.getDataManager().addPosition(position);
            Position lastPosition = Context.getConnectionManager().getLastPosition(position.getDeviceId());
            if (position.getFixTime().compareTo(lastPosition.getFixTime()) > 0) {
                Context.getDataManager().updateLatestPosition(position);
            }
        } catch (Exception error) {
            Log.warning(error);
        }

        return position;
    }

}

Update position only when latest

Update position only when latest


/*
 ** 2013 August 11
 **
 ** The author disclaims copyright to this source code.  In place of
 ** a legal notice, here is a blessing:
 **    May you do good and not evil.
 **    May you find forgiveness for yourself and forgive others.
 **    May you share freely, never taking more than you give.
 */
package info.ata4.disunity.cli;

import com.beust.jcommander.Parameter;

/**
 * DisUnity configuration class.
 *
 * @author Nico Bergemann <barracuda415 at yahoo.de>
 */
public class DisUnityOptions {

    @Parameter(
        names = {"-h", "--help"},
        description = "Print this help.",
        help = true
    )
    private boolean help;

    @Parameter(
        names = { "-v", "--verbose" },
        description = "Show more verbose log output."
    )
    private boolean verbose;

    @Parameter(
        names = { "-f", "--output-format" },
        description = "Set output text format."
    )
    private OutputFormat outputFormat;

    public boolean isHelp() {
        return help;
    }

    public boolean isVerbose() {
        return verbose;
    }

    public OutputFormat getOutputFormat() {
        return outputFormat;
    }
}

/*
 ** 2013 August 11
 **
 ** The author disclaims copyright to this source code.  In place of
 ** a legal notice, here is a blessing:
 **    May you do good and not evil.
 **    May you find forgiveness for yourself and forgive others.
 **    May you share freely, never taking more than you give.
 */
package info.ata4.disunity.cli;

import com.beust.jcommander.Parameter;

/**
 * DisUnity configuration class.
 *
 * @author Nico Bergemann <barracuda415 at yahoo.de>
 */
public class DisUnityOptions {

    @Parameter(
        names = {"-h", "--help"},
        description = "Print this help.",
        help = true
    )
    private boolean help;

    @Parameter(
        names = { "-v", "--verbose" },
        description = "Show more verbose log output."
    )
    private boolean verbose;

    @Parameter(
        names = { "-f", "--output-format" },
        description = "Set output text format."
    )
    private OutputFormat outputFormat = OutputFormat.PLAINTEXT;

    public boolean isHelp() {
        return help;
    }

    public boolean isVerbose() {
        return verbose;
    }

    public OutputFormat getOutputFormat() {
        return outputFormat;
    }
}

Set default output format to plain text

Set default output format to plain text


package nuclibook.routes;

import nuclibook.constants.P;
import nuclibook.entity_utils.ExportUtils;
import nuclibook.entity_utils.PatientUtils;
import nuclibook.entity_utils.SecurityUtils;
import nuclibook.models.Patient;
import nuclibook.server.HtmlRenderer;
import spark.Request;
import spark.Response;

import java.util.List;

public class ExportRoute extends DefaultRoute {

    @Override
    public Object handle(Request request, Response response) throws Exception {
        // necessary prelim routine
        prepareToHandle();

        String[] fileSplit = request.params(":file:").split("\\.", 2);
        String table = fileSplit[0];

        String type = "";
        try {
            type = fileSplit[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            return null;
        }

        String exportData = null;

        if (table.equals("patients")) {
            if (SecurityUtils.requirePermission(P.VIEW_PATIENT_LIST, response)) {
                if (type.equals("csv")) {
                    exportData = ExportUtils.exportCSV(Patient.class);
                }
            }
        }

        if (exportData != null) {
            response.header("Content-Disposition", "attachment");
        }

        return exportData;
    }
}

package nuclibook.routes;

import nuclibook.constants.P;
import nuclibook.entity_utils.ActionLogger;
import nuclibook.entity_utils.ExportUtils;
import nuclibook.entity_utils.PatientUtils;
import nuclibook.entity_utils.SecurityUtils;
import nuclibook.models.Patient;
import nuclibook.server.HtmlRenderer;
import spark.Request;
import spark.Response;

import java.util.List;

public class ExportRoute extends DefaultRoute {

    @Override
    public Object handle(Request request, Response response) throws Exception {
        // necessary prelim routine
        prepareToHandle();

        String[] fileSplit = request.params(":file:").split("\\.", 2);
        String table = fileSplit[0];

        String type = "";
        try {
            type = fileSplit[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            return null;
        }

        String exportData = null;

        if (table.equals("patients")) {
            if (SecurityUtils.requirePermission(P.EXPORT_PATIENTS, response)) {
                if (type.equals("csv")) {
                    exportData = ExportUtils.exportCSV(Patient.class);
                }
                ActionLogger.logAction(ActionLogger.EXPORT_PATIENTS, 0);
            } else {
                ActionLogger.logAction(ActionLogger.ATTEMPT_EXPORT_PATIENTS, 0, "Failed as user does not have permissions for this action");
            }
        }

        if (exportData != null) {
            response.header("Content-Disposition", "attachment");
        }

        return exportData;
    }
}

Add export log + permissions

Add export log + permissions


package org.synyx.minos.core.web.support;

import org.synyx.minos.core.web.event.Event;

/**
 * @author Oliver Gierke - gierke@synyx.de
 */
public class ProjectDeletedEvent implements Event {

    private String name;

    /**
     * @param name
     */
    public ProjectDeletedEvent(String name) {

        super();
        this.name = name;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {

        // TODO Auto-generated method stub
        return getClass().getSimpleName() + ": " + name;
    }

}

package org.synyx.minos.core.web.support;

import org.synyx.minos.core.web.event.Event;

/**
 * @author Oliver Gierke - gierke@synyx.de
 */
public class ProjectDeletedEvent implements Event {

    private String name;

    /**
     * @param name
     */
    public ProjectDeletedEvent(String name) {

        super();
        this.name = name;
    }

    @Override
    public String toString() {

        return getClass().getSimpleName() + ": " + name;
    }
}

Comment boyscouting: leaving the comments cleaner than you found them

git-svn-id: 14e2c384b8d34cccbaaca68230c28851bca468ab@15549 5a64d73e-33d6-4ccc-9058-23f8668ecac9


package org.jvirtanen.nassau.binaryfile;

import org.jvirtanen.nassau.ProtocolException;

public class BinaryFILEException extends ProtocolException {

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

}

package org.jvirtanen.nassau.binaryfile;

import org.jvirtanen.nassau.ProtocolException;

/**
 * Indicates a protocol error while handling the BinaryFILE file format.
 */
public class BinaryFILEException extends ProtocolException {

    /**
     * Construct an instance with the specified detail message.
     *
     * @param message the detail message
     */
    public BinaryFILEException(String message) {
        super(message);
    }

}

Add documentation for BinaryFILE exception


package floobits;

import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.util.text.StringUtil;

public class JoinWorkspace extends AnAction {

    private static class URLInputValidator implements InputValidator {
        @Override
        public boolean canClose(String inputString) {
            return true;
        }

        @Override
        public boolean checkInput(String inputString) {
            try {
                final URL url = new URL(inputString);
                return StringUtil.isNotEmpty(url.getHost());
            } catch (MalformedURLException e) {
                return false;
            }
        }
    }

    public void actionPerformed(AnActionEvent e) {
        String inputValue = JOptionPane.showInputDialog("Workspace URL", "https://floobits.com/kansface/asdf");
        Flog.info(inputValue);
        FloobitsPlugin.joinWorkspace(inputValue);
    }
}

package floobits;

import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.util.text.StringUtil;

public class JoinWorkspace extends AnAction {

    private static class URLInputValidator implements InputValidator {
        @Override
        public boolean canClose(String inputString) {
            return true;
        }

        @Override
        public boolean checkInput(String inputString) {
            try {
                final URL url = new URL(inputString);
                return StringUtil.isNotEmpty(url.getHost());
            } catch (MalformedURLException e) {
                return false;
            }
        }
    }

    public void actionPerformed(AnActionEvent e) {
        String inputValue = JOptionPane.showInputDialog("Workspace URL", "https://floobits.com/");
        Flog.info(inputValue);
        FloobitsPlugin.joinWorkspace(inputValue);
    }
}

Remove kansface repo from input.

Remove kansface repo from input.


/**
 * This file is part of AlmuraSDK, All Rights Reserved.
 *
 * Copyright (c) 2015 AlmuraDev <http://github.com/AlmuraDev/>
 */
package com.almuradev.almurasdk.permissions;

import java.util.HashSet;
import java.util.Set;

public class PermissibleAllMods implements Permissible {

    private Set<Permissible> permissibles = new HashSet<>();

    public void addPermissible(Permissible permissible) {
        this.permissibles.add(permissible);
    }

    @Override
    public String getPermissibleModName() {
        return "all";
    }

    @Override
    public float getPermissibleModVersion() {
        return 0.0F;
    }

    @Override
    public void registerPermissions(PermissionsManagerClient permissionsManager) {
    }

    @Override
    public void onPermissionsCleared(PermissionsManager manager) {
        for (Permissible permissible : this.permissibles) {
            permissible.onPermissionsCleared(manager);
        }
    }

    @Override
    public void onPermissionsChanged(PermissionsManager manager) {
        for (Permissible permissible : this.permissibles) {
            permissible.onPermissionsChanged(manager);
        }
    }
}

/**
 * This file is part of AlmuraSDK, All Rights Reserved.
 *
 * Copyright (c) 2015 AlmuraDev <http://github.com/AlmuraDev/>
 */
package com.almuradev.almurasdk.permissions;

import java.util.HashSet;
import java.util.Set;

public class PermissibleAllMods implements Permissible {

    private Set<Permissible> permissibles = new HashSet<>();

    public void addPermissible(Permissible permissible) {
        this.permissibles.add(permissible);
    }

    @Override
    public String getPermissibleModName() {
        return "all";
    }

    @Override
    public float getPermissibleModVersion() {
        return 0.0F;
    }

    @Override
    public void registerPermissions(PermissionsManager permissionsManager) {
    }

    @Override
    public void onPermissionsCleared(PermissionsManager manager) {
        for (Permissible permissible : this.permissibles) {
            permissible.onPermissionsCleared(manager);
        }
    }

    @Override
    public void onPermissionsChanged(PermissionsManager manager) {
        for (Permissible permissible : this.permissibles) {
            permissible.onPermissionsChanged(manager);
        }
    }
}

Update build.gradle and fix compilation

Update build.gradle and fix compilation

Signed-off-by: Steven Downer <e51bce9123e792aec8a98724fb48684dc936521f@outlook.com>


package com.samovich.java.basics.collections.list.arraylist;

/**
 * Created by Samovich on 1/20/2015.
 */
public class ArrayListForEach {
}

/**
 * @file ArrayListForEach.java
 * @author Valery Samovich
 * @version 1
 * @date 2014/01/09
 */

/*
 *  Following code shows an example how to create a Collection of type List
 *  which is parameterized with <String> to indicate to the Java compiler
 *  that only Strings are allowed in this list.
 */
package com.samovich.java.basics.collections.list.arraylist;

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

public class ArrayListForEach {

    public static void main(String[] args) {

        // Create a list, use is ArrayList as concrete type
        // ArrayList<> infers the String type from the left side
        List<String> myList = new ArrayList<String>();

        myList.add("string1");
        myList.add("string2");
        myList.add("string3");

        // Loop over it and print the result to the console
        for(String value : myList) {
            System.out.println(value);
        }
    }
}

Refactor the code and add the ArrayList with For Statement


package net.squanchy.eventdetails.widget;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.util.AttributeSet;

import net.squanchy.R;
import net.squanchy.schedule.domain.view.Event;

public class EventDetailsCoordinatorLayout extends CoordinatorLayout {

    private FloatingActionButton floatingActionButton;
    private EventDetailsHeaderLayout headerLayout;
    private EventDetailsLayout detailsLayout;

    public EventDetailsCoordinatorLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EventDetailsCoordinatorLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        floatingActionButton = (FloatingActionButton) findViewById(R.id.favorite_fab);
        headerLayout = (EventDetailsHeaderLayout) findViewById(R.id.event_details_header);
        detailsLayout = (EventDetailsLayout) findViewById(R.id.event_details);
    }

    public void updateWith(Event event) {
        headerLayout.updateWith(event);
        detailsLayout.updateWith(event);
    }
}

package net.squanchy.eventdetails.widget;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.util.AttributeSet;

import net.squanchy.R;
import net.squanchy.schedule.domain.view.Event;

public class EventDetailsCoordinatorLayout extends CoordinatorLayout {

    private FloatingActionButton floatingActionButton;
    private EventDetailsHeaderLayout headerLayout;
    private EventDetailsLayout detailsLayout;

    public EventDetailsCoordinatorLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EventDetailsCoordinatorLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        floatingActionButton = (FloatingActionButton) findViewById(R.id.favorite_fab);
        headerLayout = (EventDetailsHeaderLayout) findViewById(R.id.event_details_header);
        detailsLayout = (EventDetailsLayout) findViewById(R.id.event_details);
    }

    public void updateWith(Event event) {
        headerLayout.updateWith(event);
        detailsLayout.updateWith(event);

        floatingActionButton.setImageResource(
                event.favorited() ?
                        R.drawable.ic_favorite_filled :
                        R.drawable.ic_favorite_empty
        );
    }
}

Swap FAB icon based on favorite status

Swap FAB icon based on favorite status


package com.github.games647.changeskin.bungee.listener;

import com.github.games647.changeskin.bungee.ChangeSkinBungee;
import com.github.games647.changeskin.core.SkinData;
import com.github.games647.changeskin.core.UserPreference;

import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;

public class JoinListener extends AbstractSkinListener {

    public JoinListener(ChangeSkinBungee plugin) {
        super(plugin);
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerLogin(PostLoginEvent postLoginEvent) {
        ProxiedPlayer player = postLoginEvent.getPlayer();

        //updates to the chosen one
        UserPreference preferences = plugin.getLoginSession(player.getPendingConnection());
        SkinData targetSkin = preferences.getTargetSkin();
        if (targetSkin == null) {
            setRandomSkin(preferences, player);
        } else {
            plugin.applySkin(player, targetSkin);
        }
    }
}

package com.github.games647.changeskin.bungee.listener;

import com.github.games647.changeskin.bungee.ChangeSkinBungee;
import com.github.games647.changeskin.core.SkinData;
import com.github.games647.changeskin.core.UserPreference;

import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;

public class JoinListener extends AbstractSkinListener {

    public JoinListener(ChangeSkinBungee plugin) {
        super(plugin);
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerLogin(PostLoginEvent postLoginEvent) {
        ProxiedPlayer player = postLoginEvent.getPlayer();

        //updates to the chosen one
        UserPreference preferences = plugin.getLoginSession(player.getPendingConnection());
        if (preferences == null) {
            return;
        }

        SkinData targetSkin = preferences.getTargetSkin();
        if (targetSkin == null) {
            setRandomSkin(preferences, player);
        } else {
            plugin.applySkin(player, targetSkin);
        }
    }
}

Fix NPE on bungeecord lazy loading

Fix NPE on bungeecord lazy loading


package de.retest.recheck.persistence;

/**
 * Extends the standard {@link ClassAndMethodBasedNamingStrategy}, but instead of the qualified class name (e.g.
 * `com.mycompany.MyTest`) returns the {@link Class#getSimpleName()} of the class (e.g. `MyTest`).
 */
public class ClassAndMethodBasedShortNamingStrategy extends ClassAndMethodBasedNamingStrategy {

	/**
	 * @return The {@link Class#getSimpleName()} of the test class (e.g. `MyTest`).
	 */
	@Override
	public String getSuiteName() {
		String result = super.getSuiteName();
		if ( result.contains( "." ) ) {
			result = result.substring( result.lastIndexOf( "." ) + 1 );
		}
		if ( result.contains( "$" ) ) {
			result = result.substring( 0, result.indexOf( "$" ) );
		}
		return result;
	}
}

package de.retest.recheck.persistence;

/**
 * Extends the standard {@link ClassAndMethodBasedNamingStrategy}, but instead of the qualified class name (e.g.
 * `com.mycompany.MyTest`) returns the {@link Class#getSimpleName()} of the class (e.g. `MyTest`).
 */
public class ClassAndMethodBasedShortNamingStrategy extends ClassAndMethodBasedNamingStrategy {

	/**
	 * @return The {@link Class#getSimpleName()} of the test class (e.g. `MyTest`).
	 */
	@Override
	public String getSuiteName() {
		String result = super.getSuiteName();
		if ( result.contains( "." ) ) {
			result = result.substring( result.lastIndexOf( '.' ) + 1 );
		}
		if ( result.contains( "$" ) ) {
			result = result.substring( 0, result.indexOf( '$' ) );
		}
		return result;
	}
}

Change to single quotes for faster lastInfexOf


package io.github.tatools.sunshine.core;

import java.util.List;

/**
 * @author Dmytro Serdiuk (dmytro.serdiuk@gmail.com)
 * @version $Id$
 * @since 0.1
 */
public final class SunshineSuitePrintable implements SunshineSuite {

    private final SunshineSuite sunshineSuite;

    public SunshineSuitePrintable(SunshineSuite sunshineSuite) {
        this.sunshineSuite = sunshineSuite;
    }

    @Override
    public List<SunshineTest> tests() throws SuiteException {
        System.out.println("Sunshine suite contains the following tests:");
        this.sunshineSuite.tests().forEach(System.out::println);
        return this.sunshineSuite.tests();
    }
}

package io.github.tatools.sunshine.core;

import java.util.List;

/**
 * @author Dmytro Serdiuk (dmytro.serdiuk@gmail.com)
 * @version $Id$
 * @since 0.1
 */
public final class SunshineSuitePrintable implements SunshineSuite {

    private final SunshineSuite sunshineSuite;

    public SunshineSuitePrintable(SunshineSuite sunshineSuite) {
        this.sunshineSuite = sunshineSuite;
    }

    @Override
    public List<SunshineTest> tests() throws SuiteException {
        final List<SunshineTest> tests = this.sunshineSuite.tests();
        final StringBuilder message = new StringBuilder();
        message.append("Sunshine found ")
                .append(tests.size())
                .append(" classes by the specified pattern. They all will be passed to appropriate xUnit engine.")
                .append("\nClasses:");
        tests.forEach(c -> message.append("\n- ").append(c));
        System.out.println(message);
        return tests;
    }
}

Print found classes count and their names

Affects #16


package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import info.u_team.u_team_core.api.registry.IUBlockRegistryType;
import net.minecraft.block.Block;
import net.minecraft.item.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;

public class BlockDeferredRegister {

	public final DeferredRegister<Block> blocks;
	public final DeferredRegister<Item> items;

	public BlockDeferredRegister(String modid) {
		blocks = DeferredRegister.create(ForgeRegistries.BLOCKS, modid);
		items = DeferredRegister.create(ForgeRegistries.ITEMS, modid);
	}

	public <B extends Block & IUBlockRegistryType, I extends BlockItem> BlockRegistryObject<B, I> register(String name, Supplier<? extends B> supplier) {
		final RegistryObject<B> block = blocks.register(name, supplier);
		final RegistryObject<I> item = RegistryObject.of(new ResourceLocation(name), ForgeRegistries.ITEMS);

		return new BlockRegistryObject<B, I>(block, item);
	}

	public void register(IEventBus bus) {
		blocks.register(bus);
		items.register(bus);
	}

}

package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import info.u_team.u_team_core.api.registry.IUBlockRegistryType;
import net.minecraft.block.Block;
import net.minecraft.item.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;

public class BlockDeferredRegister {

	public final DeferredRegister<Block> blocks;

	public BlockDeferredRegister(String modid) {
		blocks = DeferredRegister.create(ForgeRegistries.BLOCKS, modid);
	}

	public <B extends Block & IUBlockRegistryType, I extends BlockItem> BlockRegistryObject<B, I> register(String name, Supplier<? extends B> supplier) {
		final RegistryObject<B> block = blocks.register(name, supplier);
		final RegistryObject<I> item = RegistryObject.of(new ResourceLocation(name), ForgeRegistries.ITEMS);

		return new BlockRegistryObject<B, I>(block, item);
	}

	public void register(IEventBus bus) {
		blocks.register(bus);
	}

}

Remove unused item deferred register in block deferred register


/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

package org.tensorflow.lite;

import static com.google.common.truth.Truth.assertThat;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link org.tensorflow.lite.TensorFlowLite}. */
@RunWith(JUnit4.class)
public final class TensorFlowLiteTest {

  @Test
  @SuppressWarnings("deprecation")
  public void testVersion() {
    assertThat(TensorFlowLite.version()).isEqualTo("3");
  }

  @Test
  public void testSchemaVersion() {
    assertThat(TensorFlowLite.schemaVersion()).isEqualTo("3");
  }

  @Test
  public void testRuntimeVersion() {
    assertThat(TensorFlowLite.runtimeVersion()).startsWith("1.");
  }
}

/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

package org.tensorflow.lite;

import static com.google.common.truth.Truth.assertThat;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link org.tensorflow.lite.TensorFlowLite}. */
@RunWith(JUnit4.class)
public final class TensorFlowLiteTest {

  @Test
  @SuppressWarnings("deprecation")
  public void testVersion() {
    assertThat(TensorFlowLite.version()).isEqualTo("3");
  }

  @Test
  public void testSchemaVersion() {
    assertThat(TensorFlowLite.schemaVersion()).isEqualTo("3");
  }

  @Test
  public void testRuntimeVersion() {
    // Unlike the schema version, which should almost never change, the runtime version can change
    // with some frequency, so simply ensure that it's non-empty and doesn't fail.
    assertThat(TensorFlowLite.runtimeVersion()).isNotEmpty();
  }
}

Fix brittle TFLite Java version test

Fix brittle TFLite Java version test

Mirror the native TF test for version checking.

PiperOrigin-RevId: 305948727
Change-Id: I18169d0a1b6b0deaefed7984237ea76481c2c59b


/*
 * 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.commons.vfs2.example;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.VFS;

/**
 * Simply changed the last modification time of the given file
 */
public class ChangeLastModificationTime
{
    public static void main(String[] args) throws Exception
    {
        if (args.length == 0)
        {
            System.err.println("Please pass the name of a file as parameter.");
            return;
        }

        FileObject fo = VFS.getManager().resolveFile(args[0]);
        long setTo = System.currentTimeMillis();
        System.err.println("set to: " + setTo);
        fo.getContent().setLastModifiedTime(setTo);
        System.err.println("after set: " + fo.getContent().getLastModifiedTime());
    }
}

/*
 * 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.commons.vfs2.example;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.VFS;

/**
 * Simply changed the last modification time of the given file.
 */
public class ChangeLastModificationTime
{
    public static void main(String[] args) throws Exception
    {
        if (args.length == 0)
        {
            System.err.println("Please pass the name of a file as parameter.");
            return;
        }

        FileObject fo = VFS.getManager().resolveFile(args[0]);
        long setTo = System.currentTimeMillis();
        System.err.println("set to: " + setTo);
        fo.getContent().setLastModifiedTime(setTo);
        System.err.println("after set: " + fo.getContent().getLastModifiedTime());
    }
}

Fix Checkstyle issues: First sentence should end with a period.

git-svn-id: c455d203a03ec41bf444183aad31e7cce55db786@1352225 13f79535-47bb-0310-9956-ffa450edef68


package modules.admin.User.actions;

import modules.admin.domain.Contact;
import modules.admin.domain.Contact.ContactType;
import modules.admin.domain.User;
import modules.admin.domain.User.WizardState;

import org.skyve.metadata.controller.ServerSideAction;
import org.skyve.metadata.controller.ServerSideActionResult;
import org.skyve.web.WebContext;

public class New implements ServerSideAction<User> {
	/**
	 * For Serialization.
	 */
	private static final long serialVersionUID = 7776867319664519408L;

	@Override
	public ServerSideActionResult<User> execute(User adminUser, WebContext webContext) throws Exception {

		// Clear out old matches
		adminUser.getCandidateContacts().clear();

		Contact contact = Contact.newInstance();
		String searchContactName = adminUser.getSearchContactName();
		if (searchContactName == null) {
			searchContactName = "<New Person>";
		}
		contact.setName(searchContactName);
		contact.setEmail1(adminUser.getSearchEmail());
		contact.setContactType(ContactType.person);
		adminUser.setContact(contact);

		adminUser.setWizardState(WizardState.createContact);

		return new ServerSideActionResult<>(adminUser);
	}
}

package modules.admin.User.actions;

import org.skyve.metadata.controller.ServerSideAction;
import org.skyve.metadata.controller.ServerSideActionResult;
import org.skyve.web.WebContext;

import modules.admin.domain.Contact;
import modules.admin.domain.Contact.ContactType;
import modules.admin.domain.User;
import modules.admin.domain.User.WizardState;

public class New implements ServerSideAction<User> {

	private static final long serialVersionUID = 7776867319664519408L;

	@Override
	public ServerSideActionResult<User> execute(User adminUser, WebContext webContext) throws Exception {

		// Clear out old matches
		adminUser.getCandidateContacts().clear();

		Contact contact = Contact.newInstance();
		String searchContactName = adminUser.getSearchContactName();
		contact.setName(searchContactName);
		contact.setEmail1(adminUser.getSearchEmail());
		contact.setContactType(ContactType.person);
		adminUser.setContact(contact);

		adminUser.setWizardState(WizardState.createContact);

		return new ServerSideActionResult<>(adminUser);
	}
}

Remove confusing contact name placeholder value during new user creation.


package info.u_team.u_team_test.integration;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.api.integration.*;

@Integration("uteamcore")
public class TestIntegrationCall implements IModIntegration {

	public static final Logger LOGGER = LogManager.getLogger("IntegrationCall");

	static {
		LOGGER.info("Integration call is cinit!");
	}

	@Override
	public void construct() {
		LOGGER.info("Integration call is constructed!");
	}

}

package info.u_team.u_team_test.integration;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.api.integration.*;
import info.u_team.u_team_test.TestMod;

@Integration(modid = TestMod.MODID, integration = "uteamcore")
public class TestIntegrationCall implements IModIntegration {

	public static final Logger LOGGER = LogManager.getLogger("IntegrationCall");

	static {
		LOGGER.info("Integration call is cinit!");
	}

	@Override
	public void construct() {
		LOGGER.info("Integration call is constructed!");
	}

}

Add the new modid field in the integration call


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.stuy.commands;

import edu.wpi.first.wpilibj.Compressor;
import java.lang.Math;

/**
 *
 * @author Kevin Wang
 */
public class DriveManualJoystickControl extends CommandBase {

    public DriveManualJoystickControl() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(drivetrain);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
        drivetrain.compressor.start();

    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        drivetrain.tankDrive(-oi.getLeftStick().getY(), -oi.getRightStick().getY());
        // If we're driving, stop the compressor from turning on. Otherwise, it's fine.
        if ( Math.abs(oi.getLeftStick().getY()) < 0.1  || Math.abs(oi.getRightStick().getY()) < 0.1) {
            drivetrain.compressor.stop();
        } else {
            drivetrain.compressor.start();
        }
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.stuy.commands;

import edu.wpi.first.wpilibj.Compressor;
import java.lang.Math;

/**
 *
 * @author Kevin Wang
 */
public class DriveManualJoystickControl extends CommandBase {

    public DriveManualJoystickControl() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(drivetrain);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
        drivetrain.compressor.start();

    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        drivetrain.tankDrive(-oi.getLeftStick().getY(), -oi.getRightStick().getY());
        // If we're driving, stop the compressor from turning on. Otherwise, it's fine.
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

Remove compressor disablement while driving


package by.triumgroup.recourse.supplier.entity.model;

import by.triumgroup.recourse.entity.model.BaseEntity;
import org.springframework.data.util.Pair;

public interface EntityIntegerPKSupplier<E extends BaseEntity<Integer>> extends EntitySupplier<E, Integer>{
    @Override
    default Integer getAnyId(){
        return 1;
    }

    @Override
    default Pair<Integer, Integer> getDifferentIds(){
        return Pair.of(1, 2);
    }
}

package by.triumgroup.recourse.supplier.entity.model;

import by.triumgroup.recourse.entity.model.BaseEntity;
import org.springframework.data.util.Pair;

import java.util.Random;

public interface EntityIntegerPKSupplier<E extends BaseEntity<Integer>> extends EntitySupplier<E, Integer>{
    @Override
    default Integer getAnyId(){
        return new Random().ints(1, Integer.MAX_VALUE).findFirst().getAsInt();
    }

    @Override
    default Pair<Integer, Integer> getDifferentIds(){
        Integer first = getAnyId();
        Integer second = first + 1;
        return Pair.of(first, second);
    }
}

Add random id generating for tests

Add random id generating for tests


package com.galvarez.ttw.model.components;

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

import com.artemis.Component;
import com.artemis.Entity;
import com.galvarez.ttw.model.DiplomaticSystem.Action;
import com.galvarez.ttw.model.DiplomaticSystem.State;

public final class Diplomacy extends Component {

  public final Map<Entity, State> relations = new HashMap<>();

  public final Map<Entity, Integer> lastChange = new HashMap<>();

  public final Map<Entity, Action> proposals = new HashMap<>();

  public final EnumSet<State> knownStates = EnumSet.of(State.NONE);

  public Diplomacy() {
  }

  public State getRelationWith(Entity other) {
    State state = relations.get(other);
    return state != null ? state : State.NONE;
  }

  public Action getProposalTo(Entity other) {
    Action action = proposals.get(other);
    return action != null ? action : Action.NO_CHANGE;
  }

}

package com.galvarez.ttw.model.components;

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

import com.artemis.Component;
import com.artemis.Entity;
import com.galvarez.ttw.model.DiplomaticSystem.Action;
import com.galvarez.ttw.model.DiplomaticSystem.State;

public final class Diplomacy extends Component {

  public final Map<Entity, State> relations = new HashMap<>();

  public final Map<Entity, Integer> lastChange = new HashMap<>();

  public final Map<Entity, Action> proposals = new HashMap<>();

  public final EnumSet<State> knownStates = EnumSet.of(State.NONE);

  public Diplomacy() {
  }

  public State getRelationWith(Entity other) {
    State state = relations.get(other);
    return state != null ? state : State.NONE;
  }

  public Action getProposalTo(Entity other) {
    Action action = proposals.get(other);
    return action != null ? action : Action.NO_CHANGE;
  }

  /** Get all empires whose state is the one passed as a parameter. */
  public List<Entity> getEmpires(State state) {
    List<Entity> others = new ArrayList<Entity>();
    for (Entry<Entity, State> e : relations.entrySet()) {
      if (e.getValue() == state)
        others.add(e.getKey());
    }
    return others;
  }

}

Add helper method to get all the empires we have some relation with.


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

package androidx.navigation;

/**
 * Dummy file, because android gradle plugin requires not empty sources
 */
public class Foo {
}

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

package androidx.navigation;

/**
 * Placeholder file, because android gradle plugin requires not empty sources
 */
public class Foo {
}

Update language to comply with Android's inclusive language guidance

See https://source.android.com/setup/contribute/respectful-code for reference

BUG=161896447
Test: ./gradlew bOS

Change-Id: I3479185e782542fc3d5164ba00c04888806e0068


package com.pushtechnology.adapters.rest.model.latest;

import java.util.List;

import com.pushtechnology.adapters.rest.model.AnyModel;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;

/**
 * Configuration model. Version 4.
 *
 * @author Push Technology Limited
 */
@Value
@Builder
@AllArgsConstructor
public class Model implements AnyModel {
    /**
     * The version of the model.
     */
    public static final int VERSION = 3;

    /**
     * The Diffusion server.
     */
    private Diffusion diffusion;

    /**
     * The REST services to poll.
     */
    List<Service> services;
}

package com.pushtechnology.adapters.rest.model.latest;

import java.util.List;

import com.pushtechnology.adapters.rest.model.AnyModel;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;

/**
 * Configuration model. Version 4.
 *
 * @author Push Technology Limited
 */
@Value
@Builder
@AllArgsConstructor
public class Model implements AnyModel {
    /**
     * The version of the model.
     */
    public static final int VERSION = 4;

    /**
     * The Diffusion server.
     */
    private Diffusion diffusion;

    /**
     * The REST services to poll.
     */
    List<Service> services;
}

Correct the version number of the lastest model.


package com.wakatime.android.support.log;

import android.util.Log;

import com.crashlytics.android.Crashlytics;

import timber.log.Timber;

/**
 * @author Joao Pedro Evangelista
 */
public class CrashlyticsTree extends Timber.Tree {
    private static String formatMessage(String message, Throwable throwable) {
        String traceAsString = Log.getStackTraceString(throwable);
        return String.format("%s. Nested exception is: %s", message, traceAsString);
    }

    @Override
    protected void log(int priority, String tag, String message, Throwable t) {
        if (priority == Log.ERROR) {
            Crashlytics.log(priority, tag, formatMessage(message, t));
        } else {
            Log.println(priority, tag, formatMessage(message, t));
        }
    }
}

package com.wakatime.android.support.log;

import android.util.Log;

import com.crashlytics.android.Crashlytics;

import timber.log.Timber;

/**
 * @author Joao Pedro Evangelista
 */
public class CrashlyticsTree extends Timber.Tree {
    private static String formatMessage(String message, Throwable throwable) {
        String traceAsString = Log.getStackTraceString(throwable);
        return String.format("%s. Nested exception is: %s", message, traceAsString);
    }

    @Override
    protected void log(int priority, String tag, String message, Throwable t) {
        if (priority == Log.ERROR) {
            Crashlytics.log(priority, tag, formatMessage(message, t));
        }
    }
}

Make Crashlytics Tree handle only errors


package com.jmb.springfactory.service.productionschedule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jmb.springfactory.dao.GenericMySQLService;
import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
import com.jmb.springfactory.model.bo.BusinessObjectBase;
import com.jmb.springfactory.model.dto.ProductionScheduleDto;
import com.jmb.springfactory.model.entity.ProductionSchedule;
import com.jmb.springfactory.service.GenericServiceImpl;

@Service
public class ProductionScheduleServiceImpl extends GenericServiceImpl<ProductionSchedule, ProductionScheduleDto,
  BusinessObjectBase, Integer> implements ProductionScheduleService {

  @Autowired
  private ProductionScheduleMySQLService productionScheduleMySQLService;

  @Override
  public GenericMySQLService<ProductionSchedule, Integer> genericDao() {
    return productionScheduleMySQLService;
  }

  @Override
  public Class<? extends ProductionSchedule> getClazz() {
    return ProductionSchedule.class;
  }

  @Override
  public Class<? extends ProductionScheduleDto> getDtoClazz() {
    return ProductionScheduleDto.class;
  }

  @Override
  public Class<? extends BusinessObjectBase> getBoClazz() {
    return BusinessObjectBase.class;
  }

}

package com.jmb.springfactory.service.productionschedule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jmb.springfactory.dao.GenericMySQLService;
import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
import com.jmb.springfactory.exceptions.ServiceLayerException;
import com.jmb.springfactory.model.bo.BusinessObjectBase;
import com.jmb.springfactory.model.dto.ProductionScheduleDto;
import com.jmb.springfactory.model.entity.ProductionSchedule;
import com.jmb.springfactory.model.enumeration.ProductionScheduleStateEnum;
import com.jmb.springfactory.service.GenericServiceImpl;

@Service
public class ProductionScheduleServiceImpl extends GenericServiceImpl<ProductionSchedule, ProductionScheduleDto,
  BusinessObjectBase, Integer> implements ProductionScheduleService {

  @Autowired
  private ProductionScheduleMySQLService productionScheduleMySQLService;

  @Override
  public GenericMySQLService<ProductionSchedule, Integer> genericDao() {
    return productionScheduleMySQLService;
  }

  @Override
  public Class<? extends ProductionSchedule> getClazz() {
    return ProductionSchedule.class;
  }

  @Override
  public Class<? extends ProductionScheduleDto> getDtoClazz() {
    return ProductionScheduleDto.class;
  }

  @Override
  public Class<? extends BusinessObjectBase> getBoClazz() {
    return BusinessObjectBase.class;
  }

  @Override
  public ProductionScheduleDto save(ProductionScheduleDto schedule) throws ServiceLayerException {
    schedule.setState(ProductionScheduleStateEnum.OPEN.name());
    return super.save(schedule);
  }

}

Set schedule status as OPEN when it is created


package com.github.valfirst.jbehave.junit.monitoring;

import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

/**
 * Class IgnoredTestsTest.
 *
 * The purpose of this class is to see how an IDE behaves when there is a unit test that passes and a test is ignored.
 *
 * The result in IntelliJ 2017.2.5 Community Edition is that there are two lines of info reported about test outcomes:
 * (OK) IgnoredTestsTest
 *      (OK) shouldPass
 *
 * This implies to me that the jbehave-junit-runner should behave similarly that even if there are stories/scenarios
 * that are ignored (via meta tag filtering) then the highest level node should show (OK) and not (Pending).
 */
public class IgnoredTestsTest {

	@Test
	public void shouldPass() {
		// Nothing to do. Wish this test to pass.
		assertTrue(true);
	}

	@Ignore
	public void shouldBeIgnored() {
		// Nothing to do. Wish this test to be ignored.
		assertTrue(false);
	}
}

package com.github.valfirst.jbehave.junit.monitoring;

import org.junit.Ignore;
import org.junit.Test;

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

/**
 * Class IgnoredTestsTest.
 *
 * The purpose of this class is to see how an IDE behaves when there is a unit test that passes and a test is ignored.
 *
 * The result in IntelliJ 2017.2.5 Community Edition is that there are two lines of info reported about test outcomes:
 * (OK) IgnoredTestsTest
 *      (OK) shouldPass
 *
 * This implies to me that the jbehave-junit-runner should behave similarly that even if there are stories/scenarios
 * that are ignored (via meta tag filtering) then the highest level node should show (OK) and not (Pending).
 */
public class IgnoredTestsTest {

	@Test
	public void shouldPass() {
		// Nothing to do. Wish this test to pass.
		assertTrue(true);
	}

	@Ignore
	public void shouldBeIgnored() {
		// Nothing to do. Wish this test to be ignored.
		fail();
	}
}

Use Assert.fail instead of Assert.assertTrue(false)


package com.fincatto.documentofiscal.nfe400.classes;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

import com.fincatto.documentofiscal.DFBase;

@Root(name = "protNFe")
public class NFProtocolo extends DFBase {
    private static final long serialVersionUID = -784305871769382618L;

    @Attribute(name = "versao", required = true)
    private String versao;

    @Element(name = "infProt", required = true)
    private NFProtocoloInfo protocoloInfo;

    public void setVersao(final String versao) {
        this.versao = versao;
    }

    public void setProtocoloInfo(final NFProtocoloInfo protocoloInfo) {
        this.protocoloInfo = protocoloInfo;
    }

    public NFProtocoloInfo getProtocoloInfo() {
        return this.protocoloInfo;
    }

    public String getVersao() {
        return this.versao;
    }
}

package com.fincatto.documentofiscal.nfe400.classes;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

import com.fincatto.documentofiscal.DFBase;

@Root(name = "protNFe")
public class NFProtocolo extends DFBase {
    private static final long serialVersionUID = -784305871769382618L;

    @Attribute(name = "versao", required = false)
    private String versao;

    @Element(name = "infProt", required = true)
    private NFProtocoloInfo protocoloInfo;

    public void setVersao(final String versao) {
        this.versao = versao;
    }

    public void setProtocoloInfo(final NFProtocoloInfo protocoloInfo) {
        this.protocoloInfo = protocoloInfo;
    }

    public NFProtocoloInfo getProtocoloInfo() {
        return this.protocoloInfo;
    }

    public String getVersao() {
        return this.versao;
    }
}

Remove obrigatoriedade da versão para retorno da SEFAZ MG


import parse.GreetParser;

public class App {
  public String getGreeting() {
    return "Hello world.";
  }

  /**
   * Main entry point to G2Tutorial.
   *
   * @param  args commandline arguments
   */
  public static void main(String[] args) {
    if (args.length > 0 && args[0].equals("greet")) {
      GreetParser p = new GreetParser(args);
      p.parse();
    } else {
      System.out.println("Available commands:\n\tgreet");
      System.exit(1);
    }
  }
}

import backend.Core;
import java.io.IOException;
import parse.GreetParser;

public class App {
  public String getGreeting() {
    return "Hello world.";
  }

  /**
   * Main entry point to G2Tutorial.
   *
   * @param  args commandline arguments
   */
  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Available commands:\n\tgreet");
      System.exit(1);
    }

    if (args[0].equals("greet")) {
      // Greet just exists as a template for parsing
      GreetParser p = new GreetParser(args);
      p.parse();
    } else if (args[0].equals("init")) {
      // Initializes an empty git repo
      try {
        Core.initCore();
      } catch (IOException e) {
        System.err.println("Could not init g2t");
        e.printStackTrace();
      }
      System.exit(0);
    } else {
      System.out.println("Available commands:\n"
          + "\tgreet, init");
      System.exit(1);
    }
  }
}

Add init as a command

Add init as a command

resolves #5


/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
package com.facebook.react.fabric;

// This is a wrapper for the ReactNativeConfig object in C++
public interface ReactNativeConfig {
  boolean getBool(String param);
  int getInt64(String param);
  String getString(String param);
  double getDouble(String param);
}

/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
package com.facebook.react.fabric;

// This is a wrapper for the ReactNativeConfig object in C++
public interface ReactNativeConfig {
  /**
   * Get a boolean param by string name. Default should be false.
   *
   * @param param The string name of the parameter being requested.
   */
  boolean getBool(String param);

  /**
   * Get an integer param by string name. Default should be 0.
   *
   * @param param The string name of the parameter being requested.
   */
  int getInt64(String param);

  /**
   * Get a string param by string name. Default should be "", empty string.
   *
   * @param param The string name of the parameter being requested.
   */
  String getString(String param);

  /**
   * Get a double param by string name. Default should be 0.
   *
   * @param param The string name of the parameter being requested.
   */
  double getDouble(String param);
}

Enable support for using new MobileConfigNativeModule in RN Core/Fabric C++

Summary: Enable support for using new MobileConfigNativeModule in RN Core/Fabric C++. Hack will be removed as part of T40273916 once MobileConfigNativeModule has rolled out to 100% of users and FbReactMobileConfigModule has been removed.

Reviewed By: mdvacca

Differential Revision: D14015962

fbshipit-source-id: 1b8ff0fb447040393a25fd03d9fb868877228ecc