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);
                return;
            }

            HelloHandler handler = new HelloHandler(packet);
            handlers.put(address, handler);
            server.getExecutor().execute(handler);
            return;
        }

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

            HelloHandler handler = handlers.get(address);

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

            handler.handleUser(packet);
        }

    }

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

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

    @Override
    public void run() {

        DatagramPacket packet;

        try {

            packet = processKeyExchange();
            server.send(packet);

            keyExchange = null; // help GC

            packet = waitForPacket();

            if (!server.isRunning())
                return;

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

            packet = processUserData();
            if (packet != null)
                server.send(packet);

            return;

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

        } finally {
            handlers.remove(address);
        }
    }

    private DatagramPacket waitForPacket() {
        
        // Use the simplest polling
        long timeOutTime = System.currentTimeMillis() + MSG_TIMEOUT;
        boolean timeOut = false;
        
        while (userData == null && !timeOut && server.isRunning()) {
            try {
                Thread.sleep(100);
            } 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 PacketBuilder.build(DH_EXCH, 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);

        System.out.println(message.getData().toString());
        repository.put(message.getData());

        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(PacketBuilder.build(type, text, address));
    };

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

        StringBuilder sb = new StringBuilder();
        sb.append("Hello handler: ");
        sb.append(text);
        sb.append(" form: ");
        sb.append(Util.sockAddrToString(address));

        return sb.toString();

    }

}

performance – How to make my code with for/if loop more efficient in R

My code is structured so that I create an ellipse through my first three points of data. Then I go through each next row, and if the point falls outside the ellipse, I record the minimum distance between the point and ellipse. These points have datetime associated with it so I can only keep points 10 minutes old in my ellipse (so it doesn’t get too big). The code works great until I have to process 100K+ of observations. Then the process time goes from minutes to hours. My question is, is there any part of my for loop portion of code that I can restructure to cut process time? I vectorized what I could (I think), and I know taking conditions out of for loop helps but now sure how to do it. Code below for reference. Any help is greatly appreciated.

library(sp)
library(cluster)
#create new empty column in dataframe
df$Distances <- NA

#get first three points and fit an ellipse around it
FlashPoints <- cbind(df$Lat(1:3),df$Long(1:3))
EllipseShape <- ellipsoidhull(FlashPoints)
EllipseShape

#get set of points that represent ellipse
EllipsePoints <- predict(EllipseShape)
EllipseGroup <- cbind(EllipsePoints(,2),EllipsePoints(,1))

#function to check if the next flashpoint (xp, yp) belongs to the ellipse with parameters a,b,... with tolerance eps
onEllipse <- function (xp, yp, a, b, x0, y0, alpha, eps=1e-3) {
  return(abs((cos(alpha)*(xp-x0)+sin(alpha)*(yp-y0))^2/a^2+(sin(alpha)*(xp-x0)-cos(alpha)*(yp-y0))^2/b^2 - 1) <= eps)
} 

#function to check if the point (xp, yp) is inside the ellipse with parameters a,b,...
insideEllipse <- function (xp, yp, a, b, x0, y0, alpha) {
  return((cos(alpha)*(xp-x0)+sin(alpha)*(yp-y0))^2/a^2+(sin(alpha)*(xp-x0)-cos(alpha)*(yp-y0))^2/b^2 <= 1)
}

#loop from row 4 to last row
for (i in 4:nrow(df)){

#get location of next point
nextFlash <- cbind(df$Long(i),df$Lat(i))

#Establish/Re-establish parameters
xp <- df$Lat(i)
yp <- df$Long(i)
x0 <- EllipseShape$loc(1) # centroid locations
y0 <- EllipseShape$loc(2)
eg <- eigen(EllipseShape$cov)
axes <- sqrt(eg$values)
alpha <- atan(eg$vectors(1,1)/eg$vectors(2,1)) # angle of major axis with x axis
a <- sqrt(EllipseShape$d2) * axes(1)  # major axis length
b <- sqrt(EllipseShape$d2) * axes(2)  # minor axis length


#Check to see if next point is outside the ellipse, then get distance. If it is, add to distance list
if((insideEllipse(xp, yp, a, b, x0, y0, alpha)==FALSE) && onEllipse(xp, yp, a, b, x0, y0, alpha)==FALSE){
  nextDist <- min(spDistsN1(EllipseGroup, nextFlash, longlat = TRUE))
  df$Distances(i) <- nextDist
    
#Omit points 10 minutes old from group
  movingGroup <- subset(df(1:i,), difftime(df$DateTime(1:i),df$DateTime(i),units = "mins")<10)
  movingTstorm
  FlashPoints <- cbind(movingGroup$Lat(1:i),movingGroup$Long(1:i))
  FlashPoints
  
  #Fit an ellipse around flashpoints
  EllipseShape <- ellipsoidhull(FlashPoints)
  EllipseShape
  
  #Get set of points that make an ellipse
  EllipsePoints <- predict(EllipseShape)
  EllipseGroup <- cbind(EllipsePoints(,2),EllipsePoints(,1))
} 
  
next(i)
}
}
```

post thumbnails – use my custom code in woocommerce product image

I want to use my custom code in woocommerce products gallery image , I have done that before for a simple gallery but this time my code is little more professional and i want use the tag in woocommerce products gallery , here is the code:

<div class="product-gallery">
                            <span class="badge">Offer</span>
                            <div class="product-carousel owl-carousel">
                                <div class="item">
                                    <a class="gallery-item" href="./assets/img/single-product/thumbnail-1.jpg"
                                        data-fancybox="gallery1" data-hash="one">
                                        <img src="./assets/img/single-product/thumbnail-1.jpg" alt="Product">
                                    </a>
                                </div>
                                <div class="item">
                                    <a class="gallery-item" href="./assets/img/single-product/thumbnail-2.jpg"
                                        data-fancybox="gallery1" data-hash="two">
                                        <img src="./assets/img/single-product/thumbnail-2.jpg" alt="Product">
                                    </a>
                                </div>
                                <div class="item">
                                    <a class="gallery-item" href="./assets/img/single-product/thumbnail-3.jpg"
                                        data-fancybox="gallery1" data-hash="three">
                                        <img src="./assets/img/single-product/thumbnail-3.jpg" alt="Product">
                                    </a>
                                </div>
                                <div class="item">
                                    <a class="gallery-item" href="./assets/img/single-product/thumbnail-4.jpg"
                                        data-fancybox="gallery1" data-hash="four">
                                        <img src="./assets/img/single-product/thumbnail-4.jpg" alt="Product">
                                    </a>
                                </div>
                            </div>
                            <ul class="product-thumbnails">
                                <li class="active">
                                    <a href="#one">
                                        <img src="./assets/img/single-product/thumbnail-1.jpg" alt="Product">
                                    </a>
                                </li>
                                <li>
                                    <a href="#two">
                                        <img src="./assets/img/single-product/thumbnail-2.jpg" alt="Product">
                                    </a>
                                </li>
                                <li>
                                    <a href="#three">
                                        <img src="./assets/img/single-product/thumbnail-3.jpg" alt="Product">
                                    </a>
                                </li>
                                <li>
                                    <a href="#four">
                                        <img src="./assets/img/single-product/thumbnail-4.jpg" alt="Product">
                                    </a>
                                </li>
                                <li>
                                    <a class="navi-link text-sm" href="./assets/video/download.mp4" data-fancybox
                                        data-width="960" data-height="640">
                                        <i class="mdi mdi-video text-lg d-block mb-1"></i>
                                    </a>
                                </li>
                            </ul>
                        </div>

performance – How to make arm assembly code optimal and clear

The following is a program I wrote for an assignment. It runs with no problems. It removes “the” if found as a word in a string.

I am posting to ask of ways to make the code better. The reason is my friend showed me his code and it was much shorter and much more clearer than mine (is he smarter than me? I wondered). Although this is only my second arm program I’ve been coding for 3 years and I don’t feel I’m getting any where. I want to know how to improve this code and any advice would be appreciated (Also any feedback and any ways to improve as a coder).

        AREA prog, CODE, READWRITE
        ENTRY   
        LDR     r1, =STRING1        ; r1 points to string with the
        LDR     r2, =STRING1        ; r2 points to string with the
        LDR     r3, =STRING2        ; r3 points to string without the

Loop    CMP     r4, #ZERO           ; r4 main loop counter (check if first word)
        CMPNE   r5, #WSpace         ; check if start of word
        LDRB    r5, (r1), #ONE      ; load current letter
        ADD     r4,r4,#ONE          ; increment counter r4
        BEQ     checkt              ; if start of word check if word is "the"

Store   CMP     r5, #EoS            ; check if end
        STRB    r5, (r3,#ONE)!      ; str other words litters (not the)
        BNE     Loop                ; if not prepare the next letter
        BEQ     Quit                ; if end go to if end branch

checkt  CMP     r5, #t              ; if start ofword check if first litter is t

        LDRBEQ  r6, (r2,r4)         ; if so load next letter
        CMPEQ   r6, #h              ; and cmp to h
        ADDEQ   r7, r4,#ONE         ; if h load next then increment subcounter
        LDRBEQ  r6, (r2,r7)         ; and load next letter

        CMPEQ   r6, #e              ; and cmp to e
        ADDEQ   r7, r7, #ONE        ; if e increment subcounter
        LDRBEQ  r6, (r2,r7)         ; and load next letter 
        BNE     Store               ; store the non the word

        CMP     r6, #WSpace         ; check if white space 
        BNE     ifend               ; if not then check if end of the string the        

        ADD     r4, #THREE          ; if the word was the increment main counter by 3
        MOV     r8, #ZERO           ; and set local counter to 0

skip    LDRB    r5, (r1), #ONE      ; load the the letters to skip
        ADD     r8, r8, #ONE        ; keep track of how many letters have been skiped
        CMP     r8, #THREE          ; if 3 letters have been skipped 
        BEQ     Loop                ; end this loop and go back to main loop
        BNE     skip                ; otherwise keep looping

ifend   CMP     r6, #EoS            ; check if end of the string the
        BNE     Store               ; if not then store the word( not the)

Quit    B       Quit                ; denotes the end of the program

            AREA prog, DATA, READWRITE
STRING1     DCB     "the and the man said they must go the"             ; String1
EoS         EQU     0x00                                                ; end of string1
STRING2     space   0x7F                                                ; just allocating 127 bytes
t           EQU     0x74                                                ; the value of 't'
h           EQU     0x68                                                ; the value of 'h'
e           EQU     0x65                                                ; the value of 'e'
WSpace      EQU     0x20                                                ; the value of white space ' '
ONE         EQU     1                                                   ; Just the number one to increase readability   
THREE       EQU     3                                                   ; Just the number three to increase readability 
ZERO        EQU     0                                                   ; Just the number three to increase readability 
        END
```

c++ – (from codeabbey) This code is supposed to add or multiply a bunch of numbers and at the end divide by a certain number and outpout the decimals

For example if the numbers are:
5 + 3 * 7 + 10 * 2 * 3 + 1 % 11

then it would multiply and add all the numbers giving 397 and divide by 11 giving 36.09 so therefore it must output 1.

My code works in this scenario but if I do more larger numbers it doesn’t seem to work. This is what I have

#include <iostream>
using std::cout;
using std::cin;

int main() {


    int num1, num2;
    char opp = 'a';

    cout << "Firt nubmer";
    cin >> num1;

    while (opp != '%') {
        cin >> opp;
        cin >> num2;

        if (opp == '+') {
            num1 += num2;
            
        }
        else if (opp == '*') {
            num1 *= num2; 
            
        }
        else {
            cout << num1 << " " << num2 <<  std::endl;
            num1 %= num2;

        }

    }
    
    cout << num1;

}

qrcode – How can I securely create a QR code from a bitcoin address?

I am trying to generate a QR code for a public bitcoin address, preferably using command-line tools. The process poses a security risk because malicious software can generate a QR code that represents an address different than the one given as input.

Searching this site and Github. I only found some unmaintained repos with very low usage.

How can I securely generate a QR representation for a bitcoin address from the command, using open-source software I can trust?

Issue when importing the Android source code into Intellij-IDEA

I followed the standard process of importing android source code into IDEA.

Like this:

https://wiki.lineageos.org/import-android-studio-howto.html

Why not navigate to Message.java but Message.class in jar?

Why not navigate to Message.java but Message.class in jar

Anyone knows how to fix it?

I have successfully built the source code.

unity – How do I set horizonal Field of View by code as in Inspector?

I have a camera that I have set to

RenderType = Base
Projection = Perspective
FOV Axis = Horizontal
Field of View = 75
Physical Camera = False
Clipping Planes Near = 0.3, Far  = 1000

enter image description here

If I set Field of View values during gameplay in the Inspector, it works as expected.

For example, I type 75, and the camera behaves as I think it should. I’m comparing with Resident Evil 4. It has a camera cheat, and if I select FOV 75 in this cheat, the Resident Evil 4 camera behaves like my Unity game camera.

However, when I set the camera.fieldOfView to a 75 by code, the Inspector shows 104, and the code does not look as it looks when I type 75 in the Inspector.

_camera.fieldOfView however returns 75.

What is going on here, and how do I fix it?

Thank you!

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'))
os.chdir(data)
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?

Formatted text, code block in draw.io

I want to add JSON code snippets to my diagram in draw.io. When I use copy/paste to a text box, the indented spaces/tabs get lost.

Does anyone know how to copy formatted snippets from notepad++/VS Code to draw.io?