Andengine Sprites array IndexoutofboundException - arrays

I am developing a game and having problem in the following code.
for(intReps = 0; intReps <=9; intReps++)
{
final Path path = new Path(2).to(sprBalls[intReps].getX(), sprBalls[intReps].getY()).to(sprBalls[intReps].getX(), -50);
// sprBalls[intReps].registerEntityModifier(new LoopEntityModifier(new PathModifier(10, path, null, new IPathModifierListener() {
final Path path1 = new Path(2).to(fly[intReps].getX(), fly[intReps].getY()+10).to(fly[intReps].getX(), -50);
sprBalls[intReps].registerEntityModifier(new PathModifier(10, path, null, new IPathModifierListener() {
#Override
public void onPathStarted(PathModifier pPathModifier,
IEntity pEntity) {
// TODO Auto-generated method stub
}
#Override
public void onPathWaypointStarted(PathModifier pPathModifier,
IEntity pEntity, int pWaypointIndex) {
// TODO Auto-generated method stub
}
#Override
public void onPathWaypointFinished(PathModifier pPathModifier,
IEntity pEntity, int pWaypointIndex) {
// TODO Auto-generated method stub
}
#Override
public void onPathFinished(PathModifier pPathModifier,
IEntity pEntity) {
Log.e("Msg","intReps : "+intReps); // Output is 10
// TODO Auto-generated method stub
// mScene.detachChild(pEntity);
sprBalls[intReps].detachSelf(); // Error on this line.
// pEntity.detachSelf();
// sprBalls[intReps].dispose();
}
}, EaseSineInOut.getInstance()));
}
Array's length is 10. I get IndexOutOfBoundException on the line with error (sprBalls[intReps].detachSelf();)
I am running the loop from 0 to 9 but on printing the value of intReps it shows 10 that is why it generates the error. I don't understand how to clear this problem. I wan't to create an array of sprites with 10 sprites in it and want to move them from one end to other and upon path finished I want them to get cleared from memory.

You should remove your entities, using update thread:
/* Removing entities can only be done safely on the UpdateThread.
* Doing it while updating/drawing can
* cause an exception with a suddenly missing entity.
* Alternatively, there is a possibility to run the TouchEvents on the UpdateThread by default, by doing:
* engineOptions.getTouchOptions().setRunOnUpdateThread(true);
* when creating the Engine in onLoadEngine(); */
this.runOnUpdateThread(new Runnable() {
#Override
public void run() {
/* Now it is save to remove the entity! */
yourEntity.detachSelf()
}
});

Related

Summing a number from a random number source

I'm just starting to learn flink and trying to build a very basic toy example which sums an integer over time and periodically prints the total sum so far
I've created a random number generator source class like this:
// RandomNumberSource.java
public class RandomNumberSource implements SourceFunction<Integer> {
public volatile boolean isRunning = true;
private Random rand;
public RandomNumberSource() {
this.rand = new Random();
}
#Override
public void run(SourceContext<Integer> ctx) throws Exception {
while (isRunning) {
ctx.collect(rand.nextInt(200));
Thread.sleep(1000L);
}
}
#Override
public void cancel() {
this.isRunning = false;
}
}
As you can see, it generates a random number every 1 second
Now how would I go about summing the number that's being generated?
// StreamJob.java
public class StreamingJob {
public static void main(String[] args) throws Exception {
// set up the streaming execution environment
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<Integer> randomNumber = env.addSource(new RandomNumberSource());
// pseudo code:
// randomNumber
// .window(Time.seconds(5))
// .reduce(0, (acc, i) => acc+i) // (initial value, reducer)
// .sum()
// execute program
env.execute("Flink Streaming Random Number Sum Aggregation");
}
}
I've added pseudo code to explain what I'm trying to do. i.e every 5 seconds, perform a sum of all the numbers and print it out.
I feel like I'm missing something in my approach and might need some guidance on how to do this.
window operator is used for keyed streams. You should instead use windowAll for this task. Here's the snippet:
randomNumber
.windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)))
.sum(0)
.print()
.setParallelism(1);
Also check this for reference on various window considerations.

Apache Flinkļ¼šOperator State Checkpoint

I want to use the Operator State API in No-Keyed Stream to save the sate of count in the example below. what should I do?
public static class MapFunction implements MapFunction<String, String>,CheckpointedFunction{
int count = 0;
#Override
public String map(String value) throws Exception {
// TODO Auto-generated method stub
String message;
message = value;
count++;
return message;
}
#Override
public void snapshotState(FunctionSnapshotContext context) throws Exception {
// TODO Auto-generated method stub
}
#Override
public void initializeState(FunctionInitializationContext context) throws Exception {
// TODO Auto-generated method stub
}
}
Thank you for your answer.
As Dawid noted, the docs are a good starting point. The easiest approach would be for you to implement the ListCheckpointed interface. When snapshotState() is called, you'd return a singleton list of your count (as an Integer). When restoreState() is called, you'd iterate over the list of Integer values, and sum them to set your count variable.

Unity prefab array instantiate and destroy

I am having a very little problem in my Unity project but can't find a proper help or way to do. I am stuck at point where I have an array of prefab GameObjects and I am trying to instantiate index 1 GameObject and when it destroyed instantiate the next index. Here is how I am doing it. I have two scripts: One to instantiate and other one to destroy it.
Scripts 1:
public class GameObjectsArray : MonoBehaviour {
public static GameObjectsArray Instance { get; set; }
public GameObject[] Objects;
public int i=0;
// Use this for initialization
void Start()
{
InstiatingMethod();
//Instantiate(Objects[i]);
}
public void InstiatingMethod()
{
Instantiate(Objects[i]);
}
}
Scripts 2:
public class CheckDestroy : MonoBehaviour {
//public GameObject[] Objects;
//int i;
// Use this for initialization
void Start () {
Debug.Log("executed");
//Objects = GameObject.FindGameObjectsWithTag("Player");
//OnMouseDown();
//Instantiate(Objects[i], transform.position, transform.rotation);
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
BoxCollider boxCollider = hit.collider as BoxCollider;
if (boxCollider != null)
{
GameObjectsArray.Instance.i++;
GameObjectsArray.Instance.InstiatingMethod();
Destroy(boxCollider.gameObject);
}
}
}
}
}
So I created a very quick project to make a good response:
Scene Image
In the scene, we will have an empty game object that will contain our script that I called "GameManager", basically this script will do everything, it's more logic to put your logic in one script.
public GameObject[] GameObjects;
private int _targetIndex = -1;
private RaycastHit _hit;
private void Start()
{
InstantiateNextGameObject();
}
public void InstantiateNextGameObject()
{
//if the index is pointing at the last game object in the array, init the index to -1
if (_targetIndex == GameObjects.Length - 1)
_targetIndex = -1;
Instantiate(GameObjects[++_targetIndex]);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out _hit))
{
BoxCollider boxCollider = _hit.collider as BoxCollider;
if (boxCollider != null)
{
InstantiateNextGameObject();
Destroy(boxCollider.gameObject);
}
}
}
}
we will have an array of gameobjects following with the targetIndex which will start from -1.
The function InstantiateNextGameObject() will simply increment targetIndex and then instantiate a gameobject from the array (++targetIndex the first time will be 0, second time 1 etc). We have to check also if the targetIndex reaches the end of the array, put it back to -1.
Then basically what you did in the update, when you click on a gameobject, instantiate the next one and destroy the current.
At the end, you will get something like that:
https://ayoub-gharbi.org/youba_docs/stackoverflow/stackoverflow01.mp4
Feel free to ask me if you didn't understand anything:)
Happy coding!

How to define an array in hadoop partitioner

I am new in hadoop and mapreduce programming and don't know what should i do. I want to define an array of int in hadoop partitioner. i want to feel in this array in main function and use its content in partitioner. I have tried to use IntWritable and array of it but none of them didn't work . I tried to use IntArrayWritable but again it didn't work. I will be pleased if some one help me. Thank you so much
public static IntWritable h = new IntWritable[1];
public static void main(String[] args) throws Exception {
h[0] = new IntWritable(1);
}
public static class CaderPartitioner extends Partitioner <Text,IntWritable> {
#Override
public int getPartition(Text key, IntWritable value, int numReduceTasks) {
return h[0].get();
}
}
if you have limited number of values, you can do in the below way.
set the values on the configuration object like below in main method.
Configuration conf = new Configuration();
conf.setInt("key1", value1);
conf.setInt("key2", value2);
Then implement the Configurable interface for your Partitioner class and get the configuration object, then key/values from it inside your Partitioner
public class testPartitioner extends Partitioner<Text, IntWritable> implements Configurable{
Configuration config = null;
#Override
public int getPartition(Text arg0, IntWritable arg1, int arg2) {
//get your values based on the keys in the partitioner
int value = getConf().getInt("key");
//do stuff on value
return 0;
}
#Override
public Configuration getConf() {
// TODO Auto-generated method stub
return this.config;
}
#Override
public void setConf(Configuration configuration) {
this.config = configuration;
}
}
supporting link
https://cornercases.wordpress.com/2011/05/06/an-example-configurable-partitioner/
note if you have huge number of values in a file then better to find a way to get cache files from job object in Partitioner
Here's a refactored version of the partitioner. The main changes are:
Removed the main() which isnt needed, initialization should be done in the constructor
Removed static from the class and member variables
public class CaderPartitioner extends Partitioner<Text,IntWritable> {
private IntWritable[] h;
public CaderPartitioner() {
h = new IntWritable[1];
h[0] = new IntWritable(1);
}
#Override
public int getPartition(Text key, IntWritable value, int numReduceTasks) {
return h[0].get();
}
}
Notes:
h doesn't need to be a Writable, unless you have additional logic not included in the question.
It isn't clear what the h[] is for, are you going to configure it? In which case the partitioner will probably need to implement Configurable so you can use a Configurable object to set the array up in some way.

Remove duplicate values from the Stack in Java

I made a method that remove any duplicate in the Stack and return the resulting stack sorted in ascending order. For example, look at the main function, it should output as 1, 3, 4, 7. But it outputs the original stack data instead, which is incorrect. Any suggestions?
import java.util.ListIterator;
import java.util.Stack;
public class removeDoubleInStack {
public static Stack<Integer> removeDouble(Stack<Integer> s) {
Stack<Integer> tempStack = new Stack<Integer>();
ListIterator<Integer> iter = s.listIterator();
while(iter.hasNext()) {
int tempNext = iter.next();
if(tempNext != iter.next())
tempStack.add(tempNext);
}
return tempStack;
}
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
s.add(1);
s.add(3);
s.add(3);
s.add(4);
s.add(7);
s.add(7);
removeDouble(s);
System.out.println(s);
}
}
As you can see in the Doc, there is nothing similar to remove duplicates
https://docs.oracle.com/javase/6/docs/api/java/util/Stack.html
but you can do it when:
1- get elements of the stack as Enumeration
2- turn Enumeration into List
3- add list to Set
4- clear stack
5- add set to stack
Example:
final Stack<Integer> ms = new Stack<Integer>();
ms.add(0);
ms.add(0);
ms.add(0);
ms.add(1);
ms.add(1);
ms.add(1);
ms.add(3);
ms.add(56);
System.out.println("Before clean:\n" + ms);
final Set<Integer> s = new HashSet<Integer>(Collections.list(ms.elements()));
ms.clear();
ms.addAll(s);
System.out.println("After clean:\n" + ms);
System.out.println(s) only prints s object that initialized before. removeDouble(s) doesn't have any impact unless you create new object of Stack or reinitialized...
public static void main(String[] args){
Stack<Integer> s = new Stack<Integer>();
s.add(1);
s.add(3);
s.add(3);
s.add(4);
s.add(7);
s.add(7);
Stack<Integer> tempStack = removeDouble(s); // create new object
System.out.println(tempStack);
}

Resources