/****************************************************************
 * 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.james.transport.matchers;

import javax.mail.MessagingException;

import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.apache.mailet.Matcher;

/**
 * Matcher which can be used to set a quota for users Mailbox. This {@link Matcher} need to
 * recalculate the used space of users mailbox on every call. So use it with caution!
 *
 *
 */
public class MailboxQuotaFixed extends AbstractStorageQuota {

    /*
     * (non-Javadoc)
     * @see org.apache.james.transport.matchers.AbstractQuotaMatcher#getQuota(org.apache.mailet.MailAddress, org.apache.mailet.Mail)
     */
    protected long getQuota(MailAddress arg0, Mail arg1) throws MessagingException {
        return parseQuota(this.getCondition());
    }

}

Add concrete implementation for MailboxQuota matching. Thanks Barry. See JAMES-1196

git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@1071533 13f79535-47bb-0310-9956-ffa450edef68


package org.usfirst.frc.team3335.robot.commands;

import edu.wpi.first.wpilibj.command.CommandGroup;

public class GateUpFlapperDown extends CommandGroup {

	public GateUpFlapperDown() {
		addSequential(new GateControl(true));
		addSequential(new FlapperControl(true));
	}

}

Add gate up / flapper down command group.


package de.retest.recheck.printer;

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

import org.junit.jupiter.api.Test;

import de.retest.recheck.report.SuiteReplayResult;
import de.retest.recheck.report.TestReplayResult;

class SuiteReplayResultTest {

	@Test
	void isEmpty_should_return_true_if_no_differences() throws Exception {
		final TestReplayResult test = mock( TestReplayResult.class );
		when( test.isEmpty() ).thenReturn( true );

		final SuiteReplayResult cut = new SuiteReplayResult( "foo", 0, null, null, null );
		cut.addTest( test );

		assertThat( cut.isEmpty() ).isTrue();
	}

	@Test
	void isEmpty_should_return_false_if_differences() throws Exception {
		final TestReplayResult test = mock( TestReplayResult.class );
		when( test.isEmpty() ).thenReturn( false );

		final SuiteReplayResult cut = new SuiteReplayResult( "foo", 0, null, null, null );
		cut.addTest( test );

		assertThat( cut.isEmpty() ).isFalse();
	}
}

Add test for wrong behavior

Add test for wrong behavior


/*
 * Copyright 2015 The Mashub Project
 *
 * The Mashub Project 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 com.beatsbucket.mashub.kitchen;

public interface History {
}

Add history interface to store histories of recipe and scheduling info.


package util;

import bot.Bender.BotMove;
import bot.Bender.DirectionType;

/**
 * Created by Daniel Hofmeister on 21.11.2015.
 */
public class BotmoveDirectionConverter {

    public static DirectionType getDirectionTypeFromBotMove(BotMove move) {
        DirectionType result = null;
        if (move.equals(BotMove.EAST)) {
            result = DirectionType.EAST;
        } else if (move.equals(BotMove.SOUTH)) {
            result = DirectionType.SOUTH;
        } else if (move.equals(BotMove.WEST)) {
            result = DirectionType.WEST;
        } else if (move.equals(BotMove.NORTH)) {
            result = DirectionType.NORTH;
        } else {
            throw new IllegalArgumentException("no such BotMove");
        }
        return result;
    }

    public static BotMove getBotMoveFromDirectionType(DirectionType dir) {
        BotMove result = null;

        if(dir.equals(DirectionType.EAST)) {
            result = BotMove.EAST;
        } else if(dir.equals(DirectionType.SOUTH)) {
            result = BotMove.SOUTH;
        } else if(dir.equals(DirectionType.WEST)) {
            result = BotMove.WEST;
        } else if(dir.equals(DirectionType.NORTH)) {
            result = BotMove.NORTH;
        } else {
            throw new IllegalArgumentException("no such DirectionType");
        }
        return result;
    }
}

Add util class with botmove/dir converter


//
// ScriptEditor.java
//

/*
ImageJ software for multidimensional image processing and analysis.

Copyright (c) 2010, ImageJDev.org.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
 * Neither the names of the ImageJDev.org developers nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package imagej.script.editor;

import imagej.command.Command;
import imagej.command.CommandService;
import imagej.io.IOService;
import imagej.platform.PlatformService;
import imagej.plugin.Menu;
import imagej.plugin.Parameter;
import imagej.plugin.Plugin;
import imagej.script.ScriptService;

/**
 * The Script Editor. As plugin.
 *
 * @author Johannes Schindelin
 */
@Plugin(menu = { @Menu(label = "File"), @Menu(label = "New"),
	@Menu(label = "Script...", accelerator = "open_bracket") })
public class ScriptEditor implements Command {

	@Parameter
	private ScriptService scriptService;

	@Parameter
	private PlatformService platformService;

	@Parameter
	private IOService ioService;

	@Parameter
	private CommandService commandService;

	@Override
	public void run() {
		new TextEditor(scriptService, platformService, ioService, commandService).setVisible(true);
	}

}

Make the Script Editor a proper plugin

Make the Script Editor a proper plugin

Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>


package yuku.alkitabconverter.daily_verse;

import yuku.alkitab.yes2.io.RandomOutputStream;
import yuku.bintex.BintexWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DailyVerseProses {

	private static final String INPUT_FILE = System.getProperty("user.dir") + "/AlkitabConverter/file/daily_verse.csv";
	private static final String OUTPUT_FILE = System.getProperty("user.dir") + "/AlkitabConverter/file/daily_verse.bt";
	private List<Integer> aris = new ArrayList<>();
	private List<Integer> verseCounts = new ArrayList<>();

	public static void main(String[] args) {
		DailyVerseProses proses = new DailyVerseProses();
		proses.parse();
		try {
			File file = new File(OUTPUT_FILE);
			RandomAccessFile raf = new RandomAccessFile(file, "rw");
			raf.setLength(0);
			RandomOutputStream output = new RandomOutputStream(raf);
			BintexWriter bw = new BintexWriter(output);
			proses.write(bw);
			bw.close();

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

		System.out.println("Process finished.");

	}
	private void parse() {
		try {
			Scanner scanner = new Scanner(new File(INPUT_FILE), "utf-8");

			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
				String[] data = line.split(",");
				aris.add(Integer.parseInt(data[0]));
				verseCounts.add(Integer.parseInt(data[1]));
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}

	private void write(BintexWriter bw) {
		if (aris.size() == verseCounts.size()) {
			for (int i = 0; i < aris.size(); i++) {
				try {
					bw.writeInt(aris.get(i));
					bw.writeUint8(verseCounts.get(i));
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
	}

}

Add Daily verses writer (to bintex format).


package org.mapdb;

import org.junit.Test;

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public class HTreeMap_Expiration_Multithreaded {

    final long duration = 10 * 60 * 1000;

    static byte[] b = new byte[100];

    @Test public void expireUUID(){
        if(TT.shortTest())
            return;

        final long endTime = duration+System.currentTimeMillis();

        DB db = DBMaker.memoryDB().cacheSize(10000).make();
        final Map m = db.hashMapCreate("aa")
                .keySerializer(Serializer.UUID)
                .valueSerializer(Serializer.BYTE_ARRAY)
                .expireAfterWrite(1, TimeUnit.MINUTES)
                .expireTick(0)
                .make();

        Exec.execNTimes(10, new Callable() {
            @Override
            public Object call() throws Exception {
                try {
                    Random r = new Random(1);
                    for (int i = 0; i < 2e5; i++) {
                        UUID u = new UUID(r.nextLong(), r.nextLong());
                        m.put(u, b);
                    }

                    while (System.currentTimeMillis()<endTime) {
                        r = new Random(1);
                        for (int i = 0; i < 1e5; i++) {
                            UUID u = new UUID(r.nextLong(), r.nextLong());
                            m.get(u);
                            m.put(u,b);
                        }
                        for (int i = (int) 1e5; i < 2e5; i++) {
                            UUID u = new UUID(r.nextLong(), r.nextLong());
                            m.get(u);
                        }
                    }
                }catch(Throwable e){
                    e.printStackTrace();
                }
                return null;
            }
        });
    }
}

Add test for multithreaded expiration

Add test for multithreaded expiration


/*
 * 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.yuanheng.cookjson;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;

import javax.json.spi.JsonProvider;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonParser;

import org.junit.Assert;
import org.junit.Test;

/**
 * @author	Heng Yuan
 */
public class BsonParserTest
{
	void testFile (String f1, String f2) throws IOException
	{
		File file1 = new File (f1.replace ('/', File.separatorChar));
		File file2 = new File (f2.replace ('/', File.separatorChar));

		StringWriter out1 = new StringWriter ();
		JsonParser p1 = new BsonParser (new FileInputStream (file1));
		TextJsonGenerator g1 = new TextJsonGenerator (out1);
		Utils.convert (p1, g1);
		p1.close ();
		g1.close ();

		StringWriter out2 = new StringWriter ();
		JsonProvider provider = new org.glassfish.json.JsonProviderImpl ();
		JsonParser p2 = provider.createParser (new FileInputStream (file2));
		JsonGenerator g2 = new TextJsonGenerator (out2);
		Utils.convert (p2, g2);
		p2.close ();
		g2.close ();

		Assert.assertEquals (out1.toString (), out2.toString ());
	}

	@Test
	public void test () throws IOException
	{
		// data1.bson has 0 in Document / Array length
		testFile ("../tests/data/data1.bson", "../tests/data/data3.json");
		// data2.bson has the correct length
		testFile ("../tests/data/data2.bson", "../tests/data/data3.json");
	}
}

Add a simple BSON unit test.

Add a simple BSON unit test.


// Copyright (C) 2013 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 com.google.gwtexpui.safehtml.client;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;

public class SafeHtml_WikifyQuoteTest {
  private static final String B = "
";
  private static final String E = "
";

  private static String quote(String raw) {
    return B + raw + E;
  }

  @Test
  public void testQuote1() {
    final SafeHtml o = html("> I'm happy\n > with quotes!\n\nSee above.");
    final SafeHtml n = o.wikify();
    assertNotSame(o, n);
    assertEquals(
        quote("I'm happy\nwith quotes!")
        + "
See above.
",
      n.asString());
  }

  @Test
  public void testQuote2() {
    final SafeHtml o = html("See this said:\n\n > a quoted\n > string block\n\nOK?");
    final SafeHtml n = o.wikify();
    assertNotSame(o, n);
    assertEquals(
        "
See this said:
"
        + quote("a quoted\nstring block")
        + "
OK?
",
      n.asString());
  }

  @Test
  public void testNestedQuotes1() {
    final SafeHtml o = html(" > > prior\n > \n > next\n");
    final SafeHtml n = o.wikify();
    assertEquals(
      quote(quote("prior") + "next\n"),
      n.asString());
  }

  private static SafeHtml html(String text) {
    return new SafeHtmlBuilder().append(text).toSafeHtml();
  }
}

Add test for reply quoting in wikify()

Add test for reply quoting in wikify()

Change-Id: I273948bb67aa8069f4cbafea441ca27e8f70779f


/* Hidden stub code will pass a root argument to the function below. Complete the function to solve the challenge. Hint: you may want to write one or more helper functions.

The Node class is defined as follows:*/

/**
 * Hackerrank: Trees: Is This a Binary Search Tree?
 *
 * @see Trees: Is This a Binary Search Tree?
 */
class Node {
    int data;
    Node left;
    Node right;

    /**
     * Check whether the current binary tree is a binary search tree
     *
     * @param root Root node of the binary tree
     * @return true if it is a binary search tree and false otherwise
     */
    boolean checkBST(Node root) {
        if (root == null) {
            return true;
        }
        if ((root.left != null) && (root.left.data >= root.data)) {
            return false;
        }
        if ((root.right != null) && (root.right.data <= root.data)) {
            return false;
        }
        return checkBST(root.right) && checkBST(root.left) && checkLeft(root.data, root.left) && checkRight(root.data, root.right);
    }

    /**
     * Checking the left subtree if there are no values greater than the root value max
     *
     * @param max  value of the root of the current subtree
     * @param node current node
     * @return true if the values in the subtree are smaller than the max value and false otherwise
     */
    boolean checkLeft(int max, Node node) {
        if (node == null) {
            return true;
        }
        if (node.data < max) {
            return checkLeft(max, node.left) && checkLeft(max, node.right);
        } else {
            return false;
        }
    }

    /**
     * Checking the right subtree if there are no values smaller than the root value min
     *
     * @param min  value of the root of the current subtree
     * @param node current node
     * @return true if the values in the subtree are greater than the min value and false otherwise
     */
    boolean checkRight(int min, Node node) {
        if (node == null) {
            return true;
        }
        if (node.data > min) {
            return checkRight(min, node.left) && checkRight(min, node.right);
        } else {
            return false;
        }
    }

}

Check binary tree whether it is a binary search tree


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

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

public interface IPackageManager {

	public abstract CommandResponse install();

	public abstract CommandResponse uninstall();

	public abstract String latest();

	public abstract void setPackageProperties(PackageProperties properties);

	public abstract PackageProperties getPackageProperties();
}

Create interface to package manager implementations.


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

package org.graylog2.gelfclient.transport;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.graylog2.gelfclient.Configuration;
import org.graylog2.gelfclient.GelfMessage;
import org.graylog2.gelfclient.GelfMessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Bernd Ahlers <bernd@torch.sh>
 */
public class GelfTcpTransport implements GelfTransport {
    private final Logger LOG = LoggerFactory.getLogger(GelfTcpTransport.class);
    private final Configuration config;
    private final GelfMessageEncoder encoder;

    private final EventLoopGroup workerGroup;
    private final Bootstrap bootstrap;
    private final GelfTcpChannelHandler handler;
    private final ChannelFuture channelFuture;

    public GelfTcpTransport(Configuration config, GelfMessageEncoder encoder) {
        this.config = config;
        this.encoder = encoder;

        this.workerGroup = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        this.handler = new GelfTcpChannelHandler(config, encoder);

        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .remoteAddress(config.getHost(), config.getPort())
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(handler);
                    }
                });

        this.channelFuture = bootstrap.connect();

        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    LOG.debug("Connected!");
                } else {
                    LOG.error("Connection failed", future.cause());
                    future.cause().printStackTrace();
                }
            }
        });
    }

    @Override
    public void send(GelfMessage message) {
        handler.send(message);
    }

    @Override
    public void stop() {
        handler.stop();
        workerGroup.shutdownGracefully();
    }

    @Override
    public void sync() throws InterruptedException {
        channelFuture.sync();
    }
}

Add GELF TCP transport class.

Add GELF TCP transport class.


package de.fau.amos.virtualledger.android.dagger.module;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import de.fau.amos.virtualledger.android.api.savings.SavingsProvider;
import de.fau.amos.virtualledger.android.data.SavingsAccountsDataManager;

@Module(includes = {SavingsModule.class})
public class SavingsAccountsDataModule {

    @Provides
    @Singleton
    SavingsAccountsDataManager provideBankingDataManager(final SavingsProvider savingsProvider) {
        return new SavingsAccountsDataManager(savingsProvider);
    }
}

Add dagger module for SavingsAccountsDataManager


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

package com.google.android.gnd.workers;

import androidx.lifecycle.LiveData;
import androidx.work.Constraints;
import androidx.work.ExistingWorkPolicy;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

/** Enqueues file download work to be done in the background. */
public class FileDownloadWorkManager {
  private final WorkManager workManager;

  public FileDownloadWorkManager() {
    this.workManager = WorkManager.getInstance();
  }

  /**
   * Enqueues a worker that downloads files when a network connection is available, returning live
   * data that contains {@link WorkInfo}. Observe the returned live data to do something with the
   * worker's result.
   */
  public LiveData<WorkInfo> enqueueFileDownloadWorker(String url, String filename) {
    return getWorkManager()
        .getWorkInfoByIdLiveData(enqueueFileDownloadWorkerInternal(url, filename).getId());
  }

  private OneTimeWorkRequest enqueueFileDownloadWorkerInternal(String url, String filename) {
    OneTimeWorkRequest request = buildWorkerRequest(url, filename);

    getWorkManager()
        .enqueueUniqueWork(FileDownloadWorker.class.getName(), ExistingWorkPolicy.APPEND, request);

    // Return the request in order to fetch the {@link WorkInfo} for the request using the request id.
    return request;
  }

  private WorkManager getWorkManager() {
    return workManager;
  }

  private Constraints getWorkerConstraints() {
    return new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
  }

  private OneTimeWorkRequest buildWorkerRequest(String url, String filename) {
    return new OneTimeWorkRequest.Builder(FileDownloadWorker.class)
        .setConstraints(getWorkerConstraints())
        .setInputData(FileDownloadWorker.createInputData(url, filename))
        .build();
  }
}

Add file download work manager

Offline-Imagery: Add file download work manager

This change introduces a work manager for file download workers. This
manager is primarily a lightweight wrapper around WorkManager that makes
it easier to make FileDownloadWorker requests and ensures requests to
the FileDownloadWorker meet certain constraints.


public class Solution {

    public boolean judgeSquareSum(int c) {

        int low = 0;
        int high = (int) Math.sqrt(c);

        while (low <= high) {

            int sum = low * low + high * high;

            if (sum == c) {
                return true;
            }

            if (sum < c) {
                low++;
            } else if (sum > c) {
                high--;
            }

        }

        return false;

    }

}

Create : 633 Sum of Square Numbers

Create : 633 Sum of Square Numbers


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String args[]) throws IOException {
        InputStreamReader ir = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(ir);

        String a;
        float b, c;

        a = in.readLine();
        b = Float.parseFloat(in.readLine());
        c = Float.parseFloat(in.readLine());

        System.out.printf("TOTAL = R$ %.2f\n", b + (c * 0.15));
    }
}

Solve Salary with Bonus in java

Solve Salary with Bonus in java


package org.cyclops.cyclopscore.helper;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Helper methods for collections.
 * @author rubensworks
 */
public final class CollectionHelpers {

    /**
     * Add the given key value pair in a map structure where multiple values for a key can exist.
     * This will take care of making a new list into the map when one did not exist before.
     * @param map The map.
     * @param key The key.
     * @param value The value.
     * @param <K> The key type.
     * @param <V> The value type.
     */
    public static <K, V> void addToMapList(Map<K, List<V>> map, K key, V value) {
        if(!map.containsKey(key)) {
            map.put(key, Lists.<V>newLinkedList());
        }
        map.get(key).add(value);
    }

    /**
     * Add the given key value pair in a map structure where multiple values for a key can exist.
     * This will take care of making a new set into the map when one did not exist before.
     * @param map The map.
     * @param key The key.
     * @param value The value.
     * @param <K> The key type.
     * @param <V> The value type.
     */
    public static <K, V> void addToMapSet(Map<K, Set<V>> map, K key, V value) {
        if(!map.containsKey(key)) {
            map.put(key, Sets.<V>newHashSet());
        }
        map.get(key).add(value);
    }

}

Add collection helper methods Adds convenience methods for insertion into Map<?, List<?>> and Map<?, Set<?>>.


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem22;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseLinkedListTest {
}

/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem22;

import com.github.pedrovgs.linkedlist.ListNode;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseLinkedListTest {

  private ReverseLinkedList reverseLinkedList;

  @Before public void setUp() {
    reverseLinkedList = new ReverseLinkedList();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullElements() {
    reverseLinkedList.reverse(null);
  }

  @Test public void shouldAcceptLinkedListWithJustOneElement() {
    ListNode<Integer> head = new ListNode<Integer>(1);

    assertEquals(head, reverseLinkedList.reverse(head));
  }

  @Test public void shouldReverseLinkedList() {
    ListNode<Integer> head = new ListNode<Integer>(1);
    ListNode<Integer> n2 = new ListNode<Integer>(2);
    ListNode<Integer> n3 = new ListNode<Integer>(3);
    ListNode<Integer> n4 = new ListNode<Integer>(4);
    head.setNext(n2);
    n2.setNext(n3);

    ListNode reversedList = reverseLinkedList.reverse(head);

    assertEquals(n4, reversedList);
  }
}

Add some tests to problem 22

Add some tests to problem 22


package parser.model;

import java.util.ArrayList;

public class FindBubbles {

	private Graph graph;

	public FindBubbles(Graph graph) {
		this.graph = graph;
	}

	public void calculateFlows() {
		sendFlow();
	}

	private void sendFlow() {
		double flowStart = (double)graph.getSize();
		graph.getRoot().setFlow(flowStart);

		for (Node node : graph.getNodes()) {
			System.out.println(node);
			ArrayList<Edge> outEdges = node.getOut();
			double remainingFlow = node.getFlow();

			for (int i = 0; i < outEdges.size(); i++) {
				Node target = outEdges.get(i).getTarget();

				if (i == node.getOut().size() - 1) {
					target.addFlow(remainingFlow);
				} else {
					double random = Math.random();
					double flowToAdd = random * remainingFlow;
					remainingFlow -= flowToAdd;
					target.addFlow(flowToAdd);
				}
			}
		}
	}
}

Send flow through graph to easily detect what bubbles there are


package com.easternedgerobotics.rov.io;

import com.easternedgerobotics.rov.event.EventPublisher;
import com.easternedgerobotics.rov.value.ThrusterValue;

import java.io.IOException;
import java.nio.ByteBuffer;

public class Thruster {

    private static final int BYTE_SIZE = 8;

    private static final byte WRITE_ADDRESS = 0x00;

    private static final byte READ_ADDRESS = 0x02;

    private static final int READ_BUFFER_SIZE = 9;

    private static final int VOLTAGE_INDEX = 0;

    private static final int CURRENT_INDEX = 2;

    private static final float CURRENT_SCALAR = 5.0f * 6.45f / 65536.0f;

    private static final int TEMPERATURE_INDEX = 6;

    private static final float TEMPERATURE_OFFSET = 32767;

    private static final float TEMPERATURE_SCALAR =  5.0f * 14.706f / 65535.0f;

    private final byte[] zeroBuffer = new byte[] {0x00, 0x00};

    private Device device;

    private ThrusterValue thrusterValue;

    private EventPublisher eventPublisher;

    public Thruster(final EventPublisher event, final ThrusterValue thruster, final Device dev) {

        device = dev;

        eventPublisher = event;

        thrusterValue = thruster;

        eventPublisher.valuesOfType(ThrusterValue.class).subscribe(t -> {
            if (thrusterValue.getName().equals(t.getName())) {
                thrusterValue = t;
            }
        });
    }

    public final void write() throws IOException {
        final short speed = (short) (thrusterValue.getSpeed() * Short.MAX_VALUE);
        final byte[] writeBuffer = ByteBuffer.allocate(2).putShort(speed).array();
        device.write(WRITE_ADDRESS, zeroBuffer);
        device.write(WRITE_ADDRESS, writeBuffer);
    }

    public final void writeZero() throws IOException {
        device.write(WRITE_ADDRESS, zeroBuffer);
    }

    public final void read() throws IOException {
        final byte[] readBuffer = device.read(READ_ADDRESS, READ_BUFFER_SIZE);

        final float voltage = parseShort(readBuffer, VOLTAGE_INDEX);
        final float current = parseShort(readBuffer, CURRENT_INDEX) * CURRENT_SCALAR;
        final float temperature = (parseShort(readBuffer, TEMPERATURE_INDEX) - TEMPERATURE_OFFSET) * TEMPERATURE_SCALAR;

        eventPublisher.emit(ThrusterValue.create(
            thrusterValue.getName(),
            thrusterValue.getSpeed(),
            voltage,
            current,
            temperature
        ));
    }

    // reads a short from two consecutive bytes.
    // MSB located at offset.
    // LSB located at offset + 1.
    private short parseShort(final byte[] bytes, final int offset) {
        return (short) (((bytes[offset]) << BYTE_SIZE) | bytes[offset + 1]);
    }
}

Send speed commands and read status of a thruster


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

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class SupplierDeserializer implements JsonDeserializer<Supplier<?>> {

  @Override
  public Supplier<?> deserialize(JsonElement json, Type typeOfT,
      JsonDeserializationContext context) throws JsonParseException {
    checkArgument(typeOfT instanceof ParameterizedType);
    ParameterizedType parameterizedType = (ParameterizedType) typeOfT;
    if (parameterizedType.getActualTypeArguments().length != 1) {
      throw new JsonParseException(
          "Expected one parameter type in Supplier interface.");
    }
    Type supplierOf = parameterizedType.getActualTypeArguments()[0];
    return Suppliers.ofInstance(context.deserialize(json, supplierOf));
  }
}

Add custom JSON deserializer for Supplier

This deserializer is useful for plugins to deserialize Events wrapped in
the Supplier interface.

Deserialization using EventDeserializer was broken by change 73527 [1].

[1] https://gerrit-review.googlesource.com/73527

Change-Id: Ia681fafe25054fca6ce98f9a5c93592697c162fa
Signed-off-by: Dariusz Luksza <d9c42035ad9447bda4101be2f02a7db3fa874023@luksza.org>


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

package io.spine.validate;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.List;

import static com.google.common.truth.Truth.assertThat;
import static java.util.stream.Collectors.toList;

@DisplayName("ValidatorFactoryLoader should")
class ValidatorFactoryLoaderTest {

    @Test
    @DisplayName("load common options")
    void loadCommon() {
        List<ValidatorFactory> implementations = ValidatorFactoryLoader.INSTANCE
                .implementations()
                .collect(toList());
        assertThat(implementations).hasSize(1);
        assertThat(implementations.get(0)).isInstanceOf(CommonValidatorFactory.class);
    }
}

Add a test for service loading.

Add a test for service loading.


package com.kevlindev.tvm.display;

public class FontInfo {
	public String name;
	public int columns;
	public int rows;
	public int defaultScale;
	public int offset;

	public FontInfo(String name, int columns, int rows) {
		this(name, columns, rows, 1, 0);
	}

	public FontInfo(String name, int columns, int rows, int defaultScale) {
		this(name, columns, rows, defaultScale, 0);
	}

	public FontInfo(String name, int columns, int rows, int defaultScale, int offset) {
		this.name = name;
		this.columns = columns;
		this.rows = rows;
		this.defaultScale = defaultScale;
		this.offset = offset;
	}
}

Create a custom class to contain info about each needed. This info is used to decompose the tiles and to account for any offsets that need to be applied to get the right tile for a given ascii code.


/*
 * Copyright 2018 Red Hat, Inc. and/or its affiliates.
 *
 * 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.jboss.perspicuus.rest;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class CatalogApplication extends Application {

    public CatalogApplication() {
    }
}

Add jax-rs app file, as newer versions of swarm will no longer infer it.


package de.retest.recheck.ui.diff;

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

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;

import org.junit.Before;
import org.junit.Test;

import de.retest.recheck.image.ImageDifference;
import de.retest.recheck.image.ImageDifferenceCalculator;
import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.descriptors.IdentifyingAttributes;
import de.retest.recheck.ui.descriptors.RootElement;
import de.retest.recheck.ui.descriptors.ScreenshotAttributeDifference;
import de.retest.recheck.ui.image.Screenshot;

public class RootElementDifferenceTest {

	RootElementDifference cut;

	@Before
	public void setup() {
		final Screenshot expected = mock( Screenshot.class );
		final Screenshot actual = mock( Screenshot.class );
		final AttributeDifference screenshotDiff = new ScreenshotAttributeDifference( expected, actual,
				TestImageDifferenceCalculator.class.getName(), 0.99 );
		final AttributesDifference attributesDiff =
				new AttributesDifference( Collections.singletonList( screenshotDiff ) );
		final Element eleme = mock( Element.class );
		when( eleme.getIdentifyingAttributes() ).thenReturn( mock( IdentifyingAttributes.class ) );
		final ElementDifference elementDifference = new ElementDifference( eleme, attributesDiff,
				mock( IdentifyingAttributesDifference.class ), expected, actual, new ArrayList<>() );
		cut = new RootElementDifference( elementDifference, mock( RootElement.class ), mock( RootElement.class ) );
	}

	@Test
	public void getScreenshotDifference_should_find_difference() {
		assertThat( cut.getScreenshotDifference() ).isNotNull();
	}

	@Test
	public void getExpectedScreenshot_should_recalc_diff() throws Exception {
		// image2Screenshot will return null instead of mocked screenshot.
		assertThat( cut.getExpectedScreenshot() ).isNull();
	}

	static class TestImageDifferenceCalculator implements ImageDifferenceCalculator {

		@Override
		public ImageDifference compare( final BufferedImage img1, final BufferedImage img2 ) {
			return mock( ImageDifference.class );
		}

		@Override
		public ImageDifference compare( final Screenshot expected, final Screenshot actual ) {
			return mock( ImageDifference.class );
		}

	}

}

Move tests for RootElementDifference from review


/*
 * Copyright 2017, 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.google.instrumentation.internal;

import com.google.instrumentation.common.Clock;
import com.google.instrumentation.common.Timestamp;

/**
 * A {@link Clock} that uses {@link System#currentTimeMillis()} and {@link System#nanoTime()}.
 */
public final class MillisClock extends Clock {
  private static final MillisClock INSTANCE = new MillisClock();

  private MillisClock() {}

  /**
   * Returns a {@code MillisClock}.
   *
   * @return a {@code MillisClock}.
   */
  public static MillisClock getInstance() {
    return INSTANCE;
  }

  @Override
  public Timestamp now() {
    return Timestamp.fromMillis(System.currentTimeMillis());
  }

  @Override
  public long nowNanos() {
    return System.nanoTime();
  }
}

Add a clock that uses System.currentTimeMillis() and System.nanoTime().


package com.proofpoint.http.client.testing;

import com.google.common.base.Function;
import com.proofpoint.http.client.AsyncHttpClient.AsyncHttpResponseFuture;
import com.proofpoint.http.client.Request;
import com.proofpoint.http.client.Response;
import com.proofpoint.http.client.ResponseHandler;
import org.testng.annotations.Test;

import java.net.URI;

import static com.proofpoint.http.client.Request.Builder.prepareGet;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.fail;

public class TestTestingHttpClient
{
    @Test
    public void testExceptionFromProcessor()
            throws Exception
    {
        Request request = prepareGet()
                .setUri(URI.create("http://example.org"))
                .build();

        final RuntimeException expectedException = new RuntimeException("test exception");

        AsyncHttpResponseFuture<String,CapturedException> future = new TestingHttpClient(
                new Function<Request, Response>()
                {
                    @Override
                    public Response apply(Request input)
                    {
                        throw expectedException;
                    }
                }).executeAsync(request, new CaptureExceptionResponseHandler());

        try {
            future.checkedGet();
            fail("expected exception");
        }
        catch (CapturedException e) {
            assertSame(e.getCause(), expectedException);
        }
    }

    @Test
    public void testExceptionFromProcessorWithDefaultingHandler()
            throws Exception
    {
        Request request = prepareGet()
                .setUri(URI.create("http://example.org"))
                .build();

        final RuntimeException testingException = new RuntimeException("test exception");
        final Object expectedResponse = new Object();

        AsyncHttpResponseFuture<Object,RuntimeException> future = new TestingHttpClient(
                new Function<Request, Response>()
                {
                    @Override
                    public Response apply(Request input)
                    {
                        throw testingException;
                    }
                }).executeAsync(request, new DefaultExceptionResponseHandler(testingException, expectedResponse));

        assertSame(future.checkedGet(), expectedResponse);
    }

    public static class CaptureExceptionResponseHandler implements ResponseHandler<String, CapturedException>
    {
        @Override
        public String handleException(Request request, Exception exception)
                throws CapturedException
        {
            throw new CapturedException(exception);
        }

        @Override
        public String handle(Request request, Response response)
                throws CapturedException
        {
            throw new UnsupportedOperationException();
        }

    }

    protected static class CapturedException extends Exception
    {
        public CapturedException(Exception exception)
        {
            super(exception);
        }
    }

    private class DefaultExceptionResponseHandler implements ResponseHandler<Object, RuntimeException>
    {
        private final RuntimeException expectedException;
        private final Object response;

        public DefaultExceptionResponseHandler(RuntimeException expectedException, Object response)
        {
            this.expectedException = expectedException;
            this.response = response;
        }

        @Override
        public Object handleException(Request request, Exception exception)
        {
            assertEquals(exception, expectedException);
            return response;
        }

        @Override
        public Object handle(Request request, Response response)
        {
            throw new UnsupportedOperationException();
        }
    }
}

Test exception handling behavior of TestingHttpClient


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

package com.github.smallcreep.cucumber.seeds.context;

import com.github.smallcreep.cucumber.seeds.Context;
import java.util.Properties;
import org.cactoos.map.MapEntry;
import org.cactoos.map.MapOf;

/**
 * Context from properties.
 * @since 0.1.1
 */
public final class CxProperties implements Context {

    /**
     * Origin context.
     */
    private final Context origin;

    /**
     * Ctor.
     * @param properties Properties
     */
    CxProperties(final Properties properties) {
        this(
            new CxSimple(
                new MapOf<String, Object>(
                    (name) -> new MapEntry<>(
                        name,
                        properties.getProperty(name)
                    ),
                    properties.stringPropertyNames()
                )
            )
        );
    }

    /**
     * Ctor.
     * @param origin Origin context
     */
    private CxProperties(final Context origin) {
        this.origin = origin;
    }

    @Override
    public Object value(final String key) {
        return this.origin.value(key);
    }

    @Override
    public void add(final String key, final Object value) {
        throw new UnsupportedOperationException(
            "Can not add value to properties context"
        );
    }

    @Override
    public boolean contains(final String key) {
        return this.origin.contains(key);
    }
}

Add Context which read properties file

Add Context which read properties file

#26 Start Implementation


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

@Version("1.3.1")
package org.apache.sling.commons.classloader;

import org.osgi.annotation.versioning.Version;

Update to parent pom 27

Update to parent pom 27

git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@1753903 13f79535-47bb-0310-9956-ffa450edef68


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class SelectValuesUpsidedown {
	public static void main(String[] args) throws SQLException{
		Connection con=DBInfo2.getConnection();
		String query="SELECT * FROM login";

		PreparedStatement stmt=con.prepareStatement(query);
		ResultSet rs=stmt.executeQuery();

		// getting meta data
		System.out.println("Getting Meta Data\n---------------------------------------");
		ResultSetMetaData rsmd=rs.getMetaData();
		int count=rsmd.getColumnCount();
		System.out.println("Column count : "+count);
		for(int i=1;i<=count;i++){
			System.out.println(rsmd.getColumnName(i)+":::"+rsmd.getColumnDisplaySize(i)+":::"+rsmd.getColumnTypeName(i));
		}
		System.out.println("---------------------------------------\nGetting Records Data\n---------------------------------------");

		// getting records data
		rs.afterLast();
		while(rs.previous()){
			System.out.println(rs.getInt(1)+":::"+rs.getString(2)+":::"+rs.getString(3)+":::"+rs.getString(4));
		}
		rs.close();
		con.close();
		stmt.close();
	}
}

Select querry implementation with meta data upsidedown


/*
 * 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.ode.axis2.util;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.TransactionManager;

public class JBossFactory {

    public static final String JNDI_LOOKUP_PATH = "java:/TransactionManager";

    /* Public no-arg contructor is required */
    public JBossFactory() {
    }

    public TransactionManager getTransactionManager() {
        InitialContext ctx;
        try {
           ctx = new InitialContext();
        } catch (NamingException except) {
            throw new RuntimeException( "Can't create InitialContext", except);
        }
        try {
            return (TransactionManager) ctx.lookup(JNDI_LOOKUP_PATH);
        } catch (NamingException except) {
            throw new RuntimeException( "Error while looking up TransactionManager at " + JNDI_LOOKUP_PATH, except);
        }
    }

}

Add JBoss transaction manager factory

Add JBoss transaction manager factory

git-svn-id: 8b22924fe593b58bc3cb32731943cdf19d9802ec@471928 13f79535-47bb-0310-9956-ffa450edef68


/*
 * 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.codec.digest;

import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;

public class XXHash32OverflowTest {

    /**
     * This test hits an edge case where a very large number of bytes is added to the incremental
     * hash. The data is constructed so that an integer counter of unprocessed bytes will
     * overflow. If this is not handled correctly then the code throws an exception when it
     * copies more data into the unprocessed bytes array.
     */
    @Test
    public void testIncrementalHashWithUnprocessedBytesAndHugeLengthArray() {
        // Assert the test precondition that a large array added to unprocessed bytes
        // will overflow an integer counter. We use the smallest hugeLength possible
        // as some VMs cannot allocate maximum length arrays.
        final int bufferSize = 16;
        final int unprocessedSize = bufferSize - 1;
        final int hugeLength = Integer.MAX_VALUE - (unprocessedSize - 1);
        Assert.assertTrue("This should overflow to negative", unprocessedSize + hugeLength < bufferSize);

        // Check the test can be run
        byte[] bytes = null;
        try {
            bytes = new byte[hugeLength];
        } catch (OutOfMemoryError ignore) {
            // Some VMs cannot allocate an array this large.
            // Some test environments may not have enough available memory for this.
        }
        Assume.assumeTrue("Cannot allocate array of length " + hugeLength, bytes != null);

        final XXHash32 inc = new XXHash32();
        // Add bytes that should be unprocessed
        inc.update(bytes, 0, unprocessedSize);
        // Add a huge number of bytes to overflow an integer counter of unprocessed bytes.
        inc.update(bytes, 0, hugeLength);
    }
}

Test XXHash32 with huge length array added to unprocessed bytes.


package com.amalgam.app;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.os.Build;

/**
 * @author KeithYokoma
 */
@SuppressWarnings("unused")
public final class FragmentUtils {
    private FragmentUtils() {
        throw new AssertionError();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void invalidateOptionsMenu(android.app.Fragment fragment) {
        fragment.getActivity().invalidateOptionsMenu();
    }

    public static void supportInvalidateOptionsMenu(android.support.v4.app.Fragment fragment) {
        fragment.getActivity().supportInvalidateOptionsMenu();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public static ContentResolver getContentResolver(android.app.Fragment fragment) {
        return fragment.getActivity().getContentResolver();
    }

    public static ContentResolver getContentResolver(android.support.v4.app.Fragment fragment) {
        return fragment.getActivity().getContentResolver();
    }
}

Add utility for the fragment

Add utility for the fragment

- invalidate options menu
- obtain content resolver


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

package com.digitalpetri.opcua.sdk.server.identity;

import com.digitalpetri.opcua.sdk.server.Session;
import com.digitalpetri.opcua.stack.core.UaException;
import com.digitalpetri.opcua.stack.core.channel.SecureChannel;
import com.digitalpetri.opcua.stack.core.types.structured.AnonymousIdentityToken;
import com.digitalpetri.opcua.stack.core.types.structured.UserTokenPolicy;

public class AnonymousIdentityValidator extends IdentityValidator {

    @Override
    public Object validateAnonymousToken(AnonymousIdentityToken token, UserTokenPolicy tokenPolicy,
                                         SecureChannel channel, Session session) throws UaException {
        return new Object();
    }

}

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

package com.digitalpetri.opcua.sdk.server.identity;

import com.digitalpetri.opcua.sdk.server.Session;
import com.digitalpetri.opcua.stack.core.UaException;
import com.digitalpetri.opcua.stack.core.channel.SecureChannel;
import com.digitalpetri.opcua.stack.core.types.structured.AnonymousIdentityToken;
import com.digitalpetri.opcua.stack.core.types.structured.UserTokenPolicy;

public class AnonymousIdentityValidator extends IdentityValidator {

    public static final Object ANONYMOUS_IDENTITY_OBJECT = new Object();

    @Override
    public Object validateAnonymousToken(AnonymousIdentityToken token, UserTokenPolicy tokenPolicy,
                                         SecureChannel channel, Session session) throws UaException {
        return ANONYMOUS_IDENTITY_OBJECT;
    }

}

Use a singleton object for anonymous identities


package com.haxademic.core.draw.filters.shaders;

import com.haxademic.core.draw.filters.shaders.shared.BaseFilter;

import processing.core.PApplet;
import processing.core.PImage;

public class BlendTowardsTexture
extends BaseFilter {

	public static BlendTowardsTexture instance;

	public BlendTowardsTexture(PApplet p) {
		super(p, "haxademic/shaders/filters/texture-blend-towards-texture.glsl");
		setBlendLerp(0.25f);
	}

	public static BlendTowardsTexture instance(PApplet p) {
		if(instance != null) return instance;
		instance = new BlendTowardsTexture(p);
		return instance;
	}

	public void setBlendLerp(float blendLerp) {
		shader.set("blendLerp", blendLerp);
	}

	public void setSourceTexture(PImage source) {
		shader.set("targetTexture", source);
	}

}

Add wrapper for texture lerp shader

Add wrapper for texture lerp shader


/**
 *
 */
package org.robotbrains.data.cloud.timeseries.server.database;

import org.kairosdb.client.HttpClient;
import org.kairosdb.client.response.GetResponse;

/**
 * @author Keith M. Hughes
 *
 */
public class KairosDbDatabaseRelay {
  private static final String KAIROS_CONNECTION_URL = "http://localhost:8090";

  public void startup() throws Exception {
    HttpClient client = new HttpClient(KAIROS_CONNECTION_URL);
    GetResponse response = client.getMetricNames();

    System.out.println("Response Code =" + response.getStatusCode());
    for (String name : response.getResults()) {
      System.out.println(name);
    }
    client.shutdown();
  }
}

Add in simple Kairos connection test

Add in simple Kairos connection test


public class Solution {

    public int trailingZeroes(int n) {

        int result = 0;

        while (n > 0) {

            result += (n / 5);
            n /= 5;

        }

        return result;

    }

}

Create : 172 Factorial Trailing Zeroes

Create : 172 Factorial Trailing Zeroes


public class TestaOrdenacao {

  public static void main(String[] args) {

    Produto produtos[] = {
      new Produto("Lamborghini", 1000000),
      new Produto("Jipe", 46000),
      new Produto("Brasília", 16000),
      new Produto("Smart", 46000),
      new Produto("Fusca", 17000)
    };

    for(int atual = 0; atual < produtos.length; atual++) {
      int menor = buscaMenor(produtos, atual, produtos.length - 1);
      Produto produtoAtual = produtos[atual];
      Produto produtoMenor = produtos[menor];
      produtos[atual] = produtoMenor;
      produtos[menor] = produtoAtual;
    }

    for(Produto produto : produtos) {
      System.out.println(produto.getNome() + " custa " + produto.getPreco());
    }

  }

  private static int buscaMenor(Produto[] produtos, int inicio, int termino) {
    int maisBarato = inicio;
    for(int atual = inicio; atual <= termino; atual++) {
      if(produtos[atual].getPreco() < produtos[maisBarato].getPreco()) {
        maisBarato = atual;
      }
    }
    return maisBarato;
  }

}

Insert new files, Alura, Projeto de Algoritmos 1, Aula 19


package com.hashnot.u.compare;

import java.util.Comparator;

/**
 * @author Rafał Krupiński
 */
public interface CompareOp<T> {
    /**
     * Allows parameters to be null
     */
    boolean eq(T o1, T o2);

    /**
     * Allows parameters to be null
     */
    boolean ne(T o1, T o2);

    boolean lt(T o1, T o2);

    boolean lte(T o1, T o2);

    boolean gt(T o1, T o2);

    /**
     * @return o1 >= o2
     */
    boolean gte(T o1, T o2);

    static <T> CompareOp<T> from(Comparator<T> from) {
        return new ComparatorOperator<>(from);
    }

    class ComparatorOperator<T> implements CompareOp<T> {
        final private Comparator<T> cmp;

        public ComparatorOperator(Comparator<T> cmp) {
            this.cmp = cmp;
        }

        /**
         * Allows parameters to be null
         */
        public boolean eq(T o1, T o2) {
            return o1 == o2 || o1 != null && o2 != null && cmp.compare(o1, o2) == 0;
        }

        /**
         * Allows parameters to be null
         */
        public boolean ne(T o1, T o2) {
            return o1 != o2 || o1 == null || cmp.compare(o1, o2) != 0;
        }

        public boolean lt(T o1, T o2) {
            return cmp.compare(o1, o2) < 0;
        }

        public boolean lte(T o1, T o2) {
            return cmp.compare(o1, o2) <= 0;
        }

        public boolean gt(T o1, T o2) {
            return cmp.compare(o1, o2) > 0;
        }

        /**
         * @return o1 >= o2
         */
        public boolean gte(T o1, T o2) {
            return cmp.compare(o1, o2) >= 0;
        }
    }
}

[compare] Add comparsion operators as a wrapper for Comparator


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

package io.spine.tools.protoc;

import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse.File;
import io.spine.type.MessageType;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

@DisplayName("ProtocPluginFiles should")
final class ProtocPluginFilesTest {

    @DisplayName("prepare File builder for supplied Type")
    @Test
    void prepareFileBuilderForType() {
        MessageType type = new MessageType(TestMessage.getDescriptor());
        File.Builder result = ProtocPluginFiles.prepareFile(type);

        assertEquals("io/spine/tools/protoc/TestMessage.java", result.getName());
    }
}

Cover ProtocPluginFiles with unit test

Cover ProtocPluginFiles with unit test


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem72;

/**
 * An array A contains all the integers from 0 through N, except for one number which is missing.
 * Can you write a method to find that number?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FindTheMissingNumber {

}

Add statement to problem 72

Add statement to problem 72


package de.uulm.mi.gdg;

import processing.core.PApplet;

/**
 * The Equalizer class is the main controller for the Animation.
 *
 * @author Tobias Lahmann
 */
public class Equalizer extends PApplet {
    /**
     * The settings() method runs before the sketch has been set up, so other Processing functions cannot be used at
     * this point.
     */
    public void settings() {
        setSize(1240, 720);
    }

    /**
     * The setup method is called before displaying any objects. The Method calls commands in the Processing API.
     */
    public void setup() {

    }

    /**
     * Draw method is responsible for displaying all objects.
     */
    public void draw() {

    }

    /**
     * Main method to instantiate the PApplet.
     *
     * @param args Arguments passed to the PApplet.
     */
    public static void main(String[] args) {
        PApplet.main(new String[]{Equalizer.class.getName()});
    }
}

Write controller to depict initial PApplet state


/**
 * 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.shindig.gadgets;

import junit.framework.TestCase;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.net.URI;

public class CachedContentFetcherTest extends TestCase {
  private RemoteContentFetcher fetcher
      = new CachedContentFetcher(new BasicRemoteContentFetcher(Integer.MAX_VALUE));

  public void testFetch() throws Exception {
    String content = "Hello, world!";
    File temp = File.createTempFile(this.getName(), ".txt");
    temp.deleteOnExit();
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write(content);
    out.close();
    RemoteContentRequest request = new RemoteContentRequest(temp.toURI());
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
    temp.delete();
    response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
  }

  public void testDontCache() throws Exception {
    String content = "Hello, world!";
    File temp = File.createTempFile(this.getName(), ".txt");
    temp.deleteOnExit();
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write(content);
    out.close();
    RemoteContentRequest request = RemoteContentRequest.getRequest(temp.toURI(), true);
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
    temp.delete();
    response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_NOT_FOUND, response.getHttpStatusCode());
  }

  public void testNotExists() throws Exception {
    RemoteContentRequest request
        = new RemoteContentRequest(new URI("file:///does/not/exist"));
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_NOT_FOUND, response.getHttpStatusCode());
  }

  // TODO test caching of POST requests, headers, options, etc.
}

Test that nocache is honored by CachedContentFetcher

git-svn-id: 2d40e98957f9f20f5ce77bde55198011fc5ba896@646542 13f79535-47bb-0310-9956-ffa450edef68


package com.dyhpoon.fodex;

import android.content.ContentUris;
import android.net.Uri;
import android.test.AndroidTestCase;

import com.dyhpoon.fodex.data.actual.FodexContract;

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

/**
 * Created by darrenpoon on 2/4/15.
 */
public class ContractTest extends AndroidTestCase {

    public void testBuildImageUri() {
        long id = 0;
        Uri uri = FodexContract.ImageEntry.buildImageUri(id);
        assertEquals(ContentUris.withAppendedId(FodexContract.ImageEntry.CONTENT_URI, id), uri);
    }

    public void testBuildTagUri() {
        long id = 0;
        Uri uri = FodexContract.TagEntry.buildTagUri(id);
        assertEquals(ContentUris.withAppendedId(FodexContract.TagEntry.CONTENT_URI, id), uri);
    }

    public void testSearchTagName() {
        String expected = "hello";
        Uri uri = FodexContract.TagEntry.buildSearchTagName(expected);
        String actual = FodexContract.TagEntry.getSearchTagName(uri);
        assertEquals(expected, actual);
    }

    public void testTagName() {
        String expected = "morning";
        Uri uri = FodexContract.TagEntry.buildTagName(expected);
        String actual = FodexContract.TagEntry.getTagName(uri);
        assertEquals(expected, actual);
    }

    public void testBuildImageTagUri() {
        long id = 0;
        Uri uri = FodexContract.ImageTagEntry.buildImageTagUri(id);
        assertEquals(ContentUris.withAppendedId(FodexContract.ImageTagEntry.CONTENT_URI, id), uri);
    }

    public void testTagNames() {
        List<String> expected = Arrays.asList("hello");
        Uri uri = FodexContract.ImageTagEntry.buildTagNames(expected);
        List<String> actual = FodexContract.ImageTagEntry.getTagNames(uri);
        assertEquals(expected, actual);

        expected = Arrays.asList("hello", "morning");
        uri = FodexContract.ImageTagEntry.buildTagNames(expected);
        actual = FodexContract.ImageTagEntry.getTagNames(uri);
        assertEquals(expected, actual);
    }

    public void testSearchId() {
        long expected = 0;
        Uri uri = FodexContract.ImageTagEntry.buildSearchId(expected);
        long actual = Long.parseLong(FodexContract.ImageTagEntry.getSearchId(uri));
        assertEquals(expected, actual);
    }

    public void testSearchName() {
        String expected = "hello";
        Uri uri = FodexContract.ImageTagEntry.buildSearchName(expected);
        String actual = FodexContract.ImageTagEntry.getSearchName(uri);
        assertEquals(expected, actual);
    }

    public void testBuildShareUri() {
        long id = 0;
        Uri uri = FodexContract.ShareEntry.buildShareUri(id);
        assertEquals(ContentUris.withAppendedId(FodexContract.ShareEntry.CONTENT_URI, id), uri);
    }
}

Add test cases for FodexContract

Add test cases for FodexContract


package to.etc.domui.hibernate.types;

import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import to.etc.util.DateUtil;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;

/**
 * @author Frits Jalvingh
 * Created on 31-10-17.
 */
public class DateNonnullType implements UserType {
	@Override
	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return null;
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		if(value == null)
			return value;
		return new Date(((java.util.Date) value).getTime());
	}

	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return null;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		if(x != null)
			return x.equals(y);
		else
			return x == y;
	}

	@Override
	public int hashCode(Object arg0) throws HibernateException {
		return arg0.hashCode();
	}

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

	@Override
	public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
		if(resultSet == null)
			return null;
		Date v = resultSet.getDate(names[0]);
		if(resultSet.wasNull())
			return null;
		if(DateUtil.getYear(v) >= 9999)
			return null;
		return new java.util.Date(v.getTime());
	}

	@Override
	public void nullSafeSet(PreparedStatement statement, Object value, int index) throws HibernateException, SQLException {
		Date dt = (Date) value;
		if(null == dt) {
			dt = DateUtil.dateFor(9999, 0, 1);
		}
		statement.setDate(index, new java.sql.Date(dt.getTime()));
	}

	@Override
	public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
		return null;
	}

	@Override
	public Class< ? > returnedClass() {
		return Date.class;
	}

	@Override
	public int[] sqlTypes() {
		return new int[]{Types.DATE};
	}
}

Add Hibernate Type to store null Date values as 9999-01-01.


// Copyright (c) 2003 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

/**
 * Helper functions for doing serial arithmetic.  These should be used when
 * setting/checking SOA serial numbers.
 *
 * @author Brian Wellington
 */

public final class Serial {

private static final long MAX32 = 0xFFFFFFFFL;

private
Serial() {
}

/**
 * Compares two numbers using serial arithmetic.  The numbers are assumed
 * to be 32 bit unsigned integers stored in longs.
 * @param serial1 The first integer
 * @param serial2 The second integer
 * @return 0 if the 2 numbers are equal, a positive number if serial1 is greater
 * than serial2, and a negative number if serial2 is greater than serial1.
 * @throws IllegalArgumentException serial1 or serial2 is out of range
 */
public static int
compare(long serial1, long serial2) {
	if (serial1 < 0 || serial1 > MAX32)
		throw new IllegalArgumentException(serial1 + " out of range");
	if (serial2 < 0 || serial2 > MAX32)
		throw new IllegalArgumentException(serial2 + " out of range");
	long diff = serial1 - serial2;
	if (diff >= MAX32)
		diff -= (MAX32 + 1);
	else if (diff < -MAX32)
		diff += (MAX32 + 1);
	return (int)diff;
}

/**
 * Increments a serial number.  The number is assumed to be a 32 bit unsigned
 * integer stored in a long.  This basically adds 1 and resets the value to
 * 0 if it is 2^32.
 * @param val The serial number
 * @return The incremented serial number
 * @throws IllegalArgumentException serial is out of range
 */
public static long
increment(long serial) {
	if (serial < 0 || serial > MAX32)
		throw new IllegalArgumentException(serial + " out of range");
	if (serial == MAX32)
		return 0;
	return serial + 1;
}

}

Add a class for doing serial arithmetic.


import java.util.HashMap;
//3. Longest Substring Without Repeating Characters
/**
 * Given a string, find the length of the longest substring without repeating characters.
 *
 * Examples:
 * Given "abcabcbb", the answer is "abc", which the length is 3.
 * Given "bbbbb", the answer is "b", with the length of 1.
 * Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
 *
 * Tags: Hash Table, Two Pointers, String
 * Similar Problems: (H) Longest Substring with At Most Two Distinct Characters
 *
 * @author Xinyue Zhang
 *
 */

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0) return 0;
        //create a Hashmap, where character is key and index of the character is value
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max = 0;
        //two pointers
        for (int i = 0, j = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i)))
                j = Math.max(j, map.get(s.charAt(i)) + 1);
            map.put(s.charAt(i), i);
            max = Math.max(max, i - j + 1);
        }
        return max;
    }

    public static void main(String args[]) {
        String s = "abba";
        Solution sol = new Solution();
        System.out.println(sol.lengthOfLongestSubstring(s));
    }
}

Add solution for problem 003

Add solution for problem 003

3. Longest Substring Without Repeating Characters


package org.robockets.stronghold.robot.autonomous;

import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;
import org.robockets.stronghold.robot.highgoalshooter.FreeFire;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 * ALL VALUES ARE TEMPORARY
 */
public class AutoShootCleat extends CommandGroup {

    public  AutoShootCleat(int defense) {
        addSequential(new MoveToMiddleGoal(defense));
        addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 24, 0));
        addSequential(new FreeFire());
    }
}

Add skeleton for auto shoot cleat

Add skeleton for auto shoot cleat


package net.the4thdimension.android;

import android.os.Environment;
import android.support.test.runner.AndroidJUnit4;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;

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

import java.io.File;
import java.util.ArrayList;

/**
 * Created by jaydeepw on 1/2/17.
 */
@RunWith(AndroidJUnit4.class)
@SmallTest
public class FileUtilsInstrumentationTest extends AndroidTestCase {

    @Test
    public void listFilesMultiple() throws Exception {

        File tempFile = new File(Environment.getExternalStorageDirectory().getPath());
        File directory = new File(tempFile, "rajababu");
        boolean isDirCreated = directory.mkdir();
        assertEquals("Directory created", true, isDirCreated);

        File file1 = new File(directory, "f1.txt");
        File file2 = new File(directory, "f2.txt");
        file1.createNewFile();
        file2.createNewFile();

        ArrayList files = new ArrayList();
        FileUtils.listFiles(directory, files);

        assertEquals(2, files.size());

        // clean up
        file1.delete();
        file2.delete();
        directory.delete();
    }

    @Test
    public void listFilesZeroFiles() throws Exception {

        File tempFile = new File(Environment.DIRECTORY_DOWNLOADS);
        File directory = new File(tempFile, "rajababu");
        directory.mkdir();

        ArrayList files = new ArrayList();
        FileUtils.listFiles(directory, files);

        assertEquals(0, files.size());

        // clean up
        directory.delete();
    }

}

Disable allows backup. Creates problem with using this library with other apps.


/*
 * Copyright 2019-present Facebook, 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.facebook.buck.android;

import static com.facebook.buck.jvm.java.JavaCompilationConstants.ANDROID_JAVAC_OPTIONS;

import com.facebook.buck.android.toolchain.AndroidPlatformTarget;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.targetgraph.AbstractNodeBuilder;
import com.facebook.buck.core.toolchain.impl.ToolchainProviderBuilder;
import com.facebook.buck.jvm.java.JavaCompilationConstants;
import com.facebook.buck.jvm.java.toolchain.JavaToolchain;
import com.facebook.buck.jvm.java.toolchain.JavacOptionsProvider;

public class AndroidBuildConfigBuilder
    extends AbstractNodeBuilder<
        AndroidBuildConfigDescriptionArg.Builder,
        AndroidBuildConfigDescriptionArg,
        AndroidBuildConfigDescription,
        AndroidBuildConfig> {

  public AndroidBuildConfigBuilder(BuildTarget target) {
    super(
        new AndroidBuildConfigDescription(
            new ToolchainProviderBuilder()
                .withToolchain(
                    JavacOptionsProvider.DEFAULT_NAME,
                    JavacOptionsProvider.of(ANDROID_JAVAC_OPTIONS))
                .withToolchain(
                    AndroidPlatformTarget.DEFAULT_NAME, TestAndroidPlatformTargetFactory.create())
                .withToolchain(
                    JavaToolchain.DEFAULT_NAME, JavaCompilationConstants.DEFAULT_JAVA_TOOLCHAIN)
                .build()),
        target);
  }

  public AndroidBuildConfigBuilder setPackage(String packageName) {
    getArgForPopulating().setPackage(packageName);
    return this;
  }
}

Add a TargetNode builder for AndroidBuildConfig

Summary: Add a node builder to be used in tests later in this stack of changes.

Reviewed By: cute-jumper

shipit-source-id: dc8eac55f0


package com.github.sparkcaller.preprocessing;

import com.github.sparkcaller.Utils;
import org.apache.spark.api.java.function.Function;
import picard.sam.markduplicates.MarkDuplicates;

import java.io.File;
import java.util.ArrayList;

public class DuplicateMarker implements Function<File, File> {
    final private ArrayList<String> extraArgs;

    public DuplicateMarker(String extraArgsString) {
        this.extraArgs = Utils.possibleStringToArgs(extraArgsString);
    }

    public File call(File file) throws Exception {
        MarkDuplicates markDuplicates = new MarkDuplicates();

        ArrayList<String> markerArgs = new ArrayList<String>();
        markerArgs.add("INPUT=");
        markerArgs.add(file.getPath());

        String newFileName = Utils.removeExtenstion(file.getPath(), "bam") + "-deduped.bam";
        File outputBamFile = new File(newFileName);

        markerArgs.add("OUTPUT=");
        markerArgs.add(outputBamFile.getPath());

        markerArgs.add("METRICS_FILE=");
        markerArgs.add(file.getPath() + "-metrics.txt");

        if (this.extraArgs != null) {
            markerArgs.addAll(extraArgs);
        }

        markDuplicates.instanceMain(markerArgs.toArray(new String[0]));
        return outputBamFile;
    }
}

Create a class which is used to mark all duplicate reads.

This program also creates a metrics text file, contaning information about ex.
how many duplicates that was found.


// Write and then read back binary data.
import java.io.*;

class RWData {
	public static void main(String args[]) throws IOException {
		DataOutputStream dataOut;
		DataInputStream dataIn;

		int i = 10;
		double d = 1023.56;
		boolean b = true;

		try {
			dataOut = new DataOutputStream(new FileOutputStream("testdata"));
		}
		catch(IOException exc) {
			System.out.println("Cannot open file.");
			return;
		}

		try {
			System.out.println("Writing " + i);
			dataOut.writeInt(i);

			System.out.println("Writing " + d);
			dataOut.writeDouble(d);

			System.out.println("Writing " + b);
			dataOut.writeBoolean(b);

			System.out.println("Writing " + 12.2 * 7.4);
			dataOut.writeDouble(12.2 * 7.4);
		}
		catch(IOException exc) {
			System.out.println("Write error.");
		}

		dataOut.close();

		System.out.println();

		// Now, read them back.
		try {
			dataIn = new DataInputStream(new FileInputStream("testdata"));
		}
		catch(IOException exc) {
			System.out.println("Cannot open file.");
			return;
		}

		try {
			i = dataIn.readInt();
			System.out.println("Reading " + i);

			d = dataIn.readDouble();
			System.out.println("Reading " + d);

			b = dataIn.readBoolean();
			System.out.println("Reading " + b);

			d = dataIn.readDouble();
			System.out.println("Reading " + d);
		}
		catch(IOException exc) {
			System.out.println("Read error.");
		}

		dataIn.close();
	}
}

Write and then read back binary data

Write and then read back binary data

http://ideone.com/HnFXv1


/**
 *
 */
package de.hhu.tbus.applications.testapp;

import com.dcaiti.vsimrti.fed.app.api.interfaces.Application;
import com.dcaiti.vsimrti.fed.app.api.interfaces.ApplicationLayer;
import com.dcaiti.vsimrti.fed.app.api.util.ReceivedV2XMessage;

/**
 * @author bialon
 *
 * Empty dummy application
 */
public class TbusDummyApp implements Application {

	/**
	 * @see com.dcaiti.vsimrti.fed.app.api.interfaces.TimerCall#getMinimalTimerCallInterval()
	 */
	@Override
	public long getMinimalTimerCallInterval() {
		return 0L;
	}

	/**
	 * @see com.dcaiti.vsimrti.fed.app.api.interfaces.TimerCall#timerCall(long)
	 */
	@Override
	public void timerCall(long arg0) {}

	/**
	 * @see com.dcaiti.vsimrti.fed.app.api.interfaces.Application#dispose()
	 */
	@Override
	public void dispose() {}

	/**
	 * @see com.dcaiti.vsimrti.fed.app.api.interfaces.Application#initialize(com.dcaiti.vsimrti.fed.app.api.interfaces.ApplicationLayer)
	 */
	@Override
	public void initialize(ApplicationLayer arg0) {}

	/**
	 * @see com.dcaiti.vsimrti.fed.app.api.interfaces.Application#receiveMessage(com.dcaiti.vsimrti.fed.app.api.util.ReceivedV2XMessage)
	 */
	@Override
	public void receiveMessage(ReceivedV2XMessage arg0) {}
}

Add Dummy app for VSimRTI with TBUS

Add Dummy app for VSimRTI with TBUS


/*
 * JBoss, Home of Professional Open Source
 * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the @author tags. All rights reserved.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU Lesser General Public License, v. 2.1.
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License,
 * v.2.1 along with this distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */

package org.jboss.as.console.client.core;

import com.google.gwt.user.client.rpc.AsyncCallback;
import org.jboss.as.console.client.shared.dispatch.AsyncCommand;
import org.jboss.as.console.client.shared.dispatch.DispatchAsync;
import org.jboss.as.console.client.shared.dispatch.impl.DMRAction;
import org.jboss.as.console.client.shared.dispatch.impl.DMRResponse;
import org.jboss.dmr.client.ModelNode;

import static org.jboss.dmr.client.ModelDescriptionConstants.*;

/**
 * @author Heiko Braun
 * @date 5/19/11
 */
public class BootstrapCmd implements AsyncCommand<Boolean>{

    private BootstrapContext bootstrap;
    private DispatchAsync dispatcher;

    public BootstrapCmd(BootstrapContext bootstrap, DispatchAsync dispatcher) {
        this.bootstrap = bootstrap;
        this.dispatcher = dispatcher;
    }

    @Override
    public void execute(final AsyncCallback<Boolean> callback) {

        final ModelNode operation = new ModelNode();
        operation.get(OP).set(READ_CHILDREN_NAMES_OPERATION);
        operation.get(CHILD_TYPE).set("subsystem");
        operation.get(ADDRESS).setEmptyList();

        dispatcher.execute(new DMRAction(operation), new AsyncCallback<DMRResponse>() {
            @Override
            public void onFailure(Throwable caught) {
                bootstrap.setProperty(BootstrapContext.STANDALONE, "false");
            }

            @Override
            public void onSuccess(DMRResponse result) {

                ModelNode response = ModelNode.fromBase64(result.getResponseText());
                boolean outcome = response.get("outcome").asString().equals("success");
                bootstrap.setProperty(BootstrapContext.STANDALONE, Boolean.valueOf(outcome).toString());

                callback.onSuccess(outcome);

            }
        });

    }
}

Move bootstrap op to custom command

Move bootstrap op to custom command


package com.maddenabbott.jenny.test;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.hamcrest.Matcher;
import static org.hamcrest.Matchers.is;

/**
 * Test utility to verify multi-line Strings against content in files.
 */
public class OutputMatcher {
  /**
   * Verify that something matches exactly the content of a file. The file name given should be a
   * path relative to a directory called output at the root of the classpath,
   * with no file extension. A file extension of '.txt' will automatically be appended.
   *
   * For example "foo" would be the name of a file at classpath:output/foo.txt whilst "foo/bar"
   * would load the file classpath:output/foo/bar.txt.
   *
   * All of this is necessary because Java has no real way of having multi-line Strings so they
   * must be specified in files instead.
   *
   * @param path the path of the file to load content from
   * @return a Matcher that will verify equality with the contents of the loaded file
   */
  public static Matcher<String> isIn(final String path) {

    URL url = ClassLoader.getSystemResource("output/" + path + ".txt");
    if (url == null) {
      throw new RuntimeException("Unable to load output resource " + path);
    }

    URI uri;
    try {
      uri = url.toURI();
    } catch (URISyntaxException e) {
      throw new RuntimeException("Unable to load output resource " + path);
    }

    try {
      return is(new String(Files.readAllBytes(Paths.get(uri))));
    } catch (IOException e) {
      throw new RuntimeException("Unable to load output resource " + path);
    }
  }
}

Add utility for verifying equality of multiline strings against content in files.


package com.github.aureliano.achmed.os;

import com.github.aureliano.achmed.os.pkg.IPackageManager;
import com.github.aureliano.achmed.os.pkg.PackageManagerFactory;
import com.github.aureliano.achmed.os.service.IService;
import com.github.aureliano.achmed.os.service.RedHatService;
import com.github.aureliano.achmed.types.OperatingSystemFamily;
import com.github.aureliano.achmed.types.PackageProvider;

public class RedHat extends Linux {

	private IPackageManager packageManager;
	private IService serviceManager;

	public RedHat() {
		this.packageManager = PackageManagerFactory.createPackageManager(PackageProvider.YUM);
		this.serviceManager = new RedHatService();
	}

	public IPackageManager getDefaultPackageManager() {
		return this.packageManager;
	}

	public IService getDefaultServiceManager() {
		return this.serviceManager;
	}

	public OperatingSystemFamily getOperatingSystemFamily() {
		return OperatingSystemFamily.DEBIAN;
	}
}

Create Red Hat operating system.

Create Red Hat operating system.


package leetcode.n_queens;

import java.util.ArrayList;

public class Solution {
	public void dfs(ArrayList<String[]> ans, char[][] board, boolean[] row, boolean[] col, boolean[] diag, boolean[] rdiag, int n, int c){
		if(c == n){
			String[] cur = new String[n];
			for(int i = 0; i < n; i++){
				cur[i] = new String(board[i]);
			}
			ans.add(cur);
		}else{
			for(int r = 0; r < n; r++){
				if(!row[r] && !col[c] && !diag[r + c] && !rdiag[r - c + n - 1]){
					row[r] = col[c] = diag[r + c] = rdiag[r - c + n - 1] = true;
					board[r][c] = 'Q';
					dfs(ans, board, row, col, diag, rdiag, n, c + 1);
					row[r] = col[c] = diag[r + c] = rdiag[r - c + n - 1] = false;
					board[r][c] = '.';
				}
			}
		}
	}

    public ArrayList<String[]> solveNQueens(int n) {
        ArrayList<String[]> ans = new ArrayList<String[]>();
        if(n == 0){
        	ans.add(new String[0]);
        	return ans;
        }
        boolean[] row = new boolean[n];
        boolean[] col = new boolean[n];
        boolean[] diag = new boolean[2 * n - 1];
        boolean[] rdiag = new boolean[2 * n - 1];
        char[][] board = new char[n][n];
        for(int i = 0; i < n; i++){
        	for(int j = 0; j < n; j++){
        		board[i][j] = '.';
        	}
        }
        dfs(ans, board, row, col, diag, rdiag, n, 0);
        return ans;
    }

    public static void main(String[] args){
    	int cnt = 0;
    	for(String[] row : new Solution().solveNQueens(8)){
    		cnt++;
    		for(String s : row){
    			System.err.println(s);
    		}
    		System.err.println("");
    	}
    	System.err.println("cnt:" + cnt);
    }
}

Add java solution for 51. N-Queens

Add java solution for 51. N-Queens

51. N-Queens: https://leetcode.com/problems/n-queens/


package net.alexrose.rofretta.detection;

import net.alexrose.rofretta.core.Instrument;
import net.alexrose.rofretta.core.InstrumentString;
import net.alexrose.rofretta.core.Voicing;

import java.util.List;

/**
 * You plucked something on the guitar that sounded good.
 * You saw your idol play something.
 * Your theory isn't hot or you're a bit lazy - what WAS that, probably?
 * <p>
 * The VoicingDetector will attempt to figure out it out for you.
 */
public class VoicingDetector {

    /**
     * Given
     *
     * @return
     */
    public List<Voicing> detect(List<InstrumentString> strings, Instrument tuning) {

    }

    public List<Voicing> detect(String input) {

    }
}

Check in a rough draft of what a detection interface might look like


package org.usergrid.launcher;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class AppleUtils {

	public static void initMacApp() {
		com.apple.eawt.Application macApp = com.apple.eawt.Application
				.getApplication();
		macApp.setDockIconImage(new ImageIcon(App.class
				.getResource("dock_icon.png")).getImage());

		macApp.setAboutHandler(new com.apple.eawt.AboutHandler() {
			@Override
			public void handleAbout(com.apple.eawt.AppEvent.AboutEvent evt) {
				JOptionPane
						.showMessageDialog(
								null,
								"Usergrid Standalone Server Launcher\nCopyright 2011 Ed Anuff & Usergrid",
								"About Usergrid Launcher",
								JOptionPane.INFORMATION_MESSAGE);
			}
		});

	}
}

Move Apple-specific setup code into separate class