Comparing to array list through there given index but its returning null exception at file initialization - arraylist

package adc;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
class Result {
/*
* Complete the 'sockMerchant' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER_ARRAY ar
*/
public static int sockMerchant(int n, List<Integer> ar) {
// Write your code here
int count=0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<=n;j++){
if(ar.get(i)==ar.get(j)){
count++;
}
}
}
return(count);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); ' BufferedWriter(newFileWriter(System.getenv("F:\\")));'
int n = Integer.parseInt(bufferedReader.readLine().trim());
String[] arTemp = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
List<Integer> ar = new ArrayList<>();
for (int i = 0; i < n; i++) {
int arItem = Integer.parseInt(arTemp[i]);
ar.add(arItem);
}
int result = Result.sockMerchant(n, ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Working of code
here inputs are n("number of integer arraylist have")=9
and ar input of arraylist [10, 20, 20, 10, 10, 30, 50, 10, 20]
** In this ar arraylist we have to find the even pair of number and return the number of pair .**
In this example the output is 3.

Related

TFlite model slow/no inference

I am trying to get an opencv pipeline working on a REV control hub for FTC with tensorflow. I have a trained TFLite model and I am processing it and retrieving the confidences. It works well on an android device as an android app, but it doesn't seem to work with the REV control hub. You may see that I have a variable named here2, this always evaluates to false unless it is before model.process, showing that the model doesn't get processed. Any idea why this is?
package org.firstinspires.ftc.teamcode.vision;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import org.firstinspires.ftc.robotcontroller.internal.FtcRobotControllerActivity;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.ml.ModelUnquant;
import org.opencv.core.Mat;
import org.openftc.easyopencv.OpenCvPipeline;
import org.opencv.android.Utils;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class CircularTagDetectionPipeline extends OpenCvPipeline {
Telemetry telemetry;
public boolean done = false;
public int pos = -1;
public boolean here1 = false;
public boolean here2 = false;
public CircularTagDetectionPipeline(Telemetry telemetry){
this.telemetry = telemetry;
}
#Override
public Mat processFrame(Mat input) {
Bitmap bmp = Bitmap.createBitmap(input.width(), input.height(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(input, bmp);
pos = classifyImage(bmp);
done = true;
return input;
}
public int classifyImage(Bitmap image){
try {
image = Bitmap.createScaledBitmap(image, 224, 224, false);
//image.setWidth(224);
//image.setHeight(224);
ModelUnquant model = ModelUnquant.newInstance(FtcRobotControllerActivity.contextFTC);
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 224, 224, 3}, DataType.FLOAT32);
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*imageWidth*imageHeight*3);
byteBuffer.order(ByteOrder.nativeOrder());
int[] intValues = new int[imageWidth*imageHeight];
image.getPixels(intValues, 0, imageWidth,0, 0, imageWidth, imageHeight);
int pixel = 0;
for(int i = 0; i < imageWidth; i++){
for(int j = 0; j < imageHeight; j++){
int val = intValues[pixel++];
byteBuffer.putFloat(((val >> 16)&0xFF)*(1.f/255.f));
byteBuffer.putFloat(((val >> 8)&0xFF)*(1.f/255.f));
byteBuffer.putFloat((val & 0xFF)*(1.f/255.f));
}
telemetry.addLine(i+"");
}
here1 = true;
inputFeature0.loadBuffer(byteBuffer);
ModelUnquant.Outputs outputs = model.process(inputFeature0);
TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();
here2 = true;
float[] confidences = outputFeature0.getFloatArray();
int maxPos = 0;
float maxConfidence = 0;
for(int i = 0; i < confidences.length; i++){
if(confidences[i] > maxConfidence){
maxConfidence = confidences[i];
maxPos = i;
}
}
String[] classes = {"1", "2", "3"};
int posReturn = Integer.parseInt(classes[maxPos]);
model.close();
return posReturn;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
}
I am expecting the robot to go to execute the desired trajectory based on the confidences, but confidences never get processed. I tried on an android app and it worked, just not on the control hub.

Why am I getting the duplicates more than once? If I have 3 "3s" I get [3,3,3] instead of just [3]

package week8;
import java.util.*;
public class ArrayListDup {
//create dumps function
public static List<String> dups(List<String> list) {
List<String> result = new ArrayList<String>();
for(int i = 0;i < list.size();i++) {
for(int j = i + 1;j<list.size();j++) {
if(list.get(i).equals(list.get(j))) {
result.add(list.get(j));
}

Find the largest String in the list

I am required to find the largest string in the ArrayList, and the print it. My code is not currently working though.
public class Solution {
private static List<String> strings;
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
strings = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
String n = reader.readLine();
strings.add(n);
}
String largestString = strings.get(0);
for (int i = 0; i < strings.size(); i++) {
if (strings.get(i).length() > largestString.length()) {
largestString = strings.get(i);
System.out.println(largestString);
}
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String value = null;
int length = 0;
for (int i = 0; i < 5; i++) {
String n = reader.nextLine();
if (n != null && n.length() > length) {
length = n.length();
value = n;
}
}
System.out.println("Largest String : " + value + " of length : " + length);
}

error is occuring while creating custom tokenizer in lucene 7.3

I m trying to create new tokenizer by refering book tamingtext (which uses lucene 3.+ api) using new lucene api 7.3, but it is giving me error as mentioned below
java.lang.IllegalStateException: TokenStream contract violation: reset()/close() call missing, reset() called multiple times, or subclass does not call super.reset(). Please see Javadocs of TokenStream class for more information about the correct consuming workflow.
at org.apache.lucene.analysis.Tokenizer$1.read(Tokenizer.java:109)
at java.io.Reader.read(Reader.java:140)
at solr.SentenceTokenizer.fillSentences(SentenceTokenizer.java:43)
at solr.SentenceTokenizer.incrementToken(SentenceTokenizer.java:55)
at solr.NameFilter.fillSpans(NameFilter.java:56)
at solr.NameFilter.incrementToken(NameFilter.java:88)
at spec.solr.NameFilterTest.testNameFilter(NameFilterTest.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Here is my SentenceTokenizer class
Initializing method, in older api there was super(Reader); but in current api there is no access to Reader class
public SentenceTokenizer(SentenceDetector detector) {
super();
setReader(reader);
this.sentenceDetector = detector;
}
Here is my reset method
#Override
public void reset() throws IOException {
super.reset();
sentenceDetector = null;
}
When i tried to access this method from custom TokenFilter, I m getting above error
public void fillSentences() throws IOException {
char[] c = new char[256];
int size = 0;
StringBuilder stringBuilder = new StringBuilder();
while ((size = input.read(c)) >= 0) {
stringBuilder.append(c, 0, size);
}
String temp = stringBuilder.toString();
inputSentence = temp.toCharArray();
sentenceSpans = sentenceDetector.sentPosDetect(temp);
tokenOffset = 0;
}
#Override
public final boolean incrementToken() throws IOException {
if (sentenceSpans == null) {
//invoking following method
fillSentences();
}
if (tokenOffset == sentenceSpans.length) {
return false;
}
Span sentenceSpan = sentenceSpans[tokenOffset];
clearAttributes();
int start = sentenceSpan.getStart();
int end = sentenceSpan.getEnd();
charTermAttribute.copyBuffer(inputSentence, start, end - start);
positionIncrementAttribute.setPositionIncrement(1);
offsetAttribute.setOffset(start, end);
tokenOffset++;
return true;
}
Here is my custom TokenFilter class
public final class NameFilter extends TokenFilter {
public static final String NE_PREFIX = "NE_";
private final Tokenizer tokenizer;
private final String[] tokenTypeNames;
private final NameFinderME[] nameFinderME;
private final KeywordAttribute keywordAttribute = addAttribute(KeywordAttribute.class);
private final PositionIncrementAttribute positionIncrementAttribute = addAttribute(PositionIncrementAttribute.class);
private final CharTermAttribute charTermAttribute = addAttribute(CharTermAttribute.class);
private final OffsetAttribute offsetAttribute = addAttribute(OffsetAttribute.class);
private String text;
private int baseOffset;
private Span[] spans;
private String[] tokens;
private Span[][] foundNames;
private boolean[][] tokenTypes;
private int spanOffsets = 0;
private final Queue<AttributeSource.State> tokenQueue =
new LinkedList<>();
public NameFilter(TokenStream in, String[] modelNames, NameFinderME[] nameFinderME) {
super(in);
this.tokenizer = SimpleTokenizer.INSTANCE;
this.nameFinderME = nameFinderME;
this.tokenTypeNames = new String[modelNames.length];
for (int i = 0; i < modelNames.length; i++) {
this.tokenTypeNames[i] = NE_PREFIX + modelNames[i];
}
}
//consumes tokens from the upstream tokenizer and buffer them in a
//StringBuilder whose contents will be passed to opennlp
protected boolean fillSpans() throws IOException {
if (!this.input.incrementToken()) return false;
//process the next sentence from the upstream tokenizer
this.text = input.getAttribute(CharTermAttribute.class).toString();
this.baseOffset = this.input.getAttribute(OffsetAttribute.class).startOffset();
this.spans = this.tokenizer.tokenizePos(text);
this.tokens = Span.spansToStrings(spans, text);
this.foundNames = new Span[this.nameFinderME.length][];
for (int i = 0; i < nameFinderME.length; i++) {
this.foundNames[i] = nameFinderME[i].find(tokens);
}
//insize
this.tokenTypes = new boolean[this.tokens.length][this.nameFinderME.length];
for (int i = 0; i < nameFinderME.length; i++) {
Span[] spans = foundNames[i];
for (int j = 0; j < spans.length; j++) {
int start = spans[j].getStart();
int end = spans[j].getEnd();
for (int k = start; k < end; k++) {
this.tokenTypes[k][i] = true;
}
}
}
spanOffsets = 0;
return true;
}
#Override
public boolean incrementToken() throws IOException {
//if there's nothing in the queue
if(tokenQueue.peek()==null){
//no span or spans consumed
if (spans==null||spanOffsets>=spans.length){
if (!fillSpans())return false;
}
if (spanOffsets>=spans.length)return false;
//copy the token and any types
clearAttributes();
keywordAttribute.setKeyword(false);
positionIncrementAttribute.setPositionIncrement(1);
int startOffset = baseOffset +spans[spanOffsets].getStart();
int endOffset = baseOffset+spans[spanOffsets].getEnd();
offsetAttribute.setOffset(startOffset,endOffset);
charTermAttribute.setEmpty()
.append(tokens[spanOffsets]);
//determine of the current token is of a named entity type, if so
//push the current state into the queue and add a token reflecting
// any matching entity types.
boolean [] types = tokenTypes[spanOffsets];
for (int i = 0; i < nameFinderME.length; i++) {
if (types[i]){
keywordAttribute.setKeyword(true);
positionIncrementAttribute.setPositionIncrement(0);
tokenQueue.add(captureState());
positionIncrementAttribute.setPositionIncrement(1);
charTermAttribute.setEmpty().append(tokenTypeNames[i]);
}
}
}
spanOffsets++;
return true;
}
#Override
public void close() throws IOException {
super.close();
reset();
}
#Override
public void reset() throws IOException {
super.reset();
this.spanOffsets = 0;
this.spans = null;
}
#Override
public void end() throws IOException {
super.end();
reset();
}
}
here is my test case for following class
#Test
public void testNameFilter() throws IOException {
Reader in = new StringReader(input);
Tokenizer tokenizer = new SentenceTokenizer( detector);
tokenizer.reset();
NameFilter nameFilter = new NameFilter(tokenizer, modelName, nameFinderMES);
nameFilter.reset();
CharTermAttribute charTermAttribute;
PositionIncrementAttribute positionIncrementAttribute;
OffsetAttribute offsetAttribute;
int pass = 0;
while (pass < 2) {
int pos = 0;
int lastStart = 0;
int lastEnd = 0;
//error occur on below invoke
while (nameFilter.incrementToken()) {
}
}
I have added following changes in my code and it work fine but i m now sure it is correct answer
public SentenceTokenizer(Reader reader,SentenceDetector sentenceDetector) {
super();
this.input =reader;
this.sentenceDetector = sentenceDetector;
}

Iterate on a range of iterable

I have interface that returns a iterable object.
I need to iterate on the first 1000 items of it.
What is the best way to combine iterating using Iterator and stop after a certain count is reached.
Thanks
I'd use a loop that iterates and have a counter variable incremented; then break out of the loop when the counter reaches 1000.
What is your language?
C#:
using System.Linq;
//...
foreach (var item in iface.GetIterable().Take(1000))
{
//...
}
Python:
import itertools
#...
for item in itertools.islice(iface.get_iterable(), 1000):
#...
Make a standard loop that iterates over your collection, but check to see if the index has progress past the target index.
You may want to extract a seperate counter from the main loop index for your specific application.
int stopIndex = 1000;
for (int index = 0; index <= theInterface.Count; index++)
{
// check to see if we're at/past the stopIndex
if (index >= stopIndex)
break;
// we're still within the conditions, so do something with your interface
myObjectType localObject = (MyObjectType)theInterface.IndexOf(index);
}
Here's a test-driven (Java) wrapper around any existing iterator that should do the trick.
package com.playground;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
public class LimitedIterableTest extends TestCase {
private static class LimitedIterator<T> implements Iterator<T> {
private final Iterator<T> original;
private final int limit;
private int index = 0;
public LimitedIterator(Iterator<T> iterator, int limit) {
this.original = iterator;
this.limit = limit;
}
public boolean hasNext() {
return index < limit && original.hasNext();
}
public T next() {
index++;
return original.next();
}
public void remove() {
original.remove();
}
}
private static class LimitedIterable<T> implements Iterable<T> {
private final int limit;
private final Iterable<T> original;
public LimitedIterable(Iterable<T> iterable, int limit) {
this.original = iterable;
this.limit = limit;
}
public Iterator<T> iterator() {
return new LimitedIterator<T>(original.iterator(), limit);
}
}
final Integer[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
final List<Integer> list = Arrays.asList(array);
public void testCount() throws Exception {
assertEquals(10, count(list));
}
public void testLimitedIterable() throws Exception {
Iterable<Integer> limited = new LimitedIterable<Integer>(list, 5);
assertEquals(5, count(limited));
limited = new LimitedIterable<Integer>(list, 50);
assertEquals(10, count(limited));
}
private static <T> int count(Iterable<T> iterable) {
Iterator<T> iterator = iterable.iterator();
return count(iterator);
}
private static <T> int count(Iterator<T> iterator) {
int count = 0;
while (iterator.hasNext()) {
iterator.next();
count++;
}
return count;
}
}