Why is my diffuse illumination calculated wrongly in Java?

The equations I use for L, V and R are these:

Vector3 L = (P.subtract(light.getPosition())).normalised();
Vector3 V = P.subtract(O).normalised();
Vector3 R = L.normalised().reflectIn(N.normalised()).normalised();

ColorRGB diffuse = C_diff.scale(k_d).scale(I);
double N_dot_L = N.normalised().dot(L.normalised());
N_dot_L = Math.max(0.0, N_dot_L);
diffuse = diffuse.scale(N_dot_L);

ColorRGB specular = C_spec.scale(k_s).scale(I);
double R_dot_V = R.normalised().dot(V.normalised());
R_dot_V = Math.pow(Math.max(0.0, R_dot_V), alpha);
specular = specular.scale(R_dot_V);

Where

  • L is the light direction vector from the light source to object
  • V is the direction vector from object to camera
  • R is the reflected ray direction vector, which is opposite of L about the normal to a surface
  • C_diff and C_spec and alpha are constants in the equation

Unfortunately, SO does not let me post my picture so I can only include it in a link (see below).
Image of Equation

As this is a major project I’m unable to see why my implementations are wrong when I follow so closely to the equation. I’ve narrowed down the source of error to this code snippet and hope someone can tell me where my code went wrong.

I can’t seem to find the error as it follows the equation exactly.

How to configure Jackson to deserialize List containing named types marked with @JsonTypeName?

I have researched for the best way to implement Objects classes with inheritance and contained within an object as a List.

If you know any link which handles the scenario and provides the correct answer I will be happy to accept this as duplicate and close this item.
I have following classes:

Zoo

import com.model.DefaultZoo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
import lombok.*;
@Getter
@Setter
@Builder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
    public class Zoo extends DefaultZoo{
        private String zooName;
        private String zooLocation;
        @JsonInclude(JsonInclude.Include.NON_EMPTY)
        private @Singular List<Animal> animals;

}

Animal

@Getter
@Setter
@Builder(builderMethodName = "parentBuilder")
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(
    use = JsonTypeInfo.Id.NONE,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type",
    defaultImpl = Animal.class
)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Dog.class, name = "dog"),
    @JsonSubTypes.Type(value = Elephant.class, name = "elephant")
})
public class Animal{
    private String type;
    private String nameTag;
}

Dog

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
@JsonPropertyOrder({ "type", "nameTag"})
@JsonTypeName("dog")
public class Dog {
    private String barkingPower;
}

Elephant

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
@JsonPropertyOrder({ "type", "nameTag"})
@JsonTypeName("elephant")
public class Elephant{
    private String weight;
}

ModelHelper

public final class ModelHelper {
    private static final ObjectMapper MAPPER = new ObjectMapper();        
        .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)        
        .setSerializationInclusion(JsonInclude.Include.NON_NULL)    
        .enableDefaultTypingAsProperty(
            ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT,    "type");
    public static <T> T fromJson(@NotNull final String json, final Class<T> objectClass) {
    try {
        return MAPPER.readValue(json, objectClass);
    } catch (Exception e) {
        final String message = String.format("Error de-serialising JSON '%s' to object of %s",
                json, objectClass.getName());
            log.warn(message, e);
        return null;
    }
}
}

And I am using the ModelHelper to deserialize the JSON to an Object:

String json = "{"zooName":"Sydney Zoo","zooLocation":"Sydney","animals":[{"type":"dog","nameTag":"Dog1","barkingPower":"loud"},{"type":"elephant","nameTag":"Elephant1","weight":"heavy"}]}";
mapper.readValue(json, Zoo.class);

My Questions are:

  1. Currently the deserilization of Zoo only comes back with Animal attributes and not with Dog or Elephant attributes.
  2. What I can gather is deserialization is not working because the getter in Zoo List is of base class type and deserilaizaiton is not able to work out how to create a Dog or Zoo and based on signature it generates Animal. But I would have thought that by putting JsonTypeName and JsonSubTypes annotation I have marked the relevant subclasses.
  3. Does Animal class has to be defined as Abstract for this to work.
  4. Is the Only way to get this to work is to implement Custom deserilization? Is this a good example to follow: https://www.sghill.net/how-do-i-write-a-jackson-json-serializer-deserializer.html

Let me know if the code is not clear and I can fix it.

Thanks in advance.

I am trying to insert records in mysql table from java and keep getting error message

private static void insertData(Connection conn) throws SQLException {

      String insertsql = "INSERT INTO ng_users(username, password) VALUES (?,?)";
      PreparedStatement ps=(PreparedStatement) conn.prepareStatement(insertsql);

      for(int i = 0; i < temps.size(); i++)
      {
          String[] data= temps.get(i).trim().split(Pattern.quote("|"));
          ps.setString(1, data[0].toString());
          ps.setString(2, data[1].toString());
          ps.executeUpdate(insertsql);     
      }   
}

error msg: “You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘?,?)'”

How to shuffle a simple array

I’ve googled this question all day yesterday and still can’t get an idea on how to do what I need. Basically, I’ve declared an integer array and, to make it simple, it only has three elements from 0 to 2. All i need to do is shuffle them 100,000 times. Here’s my unfinished code. I know I need to make a for loop and import java.util.Random, however I have no clue what to do under the for loop. Again, I need it to shuffle 100,000 times. Thanks for all the help!

int [] arrayTest = new int [3];
arraytest[0] = 0;
arraytest[1] = 1;
arraytest[2] = 2;

//for loop goes here

System.out.println(arrayTest[0] + arrayTest[1] + arrayTest[2]);

Change the insertAfter method so that it will not attempt to insert a node after a null node

public void insertAfter(Node newNode, Node prev){

if(head == null)
    {
        System.out.println("'InsertAfter' is not possible.");
        return;
    }
else
{
        newNode.setNext(prev.next());
              prev.setNext(newNode);
}

I need to change the insertAfter method so that it will not attempt to insert a node after a null node, i.e. if insertAfter(n1, n2) is called, where n2 is null. This my current code and I am unsure of what to do.

How to prevent an outside application from running

Lately I’ve been using the program Cold Turkey a fair amount, however the program lacks a fair bit of functionality I would like to have. The primary function of Cold Turkey is that it can block other programs (and websites) from running during focus times. Basically, I’d like to make my own version of this software for myself, but at the same time I don’t know how to prevent a program from running (or alternatively stop it immediately after it opens). I’ve tried searching the internet for an answer, but I found litte useful information. If anyone has tried something similar, or has any ideas, any help would be much appreciated. I would love to make this question less open ended, but I simply don’t have enough knowledge on this topic to do so. I’m familiar with Java, C#, Python, and this is on a Windows 10 machine.

What does object.super() do? How to creating a State?

So I have this code:

public class A {
    private State _state;

    public abstract class State {
        protected void setState(State newState) {
            _state = newState;
        }
    }

    public A() {
        _state = new AbstractState(this);
    }
}

public abstract class AbstractState extends A.State {
    AbstractState(A a) {
        a.super();
    }
}

And I’m having a hard time understanding how it works.

So when a A object is created it creates a AbstractState object with that same A object as a parameter. And the AbstractState constructor, which receives that A object, calls a.super().

From my understanding, a.super() calls the construtor of the super class of A a, which is Object, right? So what’s the point?

I know that AbstractState is an abstract class. A subclass could be:

public class StateOne extends AbstractState {
    StateOne(A a) {
        super(a);
    }
}

The question remains though.

How to return a variable from Google Scripts to Android?

I’m trying to write an Android app that uses the Google Script Execution API to fetch data from a server, but I can’t even get so far as writing a script that returns anything at all to my application, even though the function is being called in the exact way as google’s Android Quickstart demonstration shows me, and I’ve written the function according to how anything I’ve found online says that I should. What am I doing wrong?

Here’s the function (Just a test function):

function login(username,password) { return ContentService.createTextOutput("Hello");}

Here’s what I seem to be getting back from the server:
enter image description here

(The very bottom is where I should be able to browse through the returned HashMap of strings from the google scripts function, which I’ve been able to do with the aforementioned Quickstart app which returns a list of the names of all of my folders on google drive and works successfully every time)

Thanks so much for any help you can provide!!!

Java XML manipulation

I have an XML file which I need to traverse from the top to the bottom going through all nodes one by one, to set my text fields with relevant values needed in the node. I’m expecting a simple solution method.

How to search by an object in springboot

In springboot you can have a repository that extends JpaRepository<User, String>

Now if you want to write a query to that repository, you can write multiple findBy queries such as:

User findByUsername(String username);
User findByFirstName(String firstName);
User findByFirstNameAndLastName(String firstName, String lastName);

then you need matching controllers like:

@RequestMapping(value = "/users/{username}" , method = RequestMethod.GET)
public @ResponseBody List<User> getUser(@PathVariable("username") String username) {
    return userService.findByUsername(username);
}

etc, etc…

I don’t want to have to write every single findBy for each combination of elements and create all the matching controllers like that.

So what I want to know is how you can search by a whole object. For example posting something like

{
"username":"freddy"
}

will search by username and equally

{
"firstName":"Fred",
"lastName":"Doe"
}

will search by first and last name.

Is there a way to write both a JpaRepository method and a controller that can take a (in this case) User object with any combination of fields, and perform a search for that?

Thanks.