How to initialize a variable twice? - variables

I'm trying to initialize a variable twice in 2 different functions without the second initialization having effect on the first.
float X;
void setup()
{
size(400, 400);
background(255);
}
void draw()
{
Rect1();
Rect2();
}
void Rect1()
{
fill(255,0, 0);
rect(X, 20, 40, 40);
X=20;
}
void Rect2()
{
fill(0, 255, 0);
rect(X, 200, 40, 40);
X=50;
}

You code seems to be "demonstration" code, but it doesn't really do anything significant other than show that you probably need to first sit down and learn a bit about Processing before you continue - hit up processing.org and run through some of the tutorials. It's worth it.
The code you gave can be written much more sensibly, but instead I'll answer the question; Processing uses a variation on Java's scoping rules: a local variable trumps an object instance variable, which trumps a global variable:
int x = 0;
int y = 50;
class Thing {
int y = 10;
Thing() {
// x is global, y is global and object instance
println("x (in Thing): "+x);
println("y (in Thing): "+y);
declareAndCheck();
}
void declareAndCheck() {
// now we make some local variables: they win.
int x = 40;
int y = 100;
println("x (local declared): "+x);
println("y (local declared): "+y);
}
}
void setup() {
println("x (global): "+x);
println("y (global): "+y);
Thing t = new Thing();
// and global is still global
println("x (global, again): "+x);
println("y (global, again): "+y);
}
This will generate the following output:
x (global): 0
y (global): 50
x (in Thing): 0
y (in Thing): 10
x (local declared): 40
y (local declared): 100
x (global, again): 0
y (global, again): 50
Why? First we see this:
x (global): 0
y (global): 50
because x and y are global variables with values 0 and 50. Simple enough. then we see:
x (in Thing): 0
y (in Thing): 10
because in the "Thing" object, we have an object instance variable 'y', which wins the naming conflict between it, and the global variable.
Then we enter declareAndCheck, where we see:
x (local declared): 40
y (local declared): 100
because we now have a global x, and a local x, and local always wins, and we have an instance y, and a local y, and again local always wins.
Finally we print x and y in global context again, and because there is no conflict, we see:
x (global, again): 0
y (global, again): 50
And if that did not make sense to you, run through those tutorials, they teach you programming in Processing =)

Related

How to do multiple variable assignments in one line in Kotlin like C,C++?

I had to swap 2 numbers in one line expression using no other variable except x and y.
So I wrote the following .c program to swapp two numbers with the given conditions and it works like charm.
int main() {
int x =5, y =2;
x = y-x+(y=x);
printf("X=%d, y=%d", x, y);
return 0;
}
But when i try to do the same in kotlin it gives me an error that
Assignments are not expressions, and only expressions are allowed in
this context,
I can resolve this issue by introducing a third variable just like this. But I'm not allowed to have any other variable except x and y which are already given. So is there any other way I can do this in one line using any kotlin property?
Below is the kotlin program
fun main() {
var x = 5
var y = 10
x = y-x+(y=x)
println("X = $x, Y = $y")
}
While I have two suggestions below, I want to start with a recommendation against either of them, at least in this simple example.
It's usually a lot more clear to optimise code for developers to read in the following ways:
create an extra variable with a descriptive name
prefer val over var to avoid accidental mutations
and try to make the code 'linear', so the operations can be read from top-to-bottom without jumping between functions
avoid code that needs an IDE to see what the type-hints are
And I'll trust that the compiler will make make the code performant.
fun main() {
val x = 5
val y = 10
val newX = y
val newY = x
println("X = $newX, Y = $newY")
}
Local function
You could use a local function to perform the swap, as the function will still be able to access the original values.
fun main() {
var x = 5
var y = 10
fun swap(originalX: Int, originalY: Int) {
y = originalX
x = originalY
}
swap(x, y)
println("X = $x, Y = $y")
}
Scope function
This could be code-golfed into one line
use to to create a Pair<Int, Int>,
and a scope function to use the result.
fun main() {
var x = 5
var y = 10
(x to y).apply { x = second; y = first }
println("X = $x, Y = $y")
}
One line? Yes. More difficult to read? I think so.

Is write_image atomic? Is it better to use atomic_max?

Full disclosure: I am cross-posting from the kronos opencl forums, since I have not received any reply there so far:
https://community.khronos.org/t/is-write-image-atomic-is-it-better-than-atomic-max/106418
I’m writing a connected components labelling algorithm for images (2d and 3d); I found no existing implementations and decided to write one based on pointer jumping and a “recollection step” (btw: if you are aware of an easy-to-use, production ready connected component labelling let me know).
The “recollection” step kernel pseudocode for 2d images is as follows:
1) global_id = (x,y)
2) read v from img[x,y], decode it to a pair (tx,ty)
3) read v1 from img[tx,ty]
4) do some calculations to extract a boolean value C and a target value T from v1, v, and the neighbours of (x,y) and (tx,ty)
5) *** IF ( C ) THEN WRITE T INTO (tx,ty).
Q1: all the kernels where “C” is true will compete for writing. Suppose it does not matter which one wins (writes last). I’ve done some tests on an intel GPU, and (with filtering disabled, and clamping enabled) there seems to be no issue at all, write_image seems to be atomic, there is a winning value and my algorithm converges very fast. Can I safely assume that write_image on “unfiltered” images is atomic?
Q2: What I really need is to write into (tx,ty) the maximum T obtained from each kernel. That would involve using buffers instead of images, do clamping myself (or use a larger buffer padded with zeroes), and ** using atomic_max in each kernel**. I did not do this yet out of laziness since I need to change my code to use a buffer just to test it, but I believe it would be far slower. Am I right?
For completeness, here is my actual kernel (to be optimized, any suggestions welcome!)
```
__kernel void color_components2(/* base image */ __read_only image2d_t image,
/* uint32 */ __read_only image2d_t inputImage1,
__write_only image2d_t outImage1) {
int2 gid = (int2)(get_global_id(0), get_global_id(1));
int x = gid.x;
int y = gid.y;
int lock = 0;
int2 size = get_image_dim(inputImage1);
const sampler_t sampler =
CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;
uint4 base = read_imageui(image, sampler, gid);
uint4 ui4a = read_imageui(inputImage1, sampler, gid);
int2 t = (int2)(ui4a[0] % size.x, ui4a[0] / size.x);
unsigned int m = ui4a[0];
unsigned int n = ui4a[0];
if (base[0] > 0) {
for (int a = -1; a <= 1; a++)
for (int b = -1; b <= 1; b++) {
uint4 tmpa =
read_imageui(inputImage1, sampler, (int2)(t.x + a, t.y + b));
m = max(tmpa[0], m);
uint4 tmpb = read_imageui(inputImage1, sampler, (int2)(x + a, y + b));
n = max(tmpb[0], n);
}
}
if(n > m) write_imageui(outImage1,t,(uint4)(n,0,0,0));
}
```

In Rust, what's the difference between "shadowing" and "mutability"?

In Chapter 3 of the Rust Book, Variables and Mutability, we go through a couple iterations on this theme in order to demonstrate the default, immutable behavior of variables in Rust:
fn main() {
let x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
}
Which outputs:
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:5
|
2 | let x = 5;
| -
| |
| first assignment to `x`
| help: make this binding mutable: `mut x`
3 | println!("The value of x is {}", x);
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
However, because of Rust's take on shadowing variables, we can simply do this to change the value of the nonetheless "immutable" x:
fn main() {
let x = 5;
println!("The value of x is {}", x);
let x = 6;
println!("The value of x is {}", x);
}
Which outputs (skipping the details):
The value of x is 5
The value of x is 6
Funnily enough, this code also produces the above pair of lines as output, despite the fact that we don't call let but instead mut the first time x is bound to 5:
fn main() {
let mut x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
}
This ambiguity in how variables are (not really) protected from reassignment seems contrary to the stated goal of protecting the values bound to immutable - by Rust default - variables. From the same chapter (which also contains the section Shadowing):
It’s important that we get compile-time errors when we attempt to
change a value that we previously designated as immutable because this
very situation can lead to bugs. If one part of our code operates on
the assumption that a value will never change and another part of our
code changes that value, it’s possible that the first part of the code
won’t do what it was designed to do. The cause of this kind of bug can
be difficult to track down after the fact, especially when the second
piece of code changes the value only sometimes.
In Rust, the compiler guarantees that when you state that a value
won’t change, it really won’t change. That means that when you’re
reading and writing code, you don’t have to keep track of how and
where a value might change. Your code is thus easier to reason
through.
If I can cause this important feature of my immutable x to be side-stepped with an innocent enough call to let, why do I need mut? Is there some way to really, seriously-you-guys make x immutable, such that no let x can reassign its value?
I believe the confusion is because you're conflating names with storage.
fn main() {
let x = 5; // x_0
println!("The value of x is {}", x);
let x = 6; // x_1
println!("The value of x is {}", x);
}
In this example, there is one name (x), and two storage locations (x_0 and x_1). The second let is simply re-binding the name x to refer to storage location x_1. The x_0 storage location is entirely unaffected.
fn main() {
let mut x = 5; // x_0
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
}
In this example, there is one name (x), and one storage location (x_0). The x = 6 assignment is directly changing the bits of storage location x_0.
You might argue that these do the same thing. If so, you would be wrong:
fn main() {
let x = 5; // x_0
let y = &x; // y_0
println!("The value of y is {}", y);
let x = 6; // x_1
println!("The value of y is {}", y);
}
This outputs:
The value of y is 5
The value of y is 5
This is because changing which storage location x refers to has absolutely no effect on the storage location x_0, which is what y_0 contains a pointer to. However,
fn main() {
let mut x = 5; // x_0
let y = &x; // y_0
println!("The value of y is {}", y);
x = 6;
println!("The value of y is {}", y);
}
This fails to compile because you cannot mutate x_0 while it is borrowed.
Rust cares about protecting against unwanted mutation effects as observed through references. This doesn't conflict with allowing shadowing, because you're not changing values when you shadow, you're just changing what a particular name means in a way that cannot be observed anywhere else. Shadowing is a strictly local change.
So yes, you absolutely can keep the value of x from being changed. What you can't do is keep what the name x refers to from being changed. At most, you can use something like clippy to deny shadowing as a lint.

Sprite Smooth movement and facing position according to movement

i'm trying to make this interaction with keyboard for movement using some sprites and i got stuck with two situations.
1) The character movement is not going acording to the animation itself (it only begin moving after one second or so while it's already being animated). What i really want it to do is, to move without a "initial acceleration feeling" that i get because of this problem
2) I can't think of a way to make the character face the position it should be facing when the key is released. I'll post the code here, but since it need images to work correctly and is not so small i made a skecth available at this link if you want to check it out: https://www.openprocessing.org/sketch/439572
PImage[] reverseRun = new PImage [16];
PImage[] zeroArray = new PImage [16];
void setup(){
size(800,600);
//Right Facing
for(int i = 0; i < zeroArray.length; i++){
zeroArray[i] = loadImage (i + ".png");
zeroArray[i].resize(155,155);
}
//Left Facing
for( int z = 0; z < reverseRun.length; z++){
reverseRun[z] = loadImage ( "mirror" + z + ".png");
reverseRun[z].resize(155,155);
}
}
void draw(){
frameRate(15);
background(255);
imageMode(CENTER);
if(x > width+10){
x = 0;
} else if (x < - 10){
x = width;}
if (i >= zeroArray.length){
i = 3;} //looping to generate constant motiion
if ( z >= reverseRun.length){
z = 3;} //looping to generate constant motiion
if (isRight) {
image(zeroArray[i], x, 300);
i++;
} //going through the images at the array
else if (isLeft) {
image(reverseRun[z],x,300);
z++;
} going through the images at the array
else if(!isRight){
image(zeroArray[i], x, 300);
i = 0; } //"stoped" sprite
}
}
//movement
float x = 300;
float y = 300;
float i = 0;
float z = 0;
float speed = 25;
boolean isLeft, isRight, isUp, isDown;
void keyPressed() {
setMove(keyCode, true);
if (isLeft ){
x -= speed;
}
if(isRight){
x += speed;
}
}
void keyReleased() {
setMove(keyCode, false);
}
boolean setMove(int k, boolean b) {
switch (k) {
case UP:
return isUp = b;
case DOWN:
return isDown = b;
case LEFT:
return isLeft = b;
case RIGHT:
return isRight = b;
default:
return b; }
}
The movement problem is caused by your operating system setting a delay between key presses. Try this out by going to a text editor and holding down a key. You'll notice that a character shows up immediately, followed by a delay, followed by the character repeating until you release the key.
That delay is also happening between calls to the keyPressed() function. And since you're moving the character (by modifying the x variable) inside the keyPressed() function, you're seeing a delay in the movement.
The solution to this problem is to check which key is pressed instead of relying solely on the keyPressed() function. You could use the keyCode variable inside the draw() function, or you could keep track of which key is pressed using a set of boolean variables.
Note that you're actually already doing that with the isLeft and isRight variables. But you're only checking them in the keyPressed() function, which defeats the purpose of them because of the problem I outlined above.
In other words, move this block from the keyPressed() function so it's inside the draw() function instead:
if (isLeft ){
x -= speed;
}
if(isRight){
x += speed;
}
As for knowing which way to face when the character is not moving, you could do that using another boolean value that keeps track of which direction you're facing.
Side note: you should really try to properly indent your code, as right now it's pretty hard to read.
Shameless self-promotion: I wrote a tutorial on user input in Processing available here.

Netbeans:get the X and Y co ordinate

I have an image in the jlabel. I want to get the X and Y co-ordinate when ever it is clicked on. I used the following code:
private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
f = jLabel2.getMousePosition();
m = new Point(f).toString();
}
And I got the output:
java.awt.Point[x=165,y=105]
But I don't know how take the x and y separately.
The point class two public fields which are x and y. You can access them through your instance variable.
You do the following. int x1 = m.x; int y1 = m.y.
if you need extra information and some useful methods, read the Java Api.
http://docs.oracle.com/javase/7/docs/api/java/awt/Point.html