vrijdag 31 januari 2025

Copilot / AI werkt heel goed!

Copilot oftewel Artificial Intelligence werkt erg goed tegenwoordig. Ik stel de volgende vraag:

"How to determine the byte position of an element in a C struct"

Vroeger kon je het vergeten dat je antwoord kreeg via Google. Tegenwoordig krijg je het antwoord:

#include <stdio.h>
#include <stddef.h> // For offsetof macro

struct MyStruct {
    int a;
    float b;
    char c;
};

int main() {
    // Calculate and print the offset of each member
    printf("Offset of 'a': %zu bytes\n", offsetof(struct MyStruct, a));
    printf("Offset of 'b': %zu bytes\n", offsetof(struct MyStruct, b));
    printf("Offset of 'c': %zu bytes\n", offsetof(struct MyStruct, c));

    return 0;
}

En daarmee kon ik mijn oplossing gemakkelijk programmeren:
int theOffset = offsetof(SDL_KeyboardEvent, scancode);

AI werkt goed!

donderdag 30 januari 2025

C#: anonymous lambda using class instance variable

In C#, you can write an anonymous lambda which uses an instance variable of the class you are using:

Hello hello = new Hello();
hello.methodToCall((self) =>
{
    Console.WriteLine("hallo " + self.numberToReach);
});

public class Hello
{
    public int numberToReach = 3;
    public void methodToCall(Action<Hello> operation)
    {
        operation(this);
    }
}

In Kotlin, the Hello instance is bound to this, which is nice (see my trailing lambda's post). In C#, the "this" needs to be transferred using a parameter, in this case called "self".

woensdag 29 januari 2025

Easy pagination with Spring JPA - Hibernate

*****************************
File Main
*****************************
for (theUser in userService.getUsersByClassification("Class 1", pageNr = 0, pageSize = 10)) {
	println(theUser.displayName)
}


*****************************
File UserService
*****************************
@Service
class UserService @Autowired constructor(private val userPaging: UserPagingAndSortingRepository) {
    fun getUsersByClassification(classification: String, pageNr: Int, pageSize: Int): Page<User> {
        val pageable: Pageable = PageRequest.of(pageNr, pageSize)
        return userPaging.findByClassification(classificatie, pageable)
    }
}


*****************************
File UserPagingAndSortingRepository
The Query annotation is JPQL, but in the case of JPA Hibernate, can also be HQL.
*****************************
interface UserPagingAndSortingRepository : PagingAndSortingRepository<User, Long> {
    @Query("SELECT u FROM User u JOIN u.userExtradata um WHERE um.classification = :classification")
    fun findByClassification(@Param("classification") classification: String, pageable: Pageable): Page<User>
}


*****************************
File entity.User
*****************************
@Entity
@Table(name = "\"user\"")
class User {
    @Id
    var id: Long = 0;

    @Column (name="display_name")
    var displayName: String = ""

    @OneToOne(mappedBy = "user", cascade = [CascadeType.ALL], fetch = FetchType.LAZY)
    val userExtradata: UserExtradata? = null
}


*****************************
File entity.UserExtradata
*****************************
@Entity
@Table(name = "\"user_extradata\"")
class UserExtradata {
    @Id
    var user_id: Long = 0;
    var classification: String = ""
    var phonenumber: String? = ""

    @OneToOne
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    val user: User? = null
}

Trailing lambda's in Kotlin

In Kotlin, you can do things like:


class Hello {
    val secretValue = 1;
    fun trailingLambda(trail: Hello.() -> Unit = {}) { trail() }
}

fun main() {
  val hallo: Hello = Hello()
  hallo.trailingLambda { println("trailingLambda ${this.secretValue}") }
}

Read more here.

dinsdag 14 januari 2025

Iterator in javascript

const myArray = [1, 2, 3];
const iterator = myArray[Symbol.iterator]();

for (const value of myArray) {
  console.log(value); // Outputs: 1, 2, 3
}


class MyCollection {
  constructor(items) {
    this.items = items;
  }

  [Symbol.iterator]() {
    let index = 0;
    const items = this.items;

    return {
      next() {
        if (index < items.length) {
          return { value: items[index++], done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
}

let tmp3 = new MyCollection([1,2,3,4,5]);
for (const value of tmp3) {
  console.log(value);
}

Ofcourse you don't have the typechecking that typescript has:
function getValue<T extends keyof {yoho: string, "ho"?: number}>(item: T) {
	return item;
}
console.log(getValue<"ho">("ho"));

donderdag 9 januari 2025

Spring-boot GetMapping and PostMapping parameters

What kind of parameters are possible on a GetMapping and PostMapping annotated method in Spring-Boot?

@GetMapping("/group/{groupid}/removeuser/{userid}")
suspend fun removeGroupUserById(@PathVariable groupid: Long, @PathVariable userid: Long) : ResponseEntity<Any> { code.. }

There are the following possibilities:
@PathVariable groupid: Long
@RequestParam name: String?
request: HttpServletRequest
@RequestBody group: GroupDTO