Optimisation of A* in C++ I'm working on an A* pathfinding algorithm to solve a programming problem, and part of the constraint is the runtime. I need to find a path in a 2D grid with blocked or non-blocked tiles. You can't move diagonally.

I have succeeded to make a working prototype of the function which can and will solve the problems encountered, but it lacks optimisation.

I think that I need to optimise my heuristic function. For now, I calculate candidly: the distance between the current tile and the goal if no tile were blocked, plus the current cost.

n.distGoal = abs(n.x - nTargetX) + abs(n.y - nTargetY) + n.cost;

Interestingly, I've found an answer that does not include the cost when calculating its heuristic. When trying it out, my algorithm doesn't work anymore.

Have you any clues on how I could make the function more optimised?

Here are a few more snippets of my code, to help understand and maybe spot an error that causes long runtime:

Finding the neighbours:

set<tile> neighbours;
    for(int k=-1;k<2;k+=2){
        if(!(cur.x+k < 0|| cur.x+k>=nMapWidth)){ //if we're out of bonds, there's nowhere to go
            struct tile neigh;
            neigh.x = cur.x+k;
            neigh.y = cur.y; //yum
            neigh.mapWidth = nMapWidth;
            int positionInMap = neigh.x + (neigh.y*nMapWidth);
            if(!(pMap[positionInMap] == 0)){ //if we can walk there
                neigh.cost = cur.cost + 1;
                neighbours.insert(neigh);
            }
        }

        if(!(cur.y+k < 0 || cur.y+k>=nMapHeight)){ //if we're out of bonds, there's nowhere to go
            struct tile neigh;
            neigh.x = cur.x;
            neigh.y = cur.y+k;
            neigh.mapWidth = nMapWidth;
            int positionInMap = neigh.x + (neigh.y*nMapWidth);
            if(!(pMap[positionInMap] == 0)){ //if we can walk there
                neigh.cost = cur.cost + 1;
                neighbours.insert(neigh);
            }
        }
    }

Reconstructing the path when we reached the end:

void buildPath(map<tile,tile> cameFrom, tile cur, int* pOutBuffer){ //Reconstructs the path
    int i = cur.distGoal - 1;
    pOutBuffer[i] = cur.x + cur.y*cur.mapWidth;
    map<tile,tile>::iterator it = cameFrom.find(cur);
    while (it != cameFrom.end()){
        i--;
        if(i<0){
            break;
        }
        cur = it->second;
        pOutBuffer[i] = cur.x + cur.y*cur.mapWidth;
        it = cameFrom.find(cur);
    }
}

Interestingly, I've found an answer that does not include the cost when calculating its heuristic. When trying it out, my algorithm doesn't work anymore.

Let's make sure that you understand the algorithm.  It is:

We have a queue where the entries in the queue are a possible path and an estimate of the cost of that path.
The queue keeps itself sorted by cost, lowest cost path first, highest cost path last

Basically the idea is to assume that the lowest-cost path is the one to explore first; only if that does not work out do we try the next-lowest.

So now let's talk about the cost.  The estimated cost is the sum of:

The known cost of the path so far
The estimated cost of getting to the goal from the end of the path

If you've already gone 100 squares (known) and you think you have 50 more to go (estimated), the total estimated cost is 150.

You MUST include the known cost in with the estimated cost of the remainder; if you did not then you would, say, take a path known to be at least 100 long and put it in the queue as though it had a cost of 50!

So you must compute the estimated cost in two parts: the known cost of the path, and the estimated cost of the remainder.  It is the second part that is usually called the "heuristic", because it's a guess. The known cost can be computed exactly.

  I think that I need to optimise my heuristic function. For now, I calculate candidly : the distance between the current tile and the goal if no tile were blocked, plus the current cost.

The key feature of the heuristic is that it must never overestimate. A heuristic which has this property is called admissible.

It sounds like your heuristic is admissible. If you can only move orthogonally, not diagonally, then the Manhattan distance is admissible.

Your heuristic is called the Manhattan distance because it's the distance between two points in New York City, if you're constrained to moving on the grid rather than going diagonally.

If you can move diagonally then the Manhattan distance can overestimate, and is not admissible. If diagonal movement is allowed then use the Euclidean distance: the straight-line distance between two points.

One way you can test your algorithm is to use zero as your heuristic; just say that the estimated cost is the known cost plus nothing.  That is an admissible heuristic because it always under-estimates.  A-star with a zero heuristic is also called Dijkstra's Algorithm.

You say you want to optimize your heuristic. The best way to optimize the heuristic is to make it as accurate as possible without ever overestimating, while at the same time making it fast to compute. The Manhattan distance is a great heuristic because it is very fast to compute, is often exact, and never overestimates.

The more accurate the heuristic is, the fewer paths the algorithm has to consider before finding the best one. So accuracy is important.

I would stick to using the Manhattan distance and profile your code to figure out where the performance problem is.  Likely the problem is not with your heuristic at all, but with maintaining the heap invariant in the priority queue, or with figuring out which nodes are already visited.

If you're interested in this subject you might want to read my series of articles from 2007 on implementing a-star in C#.

https://blogs.msdn.microsoft.com/ericlippert/tag/astar/


Aggregating recent trading data from Bitcoin derivatives exchange As a component of some trading software, I wrote function parse_ticks(), as part of an Exchange class that models the Bitcoin derivatives exchange BitMEX.
The purpose of parse_ticks() is to convert the previous minutes stored tick data (a list of individual trades, obtained by calling all_ticks = self.ws.get_ticks()) into a dictionary which aggregates the  OHLCV values from the list of previous minutes ticks. The list of trades is a list of dict's, each dict containing a timestamp, size of trade, if the tick was a buy or sell, etc.
parse_ticks() gets invoked once per instrument when minute elapses. In this scenario, I am watching two instruments, so parse_ticks() gets called twice at the start of each minute.
I timed parse_ticks() run time for 2400 minutes (2400 observations) with as many background processes and programs disabled as possible, and obtained these results (in seconds):
mean run time: 0.0318425
min run time: 0.00458
max run time: 0.07958
std dev: 0.02276709988
Theres a massive range here, with the min and max  substantially different, and the std dev is almost as large as the mean.
How would I lower the std. dev of parse_ticks() run time, and get the mean run time closer the minimum observation of 0.00458?
Is this kind of optimisation within the scope of python?
EDIT: To answer the questions in comments (thank you all for your help):
ws.get_ticks() has no outbound API calls, it looks like this:
def get_ticks(self):
        return self.data['trade']

where data['trade'] is a list containing ticks saved from a websocket stream in realtime. The 'trade' list is trimmed by 30% if it goes above 10000 elements, so that aspect (constantly-increasing amount of data to parse) is constant, once the limit is reached. So the data is already available when parse_ticks() is called.
The amount of ticks DOES vary, so some variance can be explained by that. But surely not the extreme range of 0.075? (min - max).
The run times are seemingly random, there are long and short runs interspersed throughout all the observations.
self.bars = {}
self.symbols = ["XBTUSD", "ETHUSD"]
self.ws = Bitmex_WS()

def parse_ticks(self):
    """Return a 1-min OHLCV dict, given a list of the previous
       minutes tick data."""

    all_ticks = self.ws.get_ticks()
    target_minute = datetime.datetime.utcnow().minute - 1
    ticks_target_minute = []
    tcount = 0

    # search from end of tick list to grab newest ticks first
    for i in reversed(all_ticks):
        try:
            ts = i['timestamp']
            if type(ts) is not datetime.datetime:
                ts = parser.parse(ts)
        except Exception:
            self.logger.debug(traceback.format_exc())

        # scrape prev minutes ticks
        if ts.minute == target_minute:
            ticks_target_minute.append(i)
            ticks_target_minute[tcount]['timestamp'] = ts
            tcount += 1

        # store the previous-to-target-minute bar's last
        # traded price to use as the open price for target bar
        if ts.minute == target_minute - 1:
            ticks_target_minute.append(i)
            ticks_target_minute[tcount]['timestamp'] = ts
            break
    ticks_target_minute.reverse()

    # reset bar dict ready for new bars
    self.bars = {i: [] for i in self.symbols}

    # build 1 min bars for each symbol
    for symbol in self.symbols:
        ticks = [i for i in ticks_target_minute if i['symbol'] == symbol]
        bar = self.build_OHLCV(ticks, symbol)
        self.bars[symbol].append(bar)
        # self.logger.debug(bar)

We (and it sounds like you as well) do not have enough information to answer this question. But some good news first: I cannot see any region where your method is obviously wasting time (like searching with in for some item in a growing list).

Before you concern yourself more with this, consider that even if the variance is large, your maximum time is less than a tenth of a second, for two instruments. In other words, you could be monitoring more than 1500 instruments before you get close to a maximum processing time on the order of your frequency (one minute). So ask yourself if you are performing needless premature optimization. Will this code run with \$\mathcal{O}(1000)\$ instruments, for longer than two days? If not, you can stop right here. If yes, or as an academic exercise, continue on.

As far as I can see, the runtime of this code will be largely determined by two factors:

How long self.ws.get_ticks() takes. Does this method connect to the internet to get it's data? Then the variance might actually be the variance in establishing the connection and getting the data. This could be influenced by your internet connection, but also the current load on the server you are trying to connect to. In this case there is nothing you can do.
How many elements are returned. The actual function getting the data might take longer for more elements, but also the processing would, since you iterate over all elements of the list.

The only way to know is to gather more data. Individually time the call to self.ws.get_ticks(), collect the len(all_ticks) and plot everything in a time-ordered way. Maybe this will help you to discover something interesting.

Here are some possibilities of what you could discover:

The server where you get the information also has some updating frequency, so only every five minutes will there be data for you.
They have a rate limit, which makes all requests in-between fail (which is faster than transmitting a bunch of data).
The call actually returns all data every time, and you just break when you have reached the point of the last minute. In this case each successive call is more expensive, so of course this increases the standard deviation. Try to find a way to pass the start date to the call.

And here is a small class that can help you keep track of different timers I just came up with:

from time import perf_counter
from statistics import mean, median, stdev
from collections import defaultdict

class Timer:
    durations = defaultdict(list)

    def __init__(self, name=""):
        self.name = name

    def __enter__(self):
        self.start = perf_counter()

    def __exit__(self, *args):
        Timer.durations[self.name].append(perf_counter() - self.start)

    @staticmethod
    def calc_stats(x):
        return {"mean": mean(x),
                "std": stdev(x),
                "median": median(x),
                "min": min(x),
                "max": max(x)}

    @staticmethod
    def stats():
        return {name: Timer.calc_stats(x) for name, x in Timer.durations.items()}

With some example usage:

from time import sleep
import pandas as pd
import matplotlib.pyplot as plt

from timer import Timer

for n in range(10):
    with Timer("a"):
        sleep(0.5)
    with Timer("b"):
        sleep(0.1 * n)

print(pd.DataFrame(Timer.stats()))
#                a         b
# mean    0.500559  0.450504
# std     0.000021  0.303079
# median  0.500552  0.450502
# min     0.500534  0.000006
# max     0.500602  0.901003

plt.plot(Timer.durations["a"], label="a")
plt.plot(Timer.durations["b"], label="b")
plt.legend()
plt.xlabel("Iteration")
plt.ylabel("Time [s]")
plt.show()

Some other comments:

Instead of self.bars = {i: [] for i in self.symbols} you can use self.bars = defaultdict(list), like I did in the Timer class.
Try to avoid single letter variables. They are OK in a few cases, but i (and n) are usually reserved for integers. Use x, or maybe even better, tick.
Don't directly compare type, use isinstance(datetime.datetime, s) instead. This also allows subclasses.
Don't lie in your docstring. You say "Return a 1-min OHLCV dict, given a list of the previous minutes tick data.", but almost none of this is true. The method does not return anything and it also does not take any parameters as input!
If you know the exception to expect, catch only that. At least you don't have a bare except, but except KeyError and maybe some specific error from the parser would be better. This way you don't miss an unexpected error. You should also ask yourself what your code does if an error occurs. I think it will just use the previous iterations ts, which would duplicate data. Just hope that you never have a problem in the first timestamp!


Java implementing task on another thread with javascript-like promise resolve-reject Background:

I have a TCP online multiplayer game server, which the player requests to log-in. However, the game server does not handle the authentication part of the login process, instead, it uses an outer micro-service which is an HTTP server to see if the user can authenticate with the given credentials.

Now why is that a problem? - Well I use netty.io networking framework, which is a non-blocking framework, it handles all connections in a sequence on the same thread. Since I don't want to cause any delays, I will not send an HTTP request on the same thread because I don't want to stop it.

Instead I followed a pattern of callbacks like java script promise resolve-reject, and I Would like to hear what you think, and if it could be done better.

Don't mind the generic types, just take the basic idea of it:

First of all this is my ServiceProvider, the point of this class is to provide a singleton of each service that interacts with microservices such as UserService which is an HTTP server to handle everything related to user (authentication, data, etc):

public class ServiceProvider {

    private static ExecutorService executorService = Executors.newFixedThreadPool(ServicesConfig.SERVICES_THREAD_POOL_CAPACITY);

    private static UserService userService;

    /**
     * Provdes an user service singleton instance
     * @return  The user service
     */
    public static UserService getUserService() {
        if (userService == null) {
            userService = new UserService();
            userService.setBaseUrl(ServicesConfig.USER_SERVICE_BASE_URL);
        }
        return userService;
    }

    public static void submitServiceTask(ServicePromise task) {
        executorService.submit(task);
    }
}

Secondly is my UserService for example:

public class UserService extends HeroesHttpService {

    /**
     * Authenticates an user
     * @param username  The username
     * @param password  The password
     * @return  ?
     */
    public ServicePromise<?> authenticateUser(String username, String password) {

        ServicePromise<HttpResponse> promise = new ServicePromise<HttpResponse>() {
            @Override
            public void run() {
                HttpClient client = HttpClients.createDefault();

                HttpGet request = new HttpGet(getBaseUrl() + "/user/authenticate");
                try {
                    HttpResponse response = client.execute(request);
                    resolve(response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        ServiceProvider.submitServiceTask(promise);
        return promise;
    }
}

Now this is my promise interface:

public abstract class ServicePromise<T> implements Runnable {

    private ServicePromiseCallback<T> callback;

    public ServicePromise<T> then(ServicePromiseCallback<T> cb) {
        this.callback = cb;
        return this;
    }

    @Override
    public void run() {
    }

    public void resolve(T data) {
        if (this.callback == null) {
            return;
        }
        this.callback.onResolve(data);
    }

    public void reject(T data) {
        if (this.callback == null) {
            return;
        }
        this.callback.onReject(data);
    }
}

And that's the callback interface:

public interface ServicePromiseCallback<T> {
    void onResolve(T response);
    void onReject(T response);
}

And finally, thats how I use it:

    ServiceProvider.getUserService().authenticateUser(player.playerName, player.playerPass).then(new ServicePromiseCallback<?> () {
        @Override
        public void onResolve(Object response) {

        }

        @Override
        public void onReject(Object response) {

        }
    });

Again, don't mind the types in resolve/reject, it's going to definitely be AuthenticateUserResponseDto and so on, but it doesn't matter right now

the ServiceProvider is supposed to provide a singleton instance of UserService but it does not follow all the principles of the Singleton design pattern. specifically, the locking mechanisms that prevent multiple threads from creating multiple instances of UserService (or rather, multiple calling of the constructor)

and while on the subject - why not use Dependency Injection?

also, reject(response) is never called

with regard to the issue of the "javascript-like promise resolve-reject": Java has such a mechanism: CompletableFuture where you supply a Runnable and for the callbacks there are thenApply() thenAccept() and thenRun() methods.  exceptions are handled by exceptionally() method. There are other capabilities like chaining CompletableFuture instances (thenCompose().


Keypress output to screen For a school project, I had to make a keylistener that would output whatever you typed to the screen. A JFrame would be initialized to have the focus required for the listener to work. It uses delete and shift methods to determine what to type/delete. Is there any way to make this more efficient, since I have two methods that I don't use and just take up space? Any and all help is appreciated!

import javax.swing.*;
import java.awt.event.*;

public class KeyHandler implements KeyListener {
    /*
     * KEY FUNCTIONS:
     * k.getKeyCode() returns ascii number
     * k.getKeyChar() returns char typed
     *
     * KEY CODES:
     * [delete] 8
     * [shift] 16
     */
    private String output;

    public KeyHandler() {
        this.output = "";
    }

    public void keyPressed(KeyEvent k) {
        if(k.getKeyCode() != 8) {
            if(k.getKeyCode() != 16) {
                this.output += k.getKeyChar();
            }
        } else {
            if(this.output.length() - 1 < 0) {
                //do nothing
            } else {
                this.output = this.output.substring(0,this.output.length() - 1);
            }
        }
        this.print();
    }
    public void keyReleased(KeyEvent k) {}
    public void keyTyped(KeyEvent k) {}

    public void print() {
        System.out.print('\f'); //clear screen in BlueJ
        System.out.println(this.output);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("KeyEvent Handler");
        frame.setSize(400,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addKeyListener(new KeyHandler());
        frame.setVisible(true);
    }
}

Unless you intend (and have carefully designed) for your KeyHandler to be extended, you should make it final.

If you extend KeyAdapter instead of implements KeyListener, you won’t have to implement keyReleased and keyTyped. The Adapter classes in Swing provide empty implementations of all the methods on the interface they implement, so you can just override the ones you care about.

Don’t use int values to represent more complex concepts - those are called “magic numbers”. In this case, just use the constants defined on KeyEvent, namely KeyEvent.VK_BACK_SPACE and KeyEvent.VK_SHIFT.

Put whitespace in between if and (. This visually differentiates control flow keywords from method names. Put whitespace after a , also, to make it easer to separate method arguments visually.

In keyPressed, you don’t need to declare nested if statements. Prefer &&.

Since String is immutable, a StringBuilder is preferred when doing String manipulation. You might not have covered that in class yet. It might be cleaner to use a switch statement on the value of the

It’s probably overkill to have a separate method for printing in this case.

You can clean up your logic by reversing the this.output.length() - 1 < 0 to be this.output.length() > 1 and getting rid of the empty clause.

Note that you’re deleting a character when the shift key gets pressed. Also, no matter how many times shift or delete are pressed, you’re not deleting the first character. These are both probably bugs.

You can just declare the initial value of output when you declare the variable. You don’t need a separate line in the constructor for that.

If you were to implement all my suggestions, your code might look more like:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;

public final class KeyHandler extends KeyAdapter {

    private String output = "";
    //private final StringBuilder stringBuilder = new StringBuilder();

    public KeyHandler() {
        super();
    }

    @Override
    public void keyPressed(final KeyEvent k) {
        if ((k.getKeyCode() != KeyEvent.VK_BACK_SPACE) && (k.getKeyCode() != KeyEvent.VK_SHIFT)) {
            this.output += k.getKeyChar();
        } else if (this.output.length() > 1) {
            this.output = this.output.substring(0, this.output.length() - 1);
        }

        System.out.print('\f'); //clear screen in BlueJ
        System.out.println(this.output);

        /*
        switch (k.getKeyCode()) {
            case KeyEvent.VK_BACK_SPACE:
                if (this.output.length() > 0) {
                    this.stringBuilder.deleteCharAt(this.stringBuilder.length() - 1);
                }
                break;
            case KeyEvent.VK_SHIFT:
                break;
            default:
                this.stringBuilder.append(k.getKeyChar());
        }

        System.out.print('\f'); //clear screen in BlueJ
        System.out.println(this.stringBuilder.toString());
         */
    }

    public static void main(final String[] args) {
        final JFrame frame = new JFrame("KeyEvent Handler");
        frame.setSize(400,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addKeyListener(new KeyHandler());
        frame.setVisible(true);
    }
}


Socket.IO handshake module For the server of which this is part, it makes a request to one of our web servers to validate whether the PHP Session ID is actually valid.  The location this._options.url is a URL that, given a PHPSESSID as a cookie, will return the user ID that is attached.

One of the issues that has crept up is the CPU utilization spiking to 100%.  While I have seen several solutions to this, one was that failure to call a callback function can cause it.  After effectively disabling the following function (I had it simply do callback(null,1); for testing purposes), the CPU utilization issue stopped.

However, I do believe a contributing cause was that the nature of performing an httpd request might not be trapping all of the errors and possibilities and have modified it to look this like:

var http = require('http');
var url = require('url');

function AuthFunc(auth_opts){
    this._options = auth_opts;
    this.checkPHPSession = function(phpsessid, callback){
        var options = {
            host: url.parse(this._options.url).host,
            port: url.parse(this._options.url).port || 80,
            path: url.parse(this._options.url).pathname,
            auth: url.parse(this._options.url).auth,
            headers: {
                'Cookie': this._options.cookie + '=' + phpsessid
            }
        };
        var data = '';
        http.get(options, function(response){
            response.on('data', function(chunk) {
                data += chunk;
            }).on('end', function(){
                try{
                    var arr = JSON.parse(data);
                }catch(e){
                    callback(e, false);
                }
                callback(null, arr.uid);
            }).on('close', function(){
                callback(true, false);
            }).on('error', function(e){
                callback(e, false);
            });
        }).on('error', function(e){
            callback(e, false);
        });
    }
}

module.exports = AuthFunc;

The code works for my purposes, but I'm not sure if it can handle fringe cases of HTTP request failure as that might be difficult to test at best.

Does this code look like it will always properly call callback in all cases, no matter what is returned from the server?  Is this the most proper way to write an HTTP request that guarantees a result callback of some kind?

Interesting question, I would rewrite

try{
    var arr = JSON.parse(data);
}catch(e){
    callback(e, false);
}
callback(null, arr.uid);

as

try{
    var arr = JSON.parse(data);
    callback(null, arr.uid);
}catch(e){
    callback(e, false);
}

Actually, I would probably go even a step further and write it as

try{
    callback(null, JSON.parse(data).uid);
}catch(e){
    callback(e, false);
}

Otherwise in case of an error, you will have 2 callbacks, which could cause all kinds of trouble, perhaps even make the CPU spike to 100% ;)

Furthermore, I would also put a try/catch around http.get itself, if there is a hardcore http layer problem, then you might not even get to 'close' or 'error'.

Then some other minor items are

Most of the options could be set outside of checkPHPSession, you should do so and prevent the repeated determinations of host, port, etc.
Why are you checking for 'close', it seems like one more way to potentially have too many calls to the callback function


Responsive horizontal scroll on mouse position I am making a responsive horizontal scroll UI. The horizontal scroll position is calculated according to the mouse horizontal position:

$(document).ready(function() {
  var docWidth = $('body').width(),
    slidesWidth = $('#imgs').width(),
    rangeX = slidesWidth - docWidth,
    $images = $('#imgs');

  $(window).on('resize', function() {
    var docWidth = $('body').width(),
      slidesWidth = $('#imgs').width(),
      rangeX = slidesWidth - docWidth;
  })

  $(document).on('mousemove', function(e) {
    var mouseX = e.pageX,
      percentMouse = mouseX * 100 / docWidth,
      offset = percentMouse / 100 * slidesWidth - percentMouse / 200 * docWidth;

    $images.css({
      '-webkit-transform': 'translate3d(' + -offset + 'px,0,0)',
      'transform': 'translate3d(' + -offset + 'px,0,0)'
    });
  });
})
body,html {
  margin: 0;
  overflow: hidden;
  height: 100%;
}
#imgs {
  position: absolute;
  top: 0; left: 0;
  width: 150%; height: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin: 0 25%;
  /* transition: transform .1s; */
}
#imgs > div {
  max-width: 9%;
  perspective: 500px;
  z-index: 1;
}
#imgs img {
  display: block;
  max-width: 100%;
  height: auto;
}

This works pretty well in the browsers I tested. And other than general performance enhancement I am concerned about this issue:
When the mouse comes out of the window and back in, the images snap to the new position. I tried to make that snap smoother  with transition:transform .1s on the #imgs element (commented out in the CSS) but:

in chrome, it is a little janky
in Firefox and edge it is very janky even on small mouse moves

Your project is looking great! But I have a few thoughts on how to improve the clarity of your javascript code:

Unused code

Your window.resize handler doesn't end up doing anything. Functions create a new scope for variables, so since you're redeclaring docWidth and slidesWidth with var, you don't actually affect the initially declared variables. The reason why all your code still works is that the body's width and the slide's width don't actually change when the window is resized. I'm not sure if this is different on mobile or even why the widths aren't changing (maybe it has something to do with your css) but you ought to either change the handler to something like:

$(window).on('resize', function() {
  docWidth = $('body').width();
  slidesWidth = $images.width(); // stay consistent with this variable
  rangeX = slidesWidth - docWidth;
})

Or just remove it to prevent confusion if the widths aren't affected by resizing.

You also don't end up using rangeX in your code. Consider removing it.

More straightforward calculation

I think you could simplify the way you calculate the offset in your document.mousemove handler by eliminating the mousePercent variable:

$(document).on('mousemove', function(e) {
  var mouseX = e.pageX,
    offset = mouseX / docWidth * slidesWidth - mouseX / 2;

  $images.css({
    '-webkit-transform': 'translate3d(' + -offset + 'px,0,0)',
    'transform': 'translate3d(' + -offset + 'px,0,0)'
  });
});

This way you don't multiply by 100 and then divide by it right after, and you also have fewer variables to worry about.

Unnecessary functionality

You don't use the 3d aspect of translate so why not just use the 2d version:

$images.css({
  '-o-transform': 'translate(' + -offset + 'px, 0)', // opera 11.5
  '-ms-transform': 'translate(' + -offset + 'px, 0)', // IE9
  '-moz-transform': 'translate(' + -offset + 'px, 0)', // firefox 3.5-15
  '-webkit-transform': 'translate(' + -offset + 'px, 0)',
  'transform': 'translate(' + -offset + 'px,0)'
});

More concise and direct jquery syntax

Another option would be to use jquery's built in methods for creating events instead of using on:

$(document).ready(function() {
  var docWidth = $('body').width(),
    slidesWidth = $('#imgs').width(),
    rangeX = slidesWidth - docWidth,
    $images = $('#imgs');

  $(window).resize(function() {
    var docWidth = $('body').width(),
      slidesWidth = $('#imgs').width(),
      rangeX = slidesWidth - docWidth;
  })

  $(document).mousemove(function(e) {
    var mouseX = e.pageX,
      percentMouse = mouseX * 100 / docWidth,
      offset = percentMouse / 100 * slidesWidth - percentMouse / 200 * docWidth;

    $images.css({
      '-webkit-transform': 'translate3d(' + -offset + 'px,0,0)',
      'transform': 'translate3d(' + -offset + 'px,0,0)'
    });
  });
});

Once again, great work so far! I wish I could have helped more with the snapping issue. I have a few ideas--mouseenter, jquery.stop().animate()--but none that are fully developed. Good luck figuring it out!


Implementing command pattern in Python I did some study on the command pattern but most of its examples were in Java so, there must be some difference in implementation in Python. I implemented it in Python with some minor differences, please let me know if something is not correct.

from abc import ABCMeta
from abc import abstractmethod
import inspect
import os

class Command(object):
    """
    Abstract / Interface base class for commands.
    """
    __metaclass__ = ABCMeta

    @abstractmethod
    def execute(self):
        pass

    @abstractmethod
    def undo(self):
        pass

class CreateCommand(Command):
    """
    Create command implementation.
    """
    def __init__(self, name):
        self.file_name = name

    def execute(self, name):
        open(self.file_name, 'w')
        print str(self) + ':::Method:::' + inspect.stack()[0][3]

    def undo(self):
        os.remove(self.file_name)
        print str(self) + ':::Method:::' + inspect.stack()[0][3]

class MoveCommand(Command):
    """
    Move command implementation.
    """
    def __init__(self, src, dest):
        self.src = src
        self.dest = dest

    def execute(self, src, dest):
        os.rename(self.src, self.dest)
        print str(self) + ':::Method:::' + inspect.stack()[0][3]

    def undo(self):
        os.rename(self.dest, self.src)
        print str(self) + ':::Method:::' + inspect.stack()[0][3]

class Invoker(object):

    def __init__(self, command):
        self.command = command

    def do(self):
        self.command.execute()

    def undo(self):
        self.command.undo()

# Client for the command pattern
if __name__ == '__main__':
    create_cmd = CreateCommand('/tmp/foo.txt')
    move_cmd = MoveCommand('/tmp/foo.txt', '/tmp/bar.txt')
    create_invoker = Invoker(create_cmd)
    move_invoker = Invoker(move_cmd)
    create_invoker.do()
    move_invoker.do()
    move_invoker.undo()
    create_invoker.undo()

O/P:

<__main__.CreateCommand object at 0xb705130c>:::Method:::execute
<__main__.MoveCommand object at 0xb705134c>:::Method:::execute
<__main__.MoveCommand object at 0xb705134c>:::Method:::undo
<__main__.CreateCommand object at 0xb705130c>:::Method:::undo

The important thing to know about commands in Python (or any language with first-class functions) is that they're usually trivial.  Commands with only one operation (execute) are simply functions. There's no need to define classes. Even commands with two operations can be represented as pairs of functions: (do, undo). The whole, heavyweight pattern is almost never used.

Comments on the above implementation:

Command parameters such as filenames should be arguments to the constructor, not to execute. The code that calls execute doesn't know what these values should be, so they need to already be in the command.
There's no reason to keep a table of commands. Just create commands as needed.
Invoker.execute manually dispatches by command name. Instead it should blindly call execute or undo, and let method dispatch find the appropriate method.
The Invoker class does nothing useful.
Why bother getting the method name from inspect.stack when the method already knows its own name?
I might call execute do, for symmetry with undo.
ABCMeta is unnecessary complexity. If you must use it, it's clearer to write class Command(metaclass=ABCMeta) rather than assigning to __metaclass__.
The file operations don't undo properly if a file was overwritten. (This is not relevant to the pattern; it's just a bug.)


Process string vector and change each string to uppercase The question below came from C++ primer 5th edition.

  Read a sequence of words from cin and store the values a
  vector. After you’ve read all the words, process the vector and change
  each word to uppercase. Print the transformed elements, eight words to a
  line.

I was just wondering if there is any way to improve my solution.

int main(){

    vector<string> stringVector;
    string s;
    while(cin >> s){
        stringVector.push_back(s);
    }
    for(string &s : stringVector){
        for(char &c : s){
            c = toupper(c);
        }
    }
    for (int i = 0; i != stringVector.size(); i++){
        if (i != 0 && i % 8 == 0){
            cout << endl;
        }
        cout << stringVector[i] << " ";
    }

    return 0;
}

I see some things that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Know when to use it and when not to (as when writing include headers).

Consider using standard algorithms

There is nothing wrong with your transformation of the words to uppercase, but it may be useful to consider an alternative using a standard algorithm.  In particular std::transform may be useful here:

for(string &s : stringVector){
    std::transform(s.begin(), s.end(), s.begin(),
        [](char c){ return std::toupper(c); });
}

Use a counter rather than the % operator

It's not really necessary to use the % operator here.  It may not make any difference for this particular application, but on many processors, the % operator requires more CPU cycles (and therefore time) while counting down is usually very fast.

Minimize the number of iterations through the vector

The code currently makes three passes through the data.  First, it gets the input, next it transforms to upper case, and finally it emits the opper case versions of the input words.  These could all three be done in a single pass, although doing so doesn't quite match the given instructions.  The advantage, however, is that now a std::vector isn't even needed any longer.  Written that way the program might look like this:

#include <iostream>
#include <string>
#include <algorithm>
#include <ctype>

int main()
{
    constexpr unsigned WORDS_PER_LINE = 8;
    std::string s;
    unsigned wordcount = WORDS_PER_LINE;
    while(std::cin >> s){
        std::transform(s.begin(), s.end(), s.begin(),
            [](int c){ return std::toupper(c); });
        std::cout << s << ' ';
        if (--wordcount == 0) {
            std::cout << '\n';
            wordcount = WORDS_PER_LINE;
        }
    }
    std::cout << '\n';
}

Omit return 0

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.


Send and receive data code using OpenSSL I need to send and receive data. Here is solution for my original problem. I want to know how safe my finished code is and how I can improve it. Here is my first try. Now I need to get review for my new code.

void sslWrite(SSL *ssl, const void *buf, unsigned size)
{
    int writedTotal = 0;
    const char *ccBuf = reinterpret_cast<const char *>(buf);

    while (writedTotal < size) {
        int writedPart = SSL_write(ssl, ccBuf + writedTotal, size - writedTotal);
        if (writedPart < 0) {
            std::string error = "SSL_write error = ";
            error += (std::to_string(writedPart) + ".");
            throw std::runtime_error(error);
        }
        writedTotal += writedPart;
    }
}

std::vector<char> sslRead(SSL *ssl, unsigned size)
{
    std::vector<char> ret(size);
    unsigned readTotal = 0;

    while (readTotal < size) {
        int readPart = SSL_read(ssl, &ret[readTotal], size - readTotal);
        if (readPart < 0) {
            std::string error = "SSL_read error = ";
            error += (std::to_string(readPart) + ".");
            throw std::runtime_error(error);
        }
        readTotal += readPart;
    }

    return ret;
}

void sslWriteSize(SSL *ssl, unsigned size)
{
    if (sizeof(u_long) > 8)
        throw std::runtime_error("Write size error.");

    u_long nlSize = htonl(size);
    sslWrite(ssl, &nlSize, 8);
}

unsigned sslReadSize(SSL *ssl)
{
    if (sizeof(u_long) > 8)
        throw std::runtime_error("Read size error.");

    u_long size = *reinterpret_cast<u_long *>(&sslRead(ssl, 8)[0]);
    size = ntohl(size);
    return size;
}

void sslWrite(SSL *ssl, const std::string &data)
{
    if (data.empty())
        throw std::runtime_error("SSL write error. Data is empty.");

    sslWriteSize(ssl, data.size());
    sslWrite(ssl, &data.at(0), data.size());
}

std::vector<char> sslRead(SSL *ssl)
{
    unsigned size = sslReadSize(ssl);
    return sslRead(ssl, size);
}

Is there a buffering problem as in my old code?

Looks good. No buffering problems anymore. Endianness is handled correctly. Reading and writing size is duly factored out.

The only suggestion is not rely on the native unsigned type to represent the size. Notice that htonl takes uint32_t as a parameter. It is a strong hint to pass size as uint32_t as well. This guarantees that the size is 4 byte long no matter which platform it is running on. Don't forget to #include <cstdint>.


Return target informations from nested api json output How could i improve the following code. This part was easy to implement but there is a lot of redondancy and i use pandas to return as dict which seems quite odd.
def pipeline_place_details(place_id, fields, lang):
    """Return a dataframe with useful information

    Args:
        place_id ([string]): Id retrieved from google api
        fields ([type]): Field retrieved from json output
    """
        fields = ['name', 'formatted_address', 'international_phone_number', 'website', 'rating', 'review']
        lang = 'fr'
        # details will give us a dict which is the result of serialized json returned from google api
        details = get_place_details(place_id, fields, "fr")
        try:
            website = details['result']['website']
        except KeyError:
            website = ""

        try:
            address = details['result']['formatted_address']
        except KeyError:
            address = ""

        try:
            phone_number = details['result']['international_phone_number']
        except KeyError:
            phone_number = ""

        try:
            reviews = details['result']['reviews']
        except KeyError:
            reviews = []
        rev_temp = []
        for review in reviews:
            author_name = review['author_name']
            user_rating = review['rating']
            text = review['text']
            time = review['relative_time_description']
            rev_temp.append((author_name, user_rating, text, time))
        rev_temp_2 = pd.DataFrame(rev_temp, columns = ['author_name', 'rating', 'text', 'relative_time'])
        rev_temp_2['place_id'] = i
        rev_temp_2['address'] = address
        rev_temp_2['phone_number'] = phone_number
        rev_temp_2['website'] = website

        review_desc = review_desc.append(rev_temp_2, ignore_index = True)

    return review_desc.to_dict('records')
```

1. Getting data from dict
When details is a dict, then instead of writing:
try:
    address = details['result']['formatted_address']
except KeyError:
    address = ""

you can do:
address = details.get('result', {}).get('formatted_address', '')

Second parameter of .get represents the default value which is returned when a dictionary doesn't contain a specific element
2. Modularization
Function pipeline_place_details is not short, so it might be a good idea to break it up into a smaller functions. Each time when you write a loop, it's worth to consider if moving body of the loop to a separate function will increase the code readability.
For example that part:
    author_name = review['author_name']
    user_rating = review['rating']
    text = review['text']
    time = review['relative_time_description']
    rev_temp.append((author_name, user_rating, text, time))

can be easiliy extracted to the new function:
def process_review(review):
        return (
            review['author_name'],
            review['rating'],
            review['text'],
            review['relative_time_description']
        )

and you can use it as below:
rev_temp = [process_review(review) for review in reviews]

3. Variables naming
Good code should be not only working and efficient but it should be also easy to read and understand. So it's a good rule to use really meaningful variable names. I belive that you can find better names than for example rev_temp or rev_temp2. ;)


Same code to parse int, float, decimal? I have a method to parse strings. It can be used to parse a float using a specific culture and then get a new string with a specific out-culture. The same applies to ints, doubles and decimals.

The code that I've written is quite repetitive for each of the different parse methods which makes it hard to maintain (especially as I am just about to make the method a lot more complex).

Is it possible to make this code less repetitive?

if (mapping.ParseDecimal)
{
    decimal i;
    if (decimal.TryParse(value, numberStyle, inCulture, out i))
    {
        return i.ToString(outCulture);
    }
    else
    {
        if (logger.IsDebugEnabled)
            logger.DebugFormat("Could not parse value \"{0\" to a decimal using the culture \"{1}\".", value, inCulture);
    }
}
else if (mapping.ParseDouble)
{
    double i;
    if (double.TryParse(value, numberStyle, inCulture, out i))
    {
        return i.ToString(outCulture);
    }
    else
    {
        if (logger.IsDebugEnabled)
            logger.DebugFormat("Could not parse value \"{0\" to a double using the culture \"{1}\".", value, inCulture);
    }
}
else if (mapping.ParseFloat)
{
    float i;
    if (float.TryParse(value, numberStyle, inCulture, out i))
    {
        return i.ToString(outCulture);
    }
    else
    {
        if (logger.IsDebugEnabled)
            logger.DebugFormat("Could not parse value \"{0\" to a float using the culture \"{1}\".", value, inCulture);
    }
}
else if (mapping.ParseInt)
{
    int i;
    if (int.TryParse(value, numberStyle, inCulture, out i))
    {
        return i.ToString(outCulture);
    }
    else
    {
        if (logger.IsDebugEnabled)
            logger.DebugFormat("Could not parse value \"{0\" to a int using the culture \"{1}\".", value, inCulture);
    }
}

If repetition is your primary concern, you could try doing something like this:

public delegate string ParserMethod(string value, NumberStyles numberStyle, CultureInfo inCulture, CultureInfo outCulture);

public static class NumericParser
{
    public static readonly ParserMethod ParseInt = Create<int>(int.TryParse);
    public static readonly ParserMethod ParseFloat = Create<float>(float.TryParse);
    public static readonly ParserMethod ParseDouble = Create<double>(double.TryParse);
    public static readonly ParserMethod ParseDecimal = Create<decimal>(decimal.TryParse);

    public static Logger Logger { get; set; }

    delegate bool TryParseMethod<T>(string s, NumberStyles style, IFormatProvider provider, out T result);
    static ParserMethod Create<T>(TryParseMethod<T> tryParse) where T : IFormattable
    {
        return (value, numberStyle, inCulture, outCulture) =>
        {
            T result;
            if (tryParse(value, numberStyle, inCulture, out result))
            {
                return result.ToString(null, outCulture);
            }
            else
            {
                if (Logger != null && Logger.IsDebugEnabled)
                    Logger.DebugFormat("Could not parse value \"{0}\" to a {1} using the culture \"{2}\".", value, typeof(T).Name, inCulture);
                return "";
            }
        };
    }
}

This way, you only have to pass around the appropriate ParserMethod you want to use.  In your case, you could map your different mapping values to the appropriate ParserMethod.  And call it when needed.


Find the 10001st prime number (in C++) I wrote this solution for project Euler #7, to find the 10001th prime number using sieve of eratosthenes. It's really slow though. Any suggestions to improve performance (without using more complex sieves like sieve of atkin)?

#include<iostream>
#include<bits/stdc++.h>
#include<climits>
#define max 500000
using namespace  std;

int main()
{
 int ctr = 0;
 int i=2,j,n=10001,p=2;
 int arr[max];
 memset(arr,0,sizeof(arr));
 while(1)
 {

 p=2;
 while(p*p<=i)
 {

  if(arr[p] == 0)
     for(j=p*p;j<=i;j+=p)
        arr[j] = 1;

        p++;

    }
   if(arr[i]==0)
    ctr++;
   if(ctr==n)
    break;
   i++;

  }

 cout<<i;

 }

Why is everybody using #include<bits/stdc++.h>? It is so hard to include <cstring> to get memset working?
Why do you need <climits>?
Don't use using namespace std;. It's a bad practice.
Static array of ints with size 500000 is likely too big to fit into stack. Use int * arr = new int[max] and delete [] arr; instead.
Using whole integers to store boolean value is just a waste of memory.
It takes 42 seconds to find result. My version (without sieve) takes about real: 0.015s, user: 0.013s.

#include <iostream>

bool isPrime(int num) {
  for (int i = 2; i*i <= num; ++i) {
    if ((num % i) == 0) return false;
  }
  return num > 1;
}

int main() {
  int i = 2;
  for (int primes = 0; ; ++i) {
    if (isPrime(i)) {
      if (++primes == 10001) {
        std::cout << i << "\n";
        break;
      }
    }
  }
}


Read and sort 100 numbers from a text file The program itself reads 100 values from a text file named input.txt. Then sorts those values in ascending order and writes the values to a new file called output.txt.
I used two try-catches for the Scanner and the PrintWriter since to my very basic knowledge they can throw different exceptions. So if anyone can review the code and let me know if my style is bad/good and what could be better, that would be much appreciated.
    //Create new file in, used for input.
    File in = new File("input.txt");

    /* Used two try-catch blocks to narrow down the potential error.
    * Read online if you use try-catch you want to keep them as
    * narrow as possible to know what to catch.
    * If this is bad style let me know.
    */

    try {
        Scanner input = new Scanner(in);
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = input.nextInt();
        }
        input.close();
        Arrays.sort(numbers);
    } catch (FileNotFoundException e) {
        /*Assume the file is missing since new Scanner(in);
        * will implicitly check if the input file actually exists.
        */
        System.err.println("File missing. Exiting with code: 1");
        System.exit(1);
    }

    try {
        PrintWriter output = new PrintWriter("output.txt");
        for (int i = 0; i < numbers.length; i++) {
            output.println(numbers[i]);
        }
        output.close();
    } catch (IOException ex) {
            System.err.printf("File name does not denote an existing, writable regular file %n"
                            + "and a new regular file of that name cannot be created%n"
                            + "Or another error occured creating/writing to the specified file.%n"
                            + "Exiting with code: 2");
            System.exit(2);
    }

File in = new File("input.txt");

Do not shorten variable names, it makes the code harder to understand and maintain.

        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = input.nextInt();
        }

I'm a very persistent advocate that you're only allowed to use single-letter variable names if you're dealing with dimensions. Even for simple for loops one should use index or counter or something similar descriptive.

    try {
        Scanner input = new Scanner(in);

Could have used a try-with-resources instead.

System.exit(1);

Just as a note, that is not "let's exit the application" kind of call, it's "let's end the JVM abruptly" kind of call. When calling System.exit, not even finally blocks will be executed.

for (int i = 0; i < numbers.length; i++) {

You could use a for-each instead.

            System.err.printf("File name does not denote an existing, writable regular file %n"
                            + "and a new regular file of that name cannot be created%n"
                            + "Or another error occured creating/writing to the specified file.%n"
                            + "Exiting with code: 2");

That's completely unhelpful error handling and is on the same level as Microsoft Windows' infuriating "Your PC had a problem :)" message. Never throw away error information that you have, it will make debugging a lot harder. Printing the exception message would be a minimum that you should do because from that error message, even though you did put a lot of thought and work into it, it's completely impossible to deduce the actual error and what to do to remedy it.
Short story time: I've been working with a third-party service lately and that service tries to contact yet another service. Whenever there is a problem with the communication with the other service, the service will spew out the log message "Failed to communicate with that other service, is the other service really already started?" followed by the exception message that clearly shows that an HTTP response was received. Not helpful, because you know that somebody will get hung up at some point on that message even though the question is bogus.

Coming around to your actual question, if you put your logic into a method of its own, your question simply goes away.
public static final void sortContent(File inputFile, File outputFile) throws IOException {
    // TODO Add verification that inputFile is not null.
    // TODO Add verification that outputFile is not null.

    int[] numbers = new int[100];

    try (Scanner scanner = new Scanner(inputFile) {
        // Logic goes here.
    }

    // Rest of logic goes here.
}

Now all you need to worry about is closing the resources correctly, which the try-with-resources will do for you. The IOException will simply being thrown and bubble up until it is being handled. For example in your main method:
public static final void main(String[] args) {
    try {
        sortContent(new File("input.txt"), new File("output.txt"));
    } catch (IOException e) {
        ex.printStackTrace();
    }
}

If you feel especially inclined to provide more information, you can always wrap the thrown exception.
public static final void sortContent(File inputFile, File outputFile) throws IOException {
    // ...

    try (Scanner scanner = new Scanner(inputFile) {
        // ...
    } catch (IOException e) {
        throw new IOException("Failed to read from input file <" + inputFile.toString() + ">.", e);
    }

    // ....
}

Notice that we do not throw away the original exception, but instead use it as cause for the one we are throwing.

Optional appendix: Why are one letter variable names not so good and should be avoided if possible?
Good code is expressive, as it is with the spoken language, expressiveness tends to depend on three things:

More letters
More words
The correct terms

If we only use few letters to communicate something, we are not very expressive, example "ltns gr8 cu 2d asap". Of course this is readable to some, but not as widely as if it would be a written as "long time no see, great idea, see you tonight as soon as possible".
If we only use few words to communicate something, we are not very expressive, example "tomorrow margaritas". Again, we can deduce the meaning if we are familiar with the context, but without the necessary context we have a hard time understanding "We'll meet tomorrow at your place, I bring the margaritas".
If we use the incorrect terms to communicate something, we are note very expressive, example "you can use our typewriter". Again, it will take use much longer to figure out that "typewriter" is used her interchangeably with "printer".
So we can establish the simple rule: The more expressive, the better.
Let's map this to code. We do not always have the luxury of being aware of the complete context of the code we are looking at. Here is a simple example:
a[i] = a[i] + 5;

We can deduce from this line the following assumptions:

a is an array, very likely int.
i is very likely a loop counter.
5 is added to the value at the index i.

There's a good chance that these assumptions would be correct. However, we still do not know what a is, or what range i has (spoiler: we'll never know, actually), or why 5 is being added to these values. So if we look at the same snippet with better naming, at least the first question becomes clear:
readValues[index] = readValues[index] + THE_MAGIC_VALUE_THIS_NAME_TELLS_YOU_SOMETHING;

Notice how index still doesn't tell us much besides "it's most likely a loop over the whole array, otherwise it would have a better name". But if we swap out index with counter, we suddenly have a completely different meaning of this line:
readValues[counter] = readValues[counter] + THE_MAGIC_VALUE_THIS_NAME_TELLS_YOU_SOMETHING;

We know that it is very likely not a loop over the whole array, but instead over a different range, maybe this is not even a for loop, but a while loop. So with a simple name change we can already transport some meaning. Let's build up a larger example:
// Assume a to be non-null int[]

for (int i = 0; i < a.length; i++) {
    for (int j = a.length - 1; j > i; j--) {
        if (a[i] == a[j]) {
            storeForLater(a, i, j);
        }
    }
}

Additionally, because the code was refactored the names carried over into the function that we call inside the loops, storeForLater(int[] a, int i, int j). And I believe at this point we can all agree that the names are not that good. Also notice how I sneakily extended the scope of the argument by introducing the refactored method. Let's see if we can improve that with proper names:
for (int leftIndex = 0; leftInex < readValues.length; leftIndex++) {
    for (int rightIndex = readValues.length - 1; rightIndex > leftIndex; rightIndex--) {
        if (readValues[leftIndex] == readValues[rightIndex]) {
            storeForLater(readValues, leftIndex, rightIndex);
        }
    }
}

Now that's quite a mouthful, but every line on its own has become much more expressive. Let's have an isolated look at the if:
if (a[i] == a[j]) {

if (readValues[leftIndex] == readValues[rightIndex]) {

Given the more expressive names in the second if, we can make quite a few assumptions more about the code and what it is supposed to do and what it is about.
Let's do another quick example, assume the following line of code:
    s[j][i] = getValueFromExternalSource(i, j);

Speed question: What is i and j?
Yes, "a loop counter" is also a correct answer I guess.
    spreadsheet[column][row] = getValueFromExternalSource(row, column);

As we can see, that one cleared it up quite nicely.
I earlier said  that "you're only allowed to use single-letter names when dealing with dimensions", what I meant are "x", "y" and "z" (possible "w" and "v", if you need another two), because these are on their own expressive enough and there is not really a more expressive way:
for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        process(data[x][y]);
    }
}

That's as good as it gets when you simply deal with two dimensional data, or more dimensions. So there is no really a point in enforcing "dimensionX" or "indexX" or something like that. Yet I still feel the need to point out that if you're working on data that is consisting of rows and columns, row and column would be the preferred names for the loop.
We've already seen that the gains are not world-changing, but still quite interesting and in some cases can be significant. Now let's move on the whole point of the exercise: Production code. Does it matter whether or not you use i in your exercise snippets? No, it does not. Does it matter whether you use i in your production code? Given that I have seen code that is 40 years old and still is maintained, I'd say yes, yes it does. The worst example in this regard was a 250 line logic that was something like this:
// Lots of setup code.

for (int x = 0; x < someArraySize; x++) {
    // Some logc goes here.

    for (int a = 0; a < someOtherValueCantRemember; a++) {
        // More logic goes here.

        for (int b = someValue; b < yetAnotherValue; b++) {
            // The main part of the logic.
        }

        // A little bit of logic here.
    }

    // Some more logic here.
}

Again, we can all agree that this code is already badly structured, I believe it was something around 8 years or so old and the programmer long since gone. But especially in this case every name counts to make sure that you're able to follow the code. On my 1920x1080 screen I can see ~65 lines of code at once, in this case it means the logic was 4 pages long. That's quite some scrolling you have to do if you need to look up what a variable does because "a" tells you exactly nothing. And no, x had nothing to do with a dimension, it was a normal index loop.
Short interjection for everyone who now wants to say "At my work we throw that away and rewrite it": Great for you! Our customers pay for features, and redoing work our own company has done is not a feature.
Short interjection for everyone who now wants to say "Maybe you should find a better place to work, yours sucks": Great, thank yo! In the mean time I'd like to pay rent and buy food.
Back on topic, code like this is very, very common in software that had some point a deadline and a release. There are heaps and heaps of it, and the likelihood that you will encounter this than properly structured code is very good. What we can do, what we should try every day, is not to add to this pile, by writing the best code we can. And in my opinion, we should do our best to make every single line stand on its own as could as we can, without as much context as we can, because if the project is non-trivial, this line might be the only thing another programmer sees from our logic. If somebody is for example following a stacktrace, they will not want to familiarize themselves with every single piece of code on the way (who's got the time?). So every single line must be as expressive as possible.
Last but not least, I said it does not matter what you use in your exercises, so why to I raise the point in this review? Habit. Humans are pieces of habit. Making exceptions to a rule is always a bad thing, because you now have a special case at your hand that you need to deal with, that you need to remember, that you need to honor. Not making exceptions to a habit is much easier.


Git hook to detect existing tag case insensitive In my company, we use git as VCS, the main server run under linux but all our code is for Windows and we all develop on Windows.

The git tag system is case sensitive on linux but is case insensitive on windows.
That is:

under linux Test/Tag and TEST/Tag are different tags
under windows Test/Tag and TEST/Tag are the same tag

We had a lot of issues from that.

So we decided to add a git hook on server side, that is, a script that will test if a pushed tag already exists on the server case insensitively.

Here is the content of the pre-receive git hook.

#!/bin/sh

process_ref() {
        target="$2"   # target hash. 0s for a delete command
        refname="$3"  # the full ref name

        #detect tags
        case "$refname" in
                refs/tags/*)

                # use grep to count matching refs in .git/refs/tags folder (case unsensitivly)
                count1=`find ./refs/tags -print | grep -ic $refname`

                # use grep to count matching refs in packed-refs if present
                if [ -e "./packed-refs" ]; then
                        count2=`grep -ic "$refname" ./packed-refs`
                else
                        count2="0"
                fi

                # abort if the ref already exist and it's not a delete ref command
                if ([ $count1 -ne 0 ] || [ $count2 -ne 0 ]) && [ $target != "0000000000000000000000000000000000000000" ]; then
                        echo "push failed"
                        echo "tag already exists: $refname"
                        echo "please contact dev team"
                        exit 1
                fi
        esac
}

# iterate thru all given refs.
while read REF; do process_ref $REF; done

Finding existing Git tags

The files in a Git repository's meta storage,
such as the content of ./refs/tags, ./packed-refs,
are not API.
It's best to interact with Git through commands.

You can get the list of tags with the git tag -l command.
This will include packed refs as well.

Use early returns

The hook collects counts of matching tags, then matching packed refs,
and finally it decides if it should fail based on the collected counts,
and if the operation is not a delete.
It's usually better to not delay actions when you have enough information to take them.

For example,
very early in the process_ref function you can already know if it's a delete operation.
It would be better to return 0 right there,
to avoid any further unnecessary processing.

The same goes for checking the counts.
If the first count in tags is non-zero,
you can already fail without further processing.

Use grep -q instead of grep -c and checking for non-zero

When grep -q finds a match,
it stops further processing.
grep -c continues until the end of the input to collect all counts.
That's not necessary in your example.

Use more strict pattern matching

Using grep -ic $refname to find a matching ref in the list of refs may leave room for false positives.
For example if there is a tag v1.1,
and then you try to push v1, it will fail.
This is a bit tortured example,
because obviously you won't release v1 after v1.1,
but it's good to be aware of this point.

You could make the matching more strict by adding a $ to anchor the end.
If both the beginning and the end can be anchored,
then you could use the -x flag of grep to match entire lines.
Now that would be rock-solid strict.

Always quote parameters

Even though you know that $refname will never contain unsafe characters,
it's a good habit to always surround with double-quotes when used as command arguments, for example in grep -ic "$refname".

Use $(...) instead of `...`

`...` is obsolete, use $(...) instead.

Alternative implementation

Putting the above together (and some more),
I'd implement the hook like this:

#!/bin/sh

is_delete() {
    [ "$1" = "0000000000000000000000000000000000000000" ]
}

tag_exists() {
    git tag -l | grep -qix "$1"
}

fail() {
    echo "push failed"
    echo "tag already exists: $1"
    echo "please contact dev team"
    exit 1
}

process_ref() {
    target="$2"   # target hash. all 0s for a delete command
    refname="$3"  # the full ref name

    is_delete "$target" && return

    case $refname in
        refs/tags/*)
            tagname=${refname#refs/tags/}
            tag_exists "$tagname" && fail "$refname"
    esac

    return 0
}

while read REF; do process_ref $REF; done


Count solutions of a equation with a constraint How to count the solutions of the equation \$x \cdot y + x \cdot z + y \cdot z = n,  (0 \leq n \leq 10^4)\$ with the constraint that \$x \geq y \geq z \geq 0\$ ?

To solve this i've isolated the z value and brute-forced the values of x and y. If the values x,y,z satisfy the constraint and equation than its a valid solution.

#include <stdio.h>

int main () {
    int x,y,z,n,counter;
    while ( scanf("%d", &n), n != -1 ) {

        counter = 0;

        for ( x = n ; x >= 0; --x ) {
            for ( y = x ; y > 0 ; --y ) {
                z = (n - x*y);

                //negative z isn't valid
                if(z < 0)
                    continue;

                z /= (x + y);

                if( z <= y && y <= x && x*y + x*z + y*z == n ) {
                    ++counter;
                }
            }
        }

        printf("%d\n",counter);
    }
    return 0;
}

The input contains several lines with one value for n. The program must stop when this value is -1.

The output is the number of solutions of the equation in separated lines.

Sample Input:

20
1
9747
-1

Sample Output:

5
1
57

How to make this code faster ?

Repeating work

Suppose one test case were 9747 and another test case were 9748.  Right now, you do the full work for each test case, throwing away the work done for other test cases.  This causes your program to take a long time if there are many large test cases.

There is a way to compute all the answers for each of the 10000 test cases in one computation, so you can immediately find the answer to any test case instantly after that.

Sieve-like algorithm

This algorithm works similar to the Sieve of Eratosthenes.  It loops through each (x,y,z) combination and increments count[n] by one.  Once that is done, count[n] is the answer for any test case n.

#include <stdio.h>

#define MAX        10000
int counts[MAX+1];

int main(void)
{
    int x, y, z, n;

    // For each (x,y,z) combination, increment counts[n] by one, where
    // n = x*y + x*z + y*z, or in other words: n = x*y + z*(x+y)
    for (x = 0; x <= MAX; x++) {
        for (y = 0; y <= x; y++) {
            int sum = x+y;
            for (z = 0, n = x*y; z <= y && n <= MAX; z++, n += sum) {
                counts[n]++;
            }
        }
    }

    // Read test cases and print out answers.
    do {
        scanf("%d", &n);
        if (n == -1 || n > MAX)
            break;
        printf("%d\n", counts[n]);
    } while(1);

    return 0;
}

Timing comparison

The sieve program takes 0.04 seconds on my computer no matter how many test cases are thrown at it.  The original program took 0.03 seconds for the sample input shown (3 test cases), but it took 0.56 seconds to handle a test input of 20 large test cases (9900..9919).  So as you can see, the original program is \$O(n)\$ on the number of test inputs when it could be made to be \$O(1)\$ using the sieve method.


JOIN and sprintf rather than two queries and echo It works fine, however it's a little messy. I understand it would be better for performance to use JOIN and have been advised before to use sprintf. However, it's pretty confusing and I cannot understand the PHP tutorials on it.

<?php
$exerciseID = get_the_ID();
$blogUrl = get_site_url();

global $wpdb;

$getImageIdQuery = "
SELECT image_map
FROM wp_posts
WHERE ID = '".$exerciseID."'";

$imageID = $wpdb->get_results($getImageIdQuery);

foreach($imageID as $row2) {
 }

$mappedImage = $row2->image_map;

$query = "
SELECT id
FROM imagemap
WHERE exercise = '".$mappedImage."'";

$result = $wpdb->get_results($query);

foreach($result as $row) {
 }
echo '
';
echo '
' .the_title(). '
';
echo '
';
echo "id. ".jpg />";

?>

Escaping Variable Part of Query

Check out this and this post about correctly using the wordpress database class to avoid SQL injection. Even if the variable data is not directly user supplied, I would always use prepared statements or at least escape data as defense in depth, and to prevent second order SQL injection.

Your code should look something like this:

$getImageIdQuery = "
SELECT image_map
FROM wp_posts
WHERE ID = %d";

$sql = $wpdb->prepare( $getImageIdQuery, $exerciseID );
$imageID = $wpdb->get_results($sql);

Same goes for the other query (the added benefit is that this way, you don't need sprintf because the SQL code and the PHP code are already separated).

Escaping Variable Part of Output

I would also sanitize all variable data when echoing it to the user. Right now, anybody who can create posts can include arbitrary javascript via the_title. This might actually be ok, but still, to be save I would write it like this:

echo '
';
echo '
' . esc_html(the_title()) . '
';
echo '
';
echo "id. ".jpg") . "/>";

Foreach

You have two foreach statements which do not do anything. but their side-effect is that your are always only working on the last entry retrieved by the query.

Instead of returning all matching entries, you should only retrieve this one entry and remove your foreach loops (you can use get_row (if needed in combination with limit and order by)).

Misc

I would use more spaces to make the code more readable (for example around .). See also the wordpress style guide.
use single and double quotes consistently (for example "<img src=" vs '
'; both should use single quotes)

sprintf

I don't really like using sprintf, but if you want to, it would look like this:

echo '
';
echo sprintf('
%s
', esc_html(the_title()));
echo '
';
echo sprintf("", esc_url($blogUrl . "/image/medium/".$row->id. ".jpg"));

%s is a placeholder for any string (you would use %d for numbers), and it will be replaced by the rest of the arguments for sprintf.

The advantage is that you do not have PHP variables/function calls inside your HTML/SQL/etc.

join

You can read about join here and a bit more in-depth here.

Your query should look something like this:

SELECT imagemap.id FROM imagemap JOIN wp_posts ON imagemap.exercise = wp_posts.image_map WHERE wp_posts.ID = $exerciseID

What it basically does is combine the two tables (based on the ON clause).

For example, if the tables looked like this:

imagemap:
id exercise
1  1
2  2
3  2
4  3

wp_posts:
pid image_map
6   1
7   1
8   2

the combined table would look like this:

id exercise pid image_map
1  1        6   1
1  1        7   1
2  2        8   2
3  2        8   2

and then the where clause is applied (I called wp_posts.ID pid for the example).


Find the smallest number Q whose product of digits is N How do I make this efficient?

#include <stdio.h>
#define MAX 1000000000

int main()
{
    int n,temp,prod,i,j=0;
    scanf("%d",&n);

    for(i=1;i<MAX;i++)
    {
        temp=i;
        prod=1;
        while(temp!=0)
        {
           prod=prod*(temp%10);
           temp=temp/10;
        }
        if(prod==n)
        {
            printf("%d",i);
            j=1;
            break;
        }

    }
    if(j==0)
    {
        printf("-1");
    }
    return 0;
}

An efficient solution would be to express n as its prime
  factorization \$2^a3^b5^c7^d\$. Then, try to regroup those factors into the
  fewest number of 2, 3, 4, 5, 6, 7, 8 digits possible, in increasing
  order. If n has a prime factor larger than 7, then there is no
  solution.

The right way to group the \$2^a3^b\$ factors in 2,3,6,8,9 digits is first to minimize the number of digits, giving priority to \$2^3\$. You then end up with \$3^b\$ or \$2^13^b\$ or \$2^23^b\$. For \$b>2\$ you group by \$3^2\$. I then solved all the solutions for \$2^a3^b\$ with \$a,b\leq2\$ and figured out that the following precedence works : (9,8,7,6,5,4,3,2). So there must be a more elegant proof!

Note that the solution will have at most one 2 or one 3 or one 4.

int numberOfFactor(int * n, int factor)
{
    int number_of_factor = 0;
    while (*n % factor == 0)
    {
        *n /= factor;
        number_of_factor++;
    }
    return number_of_factor;
}

int appendDigits(int digit, int n_digit, int initial_shift)
{
    int i;
    int ret = 0;

    for (i=0; i<n_digit; i++)
        ret = ret + digit * pow (10, i + initial_shift);

    return ret;
}

int main()
{
    int n;
    int q;
    int n9, n8, n7, n6, n5;
    scanf("%d", &n);

    if (n <= 9)
    {
        printf("%d", n);
        return 0;
    }

    n9 = numberOfFactor(&n, 9);
    n8 = numberOfFactor(&n, 8);
    n7 = numberOfFactor(&n, 7);
    n6 = numberOfFactor(&n, 6);
    n5 = numberOfFactor(&n, 5);

    if (n>4)
    {
        printf("-1");
        return 1;
    }

    q = appendDigits(9,n9,0)
      + appendDigits(8,n8,n9)
      + appendDigits(7,n7,n9+n8)
      + appendDigits(6,n6,n9+n8+n7)
      + appendDigits(5,n5,n9+n8+n7+n6)
      + ((n!=1)?appendDigits(n,1,n9+n8+n7+n6+n5):0);

    printf("%d", q);
    return 0;
}

My first post, please be indulgent.


Interpreting a basic math string I've written code that will take any basic math sum input as a string (for instance, 2*3+4/4) and solve it. The way I achieve this is by splitting the string into sub-strings, with multiplication and division being done first (based on the regular order of operations). So in our example sum we would be left with 2*3 and 4/4.

It then solves these sums and replaces the original sub-string with the answer : 2*3+4/4 would become 6+1. The numbers left in the addition string are then added into an array. All elements in the array are then added.

The part of my code in question is the function that identifies if there are any multiplication or division operations left to do, and if so, performs them. I feel like this function is very long and cumbersome and needs to be shortened, hence why I'm posting it here on CodeReview.

void mathInterpreter::format()
{
    BasicQuestion TempQuestion;
    basic_ops *solver = new basic_ops();

    //If we have multiplication or division in our sum then we should do this loop.
    for (int i = 0; MultDevCount != 0; i++)
    {
        //get some information about the question we are on, and create a temp string.
        op_positions temp;
        temp = positions_d[i];
        std::string temp_str;

        double MyAnswer;

        //if the operation that we are on in the for loop happens to be a multiply or divide, then lets do that.
        if (temp.operation == MULTIPLY || temp.operation == DIVIDE)
        {
            if (operation_count == 1) /* ONLY ONE OPERATION */
            {
                temp_str = user_string;
            }
            else if (positions_d[i].operation_at == positions_d.front().operation_at) /* FIRST OPERATION IN SUM */
            {
                temp_str = get_sum(temp, 0, positions_d[i + 1].operation_at);
            }
            else if (positions_d[i].operation_at == positions_d.back().operation_at) /* LAST OPERATION IN SUM */
            {
                temp_str = get_sum(temp, positions_d[i - 1].operation_at, 0);
            }
            else /* THE OPERATION IS IN THE MIDDLE OF THE SUM */
            {
                temp_str = get_sum(positions_d[i], positions_d[i - 1].operation_at, positions_d[i + 1].operation_at);
                if (positions_d[i - 1].operation == SUBTRACT) temp_str = SUBTRACT_SYM + temp_str;
            }

            //setup the return question properly and then send it to the solver.
            TempQuestion = quest_from_tuple(get_nums(temp_str));

            answer SumAns;

            SumAns = solver->performCalc(TempQuestion);
            MyAnswer = SumAns.answer;

            if (SumAns.error)
            {
                error = true;
                delete TempQuestion.numbers;
                return;
            }

            //replace the original sum string with it's answer string.
            user_string = replace_strings(std::to_string(MyAnswer), temp_str, user_string);

            delete (TempQuestion.numbers);

            //sort operation counts.
            operation_count = CountOperations();
            positions_d.clear();
            populate_op_positions();

            //an operation has been removed, so positions_d[i] may have changed. If positions_d[i] is still a mult or dev, we need to
            //redo this loop with the same value for i. So subtract one so that the loop is redone with the same value.
            if (positions_d[i].operation == MULTIPLY || positions_d[i].operation == DIVIDE) i--;

        }
    }

}

Some additional information: positions_d is a deque which holds struct elements - the struct contains the position of an operation and what it is.

The get_sum() function takes in a struct element (same struct as mentioned above) and the positions of the operations before and after it. It will then return a string with two operands and the operation (e.g. 2*3).

My advice here is not to use C++ (directly) for this type of job. There are tools out there to help you parse formatted streams (you have to learn another tool though).

Personally I use flex and bison. BUT I recommend you look around and see if there are more modern version or alternatives.

Flex Rules

This converts a stream of characters into a stream of tokens.

%%
\+              return '+';
\-              return '-';
\*              return '*';
\/              return '/';
\(              return '(';
\)              return ')';
{Number}        return 259;
{WhiteSpace}    /* Ignore */
.               throw std::runtime_error("Invalid Character");
%%

Bison Rules

This converts a stream of tokens and build a parse stack that is processed.

%%
result  :   exp                     {value = $1;}
exp     :   add_exp
add_exp :   mul_exp
        |   add_exp '+' mul_exp     {$$ = $1 + $3;}
        |   add_exp '-' mul_exp     {$$ = $1 - $3;}
mul_exp :  pri_exp
        |   mul_exp '*' pri_exp     {$$ = $1 * $3;}
        |   mul_exp '/' pri_exp     {$$ = $1 / $3;}
pri_exp :   '(' exp ')'             {$$ = $2;}
        |   Number
Number  :   NUMBER                  {$$ = getCurrentNumber();}
%%

The actual files are slightly bigger as there are some boiler plate that you need get everything working together. But this boilerplate is very similar so once you have it no need to worry about it. The languages are very concise and understandable (but that is relative).

A lot of research has already been done on parsing so there is very little need to reinvent the wheel.


Histogram of Maxwell-Boltzmann distribution The following C# source code creates a histogram of Maxwell-Boltzmann's distribution:

using System;
using System.Drawing;
using ZedGraph;

public class CommonDistributions
{
    public static double Uniform(Random random)
    {
        return random.NextDouble();
    }

    static double Gaussian(Random random)
    {
        return Math.Sqrt(-2 * Math.Log(Uniform(random))) * Math.Cos(2 * Math.PI * Uniform(random));
    }
    public static double Gaussian(Random random, double mu, double sigma)
    {
        return sigma * Gaussian(random) + mu;
    }
}

public class MaxwellBolzman
{
    private static double KB = 1.38064852e-23;

    public static double MaxwellVariance(double mass, double temperature)
    {
        return Math.Sqrt(KB * temperature / mass);
    }

    public static double MaxwellComponent(Random random, double mass, double temperature)
    {
        double mu = 0.0;
        double sigma = MaxwellVariance(mass, temperature);

        return CommonDistributions.Gaussian(random, mu, sigma);
    }
    public static double MaxwellSpeed(Random random, double mass, double temperature)
    {
        double one = MaxwellComponent(random, mass, temperature);
        double two = MaxwellComponent(random, mass, temperature);
        double thr = MaxwellComponent(random, mass, temperature);

        return Math.Sqrt(one * one + two * two + thr * thr);
    }
}

public static class Normalization
{
    public static int Normalize(double n_bins, double mu, double sigma, double gaussian)
    {
        var z = (mu - gaussian)/sigma;

        if (z > 3 || z < -3)
        {
            return -1;
        }
        else
        {
            return (int)((z + 3) * n_bins / 6d);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        const double N = 1000000;
        int time = (int)N;
        int binsCount = 51;

        Random rand = new Random();
        int[] bins = new int[binsCount];

        double mass = 14 * 1.67e-27;
        double T = 300;

        for (int i = 0; i < time; i++)
        {
            double gauss = MaxwellBolzman.MaxwellSpeed(rand, mass, T);
            double mu = MaxwellBolzman.MaxwellComponent(rand, mass, T);
            double sigma = MaxwellBolzman.MaxwellVariance(mass, T);

            int index = Normalization.Normalize(binsCount,  mu, sigma, gauss);

            if (index >= 0)
            {
                bins[index]++;
            }
        }

        PointPairList list = new PointPairList();
        for (int i = 0; i < bins.Length; i++)
        {
            list.Add(i, bins[i]);
        }

        PlotForm form = new PlotForm("Maxwell-Bolzman");
        form.AddBar(list, "Actual", Color.Blue);
        form.AxisChange();
        form.ShowDialog();
    }
}

Kindly, review the code.

N.B. The curve seems to be off the shape.

Static classes

You've (correctly) marked Normalization as static. You should do the same for every other class in your program - they are all currently being used as statics.

Expression bodies

C# has a wonderful bit of syntactic sugar - expression bodies - that lets you rewrite this:

public static double MaxwellVariance(double mass, double temperature)
{
    return Math.Sqrt(KB * temperature / mass);
}

as

public static double MaxwellVariance(double mass, double temperature) =>
    Math.Sqrt(KB * temperature / mass);

Classes

You're in C#, so you're stuck without the ability to have global functions. It's somewhat similar to Java in this way: it really pushes you to think about your code in an OOP style.

Going down this path, you would make a class to encapsulate your graph, which would take most of the code out of your Main. Potentially, everything up to and including the initialization of your point list could go in the constructor, and the PlotForm calls could go in a plot method. There are some advantages to this approach, including reusability, re-entrance, and testability.

As for MaxwellBolzman - I think you should refactor it to be a non-static class, with members for mass and temperature. random can be accepted as an optional parameter or the class could instantiate it itself. That will simplify many things:

Variance will turn into a one-line property with an expression body
Component and Speed will turn into parameter-less properties

Names

This is minor, but I find the Maxwell prefixes in all of the methods of MaxwellBolzman to be redundant; I think they would be even more legible if you simply named them Variance, Component and Speed.

Loops

I would find Speed more legible as

double sum = 0;
for (int i = 0; i < 3; i++) {
    double comp = Component;
    sum += comp*comp;
}
return Math.Sqrt(sum);


Javascript reducing an array of arrays to a single array with concat or push Which is more efficient? (Both memory usage and speed.)

arrayOfArrays.reduce((acc, innerArray) => {
  acc.push(...innerArray);
  return acc;
}, []);

Or

arrayOfArrays.reduce((acc, innerArray) => acc.concat(innerArray), []);

The first one is more efficient in a sense that you're just reusing the array, and not recreating one on each iteration like the other one. However, neither of them are "efficient" in a sense that you're still looping... and there's actually a better way.

array.concat accepts multiple args. You can just use the spread operator to spread the arrays in the array as its args.

const arr = Array.prototype.concat.call([], ...arrayOfArrays)

Or the older way to do it is using function.apply

const arr = Array.prototype.concat.apply([], arrayOfArrays)

I'm being too formal and all. A shorter version of the spread looks like:

const arr = [].concat(...arrayOfArrays)

Choose your weapon:

const arrayOfArrays = [[1,2], [3, 4], [5, 6]]
const arr1 = Array.prototype.concat.call([], ...arrayOfArrays)
const arr2 = Array.prototype.concat.apply([], arrayOfArrays)
const arr3 = [].concat(...arrayOfArrays)

console.log(arr1)
console.log(arr2)
console.log(arr3)


Unit testing F# code without using an existing test library (MSTest, xUnit, etc.) I know I can probably use MSTest (I'm under Linux without an IDE so maybe not?) or another unit testing library, but for a small project I decided to write my own unit tests without resorting to a framework (for fun and for learning).

Right now, I have only one type of assert and one test but I would like a code review to improve my code now to make sure I am on the right track.

module Tests

// modules under test
open HeightMap
open MidpointDisplacement

// assert functions
let assertAreEqual expected actual =
    printf "... "
    if expected <> actual then printfn "%s" ("Test failed, expected " + expected.ToString() + ", actual " + actual.ToString())
    else printfn "Test passed"

// tests
let testNewHeightMapReturnZeroInitializedHm () =
    let hm = newHeightMap 5
    let result = hm.Map |> Array.sum
    assertAreEqual 0.0 result

// tests included in run
let testsToRun =
    [
        ("test newHeightMap will return a 0 initialized height map",
         testNewHeightMapReturnZeroInitializedHm)
    ]

// test runner
let runSingleTest test =
    let testName, testFunction = test
    printf "%s" testName
    testFunction()

let runTests =
    testsToRun |> List.map runSingleTest |> ignore
    printfn "%s" "Ran all tests."

One thing that bugs me is that I there is some redundancy by specifying the test function and then including it in a list inside a tuple.

Overall this looks ok, just a couple nitpicks:

In assertAreEqual, you're using string concatenation and then passing the resulting string to formatting function. You could use the formatting function to begin with:

if expected <> actual then
    printfn "Test failed, expected %A, actual %A" expected actual
else
    printfn "Test passed"

Parentheses around tuples are not required, so:

let testsToRun =
[
    "test newHeightMap will return a 0 initialized height map",
    testNewHeightMapReturnZeroInitializedHm
]

Function parameters are actually patterns, so you can destructure the tuple right there, instead of on a separate line:

let runSingleTest (testName, testFunction) =
    ...

As a general rule, if you have to use ignore, it means that there is something wrong somewhere. ignore is a hack, a way to squeeze a round peg in a square hole. In your particular case, you're mapping over a list solely for the side-effects. To do this, use List.iter, which returns unit, so no need for `ignore.

testsToRun |> List.iter runSingleTest

The pervasive use of side-effecting computations (i.e. printfn etc.) sets off my spidey sense: this makes your code inflexible (e.g. what if you want to have different reporting formats - one for console run, one for CI server, etc.).
You should structure your code in such a way that it doesn't produce side effects as it runs, but instead produces a value that describes the run, and which can later be used (or not used) to produce the effects. For example, in your case, rather than printing out errors, I would return a list of them, and have the consumer decide what to do with that list. Of course, this would mean significant restructuring of your whole program, so I won't give a code example.
Finally, "parametrize all the things!" Try to take stuff as parameters as much as possible, rather than relying on stuff existing in the environment. For example, the runTests function should really take the list of tests as parameter.
As far as the thing that bugs you, there is an easy solution for it: you don't have to name your functions, you can declare them inline as lambda-expressions:

let testsToRun =
    [
        "test newHeightMap will return a 0 initialized height map",
        fun() ->
            let hm = newHeightMap 5
            let result = hm.Map |> Array.sum
            assertAreEqual 0.0 result
    ]

Or, alternatively, you can give a name to the pair of name+function, and then include that pair in the list:

let theTest = "test newHeightMap will return a 0 initialized height map", fun() ->
    let hm = newHeightMap 5
    let result = hm.Map |> Array.sum
    assertAreEqual 0.0 result

let testsToRun = [ theTest ]


Byte array to floating point such as FPE2 in Java Apple's System Management Controller uses FPE2 and SP78 as floating-point formats.

While writing a Java library that that interfaces with the SMC, I ported someone's C function to convert read a FPE2-formatted byte array as a float.

public static float strtof(byte[] bytes, int size, int e) {
    int total = 0;
    // Add up bits to left of fractional bits
    for (int i = 0; i < size; i++) {
        if (i == (size - 1))
            total += (bytes[i] & 0xff) >> e;
        else
            total += (bytes[i] & 0xff) << (size - 1 - i) * (8 - e);
    }
    // Mask fractional bits and divide
    return total + (bytes[size - 1] & (1 << e) - 1) / (float) (1 << e);
}

The bytes and size parameters come from reading a structure in Apple's SMC interface.  The array is a byte[32] value in a structure, where a second part of the structure states how many of the elements of the array are significant.  In the use case, getting fan speed, bytes[0] and bytes[1] will be populated with data (the other 30 bytes are ignored) and size will have a value of 2.

In the given code, the value of e represents how many rightmost bits out of the size bytes are for the fractional part.  If e is 2 (such as for FPE2), then the final 2 bits can have values 0, 1, 2, or 3 representing the fractions 0.0, 0.25, 0.5, and 0.75.  The remaining leading bits are interpreted as the integer part.

Example input:

bytes = { 0x00, 0x05, 0x00, 0x00, ... } // First 2 bytes binary 101
size = 2
e = 2

Example output: 1.25 // Integer portion is 1, fraction is 1/4.

Did I do it right (assuming arguments are already validated: e will never be more than 8, and size will never be more than 4)?  Points of concern are order of operation, what happens bitwise when I promote a byte to an int and then shift it.

While this function converts an FPE2 format number, I'm trying to make it a bit more general.  A similar format, SP78, is used for temperature.  The rightmost 8 bits (divided by 256) are the fractional portion, the left 8 bits are a signed byte.  (This method is not intended to handle the signed calculation but this is given as a reference.)

Documentation

I took me a while to understand and research the algorithm and the purpose of the function parameters. It would be better to write some Javadoc for reviewers and future readers (which may include yourself).

Identifiers

You should use variable and function identifiers that explain their purpose (barring obvious cases like i for a loop iterator).

strtof is a function defined since C89 and does something very different from your function; that's not a good name here. What about FPxToFloat because the function converts data in a variant of the FP* formats (x instead of *) to a float?
e is the number of bits in the integral part of the number. How about integerBits instead?
total – My first thought was “total of what?”. I usually go for a name like result in these cases since it holds the function result (or an intermediate result on the way to the final result) which should be well documented somewhere nearby.

Limitations

Why is size restricted to ≤ 4 bytes and integerBits restricted to ≤ 8. You say you want a more generic solution. I don't see a reason why size can't be 17 and integerBits 49.
Currently the encoded number needs to start at offset 0 inside the bytes array. Since Java doesn't have C's pointer arithmetic it would be useful to offer an offset parameter like the read and write functions in java.io.

You can still offer a convenience function with less boiler plate:

public static float FPxToFloat(byte[] bytes, int integerBits) {
    return FPxToFloat(bytes, 0, bytes.length, integerBits);
}

Complexity

Your implementation seems overly complicated and suffers from a number of unnecessary limitations (see first point in the section above). What about this:

double result = 0;
int exponent = integerBits - Byte.SIZE;
for (; offset < size; offset++, exponent -= Byte.SIZE) {
    result += Math.scalb(bytes[offset] & 0xFF, exponent);
}
return result;

scalb avoids multiplicative floating-point operations and overflow of integers that shall later be converted to floating-point. The only optimization I can think of is to work on long instead of byte if possible to use the available processor word size better (to achieve that one can wrap byte[] inside a java.nio.ByteBuffer and use a LongBuffer view onto it).

Full program (Ideone is currently acting up here so a Gist it has to be for now.)


Guess user number between 0 and 100 (Binary Search) I am at the beginning of learning python and one of my homeworks (in chapter regarding loops) where to write a code that would guess user number between 1 - 100.

I believe I used algorithm called binary search.

# Introduction
print('\nThink about a number between 0 - 100 and let me guess which is it.',
      '\n\nI will ask you whether my guess is lower or higher than your number',
      '\nIndicate "l" if lower than your number',
        '"h" if higher than your number and',
        '"e" if my guess is correct.'
      '\n\nYou ready?, let"s start!\n')

# Algorithm
count = 0
lborder = 0
hborder = 100
guess = 50

while True:
    answer = input('Is your number higher, lower or equal to ' + str(guess) + ':')
    if answer == 'l':
        hborder = guess
        guess = round((lborder + guess)/2)
    elif answer == 'h':
        lborder = guess
        guess = round((hborder + guess) / 2)
    elif answer == 'e':
        break
    else:
        print('Unrecognizable answer. Use: "l", "h", "e"')
    count += 1

print('\nHooray! It took me', count, 'to guess your number.', sep=' ')
input('\nPress Enter to Exit.')

My question is basically whether there is a better algorithm for finding those numbers (quicker).
Also do you have any other comments about my code.

Your calculation of count is incorrect in two ways:
 1. You don't count your last guess;
 2. You count invalid user input.

I would separate the input validation from the input processing. And I would add some logic to handle user input that leads to trying the same guess repetitively, for this the user has to lie, but who guarantees us they won't?