Minimal webserver in C++ Here's my test question for C++ programmer job:

Servers only static content, no cgi
Single process, multithreaded
1000 concurrent request at least
Valid http status codes and headers
No external libraries, just STL, POSIX and glibc

Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sstream>
#include <vector>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

using namespace std;

    const char *response_200 = "HTTP/1.1 200 OK\nContent-Type: text/html; charset=utf-8\n\nHello!";
    const char *response_400 = "HTTP/1.1 400 Bad Request\nContent-Type: text/html; charset=utf-8\n\nBad Request!";
    const char *response_404 = "HTTP/1.1 404 Not Found\nContent-Type: text/html; charset=utf-8\n\nNot Found!";

void *handle_request(void *pcliefd)
{
    int cliefd = *(int*)pcliefd;
    delete (int *)pcliefd;

    ssize_t n;
    char buffer[255];
    const char *response;

    n = recv(cliefd, buffer, sizeof(buffer), 0);
    if(n < 0) {
        perror("recv()");
        return 0;
    }

    buffer[n] = 0;
    //printf("recv() %s\n", buffer);

    response = response_400;

    string s(buffer), token;
    istringstream ss(s);
    vector<string> token_list;
    for(int i = 0; i < 3 && ss; i++) {
        ss >> token;
        //printf("token %d %s\n", i, token.c_str());
        token_list.push_back(token);
    }

    if(token_list.size() == 3
            && token_list[0] == "GET"
            && token_list[2].substr(0, 4) == "HTTP") {
        if(token_list[1] == "/index.html") {
            response = response_200;
        } else {
            response = response_404;
        }
    }

    n = write(cliefd, response, strlen(response));
    if(n < 0) {
        perror("write()");
        return 0;
    }

    close(cliefd);
    return 0;
}

int main(int argc, const char *argv[])
{
    int sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in servaddr;
    pthread_t thread;

    if(sockfd < 0) {
        perror("socket() error");
        exit(EXIT_FAILURE);
    }

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(8080);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("bind()");
        exit(EXIT_FAILURE);
    }

    if(listen(sockfd, 1000) < 0) {
        perror("listen()");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_storage clieaddr;
    int cliefd;
    char s[INET_ADDRSTRLEN];
    socklen_t cliesize;

    while(true) {

        cliesize = sizeof(clieaddr);
        cliefd = accept(sockfd, (struct sockaddr *)&clieaddr, &cliesize);
        if(cliefd < 0) {
            perror("accept()");
            continue;
        }

        inet_ntop(clieaddr.ss_family, (void *)&((struct sockaddr_in *)&clieaddr)->sin_addr, s, sizeof(s));
        printf("accept() %s\n", s);

        int *pcliefd = new int;
        *pcliefd = cliefd;
        if(true) {
            if(pthread_create(&thread, 0, handle_request, pcliefd) < 0) {
                perror("pthread_create()");
            }
        } else {
            handle_request(pcliefd);
        }
    }

    return 0;
}

The server announces HTTP 1.1, therefore it must support HTTP 1.1 features, most importantly pipelining (client has a right to send multiple requests over the same socket). In any case, if you chose to close the client socket immediately you should inform client with a Connection: close header.
You expect to consume a complete request with a single read. In a streaming world of TCP you never know how many bytes has actually been consumed. You should be prepared to get as little as one byte at a time (same goes for send/write).

A correct way to read the request is to read it in the loop until the end of headers (i.e. an empty string) is seen.
Network program must be defensive. A malicious client can play tricks with your server.

For example, it may never send anything; eventually the server would run out of file descriptors (or pthreads), resulting in denial of service. Another client may close the socket immediately upon sending a request; the server receives a SIGPIPE and dies with a core dump.


Javascript to change element property based on user input In the code below, I take the number of square the user wants, then calculate the size of each square (so that they all fit in the container.)

I then define var square as in the 3rd line of code. I find this string pasting technique very hard to read and error-prone. The general question is thus: Is there a better way to define an element using user input?

var genGrid = function(num_square) {
    var square_size = ($(".grid_container").height() / num_grid) + "px";
    var square = "

";

    $("body").append($(square));
};

As you have already stated passing an HTML string is not the best way to create a new DOM element. You can create a new one using plain Javascript, like this:

var newDiv = document.createElement('div');

and together with few changes to your code, function could look similar to this:

function generateGrid(numGrid) {
    var squareSize = $('.grid_container').height() / numGrid;
    var $square = $(document.createElement('div')); // we create and fetch a new element

    // here come some handy methods from jQuery, please check'em out on jquery.com
    $square.width(squareSize).height(squareSize).addClass('square');
    $('.grid_container').append($square);
}

generateGrid(4);

Hope this will help you!


File Async writer using Tasks or new features of .Net 4.5? This code was posted as answer to Async file writer in .Net 3.5.

How would it be done better using Tasks or new features in .Net 4.5?

public sealed class Logger : IDisposable
{
    private delegate void WriteMessage(string message);
    private static readonly Logger Instance = new Logger();
    private static object Locker = new object();
    private static readonly StreamWriter Writer =
                        new StreamWriter("c:\\temp\\logtester.log", true);
    private static bool Disposed;

    private Logger()
    {
    }

    ~Logger()
    {
        Dispose(false);
    }

    public static void Log(string message)
    {
        WriteMessage action = Instance.MessageWriter;
        action.BeginInvoke(message, MessageWriteComplete, action);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private static void Dispose(bool disposing)
    {
        lock (Locker)
        {
            if (Disposed)
            {
                return;
            }

            if (disposing)
            {
                if (Writer != null)
                {
                    Writer.Dispose();
                }
            }

            Disposed = true;
        }
    }

    private static void MessageWriteComplete(IAsyncResult iar)
    {
        ((WriteMessage)iar.AsyncState).EndInvoke(iar);
    }

    private void MessageWriter(string message)
    {
        lock (Locker)
        {
            Writer.WriteLine(message);
        }
    }
}

Before I explain how would I improve that code, I'll first mention two problems I will not try to fix (because I'm not sure how to do it properly):

Disposable singleton is a really weird combination. If something should be available anytime and anywhere, it should be a singleton. On the other hand, if something has a limited lifetime and holds an expensive resource (like an open file), it should be disposable. Those two don't go together very well.
Finalizer should execute as fast as possible. It certainly shouldn't take a lock that may not be released for quite some time (because there may be many threads also holding the lock).

The problems my solution will solve:

Writing to the log may not be in the correct order, lock doesn't guarantee any ordering.
Dispose() may not write all outstanding messages. This is again because lock doesn't guarantee ordering.
If a write attempt happens after Dispose() (either because Log() was called after Dispose(), or because of the ordering problems mentioned above), an exception will be thrown on the ThreadPool. This exception can't be caught from outside of Logger and will bring down the whole application. (More reason not to have disposable singletons.)
If there are many calls to Log() at the same time, or if the writing takes too long, there may be many threads, all waiting on the same lock.
While the message is being written, there is a thread blocking until it finishes.

My solution using TPL Dataflow (which uses .Net 4.5 extensively, available from NuGet) solves the issues so that:

Writing to the log will be always in the correct order.
Dispose() will first write all outstanding messages before returning.
If Log() is called after Dispose(), it will directly throw an exception.
There will be at most one thread doing the writing, at any time.
While the message is being written, no thread is waiting for it to finish.

public sealed class Logger : IDisposable
{
    private static readonly Logger Instance = new Logger();

    private readonly ActionBlock<string> m_writerBlock;

    private static bool Disposed;

    private Logger()
    {
        var writer = new StreamWriter("c:\\temp\\logtester.log", true);
        m_writerBlock = new ActionBlock<string>(s => writer.WriteLineAsync(s));
        m_writerBlock.Completion.ContinueWith(_ => writer.Dispose());
    }

    public static void Log(string message)
    {
        if (!Instance.m_writerBlock.Post(message))
            throw new ObjectDisposedException("Logger");
    }

    public void Dispose()
    {
        if (Disposed)
            return;

        m_writerBlock.Complete();
        m_writerBlock.Completion.Wait();

        Disposed = true;
    }
}

This works correctly, because the ActionBlock will take care of almost anything needed here, like ordering, synchronization and scheduling Tasks when necessary. WriteLineAsync() returns a Task and the block will use this Task to asynchronously wait for it to finish.


Find first non-repetitive char in a string I just had an interview for the C#.NET developer position and I was asked to find the first non repetitive char in a given string without using any library functions but just the basic constructs of the language such as fors and ifs.

I presented this solution considering the quick time constraint. I request evaluation of the solution of how truly it serves the question.

public static char findFirstNonRepetitiveChar(string input)
{
    char c = '0';

    for (int i = 0; i < input.Length; i++)
    {
        bool isdistinct = true;
        for (int j = 0; j < input.Length; j++)
        {
            if (input[i] == input[j] && i!=j)
            {
                isdistinct = false;
                break;
            }
        }
        if (isdistinct)
        {
            c = input[i];
            break;
        }
    }
    return c;
}

Some of what constitutes a "good" solution here depends on how much value you place on (for example) CPU time vs. memory usage. Another point to take into account is what size of strings you expect to process, and whether you expect them to be mostly unique, mostly repeats, basically random, or exactly what.

As it stands, this uses almost no extra space, but uses \$O(N^2)\$ CPU time. If you expect the input strings to be long, this could be quite prohibitive.

If you didn't mind using extra space, you could (for example) walk through the string, and use a hash table to count the number of occurrences of each character. Then walk through the hash table, and find the characters in the string that only occur once. Mark those, then do a final walk through the string to find which occurred first. This requires two walks through the string, and one walk through a hash table the same size as the number of unique elements in the string, so it's basically 3N operations, or \$O(N)\$ (well, we expect linear complexity, anyway--in the true worst case, it's still \$O(N^2)\$). For a long string (say, a few million or even a few thousand characters) that could be a huge win (but at the expense of approximately doubling the memory usage. If you're concerned with worst case performance more than average, you might want to use a balanced tree instead of a hash table, so insertions are \$O(N log N)\$ (both expected, and worst case).

Which one is preferable will (mostly) come down to questions like those in the first paragraph. For typical short strings (less than 20 characters long is very common), either is likely to be fast enough that a more efficient algorithm won't make much real difference. On the other hand, if the input might be megabytes instead, the faster algorithm is likely to pay off--and even if it's several megabytes, allocating an extra several megabytes on a modern desktop (or server) machine rarely matters a whole lot.


Conditional statements with doctor and patient information I'm focusing on trying to write clean, modular Python 2.7.5 code.

def main():
  type = sys.argv[1]
  dataPatient = parseJSONFile(fileName)

  if(type == "type 1"):
    patient = [d['patient_family_member_id'] for d in dataPatient if d['id'] == sys.argv[2]]
    displayList(flatten(patient), "Msg1")

  elif(type == "type 2"):
    doctor = [d['doctor_id'] for d in dataPatient if sys.argve[2] in set(d['patient_id'])]
    displayList(doctor, "Msg2")

  elif(type == "type 3"):
    dataDoctor = parseData(fileName2)
    doctor = [d['doctor_id'] for d in dataDoctor if sys.argv[2] in set(d['year_graduated'])
    #notice this is doing nearly the same thing as the "type 1" case for each doctor
    patient = [d['patient_family_member_ids'] for d in doctor for p in dataPatient if d == p['doctor']]
    displayList(flatten(patient), "Msg3")

  elif(type == "type 4"):
    patient = [d['patient'] for p in dataPatient if sys.argv[2] in set(d['age'])
    displayList(flatten(patient), "Msg4")

Most of this code in the if else statements are very similar. I feel like I might be able to use a lambda to clean this code up but I'm not sure that will work. I'm trying to make this code easy for someone to read and add more cases. What is the best way of avoiding a lot of the repetition in this code?

First things first: while this obviously comes from real code, the way you "anonymized" your code doesn't work, eg. sys.argve doesn't exist.

  I'm trying to make this code easy for someone to read and add more cases.

If you want Python developers to be able to read your code easily, please follow PEP 8 (using a tool such as pep8). That includes sticking to 80 columns, using underscored_names and using ALL_CAPS variables for constant strings.

  Most of this code in the if else statements are very similar. I feel like I might be able to use a lambda to clean this code up but I'm not sure that will work. What is the best way of avoiding a lot of the repetition in this code?

Without having tried to improve your code yet, using list comprehensions and lambdas is a good way to shorten code, but short code != readable code.


Finding the mean using RxJava I'm learning RxJava and this is what I attempted to find the mean of 'n' transactions.

List<Transaction> transactions = TransactionsStore.getTransactions();
BigDecimal nTransactions = new BigDecimal(transactions.size());
Observable.from(transactions)
        .map(transaction -> transaction.amount)
        .reduce(BigDecimal::add)
        .map(total -> total.divide(nTransactions, 2, BigDecimal.ROUND_DOWN))
        .map(mean -> String.format("The mean is %s", mean.toPlainString()))
        .subscribe(System.out::println);

I'd like to know if this could be done better.

Using RxJava-Math you can achieve the same result by this way:

List<Transaction> transactions = createRandomTransactions(10);

final Observable<Float> amountStream = Observable.from(transactions)
        .map(transaction -> transaction.amount);

MathObservable.averageFloat(amountStream)
        .map(mean -> String.format(Locale.US, "The mean is %.2f", mean))
        .subscribe(System.out::println);

Hope that helps!


Right triangle calculator I'm trying to code Python in an object-oriented style, but it just seems very forced.  Can anyone give me tips on this exercise of calculating the third leg of a right triangle from the other two?

I'm not looking for input santitization help!  I'm aware the project doesn't check if the input is a positive integer (or if the hypotenuse is the longest side, etc), but would much rather improve the general flow of how an OO project should look than the security/sanity checks on user input.

#!/usr/bin/python

import math

#Triangle has three sides; two can be defined and the third is calculated
class Triangle:

    def __init__(self):
        self.side={"adjacent":0,"opposite":0,"hypotenuse":0}

    def define_sides(self):
        for i in self.side:
            self.side[i]=self.get_side(i)

    def print_sides(self):
        for i in self.side:
            print "side",i,"equals",self.side[i]

    #return user integer or None if they enter nothing
    def get_side(self,one_side):
        prompt = "Enter length of "+one_side+": "
        try:
            return input(prompt)
        except SyntaxError:
            return None

    def count_nones(self):
        nones=0
        for side, length in self.side.iteritems():
            if self.side[side] == None:
                nones+=1
        return nones

    def validate_input(self):
        nNones=self.count_nones()

        if nNones < 1:
            print "You must leave one side blank."
            quit()
        if nNones > 1:
            print "Only one side can be left blank."

    def calculate_missing_length(self):
        h=self.side["hypotenuse"]
        a=self.side["adjacent"]
        o=self.side["opposite"]

        #hypotenuse is missing
        if h == None:
            self.side["hypotenuse"] = math.sqrt(a*a+o*o)

        #adjacent is missing
        if a == None:
            self.side["adjacent"] = math.sqrt(h*h-o*o)

        #opposite is missing
        if o == None:
            self.side["opposite"] = math.sqrt(h*h-a*a)

#begin program
triangle=Triangle()
triangle.define_sides()
triangle.print_sides()
triangle.validate_input()
triangle.calculate_missing_length()
triangle.print_sides()

State should always be valid

One of the main issues I see in your class design is that the state of your object is undefined most of the time. If I have a triangle, I want it to be... you know, a triangle. But when you start with:

triangle=Triangle()

You have an object with 3 zero sides. That's a degenerate object. Rather, you'll want to make it so that once you have a Triangle, then it must be valid.

Building up our Triangle

To that end, let's consider get_side(). As a member function, this makes little sense - it doesn't interact with Triangle at all. The get_* naming suggests that it's yielding some sort of member, when actually it's prompting the user for input. So let's rework it as a free function:

def input_side(side_name):
    try:
        return float(raw_input('Enter length of {}:'.format(side_name)))
    except ValueError:
        return None

Catching SyntaxError is questionable - it'd be better to use raw_input and a cast that returns a specific error. Otherwise, what if we had a syntax error? You'd hide it from yourself.

Once we have that, we can use that to call into our Triangle constructor:

triangle = Triangle(
    input_side('adjacent'),
    input_side('opposite'),
    input_side('hypotenuse')
)

where we rewrite the constructor to be:

def __init__(self, adjacent, opposite, hypotenuse):
    self.adjacent = adjacent
    self.opposite = opposite
    self.hypotenuse = hypotenuse

It is much better to simply have your members as members than to hide than in a dictionary. self.hypotenuse is much more direct than self.side['hypotenuse']!

Input Validation

Comparison against None should be done with is, not ==. And if you're iterating over a dictionary with iteritems(), you don't need lookup:

def count_nones(self):
    nones=0
    for side, length in self.side.iteritems():
        if length is None:
            nones+=1
    return nones

though the above can be abridged into:

def count_nones(self):
    return sum(1 for (side, length) in self.side.iteritems()
        if length is None)

Or, now that I'm proposing we not use a dictionary:

def count_nones(self):
    return (self.adjacent is None +
        self.opposite is None +
        self.hypotenuse is None)

But really, you should do all of this external to your Triangle class. As in:

Input your sides
Make sure exactly 2 of them are valid
Calculate the third
Then construct your Triangle with all three sides

Printing

In Python, you would typically add a __str__ method instead of a print sort of method:

def __str__(self):
    return 'Triangle(adjacent={}, opposite={}, hypotenuse={})'.format(
        self.adjacent, self.opposite, self.hypotenuse
    )

namedtuple

If you follow where I'm going up to now - you'll see I've made Triangle a great deal simpler. It doesn't deal with inputs. It doesn't deal with calculations. It's just a triangle. And for simple classes like that, Python has namedtuple:

>>> Triangle = namedtuple('Triangle', 'opposite adjacent hypotenuse')
>>> triangle = Triangle(3, 4, 5)
>>> triangle.adjacent
4
>>> print(triangle)
Triangle(opposite=3, adjacent=4, hypotenuse=5)

Even if you want to allow temporarily invalid Triangles, namedtuple is the way to go since it makes so many other things easier. For instance, since a namedtuple is just like a tuple with benefits, you could count your Nones directly:

triangle = Triangle(input_side('...'), ...)
if triangle.count(None) != 1:
    # do some error logic as appropriate


Implement metaclass for Maximumlikelihood estimator For the purpose of defining a lot of Maximum Likelihood estimators,
I think I need a metaclass.

At the moment I have to copy/paste a lot of code for every new class definition and just substitute the corresponding scipy.stats functions.

from scipy.stats import fisk, t
from statsmodels.base.model import GenericLikelihoodModel
from inspect import signature

class Fisk(GenericLikelihoodModel):
    """A maximum likelihood estimator for the fisk distribution.
    """

    nparams = 3

    def loglike(self, params):
        return fisk.logpdf(self.endog, *params).sum()

    def fit(self, **kwargs):
        if 'start_params' not in kwargs:
            # This is for performance and! convergence stability.
            # The scipy function provides better starting params.
            kwargs['start_params'] = fisk.fit(self.endog)
        res = super().fit(**kwargs)
        res.df_model = self.nparams
        res.df_resid = len(self.endog) - self.nparams
        return res

class T(GenericLikelihoodModel):
    """A maximum likelihood estimator for the Student-T distribution.
    """

    nparams = 3

    def loglike(self, params):
        return t.logpdf(self.endog, *params).sum()

    def fit(self, **kwargs):
        if 'start_params' not in kwargs:
            # This is for performance and! convergence stability.
            # The scipy function provides better starting params.
            kwargs['start_params'] = t.fit(self.endog)
        res = super().fit(**kwargs)
        res.df_model = self.nparams
        res.df_resid = len(self.endog) - self.nparams
        return res

With a metaclass I automated this code definition

class ML_estimator(type):
    def __new__(cls, clsname, bases, dct, f):
        return super().__new__(cls, clsname, (GenericLikelihoodModel, ), dct)

    def __init__(cls, clsname, bases, dct, f):
        cls.nparams = len(signature(f.pdf).parameters)
        def loglike(self, params):
            return f.logpdf(self.endog, *params).sum()
        cls.loglike = loglike

        def fit(self, **kwargs):
            if 'start_params' not in kwargs:
                # This is for performance and! convergence stability.
                # The scipy function provides better starting params.
                kwargs['start_params'] = f.fit(self.endog)
            res = super(cls, self).fit(**kwargs)
            res.df_model = self.nparams
            res.df_resid = len(self.endog) - self.nparams
            return res
        cls.fit = fit

class Fisk(metaclass=ML_estimator, f=fisk):
    pass

class T(metaclass=ML_estimator, f=t):
    pass

Does this seem like a reasonable application of metaclasses?
What improvements do you have?

The ML-estimator can be tested with:

sample = fisk.rvs(c=1, size=1000)
res = Fisk(sample).fit()
res.summary()

Instead of constructing the object and then modifying its methods and attributes, you can directly add them in the __new__ method of the metaclass:

class LikelihoodEstimator(type):
    def __new__(cls, name, bases, dct, f):
        def loglike(self, params):
            return f.logpdf(self.endog, *params).sum()

        def fit(self, **kwargs):
            if 'start_params' not in kwargs:
                # This is for performance and! convergence stability.
                # The scipy function provides better starting params.
                kwargs['start_params'] = f.fit(self.endog)
            res = super(cls, self).fit(**kwargs)
            res.df_model = self.nparams
            res.df_resid = len(self.endog) - self.nparams
            return res

        dct.update(loglike=loglike, fit=fit, nparams=len(signature(f.pdf).parameters))
        return super().__new__(cls, name, bases + (GenericLikelihoodModel,), dct)

I also changed the name to more nicely fit within PEP8 guidelines. I also included back bases to avoid undesirable surprises when using this metaclass.

The other option that I think is more easily understandable is to use inheritance instead of metaclasses. There will still be a bit of boilerplate left but the understanding at a glance should overweight:

from scipy.stats import fisk, t
from statsmodels.base.model import GenericLikelihoodModel as _LikelihoodModel
from inspect import signature

class GenericLikelihoodModel(_LikelihoodModel):
    """A maximum likelihood estimator for any distribution"""

    def __init__(self, distribution, endog, exog=None, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds)
        self.nparams = len(signature(distribution.pdf).parameters)
        self.distribution = distribution
        super().__init__(endog, exog, loglike, score, hessian, missing, extra_params_names, **kwds)

    def loglike(self, params):
        return self.distribution.logpdf(self.endog, *params).sum()

    def fit(self, **kwargs):
        if 'start_params' not in kwargs:
            # This is for performance and! convergence stability.
            # The scipy function provides better starting params.
            kwargs['start_params'] = self.distribution.fit(self.endog)
        res = super().fit(**kwargs)
        res.df_model = self.nparams
        res.df_resid = len(self.endog) - self.nparams
        return res

class Fisk(GenericLikelihoodModel):
    """A maximum likelihood estimator for the fisk distribution"""
    def __init__(endog, exog=None, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds)
        super().__init__(fisk, endog, exog, loglike, score, hessian, missing, extra_params_names, **kwds)

class StudentT(GenericLikelihoodModel):
    """A maximum likelihood estimator for the Student-T distribution"""
    def __init__(endog, exog=None, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds)
        super().__init__(t, endog, exog, loglike, score, hessian, missing, extra_params_names, **kwds)


"Have a safe trip"… or not, depending on four conditions I have 4 booleans and all must be met to determine the value of a String:

String message = (!isNameBlank && !isDestinationBlank
    && isDestinationValid && isAmountValid)
    ? "Have a safe trip!" : "Please try again!";

If I do this, it doesn't look elegant either:

String message = "";
if(!isNameBlank && !isDestinationBlank
    && isDestinationValid && isAmountValid) {
    message = "Have a safe trip!";
} else {
    message = "Please try again!";
}

Is there a better convention when comparing many booleans in a statement?

When it comes to long and complex logic summation I recommend, as Legato says, to use one row for each condition.
I also think it is more readable if you sum all the conditions to a new variable that explains the result with a meaningful name like this:

boolean isTripPossible =
   !isNameBlank &&
   !isDestinationBlank &&
   isDestinationValid &&
   isAmountValid;

String message = isTripPossible ? "Have a safe trip!" : "Please try again!";


Generate 6 random numbers for lottery in PHP This program generates 6 random numbers between 0 and 45 and the numbers cannot be repeated. Can this code be improved?

$numbers = [];

$i = 1;

while($i <= 6)
{
    $number = mt_rand(0, 45);

    if(!in_array($number, $numbers))
    {
        array_push($numbers, $number);
        $i++;
    }
}

sort($numbers);

echo implode(" - ", $numbers);

Your algorithm is functional, but is not necessarily very efficient, and it will collide more, and more often if the count of numbers increases.

It's generally neater to start off with a unique set of numbers, and to extract a random selection of those numbers, instead of selecting random numbers, and testing for uniqueness.

PHP makes this relatively neat, because it has a built-in shuffle function (that's essentially doing a Fisher-Yates shuffle using the same random system that you are).

So, get an array of the unique values, shuffle it, take a selection of it, and sort the result:

$count = 6;
$highball = 45;
$numbers = range(0, $highball);
shuffle($numbers);
$drawn = array_slice($numbers, - $count);
sort($drawn);

Note, using named variables instead of constants makes it clearer what you are doing.

See this running on ideone: https://ideone.com/1Hh0y8


Copying values from one sheet to another I am trying to copy values from one sheet to another using loop with two conditions and it is very slow. Removing conditions from code doesn't have any effect on the speed of the execution.
I already have sample sheet where everything is done with functions (if/match/index...) but I would like to remove all functions from this workbook.

Here is the code :

Option Explicit
Private Sub AnalitSample()
    Dim WSS As Worksheet
    Set WSS = Sheets("Source")
    Dim WSD As Worksheet
    Set WSD = Sheets("Dest")

    Dim col As String
    col = "B"

    Dim rCell As Range
    Dim rRng As Range
    Set rRng = WSS.Range("B2:B4000")

    Dim i As Integer
    i = 2

    WSD.Range("B2:G4000").ClearContents

    For Each rCell In rRng.Cells
        If rCell.Value <> "" Then
            If Len(rCell.Value) > 3 Then
            WSD.Range(col & i).Value = rCell.Offset(0, 0).Value
            WSD.Range(col & i).Offset(0, 1).Value = rCell.Offset(0, 1).Value
            WSD.Range(col & i).Offset(0, 2).Value = rCell.Offset(0, 4).Value
            WSD.Range(col & i).Offset(0, 3).Value = rCell.Offset(0, 5).Value
            WSD.Range(col & i).Offset(0, 4).Value = rCell.Offset(0, 6).Value
            WSD.Range(col & i).Offset(0, 5).Value = rCell.Offset(0, 9).Value
            i = i + 1
            End If
            End If
        Next rCell
End Sub

I am asking for a few suggestions on how to speed up this kind of code (for each loop), that I was avoiding in the past because of the speed.

Lowest Hanging VBA Fruit:

Public Sub ()
    Application.ScreenUpdating = False
    Application.EnableEvents= False
    Application.Calculation= XlManual

    ...

    Code

    ...

    Application.ScreenUpdating = True
    Application.EnableEvents= True
    Application.Calculation= XlAutomatic
End Sub

Every time you access the worksheet, events trigger, formulas recalculate and Excel re-draws the screen.
You're accessing the worksheet 4,000 times.
Turning those options off will make your code inordinately faster. Just make sure they get reset back to normal at the end.

Superfluous Logic

If rCell.Value <> "" Then
    If Len(rCell.Value) > 3 Then

If Len(value) > 0 then, by definition, value is not an empty string. So you can just drop rCell.Value <> "".

Use row/column numbers. not Strings and offsets.

This is more of a good practice thing. Get in the habit of using Cells(Row, Column) instead of Range("B" & number).

Like so:

Dim finalRow As Long
Dim iRow As Long
Const TARGET_COL As Long = 2
Dim cellText As String

For iRow = 2 To finalRow

    cellText = WSS.Cells(iRow, TARGET_COL).Text

    If Len(cellText) > 3 Then
        '/ Do Stuff
    End If

Next iRow


Finding the first pair of prime numbers that have some specified difference I tried printing the first pair of prime number in between a list of numbers with a particular difference. But my run time is still too high (for large range of numbers). I want to reduce the run time by using any method from standard library like itertools.
def prime(x):
    """To generate prime number"""
    a = x // 2 + 1
    for i in range(2, x):
        if x % i == 0:
            return False
        elif i == a:
            return True

def gap(p, q, m):
    """To generate gap in between two prime numbers"""
"""p is the difference,q is the lower limit where the list of numbers in between which prime is filtered,m is the upper limit"""
    b = []
    a = b.append
    c = prime
    q = (q // 2) * 2 + 1
    for i in range(q, m + 1, 2):
        if c(i) == True:
            a(i)
            if len(b) > 1:
                if b[-1] - b[-2] == p:
                    return [b[-2], b[-1]]

First thing first, get rid of these ugly a and c. They do not add any value, but only obfuscate the code.
def gap(p, q, m):
    """To generate gap in between two prime numbers"""
"""p is the difference,q is the lower limit where the list of numbers in between which prime is filtered,m is the upper limit"""
    b = []
    q = (q // 2) * 2 + 1
    for i in range(q, m + 1, 2):
        if prime(i):
            b.append(i)
            if len(b) > 1:
                if b[-1] - b[-2] == p:
                    return [b[-2], b[-1]]

Notice that I also removed a redundant == True.
Second, you don't need to keep the entire list of primes. You are only interested in the last two of them. Consider
def gap(p, q, m):
    b = find_first_prime_after(q)
    for i in range(b + 2, m + 1, 2):
        if prime(i):
            if i - b == p:
                return b, i
            b = i

Finally, your primality test is very suboptimal. Implementing the sieve would give you a boost.


Checking if a number is divisible by 9 I tried to develop a new way to check if a number is divisible by 9. I have written my code and it is working fine. I'm not allowed to use *,/ and %.

int isDivby9(int x)
{
    int status = 0;
    int divby8 = 0;

        int orgx = x;
        if(x>=9)
        {
            divby8 = x >> 3;
            int olddivby8 = divby8;
            while(divby8 >= 9)
            {
                divby8 = divby8 - 9;
            }
            if(divby8 == (orgx - (olddivby8 << 3)))
            {
                status = 1;
            }
            else{
                status = 0;
            }
            x = divby8;
        }

    return status;
}

Can someone please check if this is a good way to check if a number is divisibility by 9? Is it too complex? Is there any better way to perform the same? I also referred to the logic given in geeksforgeeks.

I see some things that you might want to use to improve your code.

Use an early bailout

If the passed number x is less than 9, the routine can immediately return 0.

Eliminate multiples of 2

Since 9 and 2 have no common factors, you can speed up the operation (on average) by shifting the incoming x to the right until the least significant bit is non-zero.

Eliminate unused variables

With a minor restructuring of the code, you can eliminate most of the variables and make the code shorter, faster and easier to read.

Consider implementing a test program

You have apparently already done some testing, but posting the test with the code to be reviewed may help others review the code properly.

Putting it all together

Here's what I came up with using all of these suggestions:

#include <stdio.h>
#include <assert.h>

int isDivby9(int x)
{
    while (0 == (x & 1)) {
        x >>= 1;
    }
    if(x<9)
        return 0;

    int divby8 = x >> 3;
    while(divby8 >= 9) {
        divby8 -= 9;
    }
    return divby8 == (x & 7);
}

int main()
{
    for (int i=1; i < 1000000; ++i)
        assert(isDivby9(i) == (i%9 == 0));
}

Results

On my machine (64-bit Linux box), the original code runs in 2.3 seconds, and the version above completes in 1.5 seconds; a considerable improvement in performance with identical mathematical results.  By comparison, the straightforward approach in @Edenia's answer takes 18.8 seconds on the same machine.

All were compiled with gcc 4.9.2 with -O2 optimizations.

Updated algorithm

I couldn't stop thinking about this question because I knew there was a better algorithm, but just couldn't think of it.  I finally came across this superb answer to a similar question on StackOverflow.  With that excellent answer, I translated a finite state machine implemention into C and came up with this:

#include <limits.h>

struct state {
    int nextstate[2];
};
int isDivby9 (int num)
{
    static const int HIGH_BIT = INT_MAX - (INT_MAX >> 1);
    static const struct state states[9] = {
        {{0, 1}}, {{2, 3}}, {{4, 5}},
        {{6, 7}}, {{8, 0}}, {{1, 2}},
        {{3, 4}}, {{5, 6}}, {{7, 8}}
    };
    if (num < 0)
        num = -num;
    int s = 0;
    for ( ; num ; num <<= 1) {
        s = states[s].nextstate[(num & HIGH_BIT) ? 1 : 0];
    }
    return s==0;
}

Each bit, starting from the MSB, drives the state machine to the next state.  The state is held in variable s and the branches for the 0 and 1 bits are the the two nextstate entries.  It works well (including for negative numbers and zero) and is very fast.  In fact, on my machine, this routine takes 0.045 seconds.

Updated results

In more concise timing tests on my machine, and adjusting all routines to also work correctly on negative numbers, here's what I found on this machine:

  861092 modulus operator
 1152840 JS1
 1581770 gnasher729
 2479987 Simon
 8961866 Edward DFA function

So the % operator is fastest, followed by @JS1's routine, followed by @gnasher729's, followed by @Simon's followed by the DFA routine (by a wide margin!)

Naturally, this might differ on different machines with different architectures, so as always, timing routines on your own actual hardware is recommended.

I learned some things that might well be useful for the next time I work on synthesizing my own logic or on an embedded microprocessor without a multiply instruction.


Compute the perimeter of a polygon This is taken from HackerRank, which I hope is okay.

I've been playing around with Haskell and I haven't really been able to find anything that really goes beyond toy examples in terms of how to write a readable, well-structured program.  Several parts of this seem messy but I guess I don't really know any better.  Anyway, here's my code, which works (or at least passes all the unit tests supplied at HackerRank).

import Control.Monad

-- Given a list, return the pairs of consecutive elements in the list
consec :: [a] -> [(a,a)]
consec xs = zip xs (drop 1 (cycle xs))

-- Given a list of two elements, return a 2-tuple of the elements
make2Tuple :: [a] -> (a, a)
make2Tuple [x, y] = (x, y)

-- Apply a given function to the first element of a list
applyToFirst :: (a -> a) -> [a] -> [a]
applyToFirst _ [] = []
applyToFirst f (x:xs) = (f x):xs

-- Split a list at a specified delimiter
split :: Eq a => a -> [a] -> [[a]]
split _ [] = [[]]
split y (x:xs)
  | (x == y) = []:(split y xs)
  | (x /= y) = applyToFirst (x:) (split y xs)

-- Convert a string to a list of integers
stringToInts :: [Char] -> [Int]
stringToInts = map (read :: [Char] -> Int) . (split ' ')

-- Action that reads in a 2-tuple of integers
getInt2Tuple :: IO (Int, Int)
getInt2Tuple = fmap (make2Tuple . stringToInts) getLine

euclideanDistance :: ((Int, Int), (Int, Int)) -> Double
euclideanDistance ((x1, y1), (x2, y2)) = sqrt(fromIntegral((y2-y1)*(y2-y1) + (x2-x1)*(x2-x1)))

computePerimeter :: [(Int, Int)] -> Double
computePerimeter xs = sum (map euclideanDistance (consec xs))

main :: IO ()
main = (fmap computePerimeter (fmap (read :: [Char] -> Int) getLine >>= (\n -> replicateM n getInt2Tuple))) >>= print

Sample input

4
(0, 0)
(0, 1)
(1, 1)
(1, 0)

Sample output

4

Explanation

The input says that this polygon has four vertices, and then lists the vertices of a unit square.  The perimeter of a unit square is 4 (one unit per edge times four edges), which is what's output.

consec will wrap around and pair the last element of your list as consecutive with the first. This isn't documented in the comment and IMO a little bit problematic. While it lends itself well to the problem you're solving, I'd try to change the implementation of consec a little and being explicit about the cycle property in the name.

Consider:

consec :: [a] -> [(a,a)]
consec [] = []
consec [x] = []
consec (x:xs@(y:_)) = (x,y):consec xs

This implementation has the benefit of being more explicit over zip xs (drop 1 $ cycle xs). It can be trivially extended to a consecCycle like so:

consecCycle :: [a] -> [(a,a)]
consecCycle [] = []
consecCycle [y] = []
consecCycle xs@(x:_) = consec (xs ++ [x])

For what it's worth, this is basically a stylistic call. I'm more prone to overspecifying my functions, avoiding pointfree style. I guess I just dislike oneliners...

make2Tuple is a dangerous one. You're explicitly forcing the function to be called with a list of only two elements by accepting a runtime error of "Non-exhaustive patterns in function make2Tuple".

I'd consider this bad practice. To totally define the function you could consider using a Maybe like so:

make2Tuple :: [a] -> Maybe (a,a)
make2Tuple [x,y] = Just (x,y)
make2Tuple _ = Nothing

this instantly communicates that the function is not totally defined and it avoids a runtime error.

applyToFirst is cleanly written and it clearly communicates intent. Yet I dislike the function because you're using it as a helper for something that's cleaner to implement without it.

split is a weird name for that function, I'd instead use splitWhere or splitIf and supply a predicate, which leads to the following typesignature:

splitWhere :: (a -> Bool) -> [a] -> [[a]]

which can then be implemented as follows:

splitWhere :: (a -> Bool) -> [a] -> [[a]]
splitWhere _ [] = [[]]
splitWhere p ls = go [] ls
    where
        go accum (x:xs) = if p x then accum:go [x] xs else go (accum++[x]) xs
        go accum [] = [accum]

The advantage of this implementation is in the use of an "accumulator" instead of the applyToFirst you're using to achieve the same functionality.

It's also a tad easier to grasp, IMO, but YMMV

stringToInts is map read . words. Note that without an explicit type-signature GHCI can not infer the correct type, since read is not specified out enough.

Unfortunately this makes the work put into applyToFirst and split unnecessary :(

I'd simplify euclideanDistance's pattern by splitting up the tuple of tuples into separate parameters. To keep in line with how it's invoked you can then adjust computePerimeter to uncurry it like so:

computePerimeter xs = sum $ map (uncurry euclideanDistance) (consec xs)

Finally I find it hard to keep track of how your main works. It's probably easier to rewrite this as a do like so:

main = do
    vertices <- getLine
    polygon <- replicateM (read vertices) getInt2Tuple
    print $ computePerimeter (map fromJust $ filter isJust polygon)

This is IMO significantly easier to follow than your oneliner (and it also avoids all the fmap

Zeta noted that the last line can be shortened (and secured a bit) to:

print $ computePerimeter $ catMaybes polygon

Note that I've added the following imports and changed the getInt2Tuple signature to be an IO (Maybe (Int, Int)) instead:

import Control.Monad(replicateM)
import Data.Maybe(fromJust, isJust)


An asynchronous logger I've written a simple asynchronous logger (playground):

mod logger {

    use std::sync::mpsc::{channel, Sender};
    use time::now;

    pub type LogError = std::sync::mpsc::SendError<String>;

    /// Runs a function that can logs asynchronously.
    pub fn log<F, T>(f: F) -> T
    where
        F: FnOnce(Logger) -> T,
    {
        let (sender, receiver) = channel();
        let handle = std::thread::spawn(move || {
            while let Ok(msg) = receiver.recv() {
                println!("{}", msg);
            }
            println!("LOG FINISHED");
        });
        let result = f(Logger { sender });

        handle.join().unwrap(); // Error handling?

        result
    }

    /// The actual logger.
    #[derive(Clone)]
    pub struct Logger {
        sender: Sender<String>,
    }

    impl Logger {
        /// Logs an information.
        pub fn info(&self, s: impl std::fmt::Display) -> Result<(), LogError> {
            let s = format!("[{}] [INFO ] {}", now().rfc3339(), s);

            self.sender.send(s)
        }

        /// Logs an error.
        pub fn error(&self, s: impl std::fmt::Display) -> Result<(), LogError> {
            let s = format!("[{}] [ERROR] {}", now().rfc3339(), s);

            self.sender.send(s)
        }
    }

}

// Demontration:
fn main() -> Result<(), logger::LogError> {
    logger::log(|logger| {
        logger.info("Hello world")?;

        // Cloning without overhead:
        logger.clone().error("Oops, error")
    })
}

The concept is simple: I spawn a thread with a receiver, and the logger sends the text to it.

To make this work, I was forced to use a callback to correctly join the thread when the user's code is done. Is there a better/prettier way to do that?

And also, is that pattern efficient? I know that I can buffer the lines inside the spawned thread, but I am talking about the whole pattern.

I have found a way to use a runtime struct instead of a closure. Logger needs to borrow the runtime, and it must implement Drop so that Runtime::drop is not called before Logger::drop.

mod logger {

    use std::marker::PhantomData;
    use std::sync::mpsc::{channel, Sender};
    use std::thread::JoinHandle;
    use time::now;

    pub type LogError = std::sync::mpsc::SendError<String>;

    pub struct Runtime {
        sender: Option<Sender<String>>,
        thread_handle: Option<JoinHandle<()>>,
    }

    impl Runtime {
        pub fn new() -> Self {
            let (sender, receiver) = channel();
            let thread_handle = std::thread::spawn(move || {
                while let Ok(msg) = receiver.recv() {
                    println!("{}", msg);
                }
                println!("LOG FINISHED");
            });

            Runtime {
                sender: Some(sender),
                thread_handle: Some(thread_handle),
            }
        }

        pub fn logger(&self) -> Logger {
            Logger {
                sender: self.sender.clone().unwrap(),
                _marker: PhantomData,
            }
        }
    }

    impl Drop for Runtime {
        fn drop(&mut self) {
            // Removes the last sender alive, so that the thread quits.
            let _ = self.sender.take();

            if let Some(handle) = self.thread_handle.take() {
                if let Err(e) = handle.join() {
                    eprintln!("Error while exiting the logger manager: {:?}", e);
                }
            }
        }
    }

    /// The actual logger.
    #[derive(Clone)]
    pub struct Logger<'a> {
        sender: Sender<String>,
        _marker: PhantomData<&'a ()>,
    }

    impl Logger<'_> {
        /// Logs an information.
        pub fn info(&self, s: impl std::fmt::Display) -> Result<(), LogError> {
            let s = format!("[{}] [INFO ] {}", now().rfc3339(), s);

            self.sender.send(s)
        }

        /// Logs an error.
        pub fn error(&self, s: impl std::fmt::Display) -> Result<(), LogError> {
            let s = format!("[{}] [ERROR] {}", now().rfc3339(), s);

            self.sender.send(s)
        }
    }

    impl Drop for Logger<'_> {
        fn drop(&mut self) {
            // The non-trivial drop prevents the logger to outlives the manager.
        }
    }
}

// Demontration:
fn main() -> Result<(), logger::LogError> {
    let log_manager = logger::Runtime::new();
    let logger = log_manager.logger();

    logger.info("Hello world")?;
    // Cloning without overhead:
    logger.clone().error("Oops, error")?;

    Ok(())
}

If one try to make a logger outlive the runtime, it will not compile:

fn main() -> Result<(), logger::LogError> {
    let log_manager = logger::Runtime::new();
    let logger = log_manager.logger();

    logger.clone().info("Hello world")
}

Gives:

error[E0597]: `log_manager` does not live long enough
  --> src/main.rs:85:18
   |
85 |     let logger = log_manager.logger();
   |                  ^^^^^^^^^^^ borrowed value does not live long enough
86 |
87 |     logger.clone().info("Hello world")
   |     -------------- a temporary with access to the borrow is created here ...
88 | }
   | -
   | |
   | `log_manager` dropped here while still borrowed
   | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `logger::Logger`
   |
   = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.


Find 2 numbers that multiply to a number and add to another number Here is my code, however, I am unsure whether it is the fastest way to achieve this objective.

import random

add_to = int(input("2 numbers must add to: "))
multiply_to = int(input("2 numbers must multiyply to: "))
solved = False

while solved == False:
    nums = random.sample(range(-100, 150), 2)
    if (nums[0] + nums[1] == add_to) and (nums[0] * nums[1] == multiply_to):
        print(nums)
        print('Solved')
        break

Question:
1. Is it possible for the range to be set based upon the input of numbers given by the user.

Code Review

while solved == False: is an awkward way of writing the loop condition.  while not solved: would be clearer and more Pythonic.

You never set solved = True anywhere.  Instead, you unconditionally break out of the loop.  This means your loop could actually be written while True:, but I don't think this is clearer.  Using solved = True instead of break would terminate the loop in an expected way.

This is verbose:

    nums = random.sample(range(-100, 150), 2)
    if (nums[0] + nums[1] == add_to) and (nums[0] * nums[1] == multiply_to):

You could unpack nums into to individual variables, and avoid the [0] and [1] indexing operations, for more performant code:

    x1, x2 = random.sample(range(-100, 150), 2)
    if x1 + x2 == add_to and x1 * x2 == multiply_to:

If you give values which can never work with integers, like add to 2 and multiply to 3, you have an infinite loop.  You should have a "give up after so many attempts" procedure.

Monte Carlo

As pointed out by Peilonrayz, there is an \$O(1)\$ solution to the problem.

However, if your goal is to utilize a Monte Carlo simulation method ...

If multiply_to is:

positive, then the numbers must be the same sign, both positive or both negative, which you could determine by looking at the add_to sign,
negative, then one number must be greater than zero, and the other must be less than zero,
zero, then one number must be zero.

eg)

if multiply_to > 0:
    if add_to > 0:
        r1 = range(1, add_to)
        r2 = range(1, add_to)
    else:
        r1 = range(add_to + 1, 0)
        r2 = range(add_to + 1, 0)

elif multiply_to < 0:
    r1 = range(1, 150)   # A positive value in your initial range bracket
    r2 = range(-100, 0)  # A negative value in your initial range bracket

else:
    r1 = range(add_to, add_to + 1)
    r2 = range(0, 1)

for _ in range(10_000):
    x1 = random.choice(r1)
    x2 = random.choice(r2)
    if x1 + x2 == add_to and x1 * x2 == multiply_to:
        print(f"Solved: {x1} + {x2} = {add_to}, {x1} * {x2} = {multiply_to}")
        break
else:
    print("Couldn't find a solution")


Variant optional to return error string or value I needed a class with more information than optionals give, I need to know why the optional is not valid in error states. I used a Boost variant for this. Since this will be wrapping almost all of my return values, I need to know if it's as fast as possible (i.e. did I do move semantics and all that jazz properly?).

template<typename T>
class Result
{
public:
    Result(const std::string& errorString) {
        contents = errorString;
    }

    Result(T&& value) {
        contents = std::forward<T>(value);
    }

    operator bool() {
        //is the active value our T
        return contents.which() == 0;
    }

    T unwrap() {
        return boost::get<T>(contents);
    }

    std::string unwrapErr() {
        return boost::get<std::string>(contents);
    }

private:
    boost::variant<T, std::string> contents;
};

Example use

Result<std::vector<int>> foo()
{
    if(success)
         return Result<std::vector<int>>({1,2,3});
    else
         return Result<std::vector<int>>("failure reason");
}

if(auto vec = foo())
   vec.unwrap() //do stuff to contained value
else
   std::cout << vec.unwrapErr();

You said:

  I need to know if it's as fast as possible

The only thing I could think of that would make your program potentially faster is:

Initialize the member variable using initialization list syntax

Result(const std::string& errorString) : contents(errorString) {}

// boost::variant already has a constructor that takes a rvalue reference.
Result(T&& value) : conents(value) {}

Other suggestions:

Add operator T functions instead of unwrap

This may be a matter of stylistic preference but I think it is better to use:

Result<int> r = <some function call>;
if ( r && r == 10 )
{
    // Do something with r
}

than

Result<int> r = <some function call>;
if ( r && r.unwrap() == 10 )
{
    // Do something with r
}

You can use the former syntactic construct by providing const and non-const versions of user defined conversion operators.

operator T const& () const
{
   return boost::get<T>(contents);
}
operator T& ()
{
   return boost::get<T>(contents);
}

Decide how to deal with use of Result<std::string>

If you use Result<std::string>, the function operator bool will always return true. For that use case, there is no way to tell whether a function returned with success or failure.

One way to deal with the problem will be to prevent use of Result<std::string> using static_assert.

static_assert(std::is_same_type<T, std::string>::value == false,
              "Can't use std::string as template paramete");

Use a better name than unwrapErr()

I would prefer to use something like getError() or getErrorString().

Update

The operator T functions will be problem when T is bool. If you like to use the operator T functions for all types, it will be better to change operator bool to a different function, such as isGood().

bool isGood() {
    //is the active value our T
    return contents.which() == 0;
}

then, you'll have to use

Result<int> r = <some function call>;
if ( r.isGood() && r == 10 )
{
    // Do something with r
}


Code for calculating number of variations Following up from my previous question where I put up a solution in brute for algorithm to this problem from codechef.

  Given some number \$K\$ and a list of \$N\$ numbers, count the number of pairs (\$i\$, \$j\$) such that \$1 \le i \lt j \le N\$ and \$|a_i − a_j | \ge K\$.

  \$1 \le N \le 65000\$
  \$1 \le K \le 10^8\$
  \$0 \le a_i \le 10^8\$

I changed my code quite a bit and was able to get rid of that time-limit-exceded error.Thanks to the responses, here is the updated code:

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>

std::vector<int>loadTestCases(int N){
    std::vector<int> testCases;
    for (int i = 0; i < N; i++)
    {
        int TestCase;
        std::cin >> TestCase;
        testCases.push_back(TestCase);
    }
    return testCases;
}

int main(){

    int args,k;
    std::cin >> args >> k;

    std::vector<int> nums = loadTestCases(args);
    int cases = 0;

    sort(nums.begin(),nums.end());

    for(int i=1;i<args;i++){
        int temp = std::abs(nums.at(i)-nums.at(i-1));
        if(temp >=k){
            cases = cases + i;
        }else{
            int j = i;
            while(temp < k && j > 0){
                j--;
                temp = std::abs(nums.at(i)-nums.at(j));
            }
            if(temp >= k){
                cases = cases + j + 1;
            }
        }
    }

    std::cout << cases << std::endl;
    return 0;
}

But according to me the code still looks a little ugly and can be optimized more , can someone help me to identify the parts where simplification without risking the time taken can be done?

Similar to the other question, I would suggest to utilize a std::map changing your loadTestCases accordingly

std::map<int, int>loadTestCases(int N){
    std::map<int, int> testCases;
    int TestCase;
    for (int i = 0; i < N; i++)
    {
        std::cin >> TestCase;
        auto inserted = testCases.emplace(TestCase, 1);
        if(!inserted.second) {
            testCases.at(TestCase)++;
        }
    }
    return testCases;
}

The advantage of this approach is, that you only have to traverse the keys of the std::map once and can multiply the values if there is a match.

Also given that your container is sorted you can actually skip the std::abs call, as a_i - a_j > 0 is guaranteed by that sort, if you traverse the container from the back. Also more importantly, once you find a_i - a_l > k, you automatically know, that any following pair is also valid, as by construction for an a_m < a_l we get a_i - a_m = a_i - a_l - (a_m - a_l), with (a_m - a_l) < 0.


C# Hash Code for triangle class I have a custom class to handle some triangle calculations that I am doing. For the most part I am happy with it, however, there is one aspect that I don't really trust. That is my implementation of HashCode.

Some quick information about my triangle- it has 3 Vector2 structs that represent points of two floats. This is an inbuilt class with the Unity engine but the simple version of it is that it is a struct with two floats and a couple math functions.

public class Triangle2D {
    public Vector2 point1;
    public Vector2 point2;
    public Vector2 point3;

    //... Some other methods that don't matter

    public override int GetHashCode() {
        var hashCode = -305700999;
        hashCode = hashCode * -1521134295 + (EqualityComparer<Vector2>.Default.GetHashCode (point1)
            + EqualityComparer<Vector2>.Default.GetHashCode (point2)
            + EqualityComparer<Vector2>.Default.GetHashCode (point3));
        return hashCode;
    }
}

The specific thing about this class that is special is that, it shouldn't matter what order points 1, 2 and 3 are in. If the points are shared, then the Triangle2D objects are the same. My equals function reflects that, but I worry that my hashCode function is not specific enough. Due to the additive nature of things, I suspect there could be a lot of collisions.

Is there some way that I could make the hashCode function have less collisions? Is it good enough as it is?

I use this object in a lot of hashSets to prevent duplicate triangles from getting listed.

Hash code

  it shouldn't matter what order points 1, 2 and 3 are in

There is a way to ensure that: Sorting. Sort your points locally within your hashcode method, first by their x value, then by their y value.

The algorithm for the hashcode could be this one, as also commented above by radarbob. I will leave it for you to adapt it to your own class.

General

Your class has public fields. It is better to make these private and grant public access to them (if needed) via properties. In this case, for something like a triangle, making it a struct instead of a class might be also suitable.

The following piece of code does not make much sense:

var hashCode = -305700999;
hashCode = hashCode * -1521134295 + [...]

I already added the link to a good implementation of the hash code method above, so I won't go into detail about the algorithm. But what you are doing in the above two lines before the addition is just calculating what could simply be a constant. The compiler will probably even precompute the -305700999 * -1521134295 part. Multiplying the hash code with a prime number (like 23 or 31) should happen before every addition of another value.


Bash script to extract wifi passwords from NetworkManager This is my first shell script, so I am trying to see if I can get some suggestions. It extracts saved wifi passwords from Linux.

##################################################################

# This script is used to copy wifi password files from /etc/NetworkManager/system-connections folder

# check if the wifi_pass_dir exists, and delete it if it does
if [ -d "wifi_pass_dir" ]
then
    rm -rf wifi_pass_dir
fi

# Create wifi_pass_dir folder
mkdir wifi_pass_dir

#copy the files from NetworkManager to the folder created, these files can only be read by the root user so use sudo
sudo cp /etc/NetworkManager/system-connections/* ./wifi_pass_dir

# change the file permission from read only by root to read and write by any user (666)
sudo chmod 666 ./wifi_pass_dir/*

#create a list so we know what wifi passwords are saved
sudo ls /etc/NetworkManager/system-connections > ./wifi_pass_dir/pass_list.txt

# Read name of wifi from pass_list.txt and print on screen
cd wifi_pass_dir
filename="pass_list.txt"

while read -r line
do
    name="$line"
    echo $name
    cat "$name" | grep psk=
done < "$filename"
##################################################################

General
Always include a shebang, and set options to exit the script when a command fails or when we use a variable that's not set:
#!/bin/bash

set -eu

Test for existence with -e, not -d
If wifi_pass_dir exists, but is not a directory (perhaps it's a plain file), it will not be deleted, and the mkdir will fail.  It might be better not to check (rm -f will succeed if the file doesn't exist):
# Ensure the wifi_pass_dir exists
rm -rf wifi_pass_dir
mkdir wifi_pass_dir

However, I don't believe it's necessary to copy the config files to an insecure location and make them world readable (and writeable) - see later.
sudo is for interactive use, not scripts
Avoid using sudo in a script - it expects to be interactive, and won't necessarily do what you want if not connected to a terminal.  It's easier to require that the script be run under sudo (and we can then use su to change to a non-privileged user where necessary).
Don't parse the output of ls
Filenames you don't control can contain all sorts of characters, including newlines.  Here, we don't need to do that, as we're reading from a directory.  The while read loop can simply be a for f in * loop.
Don't over-exercise the cat
This cat isn't needed:
cat "$name" | grep psk=

Just tell grep to take its input from $name directly:
grep psk= "$name"

We don't even need a loop, as we can pass all the filenames to grep in one go.

Simplified code
#!/bin/bash
exec grep 'psk=' /etc/NetworkManager/system-connections/*

Yes, that's the whole program.  Since we only execute one command, we don't need set -e, and as we use no variables, neither do we need set -u.


Algorithm to find pair with max sum from two arrays Algorithm to find pair with max sum from two arrays

A[0 ... n] and B[0 ... n]
A[i] + B[j] = max (A[i] + B[j], with i < j)
i,j < 99999; n < 99999

My best result is this:

int[] testArrayA = { 7, 1, 4, 5, 1};
int[] testArrayB = { 3, 2, 1, 5, 3};
String res = "";
int maxSum = 0;
for (int i = 0; i < testArrayA.length; i++)
{
    int i1 = testArrayA[i];
    for (int j = i; j < testArrayB.length; j++)
    {
        int j1 = testArrayB[j];
        if((j1 + i1) > maxSum)
        {
            maxSum = j1 + i1;
            res = i + " " + j;
        }
    }
}
System.out.println(res);

Expected answer "0 3"
Current complexity \$O(n^2)\$ I think it must be much lower. Can we do it better?

We can solve this in \$O(n)\$ time. The best possible sum for a particular index, \$i\$, is \$S[i] = A[i] + \max(B[i+1:])\$ (using the Python notion of slice). We can update both incrementally by counting from the back, so we have to keep track of two things: \$\max(S[i:])\$ and \$\max(B[i+1:])\$.

So for the test arrays:

int[] testArrayA = { 7, 1, 4, 5, 1};
int[] testArrayB = { 3, 2, 1, 5, 3};
                              ↑
                              starting i

At i==3, we start with maxS == 8 and maxB == 3, since those are the only two options. With i==2, we update maxB = max(maxB, B[i+1]) = 5 and maxS = max(maxS, A[i] + maxB) = max(8, 4+5) = 9. etc.

In code:

public static void printMaxIncreasingIndexSum(int[] A, int[] B)
{
    int bIdx = B.length - 1;
    int aIdx = A.length - 2;

    int maxB = bIdx;
    int maxS = A[A.length - 2] + B[maxB];

    for (int i = A.length - 3; i >= 0; --i) {
        if (B[i+1] > B[maxB]) {
            maxB = i+1;
        }

        if (A[i] + B[maxB] > maxS) {
            maxS = A[i] + B[maxB];
            aIdx = i;
            bIdx = maxB;
        }
    }

    System.out.printf("%d %d", aIdx, bIdx);
}


Pile shuffle of a vector My goal is to simulate a Pile shuffle of a vector. It takes 2 optional arguments for the number of piles to use and how many times to perform the shuffle.

As this is my first attempt at clojure code, I'm fairly sure I'm doing something terribly wrong here. I'm concerned with speed, efficiency, and indentation style. I'd also appreciate any pointers that would make this function more generic (maybe not restricting to vectors, but general collections).

(defn pile
  ([cards] (pile cards 3 1))
  ([cards num_piles] (pile cards num_piles 1))
  ([cards num_piles times]
    (loop [i 1
           piles (transient (vec (map (fn [p] []) (range num_piles))))
           the_pile 0]
      (if (<= i (count cards))
        (recur (inc i)
               (assoc!
                 piles
                 the_pile
                 (vec (concat [(nth cards (dec i))]
                               (nth piles the_pile))))
               (rem i num_piles))
        (if (> times 1)
          (pile (reduce into (persistent! piles)) num_piles (dec times) )
          (vec (reduce into (persistent! piles))))))))

You need loop/recur very rarely in most code, and almost never for operating on collections/sequences.  Using the standard library sequence functions, it’s possible to do the main pile shuffle with just a handful of expressions:

(->> (range (dec n) -1 -1) (mapcat #(take-nth n (drop % cards))) reverse)

It takes some getting used to, and familiarity with the Clojure standard library.  When I was first getting started, I found it immensely helpful to read the clojure/core.clj code.  It isn’t all idiomatic because it’s building the support for the idioms as it goes, but it demonstrates what Clojure makes possible and how it makes those things possible.


iOS/Objective-C "if" best practice I've got this code that I found in a project and I'm wondering how can it be done better:

- (void) setAlpha:(float)alpha {
    if (self.superview.tag == noDisableVerticalScrollTag) {
        if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleLeftMargin) {
            if (self.frame.size.width < 10 && self.frame.size.height > self.frame.size.width) {
                UIScrollView *sc = (UIScrollView*)self.superview;
                if (sc.frame.size.height < sc.contentSize.height) {
                    return;
                }
            }
        }
    }
    if (self.superview.tag == noDisableHorizontalScrollTag) {
        if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleTopMargin) {
            if (self.frame.size.height < 10 && self.frame.size.height < self.frame.size.width) {
                UIScrollView *sc = (UIScrollView*)self.superview;
                if (sc.frame.size.width < sc.contentSize.width) {
                    return;
                }
            }
        }
    }

    [super setAlpha:alpha];
}

First of all, using the tag to distinguish between views is almost everytime (there are exceptions) a bad idea. It's much cleaner to use your own variable (pointers to view, BOOL flags).

10 is a magic number. What does it mean? Use a constant.

Use methods. Four levels of if are terrible. Extract the code into methods.

if ([self isVerticalScrollingDisabled] || [self isHorizontalScrollingDisabled]) {
    return;
}

[super setAlpha:alpha];

By the way, changing the behavior of a method in a subclass (the method sets alpha only if some conditions are valid) is smelly from architecture point of view. Declaring a special method, e.g. setAlphaIfScrollingEnabled: would be better.


Reduce jQuery append method Is this the simplest way to write this? This code evaluates if a textbox value exceeds 20 characters, and then displays the proper message (essentially truncating the string and then adding an ellipses to the end.)

I've tried using a tertiary operator but doesn't seem to work with appending data to an element as it overwrites what was previously appended.)

if (searchBoxValue.length > numCharToDisplay) {
    searchDropDown.append('
Searching "' +
    searchBoxValue.trim().substring(0, numCharToDisplay) +
    '..." Found No Results
');
} else {
    searchDropDown.append('
Searching "' +
    searchBoxValue.trim() + '" Found No Results
');
}

Instead of writing append two times, why don't append a single time with two different values depending on the length of searchBox?

Also, moving the trimmed search value into a variable simplifies the code a bit.

var text,
    trimmedSearch = searchBoxValue.trim();
if (searchBoxValue.length > numCharToDisplay) {
    text = '
Searching "' +
    trimmedSearch.substring(0, numCharToDisplay) +
    '..." Found No Results
';
} else {
    text = '
Searching "' +
    trimmedSearch + '" Found No Results
';
}
searchDropDown.append(text);

Using ternary operators, as you suggested, wouldn't be a good practice since it complicates things up, leaving maintenance really difficult.


Reduce repetitive code in Lotto simulator I'm extremely new to Java, and I had a bit of an attempt at making something that you could call lotto. I've still got a lot more to go on it, but things are becoming tedious, and I am sure there is a simpler way to do what I am doing.  How can this code be changed to have less repetitive code/optimized?

import java.util.Random;
import java.util.Scanner;

public class Lotto {

    //Pick 6 numbers from 1 to 100
    //If all of your numbers gets called out, you win

    public static void wait (int n) {
        long t0,t1;
        t0=System.currentTimeMillis();
        do{
            t1=System.currentTimeMillis();
        }
        while (t1-t0<1000);
    }

    public static void main(String[] args) {
        Random rand = new Random();
        Scanner numScan1 = new Scanner(System.in);
        Scanner numScan2 = new Scanner(System.in);
        Scanner numScan3 = new Scanner(System.in);
        Scanner numScan4 = new Scanner(System.in);
        Scanner numScan5 = new Scanner(System.in);
        Scanner numScan6 = new Scanner(System.in);
        boolean num1Cor = false;
        boolean num2Cor = false;
        boolean num3Cor = false;
        boolean num4Cor = false;
        boolean num5Cor = false;
        boolean num6Cor = false;

        System.out.print("Pick 6 numbers from 0 to 25. Pick your first number: ");
        int num1 = numScan1.nextInt();
        System.out.println();
        System.out.print("Pick your second number: ");
        int num2 = numScan2.nextInt();
        System.out.println();
        System.out.print("Pick your third number: ");
        int num3 = numScan3.nextInt();
        System.out.println();
        System.out.print("Pick your fourth number: ");
        int num4 = numScan4.nextInt();
        System.out.println();
        System.out.print("Pick your fifth number: ");
        int num5 = numScan5.nextInt();
        System.out.println();
        System.out.print("Pick your final number: ");
        int num6 = numScan6.nextInt();
        System.out.println("Numbers will now start to be drawn, if all of your numbers are called, you win.");

        while (true) {
            int random = rand.nextInt(25);
            System.out.println("Number " + random + ".");

            if (random == num1) {
                num1Cor = true;
                System.out.println("Your number, " + num1 + ", has been called.");
            }
            else if (random == num2) {
                num2Cor = true;
                System.out.println("Your number, " + num2 + ", has been called.");
            }
            else if (random == num3) {
                num3Cor = true;
                System.out.println("Your number, " + num3 + ", has been called.");
            }
            else if (random == num4) {
                num4Cor = true;
                System.out.println("Your number, " + num4 + ", has been called.");
            }
            else if (random == num5) {
                num5Cor = true;
                System.out.println("Your number, " + num5 + ", has been called.");
            }
            else if (random == num6) {
                num6Cor = true;
                System.out.println("Your number, " + num6 + ", has been called.");
            }

            if (num1Cor == true && num2Cor == true && num3Cor == true && num4Cor == true && num5Cor == true && num6Cor == true) {
                System.out.println("You win!!");
                break;
            }

            wait(100);
        }
    }
}

First, you need just one Scanner.

Second, you could store the number choose by the user in an array.

Third, you could iterate the array to find the number there, instead of doing a lot of if and else if.

Forth, the user always wins. This looks like a bug. The while(true) ensures that the numbers are choosen in a way that eventually all the choosen numbers will be drawn. More, nothing stops the user from choosing a number more than once.

Fifth, the wait(100) will fail. You should use Thread.sleep(100) instead. EDIT, oops, I thought you were using Object.wait. It currently works, but Thread.sleep is better.


Fast case-insensitive hash-code for specific codes I'm trying to fix another bottleneck identified with a profiler (dotTrace). This time it's a case insensitive hash-code.

Currently I'm using the StringComparer.OrdinalIgnoreCase as a comparer for a dictionary and a custom  implementaion of an IComparable<string>. With 40 millions calls it costs me ~14 seconds. This is too much as there will be more calls in future. I'd like to replace it with an int to improve the lookup time.

The values I'm working with are in the format and between 1A and 99Z. There will never be other codes.

I've build a proof-of-concept for encoding and decoding these codes that works like that:

I shift each char to the left by 8 bits from left to right: for example 5A and 20F.

               5        A
       2       0        F
-------- ------- --------

The decoder unshifts them and rebuilds the string (mainly for debugging purposes as I actually won't be doing this much). Additionaly if a letter exceeds the A-Z alphabet its case is fixed to upper-case.

static class CaseInsensitiveCoordinate
{
    private const int AlphabetLength = ('Z' - 'A');
    private const int AlphabetsDistance = ('a' - 'Z');
    private const int CaseFix = AlphabetLength + AlphabetsDistance;

    public static int Encode(this string value)
    {
        var result = 0;

        // Assume the code has only two chars.
        result += (int)value[0] << 8;

        // Oh, there are tree, then shift what we have and add the next one.
        if (value.Length == 3)
        {
            result <<= 8;
            result += (int)value[1] << 8;
        }

        // Finally add the letter and fix the casing.
        var letter = (int)value[value.Length - 1];
        if (letter > 'Z')
        {
            letter -= CaseFix;
        }

        return result += letter;
    }

    public static string Decode(this int value)
    {
        // Unshift all values and rebuild the string.
        return
            (value > "9Z".Encode())
                ? new string(new[]
                {
                    (char)((value & 0xFF0000) >> 16),
                    (char)((value & 0xFF00) >> 8),
                    (char)(value & 0xFF)
                })
                : new string(new[]
                {
                    (char)((value & 0xFF00) >> 8),
                    (char)(value & 0xFF)
                });
    }
}

Simple Stopwatch measurements in LINQPad (compiled as release) result in a difference of about ~1.5 seconds for 40 million loops between the string-comparer and my hash-code.

void Main()
{

    var dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase) { ["5A"] = new object() };
    var dic2 = new Dictionary<int, object> { [13633] = new object() };

    var count = 40_000_000;

    var sw = Stopwatch.StartNew();
    for (int i = 0; i < count; i++)
    {
        var result = dic["5A"];
    }
    sw.Elapsed.Dump();

    sw = Stopwatch.StartNew();
    for (int i = 0; i < count; i++)
    {
        var result = dic2["5A".Encode()];
    }
    sw.Elapsed.Dump();
}

I call them hash-codes because I'm going to use them as such but at the same time they are a numeric representation of the string-code and they also need to remain sortable (they are use in a SortedHashSet).

There isn't much left to optimize there, just few cycles, but with 40 millions calls the difference might be at least measurable.

When value.length == 3 you perform << 8 twice and csc or JIT compiler have no chance to optimize this, given that length can be only 2 or 3 then you can make it explicit (I think you will also gain in clarity but that's just a point of view):

public static int Encode(this string value)
{
    Debug.Assert(value != null);
    Debug.Assert(value.Length == 2 || value.Length == 3);

    if (value.Length == 2)
    {
        return ((int)value[0] << 8)
            | EncodeLetter(value[1]);
    }
    else
    {
        return ((int)value[0] << 16)
            | ((int)value[1] << 8)
            | EncodeLetter(value[2]);
    }

    int EncodeLetter(char c)
        => c > 'Z' ? (return c - CaseFix) : (c);
}

In this way you should save one shift << (which isn't super-fast in all .NET environments). Also direct access to string items without value.Length - 1 should be slightly faster. Bitwise OR | may be faster than sum + but it depends on an huge amount of details (specific CPU, in primis, and how uop will be fused with surrounding code)...not something we can determine without more details. Here I like it only because of clarity.

It would be nice if we may get the JIT compiler to drop bounds checking here, is unsafe code allowed here?

I added few Debug.Assert(), not a penalty price you want to pay in released code but probably useful when running tests on your own development machine.

About Decode(): "9Z".Encode() might be saved in a static readonly field (in my case it seems it's not optimized away by compiler/JIT).


Converting a decimal into a fraction I have written a small program that converts a decimal number into a reduced fraction representation. I also designed this little program to be fairly robust, so that it can give the correct output for various inputs.

For example:

./a.out 3,000.375
24003/8
./a.out "3 000,375"
24003/8
./a.out 3.000,375
24003/8
./a.out 3000.375
24003/8

Here is the complete code for the program:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int isDigit(char);
void simplify(unsigned long long *, unsigned long long *);

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "Please enter a number to fractionize.\n");
        return EXIT_FAILURE;
    }
    char *input = argv[1];
    int i;
    char c;
    unsigned long long previous, denominator = 1, numerator = 0;
    for (i = strlen(input) - 1; i >= 0; i--, denominator *= 10) {
        c = input[i];
        if (!isDigit(c)) {
            break;
        }
        previous = numerator;
        numerator = (c - '0') * denominator + numerator;
        if (previous > numerator) {
            return EXIT_FAILURE;
        }
    }
    if (c == '-' || isDigit(c)) {
        printf("%llu/1\n", numerator);
        return EXIT_SUCCESS;
    }
    simplify(&numerator, &denominator);
    int j, negative = 0;
    unsigned long long whole = 0;
    for (j = 0; j < i; j++) {
        char c = input[j];
        if (c == '-') {
            negative = 1;
        } else if (isDigit(c)) {
            previous = whole;
            whole = whole * 10 + (c - '0');
            if (previous > whole) {
                return EXIT_FAILURE;
            }
        }
    }
    previous = numerator;
    numerator += whole * denominator;
    if (previous > numerator) {
        return EXIT_FAILURE;
    }
    simplify(&numerator, &denominator);
    if (negative) {
        printf("-");
    }
    printf("%llu/%llu\n", numerator, denominator);
    return EXIT_SUCCESS;
}

int isDigit(char c) {
    return c >= '0' && c <= '9';
}

void simplify(unsigned long long *numerator, unsigned long long *denominator) {
    while (1) {
        if ((*numerator % 2 == 0) && (*denominator % 2 == 0)) {
            *numerator   /= 2;
            *denominator /= 2;
        } else if ((*numerator % 5 == 0) && (*denominator % 5 == 0)) {
            *numerator   /= 5;
            *denominator /= 5;
        } else {
            break;
        }
    }
}

My algorithm is basically to first process the number right to left. As soon as a non-digit is detected, the part of the input that has been processed is deemed the "fractional part". This fractional part is then simplified (when possible). For example "12.34" would be processed as 34 and 100, which would then be simplified to 17 and 50.

Then, the input is processed left to right up to the point where the first scan terminated. Any non-digit characters are ignored (except the minus sign), and digits are accumulated (12 in this case). This is deemed the "whole part".

Then, the whole part is multiplied by the (simplified) denominator and it is added to the (simplified) fractional part (in this case, the fraction would be 617 over 50). The fraction is then again simplified (when possible) and the result is printed out.

My main concern is how I handle overflow. Because I am using unsigned types, overflow would simply cause the number to wrap around towards 0, so I simply check if the number before the computation (stored in previous) is larger than the number after the computation. If it is, then overflow has occurred. This seems like a fairly naive way to do it, but it seems to work for the inputs that I have tried.

Otherwise, any stylistic or performance-related inputs are always appreciated.

I think you're being too lenient with your input checking, which results in some unexpected results:

-3,000,0    results in:     -3000/1
3,000      results in: 3/1
3 results in 3/1
3-1 results in 1/1

Personally, I'd pick an expected format and then ensure that the input complies with it.  If you want to support multiple decimal marks, then I would suggest having a function for each supported format that validates the input and returns it in one common format which is then used by the rest of the code.
argc & argv
In your example you have ./a.out "3 000,375".  You're quoting the space in order to ensure it's all pushed as part of argv[1].  It seems likely that this could be forgotten.  If it was, then you would end up with the output of 3/1.  Your argc checking only checks for no parameters being supplied:
if (argc < 2) {
    fprintf(stderr, "Please enter a number to fractionize.\n");
    return EXIT_FAILURE;
}

Unless you're going to continue through the arguments supplied, appending them to the input it would be better to do something like this:
if (argc != 2) {
    fprintf(stderr, "Usage: %s <number to fractionize>\n", argv[0]);
    return EXIT_FAILURE;
}

One declaration per line
This is obviously subjective, but I don't particularly like multiple declarations on a single line.  I don't mind it so much when you're declaring several uninitialised variables, however when you're assigning values to the variables it would be better to have each declaration on a new line.  For me, denominator and previous get a bit lost on this line:
unsigned long long previous, denominator = 1, numerator = 0;


Comparing two arrays I've started reading C++ Primer a few weeks ago and there's an exercise that asks you to compare two arrays for equality. The code I made works, but is it good? What should I fix?

If the number of elements don't match, they're not equal.  If the elements are different, they are not equal.

#include <iostream>

using namespace std;

bool arrayComparer(int *a, size_t asize, int *b, size_t bsize){
    if(asize != bsize){return false;}
    for(size_t ite = 0; ite < asize; ++ite){
       if(*(a+ite) != *(b+ite)){return false;}
    }
    return true;
}

int main()
{
    int ar1[]{0,1,2,3,4,5,6,7,8,9},
        *ptr1 = ar1,
        ar2[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18},
        *ptr2 = ar2;

        size_t intSize = sizeof(int),
               asize = sizeof(ar1) / intSize,
               bsize = sizeof(ar2) / intSize;

    cout << arrayComparer(ptr1,asize,ptr2,bsize) << endl;
    return 0;
}

Since the number of elements may be different, I'm using pointers. I did not find a way to get the number of elements from the pointers, so I'm also passing the size to the function.

Comments are appreciated.

Try not to use using namespace std.
You don't need an explicit return 0 at the end of main().  As reaching the end of main() already implies successful termination, the compiler will do the return for you.
In C++, use std::size_t over size_t, the former being part of the std namespace.
Consider having your function print true or false instead of 1 or 0.  You could do this by putting std::boolalpha into the output stream before the function call.

cout << std::boolalpha << arrayComparer(ptr1,asize,ptr2,bsize) << endl;

There is no need for this:

std::size_t intSize = sizeof(int);

You can just use sizeof(int) for both size calculations, so that you can only have size variables that correspond to array sizes.  Extra possible overhead is not a problem because sizeof() is actually an operator, not a function.
If your compiler supports C++11, you can use an std::array instead of C-style arrays.  If not, use an std::vector.  They both know their own sizes, and you'll no longer need your own pointers.

Raw pointer use in C++ should generally be avoided whenever possible, and passing raw pointers can introduce ownership issues.  Passing C-style arrays to functions is also bad because they will decay to pointers.  If you must use them anyway, at least for this exercise, then perhaps you can declare ptr1 and ptr2 within arrayComparer() instead of passing them from main().


Generate a Jekyll blog post template using shell I'm creating my first Bash script newpost.sh, which generates a Markdown file containing the metadata for a new blog post. This blog post will be hosted in a Jekyll engine, like GitHub pages. The idea is to facilitate:

The generation of date
The conversion from the post title to URL
Compatible in both mac OS and Linux

So user can really focus on writing blog, instead of handling different metadata.

#!/bin/bash
#
#    This script creates a new blog post with metadata in ./_posts
#    folder. Date will be generated according to the current time in
#    the system. Usage:
#
#        ./newpost.sh "My Blog Post Title"
#

title=$1

if [ -z "$title" ]; then
    echo "usage: newpost.sh \"My New Blog\""
    exit 1
fi

bloghome=$(cd "$(dirname "$0")"; pwd)
url=$(echo "$title" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')
filename="$(date +"%Y-%m-%d")-$url.md"
filepath=$bloghome/_posts/$filename

if [ -f filepath ]; then
    echo "$filepath already exists."
    exit 1
fi

touch $filepath

echo "---" >> $filepath
echo "layout:      post" >> $filepath
echo "title:       \"$title\"" >> $filepath
echo "date:        \"$(date +"%Y-%m-%d %H:%M:%S %z")\"" >> $filepath
echo "categories:  [weekly]" >> $filepath
echo "---" >> $filepath

echo "Blog created: $filepath"

Any feedback is welcome!

Overall, it is clear and well formatted.  Here are some suggestions:

shellcheck.net

Firstly, I highly recommend running your scripts through shellcheck.net.  This reveals:

Where you're using $filepath you should use "$filepath" in case part of the path contains spaces.  Although shellcheck didn't catch it the assignment to filepath= should have quotes around the right side so it doesn't get broken up.
cd can fail and you should check the exit code, but in your case you're just using it inside of a subshell so it is probably fine as is.

double brackets

Using double brackets for conditionals in the shell is a good habit to get into.  They won't surprise you when people leave variables empty, for instance.  So

if [ -z "$title" ]; then

should be

if [[ -z "$title" ]]; then

bug

Where you check for the files existence you don't substitute the variable, you're checking for the existence of a file named filepath which probably never will be there.  Replace:

if [ -f filepath ]; then

with

if [[ -f "$filepath" ]]; then

to get the desired result.  I'm also using the quotes around the variable and double brackets previously mentioned.

heredocs

Instead of repeatedly appending to your file, why not do it in one fell swoop:

cat << EOF >> "$filepath"
---
layout:      post
title:       "$title"
date:        "$(date +"%Y-%m-%d %H:%M:%S %z")"
categories:  [weekly]
---
EOF

That can replace your block of echos.  Now you don't have to worry about escaping your double quotes and the template is clearly separated from the code.  Heredocs also make it easier to edit the template within the script without messing up what the code is doing.

finally

Thanks for posting your shell script on codereview and trying to get better.


Extract a number from a consecutive range in a Google Sheet I'm new in coding and I use google script in my spreadsheet to add a list of consecutive numbers automatically by giving the first number to add and the last one (with an arrival date and an option "A" or "B" for each number). I created a table to put all the informations with an html file. The code is "OK", it's working but it's too slow and I reached my limits in coding to improve the code so...is there somebody that can help me or give an hint on that ?

To make the message clearer, here is what I have and what I want at the end :

Before launching the code :

After launching the code, completing the table (forget about the first line) :

Final result with consecutive range of number added :

Code.gs

function onOpen(e) {
   SpreadsheetApp.getUi()
       .createMenu('Arrivage')
       .addItem('Add a new one', 'Arrivee')
       .addToUi();
 }

function Arrivee() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet().getSheetName();
  if (sheet.indexOf("Br") == 0) {
    SpreadsheetApp.getUi().alert("Vous devez sélectionner
la feuille où ajouter l'arrivage et pas celle des colis !");
    return false
  }else{
  var html = HtmlService.createHtmlOutputFromFile('index.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi()
       .showModalDialog(html, 'Remplissez les infos
nécessaires pour le nouvel arrivage des ' + sheet);
  }
}

function itemAdd(form) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var feuille = ss.getActiveSheet();
  var nb_total = form.colis2 - form.colis1;
  for (i = 0; i <= nb_total; i++) {
    if (i < form.gare){
      var a_values = [[ +form.colis1 + i, form.ddc, "A" ]];
      feuille.getRange(feuille.getLastRow() + 1, 6, 1, 3).setValues(a_values);
    }else{
      var b_values = [[ +form.colis1 + i, form.ddc, "B" ]];
      feuille.getRange(feuille.getLastRow() + 1, 6, 1, 3).setValues(b_values);
    }
  }
}

index.html

<!DOCTYPE html>

    <base target="_top" >

  <form>
    Numéro arrivage :
    <input type="text" name="br">

    Numéro colis 1 :
    <input type="text" name="colis1">

    Numéro colis 2 :
    <input type="text" name="colis2">

    Gare :
    <input type="text" name="gare">

    Date de création :
    <input type="text" name="ddc">

     <input type="button" value="Ajouter"
        onclick="google.script.run
            .withSuccessHandler(google.script.host.close)
            .itemAdd(this.parentNode)" />
    </form>

I guess the answer could be useful to someone that begin like me in coding...Anyway the tip here was to create an array first (I named it table) instead of adding objects line by line and then update the sheet in a single operation with setValues. It makes running the code way much faster !

function itemAdd(form) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var feuille = ss.getActiveSheet();
  var nb_total = form.colis2 - form.colis1;
  var table = [];
  for (i = 0; i <= nb_total; i++) {
    if (i < form.gare){
      table.push([+form.colis1 + i, form.ddc, "A"]);
      }else{
      table.push([+form.colis1 + i, form.ddc, "B"]);
      }
    }
  feuille.getRange(feuille.getLastRow() + 1, 6, table.length, 3).setValues(table);
  }


A package for sort algorithms I'm trying to learn basic algorithms which are typically taught in an introduction to CS course, which is usually taught in a compiled language like Java.  However, I want to focus on JavaScript, so I wrote the algorithms in JavaScript and encapsulated them into a library.

I'm looking for feedback on the efficiency of my implementations (bubbleSort, selectionSort, insertionSort):

/***************************************************************************************************
**ALGORITHMS
***************************************************************************************************/

(function () {
    "use strict";
    var $A,
        $P = {};

    (function manageGlobal() {
        if (window.$A && window.$A.pack) {
            $A = window.$A;
            $A.pack.algo = true;
        }
    }());

    $P.swap = function (arr, i, j) {
        var temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    };

    // checks to see if sorted
    $P.isSorted = function (arr) {
        var index_outer,
            length = arr.length;
        for (index_outer = 1; index_outer < length; index_outer++) {
            if (arr[index_outer - 1] > arr[index_outer]) {
                return false;
            }
        }
        return true;
    };

    // repeatedly orders two items ( a bubble ) at a time
    $P.bubbleSort = function (arr) {
        var index_outer,
            index_inner,
            swapped = false,
            length = arr.length;
        for (index_outer = 0; index_outer < length; index_outer++) {
            swapped = false;
            for (index_inner = 0; index_inner < length - index_outer; index_inner++) {
                if (arr[index_inner] > arr[index_inner + 1]) {
                    $P.swap(arr, index_inner, index_inner + 1);
                    swapped = true;
                }
            }
            if (swapped === false) {
                break;
            }
        }
        return arr;
    };

    // repeatedly finds minimum and places it the next index
    $P.selectionSort = function (arr) {
        var index_outer,
            index_inner,
            index_min,
            length = arr.length;
        for (index_outer = 0; index_outer < length; index_outer++) {
            index_min = index_outer;
            for (index_inner = index_outer + 1; index_inner < length; index_inner++) {
                if (arr[index_inner] < arr[index_min]) {
                    index_min = index_inner;
                }
            }
            if (index_outer !== index_min) {
                $P.swap(arr, index_outer, index_min);
            }
        }
        return arr;
    };

    // repeatedly places next item in correct spot using a "shift"
    $P.insertionSort = function (arr) {
        var index_outer,
            index_inner,
            value,
            length = arr.length;
        for (index_outer = 0; index_outer < length; index_outer++) {
            value = arr[index_outer];
            for (index_inner = index_outer - 1; (index_inner >= 0 && (arr[index_inner] > value));
                    index_inner--) {
                arr[index_inner + 1] = arr[index_inner];
            }
            arr[index_inner + 1] = value;
        }
        return arr;
    };

    // module complete, release to outer scope
    $A = $A.extendSafe($A, $P);
}());

Note that isSorted has a bit of an off-by-one error. It will check outside the bounds of its argument. This actually works OK, because it compares the last element of the array to undefined which always results in false. However, you should really only check up to index_outer < length - 1.

I haven't looked too closely at your implementations of the basic sorting algorithms, but assuming they are correct, then there isn't much that could be said about their efficiency that hasn't already. It's all well defined.