java – Message handler – Code Review Stack Exchange

The code bellow is code of “Hello” message handler. It works, but I really don’t like as it looks.
The “hello” protocol contains three messages:

  1. client -> server: diffie-hellman client public parameters
  2. server -> client: diffie-hellman server public parameters
  3. client -> server: used data

Could you please review the code. Any comments are welcome.

public class HelloHandler implements Runnable {

    final private static int MSG_TIMEOUT = 5000; // Response receive timeout in milliseconds

    final private static Server server = Server.getInstance();
    final private static Logger logger = server.getLogger();
    final private static ClientsRepository repository = server.getClientsRepository();

    final private static Map<SocketAddress, HelloHandler> handlers = new ConcurrentHashMap<SocketAddress, HelloHandler>();

    final private SocketAddress address;

    private DatagramPacket keyExchange = null;
    private DatagramPacket userData = null;
    private CipherPair ciphers;

     * Handles all hello messages
     * This method runs in context of the main thread (server)
    public static void handle(DatagramPacket packet) {

        SocketAddress address = packet.getSocketAddress();
        byte type = PacketParser.getHeader(packet);

        if (type == DH_EXCH) {  //DH exchange starts

            if (handlers.containsKey(address) || repository.containsKey(address)) {
                logAndSend(REJECT, "Already active", address);

            HelloHandler handler = new HelloHandler(packet);
            handlers.put(address, handler);

        if (type == USER) { //user sent it's data

            HelloHandler handler = handlers.get(address);

            if (handler == null) {
                logAndSend(TIMEOUT, "Timeout", address);



    private HelloHandler(DatagramPacket packet) {
        keyExchange = packet;
        address = packet.getSocketAddress();

    private void handleUser(DatagramPacket packet) {
        if (userData == null)
            userData = packet;

    public void run() {

        DatagramPacket packet;

        try {

            packet = processKeyExchange();

            keyExchange = null; // help GC

            packet = waitForPacket();

            if (!server.isRunning())

            if (packet == null) {
                logAndSend(TIMEOUT, "Timeout", address);

            packet = processUserData();
            if (packet != null)


        } catch (NullPointerException | IOException e) { // we cannot be here
            logger.severe("Hello handler: " + e.getMessage());
        } catch (IllegalMessageException e) {
            logAndSend(ILLEGAL_MSG, e.getMessage(), address);

        } finally {

    private DatagramPacket waitForPacket() {
        // Use the simplest polling
        long timeOutTime = System.currentTimeMillis() + MSG_TIMEOUT;
        boolean timeOut = false;
        while (userData == null && !timeOut && server.isRunning()) {
            try {
            } catch (InterruptedException e) {};
            timeOut = System.currentTimeMillis() >= timeOutTime;
        return userData;

     * Process first message (key exchange) sent by client
     * throws IllegalMessageException if we cannot get public key from message 
    private DatagramPacket processKeyExchange() 
    throws NullPointerException, IOException, IllegalMessageException {

        try {
            Message<DHPublicKeyParams> message = PacketParser.parse(keyExchange, DHPublicKeyParams.class);
            DHPublicKeyParams clientKeyExchangeParams = message.getData();

            SecurityHelper security = SecurityHelper.getInstance();
            DHPublicKeyParams serverKeyExchangeParams = security.getPublicKeyParams();

            ciphers = security.finalizeAggreement(clientKeyExchangeParams);
            return, serverKeyExchangeParams, address);

        } catch (InvalidKeyException | InvalidKeySpecException e) {
            throw new IllegalMessageException(e);

     * Currently it is a dummy method that shows that we can read encrypted data
    private DatagramPacket processUserData() 
    throws NullPointerException, IOException, IllegalMessageException {

        Message<UserData> message = PacketParser.parse(userData, ciphers.getReadCipher(), UserData.class);


        return null;


     * logs error and send response to client 
    private static void logAndSend(byte type, String text, SocketAddress address) {
        logger.warning(buildMessage(text, address));
        server.send(, text, address));

    private static String buildMessage(String text, SocketAddress address) {

        StringBuilder sb = new StringBuilder();
        sb.append("Hello handler: ");
        sb.append(" form: ");

        return sb.toString();



Direct Cache mapping – Computer Science Stack Exchange

Let us assume that we have a machine with $2^{24}$ byte-addressable main memory. The cache size is 4096 bytes, and each cache block contains 16 bytes. Assuming a direct mapped cache:
a. How many blocks of main memory do we have?
b. What is the size of the tag, block, and offset fields?
c. To which cache block will the memory address C12AB16 map?
d. Provide another address that would map to the same block in the cache. The
address should be listed in hexadecimal format.

PRECISE DPLL algorithm definition – Computer Science Stack Exchange

I am confused about the precise definition of the DPLL algorithm. Various sources tend to define DPLL differently:

  1. In pages 110-114 of the book Handbook of Satisfiability(Editors: Biere, A., Heule, M., Van Maaren, H., Walsh, T. Feb 2009. Volume 185 of Frontiers in Artificial Intelligence and Applications) it defines it as backtracking + unit propagation.

Also can be accessed from: (pages 106-110).

  1. In wikipedia:,solving%20the%20CNF%2DSAT%20problem.
    it defines it as backtracking + unit propagation + pure literal elimination.

  2. And in original 1962 paper:
    it mentions 3 rules: one-literal clause rule(unit propagation), affirmitive-negative rule(pure literal elimination) and rule for eliminating atomic formulas(creating resolvents).

Therefore, I am looking for a clear and strict definition of DPLL algorithm. Maybe it should be considered as purely backtracking algorithm and unit propagation and pure literal elimination as its extensions? Or maybe unit propagation is essential part of the algorithm and pure literal elimination is considered to be extention..?

python – HackerRank itertools.combinations() – Code Review Stack Exchange

I was solving the following problem on HackerRank.

Here’s my solution –

from itertools import combinations
a = input()
ls = list(map(str, a.split()))
for i in range(1, int(ls(1))+1):
    ls2 = ()
    ls2 = list(map("".join, combinations(ls(0), i)))
    for elem in ls2:
        ls2(ls2.index(elem)) = "".join(sorted(elem))
    for char in ls2:

But I feel it’s not very efficient as it uses 2 Lists and 2 nested loops.

Any suggestions as to how can I improve the code?

Unity 2019.3 HDRI SkyBox – Game Development Stack Exchange

The legacy cubemap pipeline of dragging six separate textures into a cubemap asset in Unity does not support HDR.

To get HDR (and better filtering as a bonus), you need to import your cubemap as a single image, not as six separate images.

As described in the docs, you need to lay out your 6 views into one image file with one of these arrangements:

Supported cubemap layouts

(I’ve omitted the Equirectangular/LatLong and SphereMap options since they’d require re-projecting your images instead of just pasting them side-by-side).

You can use any image editing software you like to do this arrangement.

Place the resulting single image into your Assets folder, and in its import settings, choose Texture Type: Default, Shape: Cube.

The result will be a Cubemap asset that you can use as your sky.

Exericio de Utilizando pacote Stack com Search em Java

Preciso fazer uma opção utilizando o Search do pacote Stack do Java, aonde o search ira pesquisar um valor digitado pelo usuário e dizer se ele está ou não na lista, se ele estiver, precisa mostrar o valor que está logo a baixo dele na pilha.
O modo que estou fazendo não está dando, pois o pilha.get(indice) ira mostrar o indice da ordem em que a pilha foi colocada, e não o indice em que foi encontrado usando o search

 case 6 :    if ( pilha.empty() ) {
                                System.out.println("n==> Pilha Vazia");
                                System.out.println("nDigite um valor para buscar: ");
                                valor1 =;
                                indice = valor1 );
                                if ( indice > 0 ) {
                                    for (int i = 0; i < 1; i++) {
                                        System.out.println("Valor: "+pilha.get(indice)); 
                                }else {
                                    System.out.println("Este valor não está presente na pilha.");

python: subprocess opening filles – Code Review Stack Exchange

I am using 2 functions written in python to convert DLG file to PDB energies

import glob
import os
import subprocess
import numpy as np
from vmd import vmdnumpy as vnp
from vmd import Molecule
from vmd import atomsel

def dlg_to_multiframepdb(fname):
        inputstrings = subprocess.check_output("grep "DOCKED:" %s" % fname, shell=True).decode().split("n")
        output = ""
        for s in inputstrings:
                if s(8:12) == "ATOM" or s(8:12) == "HETA":
                        output += s(8:) + "n"
                elif s(8:14) == "ENDMDL":
                        output += "ENDMDLn"
        return output
def dlg_to_energy(fname):
        inputstrings = subprocess.check_output("grep "Estimated" %s | sed 's/=//g' | awk '{print $8}'" % fname, shell=True).decode().split("n")(:-1)
        energies = np.array(inputstrings).astype(np.float)
        return energies

# simple code: loop over the directory of DLG filles and convert each file to PDB
pwd = os.getcwd()
dlg= 'dlg'
#set directory to analyse
data = os.path.join(pwd,dlg) 

dirlist = (os.path.basename(p) for p in glob.glob(data + '/*.dlg'))
for dlg_file in dirlist: 
      energies = dlg_to_energy(dlg_file)
      pdb = dlg_to_multiframepdb(dlg_file)

Briefly, the first function take some part from the initial file using shell utility GREP, skipping some unused strings; and the second function – use GREP + SED to take specific strings from the same file and store it as numpy array. How the code could be further improved?

Quarantine Enforcement – Travel Stack Exchange

I will be moving from Italy to Norway for work reasons at the beginning of next year and, at the moment, a 10 days quarantine is requested to enter the country. The website specifies that quarantine can be implemented at a suitable place of residence provided by the Norwegian employer (instead of a covid hotel). Since my wife will move with me (at the same time, on the same flight), I am wondering if she will too be allowed to spend the quarantine in the residence provided by my employer.

Has anyone some information on this? More generally, has any EU citizen travelled with the family to Norway in the last couple of weeks?

Canon Powershot Lens Error – Photography Stack Exchange

I have a Canon Powershot Camera SD1400 IS camera. It accidentally got dropped, and is now giving a Lens Error. 🙁

When I turn it on, it attempts to bring the lens out, but then retracts and says the following text:

Lens Error
Will shut down automatically
Restart Camera

In desperation, I looked at this question, and followed as many of the tips as possible. The only tip that gave any result was number 2, which says this:

Try pressing and holding the Menu, Function, Function Set, or OK while turning on the camera, or otherwise find a “factory reset” option.

On my camera, I pressed the func button and the on button, and then got this screen:

enter image description here

For those who wonder what it is, it’s just showing the time three minutes behind. When I press the left button on my camera, it changes the background color to the next color on the wheel. When I press right, it, again, changes the background color on the screen.

So what is going on here? Where is the factory reset button? Any help would be deeply appreciated, as this camera was a gift for me when I was 3. It wasn’t even me who dropped it.

Not a dupe. I explain why in the question body.

Also not a dupe. My camera lens, as explained, doesn’t stay outside. Instead, it tries to get out, but then retracts.