Extract Common Data From List of Objects I have a list of orders and for some order fields I need get the data that is common among the orders. If the data is not in common, I should indicate null. I collect the common data in a CommonData object. In addition, I also store the order codes and order ids associated with the CommonData.

I have two approaches that I'm considering:

Approach 1:

public CommonData getCommonData(List<Order> orders) {
    Order firstOrder = order.get(0);

    LocalDate commonStartDate = firstOrder.getStartDate();
    LocalDate commonEndDate = firstOrder.getEndDate();
    List<Item> commonItems = firstOrder.getItems();

    CommonData commonData= new CommonData();

    for (Order order : orders) {

        commonData.addCode(order.getCode());
        commonData.addId(order.getId());

        if (commonStartDate != null &&
                !commonStartDate.equals(order.getStartDate())) {
            commonStartDate = null;
        }

        if (commonEndDate != null &&
                !commonEndDate.equals(order.getEndDate())) {
            commonEndDate = null;
        }

        if (!equalLists(commonItems, order.getItems())) {
            commonData.setDifferentItems(true);
            commonItems = null;
        }
    }

    commonData.setCommonStartDate(commonStartDate);
    commonData.setCommonEndDate(commonEndDate);
    commonData.setCommonItems(commonItems);
    return commonData;
}

Approach 2:

private boolean haveSameDate(List<Order> orders,
        Function<Order,LocalDate> getDate) {

    return orders.stream()
            .map(getDate)
            .distinct()
            .limit(2)
            .count() == 1;
}

public CommonData getCommonData(List<Order> orders) {
    CommonData commonData = new CommonData();

    if (haveSameDate(orders,
            Order::getStartDate)) {
        commonData.setCommonStartDate(orders.get(0).getStartDate());
    }

    if (haveSameDate(orders,
            Order::getEndDate)) {
        commonData.setCommonEndDate(orders.get(0).getEndDate());
    }

    commonData.setCodes(
            orders.stream()
                .map(order -> order.getCode())
                .collect(Collectors.toList()));

    commonData.setIds(
            orders.stream()
                .map(order -> order.getId())
                .collect(Collectors.toList()));

    List<Item> firstOrderItems = orders.get(0).getItems();
    if (orders.stream()
        .map(Order::getItems)
        .allMatch(x -> equalLists(x,firstOrderItems))) {

        commonData.setCommonItems(firstOrderItems);
    } else {
        commonData.setDifferentItems(true);
    }

    return commonData;
}

Even though approach 2 involves multiple iterations over orders, the order and item lists will always be small.

In approach 2, having operations on one piece of data is in one spot within the method but it is scattered in approach 1. Approach 1 also has negative logic. Approach 2 is more complex in finding common order items.

Can approach 1 be redesigned to have the benefits of approach 2 (such as remove negative logic and keep operations on a piece of data in a single spot)? Or should approach 2 be used and perhaps be improved to better handle finding common order items?

Basically, this boils down to the question of how to find out whether a given number of items is always the same. The mathematical tool for this is a set and checking its cardinality.

Putting this into code, you can use a Set implementation in Java:

Set<LocalDate> allStartDates = new HashSet<>();

for (...) {
    ...
    allStartDates.add(order.getStartDate());
    ...
}

if (allStartDates.size() == 1)
    commonData.setCommonStartDate(allStartDates.iterator().next());

BUT: in a real-world-application, I'd move this logic to the CommonData class.

Basically, redesign the CommonData in a way, that you can simply add an order and then boil the loop down to:

CommonData commonData = new CommonData();
orders.stream().forEach(commonData::add);

and inside the common data add method, add the codes and ids, maintain two sets of dates, and do the if-logic in the appropriate getters.


Print log error and save it to a file I have created a simple custom logger to print the error log and save it to a file with specific location.

package logger

import (
    "log"
    "os"
)

var trace *log.Logger
var filePathVar string
var fileNameVar string
var prefixVar string

// use this function first before calling others.
func InitLogger(prefix, filePath, fileName string) {
    setPrefix(prefix)
    createLogFile(prefix, filePath, fileName)
    filePathVar = filePath
    fileNameVar = fileName
    prefixVar = prefix
}

func setPrefix(prefix string) {
    trace = log.New(os.Stderr,
        prefix,
        log.Ldate|log.Ltime|log.Lshortfile)

}

func createLogFile(prefix, filePath, fileName string) (*os.File, error) {
    setPrefix(prefix)
    f, err := os.OpenFile(filePath+fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
    if err != nil {
        // error file is not created
        err = os.MkdirAll(filePath, os.ModePerm)
        if err != nil {
            trace.Println(err)
            return nil, err
        }
        createLogFile(prefix, filePath, fileName)
    }

    return f, nil
}

// use this PrintLog use print the error on the terminal without exitting apps.
func PrintLog(errorLog string) {
    //assign to global variable
    if filePathVar == "" || fileNameVar == "" || prefixVar == "" {
        trace.Fatalln("Error file path and Name empty prefix Cannot be Empty")
    }

    f, err := createLogFile(prefixVar, filePathVar, fileNameVar)
    if err != nil {
        trace.Fatalln(err)
        return
    }
    trace.Println(errorLog)
    // save the log out put to file
    trace.SetOutput(f)
    trace.Println(errorLog, err)
}

// use this Fatal log to exit the application whenever got error.
func FatalLog(errorLog string) {
    //assign to global variable
    if filePathVar == "" || fileNameVar == "" || prefixVar == "" {
        trace.Fatalln("Error file path and Name empty")
    }

    f, err := createLogFile(prefixVar, filePathVar, fileNameVar)
    if err != nil {
        trace.Fatalln(err)
        return
    }
    trace.Println(errorLog)
    // save the log out put to file
    trace.SetOutput(f)
    trace.Fatalln(errorLog, err)
}

To use this package I must call the InitLogger function first

logger.InitLogger("Prefix Logger","./filpath/","filename.txt")

And then after that I can choose to print the error using either PrintLog or FatalLog.

The PrintLog function is used when we wanted to print the log without having crashing or closing the app os.Exit. The FatalLog the same as PrintLog but will crash the app or call os.Exit.

Any idea what can be improved here? source code

If some of your init values (prefix, filePath, fileName) are empty, you should fail on init, not once you try to log something. Returning errors as soon as possible is a good practice and makes debugging much easier.
setPrefix should be called setCustomLogger or something, or better, since it's a one-line function, just inline it.
You're calling setPrefix twice on init. createLogFile shouldn't call it.
Don't join paths using string concatenation. Use filepath.Join instead.
You should check that createLogFile succeeds on init, and fail fast otherwise.
InitLogger should simply be called Init, PrintLog should be Print, FatalLog should be Fatal: you're going to call them with logger.[…] from outside your package.
godoc comments should start with the name of the function they document: PrintLog prints a log message on the console, as well as in the log file… or something.
Why are you calling createLogFile many times? Just call it on init, save the file somewhere and use it each time. I think this also allows you to get rid of all these weird variables and replace them with only what you need (an open file).
Hoooo I understand why, it's because it needs to be reinitialized to os.Stderr. Damn, that's complex. Why not simply have two loggers (once initialized to os.Stderr and the other to your file, and simply call the corresponding function on each when your custom logger is called?
You're never closing your file. There is no way you can do that from your logging package (unless you open/close it every time you write a log line, but this is terribly inefficient), so maybe your Init function should take a os.File argument instead of a file path + file name. This way, the main function of your program (which will initialize the logger) can close it once the program is over. Of course, you should also close it when Fatal is called

In short: your Print method should be two lines long, your Fatal method should be three lines long, you shouldn't have more than 2 global variables, and all errors should be caught on Init.


Convert decimal to binary and vice-versa in Java I'm trying to learn Java, so I'm doing a few exercises from a programmer project idea book. This exercise requires that the program be able to convert a decimal number to binary and vice versa, like so:

Please enter the binary/decimal number to convert:9783569
100101010100100100010001

Please enter the binary/decimal number to convert:100101010100100100010001
9783569

Here's the code I came up with:

import java.util.Scanner;

public class BinaryToDecimalAndBackConverter{

    static String convertDecimalToBinary(String decimal){
            int integer = Integer.valueOf(decimal);
            String result = new String();

            while(integer > 0){
                result+=String.valueOf(integer%2);
                integer/=2;
            }

            result = new StringBuffer(result).reverse().toString();
            return result;
    }
    static int convertBinaryToDecimal(String binary){
            int result = 0;

            for(int reverseCounter = 0; reverseCounter < binary.length(); reverseCounter++){
                char currentChar = binary.charAt(binary.length() - reverseCounter - 1);
                int numericValue = Character.getNumericValue(currentChar);
                result+=Math.pow(2, reverseCounter) * numericValue;
//              System.out.println(Math.pow(2, reverseCounter) * Character.getNumericValue(binary.charAt(binary.length() - reverseCounter - 1)) + " reverseCounter " + reverseCounter);
            }

            return result;
    }
    static String isDecimalOrBinary(String input){
        for(int counter = 0; counter < input.length(); counter++){
            if(input.charAt(counter) != '0' && input.charAt(counter) != '1'){
                return "decimal";
            }
        }

        return "binary";
    }
    public static void main(String[] args){
        Scanner inputScanner = new Scanner(System.in);

        System.out.print("Please enter the binary/decimal number to convert:");
        String input = inputScanner.nextLine();

        switch(isDecimalOrBinary(input)){
            case "decimal":
                System.out.println(convertDecimalToBinary(input));
            break;
            case "binary":
                System.out.println(convertBinaryToDecimal(input));
            break;
        }
    }
}

The best way to do it:

static String convertDecimalToBinary(String decimal) {
    return Integer.toString(Integer.parseInt(decimal, 10), 2);
}

static int convertBinaryToDecimal(String binary) {
    return Integer.parseInt(binary, 2);
}

By the way your code looks good except for at least two issues:

Don't work with negative numbers
The method isDecimalOrBinary is ambiguous: what's the result of the 100 input? It's binary of course, but if i meant one hundred? I suggest to delegate the user to specify it.

I would correct it in this way:

import java.util.Scanner;

public class BinaryToDecimalAndBackConverter {

    static String convertDecimalToBinary(String decimal) {
        final boolean isNegative = decimal.startsWith("-");
        if (isNegative) {
            decimal = decimal.substring(1);
        }

        int integer = Integer.valueOf(decimal);
        String result = new String();

        while (integer > 0) {
            result += String.valueOf(integer % 2);
            integer /= 2;
        }

        // use StringBuilder instead of StringBuffer, we are sure about
        // exclusive access, no need to use a thread safe class
        final StringBuilder resultBuilder = new StringBuilder(result);
        if (isNegative) {
            resultBuilder.append("-");
        }

        return resultBuilder.reverse().toString();
    }

    static int convertBinaryToDecimal(String binary) {
        final boolean isNegative = binary.startsWith("-");
        if (isNegative) {
            binary = binary.substring(1);
        }
        int result = 0;

        for (int reverseCounter = 0; reverseCounter < binary.length(); reverseCounter++) {
            final char currentChar = binary.charAt(binary.length() - reverseCounter - 1);
            final int numericValue = Character.getNumericValue(currentChar);
            result += Math.pow(2, reverseCounter) * numericValue;
            // System.out.println(Math.pow(2, reverseCounter) *
            // Character.getNumericValue(binary.charAt(binary.length() -
            // reverseCounter - 1)) + " reverseCounter " + reverseCounter);
        }

        if (isNegative) {
            result = -result;
        }

        return result;
    }

    public static void main(String[] args) {
        final Scanner inputScanner = new Scanner(System.in);

        System.out.print("Please enter the binary/decimal number to convert:");
        // expected input: NUM D|B
        final String[] splittedInput = inputScanner.nextLine().split(" ");
        if (splittedInput.length != 2) {
            // don't forget to close the Scanner
            inputScanner.close();
            throw new IllegalArgumentException("Wrong input format: expected NUM D|B");
        }
        final String input = splittedInput[0];

        switch (splittedInput[1]) {
        case "d":
        case "D":
            System.out.println(convertDecimalToBinary(input));
            break;
        case "b":
        case "B":
            System.out.println(convertBinaryToDecimal(input));
            break;
        default:
            // don't forget to close the Scanner
            inputScanner.close();
            throw new IllegalArgumentException(
                    "Wrong input format: expected NUM D|B, the second argument was not D nor B");
        }

        // don't forget to close the Scanner
        inputScanner.close();
    }
}


Is this the most efficient way to track word changes in a string? I'm working on a writing platform and am using a modified version of the Levenshtein distance algorithm to track a writer's engagement with their writing. It tracks not only words added to their content, but also rewards editing by including words removed and words substituted in the count.

Here's my algorithm in Ruby (which I run between (auto)saves):

def words_changed_since(second)
  first = self.split # array of words in first string
  second = second.split # array of words in second string

  # initialize the matrix
  matrix = [(0..first.length).to_a]
  (1..second.length).each do |j|
    matrix << [j] + [0] * (first.length)
  end

  # for each word in the second string
  (1..second.length).each do |i|
    # for each word in the first string
    (1..first.length).each do |j|
      if first[j-1] == second[i-1]
        matrix[i][j] = matrix[i-1][j-1]
      else
        matrix[i][j] = [
          matrix[i-1][j], # word deletion
          matrix[i][j-1], # word insertion
          matrix[i-1][j-1] # word substitution
        ].min + 1
      end
    end
  end
  return matrix.last.last
end

Is this the most efficient way of tracking these changes?

Ruby is fundamentally more about simplicity (readability) than about time/memory efficiency. Otherwise you should choose another language. There are such high level languages, that can beat Ruby, like for example Javascript. And even Python handle strings faster than Ruby at the cost of eternal problems with encodings (don't waste your time on crutches, choose tools wisely).
And even inside Ruby single replacements of one method chain with another can either be efficient or not, depending on your platform (jruby? rubinius? etc.) while there are still different ways to measure an algorithmic complexity especially for your unique kind of input data.

So anyway.

The matrix creation I would write in one of these two ways:

matrix = (0..second.size).map{ |i|
  (0..first.size).map{ |j|
    i==0 ? j : j == 0 ? i : 0
  }
}

matrix = (0..second.size).map{ |i|
  i==0 ? (0..first.size).to_a : [i]+[0]*first.size
}

There is also a solution via transpose, but not functional, and one via zip in which I doubt.
You can omit the return keyword at the last line in Ruby functions.

And this is not Ruby-related, but in the main loop try to iterate through 0...second.length instead of 1..second.length (same for first). In that way you'll swap i-1 with i and i with i+1, getting rid of two decrements in total.


Refactor data tranfer object and model T_PROJECT is the class that will be retrieve data from linq to sql and ProjectOwnerDataFields is the class that will be used to show data in view. in edit mode i have to get value from model and send it back like this. is there anyway to refactor this and remove the reverse duplication on ProjectOwnerDataFields and UpdateToModel ?

    public class ProjectOwnerDataFields
    {
        public int Id { get; set; }
        public string CompanyName { get; set; }
        public string ContactPerson { get; set; }
        public string CountryIsoLetter { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string Fax { get; set; }
        public string Location { get; set; }
        public string Province { get; set; }
        public string Remark { get; set; }

        public string CountryFullName
        {
            get
            {
                if (String.IsNullOrEmpty(this.CountryIsoLetter) == false)
                {
                    return new RegionInfo(this.CountryIsoLetter).EnglishName;
                }

                return "";
            }
        }

        public ProjectOwnerDataFields()
        {

        }

        public ProjectOwnerDataFields(T_PROJECT project)
        {
            this.Id                =     project.proj_owner_id            ;
            this.CompanyName       =     project.proj_owner               ;
            this.ContactPerson     =     project.proj_owner_contact       ;
            this.CountryIsoLetter  =     project.proj_owner_country       ;
            this.Phone             =     project.proj_owner_phone         ;
            this.Email             =     project.proj_owner_email         ;
            this.Fax               =     project.proj_owner_fax           ;
            this.Location          =     project.proj_owner_location      ;
            this.Province          =     project.proj_owner_province      ;
            this.Remark            =     project.proj_remark              ;
        }

        public void UpdateToModel(T_PROJECT project)
        {
            project.proj_owner              =   this.CompanyName          ;
            project.proj_owner_contact      =   this.ContactPerson        ;
            project.proj_owner_country      =   this.CountryIsoLetter     ;
            project.proj_owner_phone        =   this.Phone                ;
            project.proj_owner_email        =   this.Email                ;
            project.proj_owner_fax          =   this.Fax                  ;
            project.proj_owner_location     =   this.Location             ;
            project.proj_owner_province     =   this.Province             ;
            project.proj_remark             =   this.Remark               ;
        }
    }

This is very close to what AutoMapper is for. Though it doesn't directly support bidirectional maps, so you'll have to write a simple class that builds two mappers at the same time:

public class TwoWayMapper<TSource, TDestination>
{
    private readonly IMappingExpression<TSource, TDestination> m_sourceMapping =
        Mapper.CreateMap<TSource, TDestination>();
    private readonly IMappingExpression<TDestination, TSource> m_destinationMapping =
        Mapper.CreateMap<TDestination, TSource>();

    public TwoWayMapper<TSource, TDestination> ForMember(
        Expression<Func<TSource, object>> sourceMember,
        Expression<Func<TDestination, object>> destinationMember)
    {
        m_sourceMapping.ForMember(destinationMember, opt => opt.MapFrom(sourceMember));
        m_destinationMapping.ForMember(sourceMember, opt => opt.MapFrom(destinationMember));
        return this;
    }
}

You can then set up your mapping like this (maybe in a static constructor of ProjectOwnerDataFields?):

new TwoWayMapper<ProjectOwnerDataFields, T_PROJECT>()
    .ForMember(f => f.Id, p => p.proj_owner_id)
    .ForMember(f => f.CompanyName, p => p.proj_owner)
    .ForMember(f => f.ContactPerson, p => p.proj_owner_contact)
    .ForMember(f => f.CountryIsoLetter, p => p.proj_owner_country);
    // etc.

With that, your methods simplify to:

public ProjectOwnerDataFields(T_PROJECT project)
{
    Mapper.Map(project, this);
}

public void UpdateToModel(T_PROJECT project)
{
    Mapper.Map(this, project);
}


Project Euler Problem #6 - sum square difference The sum of the squares of the first ten natural numbers is:

  \$1^2 + 2^2 + ... + 10^2 = 385\$

  The square of the sum of the first ten natural numbers is:

  \$(1 + 2 + ... + 10)^2 = 55^2 = 3025\$

  Hence the difference between the sum of the squares of the first ten
  natural numbers and the square of the sum is \$3025 − 385 = 2640\$.

  Find the difference between the sum of the squares of the first one
  hundred natural numbers and the square of the sum.

//Project euler problem 6

#include <iostream>
#include <cmath>
using namespace std;

unsigned int sum(int);
unsigned int sqsum(int);

int main()
{
    cout << sum(100)*sum(100) - sqsum(100);
}

unsigned int sum(int n) // function for finding sum of n numbers
{
    return (n*(n+1))/2;
}

unsigned int sqsum(int n) // function for finding sum of squares
{
     return ((n)*(n+1)*(2*n +1 ))/6 ;
}

Here are a few comments that may help you improve your code.

Use only necessary #includes

The #include <cmath> line is not necessary and can be safely removed.

Avoid "magic numbers"

Since the constant 100 is used several times within the code, it makes sense to create a constant instead.  This also helps with troubleshooting since you can quickly change it to small values (e.g. 10) for which you already know the answer:

const int maxnum = 100;

Avoid abusing using namespace std

Don't abuse using namespace std

Especially in a very simple program like this, there's little reason to use that line.  Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Eliminate function prototypes by ordering

If you put the sum and sqsum implementations above main in the source code, you don't need the function prototypes.

End the last console output with a newline

The output to the program is a little neater on most machines if you output a newline character after the last of the program's console output.

Avoid unnecessary function calls

It doesn't make a huge difference in this code, but the code dosn't need to make two calls to sum().  Instead, the main routine might look like this:

int main()
{
    const int maxnum = 100;
    unsigned square_of_sum = sum(maxnum);
    square_of_sum *= square_of_sum;
    std::cout << square_of_sum - sqsum(maxnum)-a << '\n';
}


Upvote/counter in Javascript Looking to improve building UI in pure ES6.

This is the pattern I have adopted and has worked fairly well. This code increments the count, sets a data attribute to toggle the button, and issues a POST to the server with the vote payload object.

import axios from "axios";

class Vote {
  constructor(el) {
    this.el       = el;
    this.url      = this.el.dataset.url;
    this.id       = this.el.dataset.id;
    this.count    = this.el.dataset.count;
    this.count_el = this.el.querySelector('span.count')
    this.setClickHandlers();
  }

  setClickHandlers() {
    this.el.addEventListener("click", ()=> {
      this.postVote();
      this.toggle();
      this.toggleCount();
    })
  }

  postVote() {
    axios({
      url: this.url,
      method: 'post',
      data: { "idea":
        {"id": this.id}
      }
    })
    .then((data) => {
      console.log(`${data}: Posted vote`);
    })
    .catch((data) => {
      console.log(data);
    })
  }

  toggle() {
    if (this.el.dataset.toggled == "true") {
      this.el.dataset.toggled = "false"
    } else {
      this.el.dataset.toggled = "true"
    }
  }

  toggleCount() {
    var current = parseInt(this.count_el.innerHTML);
    if (this.el.dataset.toggled == "true") {
      this.count_el.innerHTML = ++current;
    } else {
      this.count_el.innerHTML = --current;
    }
  }

}

document.addEventListener("turbolinks:load", ()=> {
  let votes = document.querySelectorAll('[data-vote]');
  if (votes.length) {
    votes.forEach((el) => {
      new Vote(el);
    })
  }
});

Consistency

Sometimes you use snake_case and sometimes you use camelCase: in JavaScript we usually use camel case, it's not mandatory but stick to one. Then, for example, count_el should be countEl (or a better, more descriptive name, IMHO no need to abbreviate element here.)

In ctor you saved a copy of some properties to abbreviate (I suppose) code elsewhere however, you use it just once. You can drop it altogether.

Reuse

You parse a boolean value twice, it's enough to introduce a more robust function:

const parseBoolean(value) => (/true/i).test(value);

There are a few different techniques to parse a boolean (direct string comparison as you're doing, regex, JSON.parse(), and few more). Just pick one, in this case it's not probably that important. Note: use === instead of ==.

Now that you have a function (which accepts, via conversion, both a boolean and a string) you can write:

toggle() {
    this.el.dataset.toggled = !parseBoolean(this.el.dataset.toggled);
}

In this example I'm storing boolean, add .toString() if appropriate. toggleCount() will then use if (parseBoolean(this.el.dataset.toggled)). You may want to introduce a function const isElementToggled = () => parseBoolean(this.el.dataset.toggled);.

Style & misc

IMHO setClickHandlers() does both too little and too much. Its responsibility is to add a click handler (and it's too little to be a separate function) but it also IS the click handler (and it's too much). Declare a separate function:

handleClick(e) {
    this.postVote();
    this.toggle();
    this.toggleCount();
}

And attach it directly in your ctor:

el.addEventListener("click", this.handleClick.bind(this));

If you're targeting ES6 then do not use (unless there is a strong compelling reason) var, use const and let instead.

The snippet where you create Vote may be simplified, no need to check Array.length if using Array.forEach():

document.addEventListener("turbolinks:load", ()=> {
  document.querySelectorAll('[data-vote]').forEach(x => new Vote(x));
});

If the AJAX call to post a vote fails then you local counter is already incremented and it won't go back. The problem is that you consider these actions as part of the click event handler when they should really be an effect of the sucessfull AJAX call:

axios({ ... }).then((data) => {
    this.toggle();
    this.toggleCount();
});

In this way if the call fails you won't have unsynchronized UI. Alternatively, if call is really slow, you may want to update UI immediately and revert it back if failed:

this.toggle();
this.toggleCount();

axios({ /* ... */ }).then((data) => {
    // ...
}).catch((data) => {
    this.toggle();
    this.toggleCount();
});

In any case the code to attach the event handler in ctor will then simply be:

el.addEventListener("click", this.postVote.bind(this));

I, personally, find that to create a discardable object only because of its side effects is slightly misleading for the reader. In JavaScript you can have nested functions and if you do not need to carry a state then you do not need classes. There is no reason to avoid something like this:

document.addEventListener("turbolinks:load", ()=> {
  document.querySelectorAll('[data-vote]').forEach(attachClickHandler);
});

Where attachClickHandler() is simply:

function attachClickHandler(element) {
    function postVote() { /* ... */ }
    function toggle() { /* ... */ }
    function toggleCount() { /* ... */ }

    el.addEventListener("click", postVote);
}

Code might be even more simple if you had a module for this "Vote Component" but it really really depends on the UI framework/library you're using (if any.)


FizzBuzz in Befunge93 The intro

Yesterday I learned of the existence of Befunge. See my (sort of) related question about a Befunge interpreter in Python. And it made me want to learn the language, and what do programmers do when they learn a new language? They make a FizzBuzz of course!

The following program prints all FizzBuzz's from 1 until 100. I don't think this implementation is the best, since I repeat quite a lot of code and there are many empty fields in my program.

You can check it with an online interpreter:

befunge_online_1 or befunge_online_2

The explanation

Read "!zzuBzziF" to stack
>:#,_ While loop to print stack untill stack is empty
Go down at the end of the line with v
Then it prints a newline ,*52,*84<
+1 Add 1 to top of the stack
: copy top of stack (current fizzbuz number)
*5*2*25 push 100 to stack
go down v and go right >
`| Checks if current fizzbuz number is bigger than 100

if bigger @ end program
if not bigger go down

>:3% copy stack and modulus with 3
Check modulo |

if modulo 3 == 0 print Fizz >"zziF",,,, and add 1 on top of the stack
if not modulo 3 == 0 add 0 to top of the stack

go down v and swap top of stack \ so top op stack is current fizzbuzz number again
%5:< copy stack and modulus with 5
Check modulo |

if modulo 5 == 0 print Buzz ,,,,"Buzz"< swap stack \ and add 1 on top of it
if not modulo 5 == 0 swap stack \ and add 0 on top of it

go down v and go right >
Check if there was a Buzz with |

if there was a Buzz burn top of the stack with $ go to step 18
if there was no Buzz go down

Check if there was a Fizz with |

if there was a Fizz do nothing
if there was no Fizz copy and print the current number :.

go up and ^ and skip following with #
go right > and go up ^ and go to step 4

The code

"!zzuBzziF">:#,_   v
v*2*5*52:+1,*52,*84<
  >@             > ^
>`|   >            v
  >:3%|            0
      >"zziF",,,, 1v
 v\            <   \
 0             |%5:<
 v1\ ,,,,"Buzz"< #
   >$            ^
 > |>            ^
   >|
    >:.          ^

The output

FizzBuzz!
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...
98
Fizz
Buzz

The question

As stated above, I really don't think my implementation is the best, and am curious how other people would solve this problem.

My current doubts about the code:

I repeat code, for example prints. Can they be reworked into functions?
It feels quite large. Can this be condensed?
Readability of the code. Do other people understand the steps I've taken?

I therefore invite you all to burn it down!

Here's mine, done basically without consulting yours.

v    >          0v    >              v >\#v_:.v
0>:3%|           >\:5%|              >:|  >   v
>    >"zziF",,,,1^    >"zzuB",,,,\1+\^ >\"!",$v
 ^+1 _@#-**455: ,*25                          <

My strategy for writing it was just to write the very simplest code possible — the body of the main loop is just

if (i divisible by 3) "Fizz"
if (i divisible by 5) "Buzz"
if (i equals 0) "!"

and then throw a loop around that. So I started by writing just

     >          v   >          v >    v
0>:3%|          >:5%|          >:|    v
>    >"zziF",,,,^   >"zzuB",,,,^ >"!",v
 ^+1 _@#-**455:                       <

But this is missing three pieces: (1) there should be a newline after each line; (2) there should be a :. to print i whenever we don't print Fizz or Buzz; and (3) we need to avoid printing i whenever we did print Fizz or Buzz.

(1) is easy to fix; we just add ,*25 to the "carriage return" code along the bottom of the loop.

(3) is awkward. I made an abortive attempt to squeeze a recomputation of something like ::3%!\5%!+#v_:. (read left-to-right) into the "carriage return" line before realizing that computing logical AND ("i mod 3 AND i mod 5") is awkward in Befunge, and I would have to add a fifth line if I wanted to branch again here with #v_. So it makes sense to do what you did and keep track of whether we've printed "Fizz" or "Buzz" as we print them. This lengthens the loop body by a few characters (most of which are \).

With (3) out of the way, (2) is easy to squeeze into the blank rectangle in the upper right. As a bonus, if we just printed "!", then we know we don't need to test for :.!

As for your code: It's definitely more convoluted than mine! :D  But in Befunge, this is not necessarily a bad thing.

There are some infelicities; for example you use *2*5*52:+1,*52,*84 where I would have used **455:+1,*52 — I don't understand why you bother printing that space character with *84 since it comes at the end of a line. Possibly a vestige of an earlier version of the code?

On the right-hand side you have a # jumping over a 5. If you were trying to be obfuscated, then you could replace this with a codepath that just runs straight through the 5 and then corrects with a $ further up. You have plenty of white space where a $ could fit in.

Rather than always using

 >A
>|
 >B

consider using

  >A
>#^_B

where it saves you a line. In my long-rusted experience, Befunge idiom still values "small number of lines" over "small number of columns" — the language may be 2D but it's still written by line-oriented chauvinists. :)

Can they be reworked into functions? — No. :) Befunge-93 has no concept of the (non-#) GOTO, and as a corollary it has no GOSUB and no RETURN. I can imagine a programming idiom that applies a binary search tree of "line numbers" down the left side of the program and can "GOTO" a line whose number is specified on the stack; but this would be way overengineered for FizzBuzz.

Can this be condensed? — Yes. :)

Do other people understand the steps I've taken? — Yes. It's pretty straightforward. :)


Robust Bubble Sort in VBA I'm creating a robust bubble sort for VBA when sorting stored arrays in VBA. Mostly this would be used when an array is stored in a single cell with a delimiter. Otherwise, one could just sort on the sheet during intake.

I'm trying to make this as robust as I can so it can be used as a tool rather than just continually rewriting it for each task when I need it. It can sort ascending or descending, the intention being that one may be able to use it to get minimums, maximums and medians.

I'd like to make it able to sort alphabetically, but right now it only sorts numbers. I mention this because I'd like to refactor the procedure that turns the variant array (hence the area with extra white space) into the double array, but I can't figure out an optimal way to do that without sending copies of arrays around, so it's just sitting in the TestBubbleSorting procedure right now. Any suggestions on that refactoring would be awesome.

Also, if the bubble sort method isn't the most robust sort algorithm to be using, I'd love to know that so I can try again.

Example input would be something like this

3
7,3,5
15,20,40
300,550,137

Option Explicit
Public Sub TestBubbleSorting()
    Const DELIMITER As String = ","
    Dim targetSheet As Worksheet
    Set targetSheet = ActiveSheet
    Dim numberOfArrays As Long
    numberOfArrays = targetSheet.Cells(1, 1)
    Dim rawArray As Variant
    Dim arrayToSort() As Double
    Dim targetRow As Long
    Dim targetElement As Long
    Dim numberOfElements As Long
    Dim inputValue As String
    Dim outputValue As String

    For targetRow = 2 To numberOfArrays + 1
        inputValue = targetSheet.Cells(targetRow, 1)
        If Replace(inputValue, DELIMITER, vbNullString) = vbNullString Then GoTo NextIteration

        rawArray = GetArrayFromCell(inputValue, DELIMITER)

        numberOfElements = UBound(rawArray) + 1
        ReDim arrayToSort(1 To numberOfElements)
        For targetElement = 0 To numberOfElements - 1
            arrayToSort(targetElement + 1) = CDbl(rawArray(targetElement))
        Next

        BubbleSortNumbers arrayToSort(), True

        For targetElement = 1 To numberOfElements - 1
            outputValue = outputValue & arrayToSort(targetElement) & DELIMITER
        Next
        outputValue = outputValue & arrayToSort(numberOfElements)
        targetSheet.Cells(targetRow, 2) = outputValue
        outputValue = vbNullString
NextIteration:
    Next
End Sub

Private Function GetArrayFromCell(ByVal inputValue As String, ByVal DELIMITER As String) As Variant
    GetArrayFromCell = Split(inputValue, DELIMITER)
End Function

Private Sub BubbleSortNumbers(ByRef arrayToSort() As Double, Optional ByVal sortAscending As Boolean = True)
    Dim temporaryHigher As Double
    Dim temporaryLower As Double
    Dim targetElement As Long
    Dim exchangeMade As Boolean
    If sortAscending Then
        Do
            exchangeMade = False
            For targetElement = 1 To UBound(arrayToSort) - 1
                If arrayToSort(targetElement) > arrayToSort(targetElement + 1) Then
                    exchangeMade = True
                    temporaryHigher = arrayToSort(targetElement)
                    arrayToSort(targetElement) = arrayToSort(targetElement + 1)
                    arrayToSort(targetElement + 1) = temporaryHigher
                End If
            Next targetElement
        Loop While exchangeMade
    Else
         Do
            exchangeMade = False
            For targetElement = UBound(arrayToSort) To 2 Step -1
                If arrayToSort(targetElement) > arrayToSort(targetElement - 1) Then
                    exchangeMade = True
                    temporaryLower = arrayToSort(targetElement)
                    arrayToSort(targetElement) = arrayToSort(targetElement - 1)
                    arrayToSort(targetElement - 1) = temporaryLower
                End If
            Next targetElement
        Loop While exchangeMade
    End If
End Sub

In large I think the sort function is right out of the book of bubblesort.

IMO your naming is a little overdone. The long names are for an inexperienced eye hard to read.

The ascending and descending sort loops are essentially the same except for the direction of the comparation, so no need for backward loop or special temporary variables etc.

The swap mechanism calls for a swap function.

All in all find below a revised version of the sort function.

Private Sub Swap(vector() As Double, i As Long, j As Long)
    Dim tmp As Double
    tmp = vector(i)
    vector(i) = vector(j)
    vector(j) = tmp
End Sub

Private Sub BubbleSortNumbers(vector() As Double, Optional sortAscending As Boolean = True)
    Dim index As Long
    Dim isChanged As Boolean
    Dim first As Long
    Dim last As Long

    first = 1
    last = UBound(vector) - 1

    If sortAscending Then
        Do
            isChanged = False
            For index = first To last
                If vector(index) > vector(index + 1) Then
                    isChanged = True
                    Swap vector, index, index + 1
                End If
            Next index
            last = last - 1 ' The not yet positioned largest value "rabbits" down to its final position for every loop, so there is no need for checking it again.
        Loop While isChanged
    Else
        Do
            isChanged = False
            For index = first To last
                If vector(index) < vector(index + 1) Then
                    isChanged = True
                    Swap vector, index, index + 1
                End If
            Next index
            last = last - 1
        Loop While isChanged
    End If
End Sub

All that said, bubble sort is not the most efficient algorithm, so if you have large data sets to sort I will suggest other more powerfull algorithms like quicksort, mergesort, heapsort or combsort where quicksort and combsort maybe are the easiest to implement (they are all well documented on Wikipedia).


Using Cache::remember for banners and stores I'm using Cache::remember to cache 3 results in my action, 2 in the same call to Cache::remember. It works, but I have 2 questions about how I can join this Cache::remember call:

Could I use two Cache::remembers in the same method?
Could I join these two Cache::remembers (I need change the first param)?
Is it possible load model outer Cache::remember?

public function favoriteStores()
{
    $userId = $this->Auth->user('id');
    $username = $this->Auth->user('username');

    list($fullBanners, $smallBanners,) = Cache::remember(
        'banners', function(){
        $this->loadModel('Banners');
        $fullBanners = $this->Banners->full();
        $smallBanners = $this->Banners->small();
        return [$fullBanners, $smallBanners];
    });

    list($stores, $favoriteStores) = Cache::remember(
        'stores', function(){
        $stores = $this->Stores->myStores($this->Auth->user('id'));
        $favoriteStores = $this->Stores->favoriteStores();
        return [$stores, $favoriteStores];
    });

    $this->set(compact('fullBanners', 'smallBanners', 'userId', 'username',
        'stores', 'favoriteStores'));
}

Could I use two Cache::remembers in the same method?

Of course. Using Cache::remember or not should not affect the decision on whether or not to use Cache::remember again for something else - the decision should be: do I want this data to be cached?

Could I join these two Cache::remembers (I need change the first param)?

You could but it is a bad idea.

Consider this contrived example:

$userId = $this->Auth->user('id');
$everything = Cache::remember('everything.' . $userId, function() use ($userId) {
    $allStuff = $this->Stuff->find('all');
    $myStuff = $this->Stuff->find('all')->where(['user_id' => $userId]);
    return compact('allStuff', 'myStuff');
});
...

And compare to this:

$allStuff = Cache::remember('allStuff', function()) {
    return $this->Stuff->find('all');
});

$userId = $this->Auth->user('id');
$myStuff = Cache::remember('mystuff.' . $userId, function() use ($userId) {
    return $this->Stuff->find('all')->where(['user_id' => $userId]);
});
...

In the first example, the same cache key is used for two purposes; One is to cache getting some data which applies to all users, and the second is to get some data that is one-user specific. There are a number of (potentially dire) consequences do doing that, most obviously:

There is one copy of "allstuff" in the cache store per user
The Cached data which is not user-specific cannot be reused

Attempting to bundle cached data together, unless it actually belongs together (e.g. total number of votes, total number of up votes, total number of down votes) is at best inefficient and at worst results in cache collisions, cache churn or similar.

The right way to manage cached data is atomically and independently; This does not mean it'll never be the case that two cache calls cannot be combined.

Is it possible load model outer Cache::remember

I'm not sure what this question means, code outside a cache call should not assuming the code in a cache call will run and vice versa. Also be aware that using $this inside a cache callback ties the code to the class where the callback is written.

Complete example

It is not clear why there are cache calls around the store information, it was suggested to wrap the banner information in a cache call in a previous question because the full/small banner information would be the same for all requests, for all users.

If the store information in the question should be cached, the user id should be in the cache key and should expect it as a parameter to the Cache::remember.

public function favoriteStores()
{
    $userId = $this->Auth->user('id');
    $username = $this->Auth->user('username');

    list($fullBanners, $smallBanners,) = Cache::remember(
        'banners', function(){
        $this->loadModel('Banners');
        $fullBanners = $this->Banners->full();
        $smallBanners = $this->Banners->small();
        return [$fullBanners, $smallBanners];
    });

    $myStores = Cache::remember(
        'stores.' . $userId, function() use ($userId) {
        $stores = $this->Stores->myStores($userId);
        $favoriteStores = $this->Stores->favoriteStores();
        return [$stores, $favoriteStores];
    });

    $this->set(compact('fullBanners', 'smallBanners', 'userId', 'username',
        'stores', 'favoriteStores'));
}

If favoriteStores is not user-specific it does not belong in that cache call. Without knowing the meaning/intended use of this data I would suggest to remove caching from the stores/favotite stores data:

public function favoriteStores()
{
    $userId = $this->Auth->user('id');
    $username = $this->Auth->user('username');

    list($fullBanners, $smallBanners,) = Cache::remember(
        'banners', function(){
        $this->loadModel('Banners');
        $fullBanners = $this->Banners->full();
        $smallBanners = $this->Banners->small();
        return [$fullBanners, $smallBanners];
    });

    // Don't needlessly cache this data
    $stores = $this->Stores->myStores($userId);
    $favoriteStores = $this->Stores->favoriteStores();

    $this->set(compact('fullBanners', 'smallBanners', 'userId', 'username',
        'stores', 'favoriteStores'));
}

Warning

If in doubt do not cache anything.

This may seem like a contradiction but if you're considering caching data "just because" without any real need or reason that's likely to end badly. Use caching to improve performance and address specific concerns/problems - when it's needed.


The eternal dilemma: bar.foo() or foo(bar)? I was using foo(bar) as it's adopted for functional programming.

console.log(
    join(
        map(function(row){ return row.join(" "); },
            tablify(
                map(function(text){return align(text},
                    view),
                20))),
    "\n");

Now, with dot operator:

view.map(function(text){return align(text)})
    .tablify(20)
    .map(function(row){return row.join(" ");})
    .join("\n")
    .log();

I guess everyone will agree this reads too much better, and the only cost is that you have to modify the native types prototype. So, which?

I think that the first variant can look nice, too, if you change the way you format the code and you always use the function as the last argument:

log(map(tablify(map(view, function(text) {
  return align(text)
}), 20), function(row) {
  return row.join(" ")
}).join("\n"))

Edit: Or if you really like indent:

log(map(tablify(map(view,
                    function(text) { return align(text) }
                ),
                20
        ),
        function(row) { return row.join(" ") }
    ).join("\n")
)


C++ Stack implementation using std::list I have the following 'interface' to the C++ std::list and I was wondering how I could make it go faster. In particular, it needs to be able to evaluate up to two million operations in a matter of a couple seconds. Right now it's at around 8 seconds.

#include <iostream>
#include <list>

int main()
{

    int n, m;
    std::cin >> n >> m;

    std::list<int> myList (n);

    for (int i = 0 ; i < m; i++) {
        std::string op;
        std::cin >> op;
        if (op[1] == 'O') {
            std::cout << myList.back() << '\n';
            myList.pop_back();
        } else {
            int val;
            std::cin >> val;
            myList.push_back(val);
        }
    }

    return 0;
}

It reads input in the form

3 4
PUSH 2
PUSH 3
POP
POP

With expected output

3
2

Where 3 corresponds to highest value, and 4 corresponds to number of operations.

The operations are guaranteed to be safe (no POPing empty stacks), and each value is used at most once (this part in particular I feel I could optimize, but I'm not sure how).

Right now I'm testing with the following Python script:

print "1000000 2000000"

for val in xrange(1,1000001):
    print "PUSH ", val

for _ in xrange(0,1000000):
    print "POP"

And getting this for time:

8.89 real         0.00 user         0.01 sys

I started out using std::stack, but tried switching to std::list in order to give a preset size, so as to not need to reallocate memory. This did not help the time any, but that's where it stands as of now.

C++ std::cin and std::cout are both tied together and and tied to C stdin and C stdout respectively. This causes a lot of performance problems when dealing with std::cin and std::cout.

You can help the situation by using:

std::ios_base::sync_with_stdio(false);   // Disconnect from C IO
std::cin.tie(NULL);                      // Disconnect in from out (otherwise they flush).

If you change the code to use std::fstream (rather than std::cin/std::cout) you can get even better performance.

I did some experiments and reading a line and parsing the line separately improves things even more.

 std::getline(std::cin, line);
 if (line[1] == 'O') {
     // STUFF
 }
 else {
     int  val;
     std::stringstream  linestream(&line[5]);
     linestream >> val;
     // STUFF;
 }

Also you should be using vector rather than list. It has two advantages: 1) You can allocate all the space you need in advance. 2) Spacial locality can make access faster.

Times:

 As written:  real  0m5.119s   user  0m4.751s   sys  0m0.362s
 Use vector:  real  0m4.906s   user  0m4.585s   sys  0m0.325s
 Un Tie:      real  0m4.247s   user  0m4.233s   sys  0m0.017s
 std::getline real  0m1.559s   user  0m1.546s   sys  0m0.017s
 std::fstream real  0m0.804s   user  0m0.766s   sys  0m0.022s

 C Version    real  0m0.434s   user  0m0.422s   sys  0m0.016s


jQuery single page navigation I've created this script and I want to use it for website navigation in my project. As my knowledge of jQuery is quite poor, I'm not sure that code is correct and enough optimized. Could you help me to find out if there are any ways to optimize the code, and indicate mistakes I've made?

$(function () { //scroll to the section, section's id is equal to li href attribute
    $("li a").click(function () {
        var liC = $(this).attr("href");
        var liD = $("#" + liC).offset().top;
        $("html, body").stop().animate({
            scrollTop: liD
        }, 'slow');
        return false;
    });

    $(window).scroll(function () { //on scrolling defines the closets section gets it's id finds li item the href of which is equal to section's id and adds padding to it

        $('.dober').each(function () {
            var hRt = $(this).attr('id');
            if ($(this).offset().top <= $(window).scrollTop()) {

                $('li a').css({ padding: 0 });
                $('a[href=' + hRt + ']').css({
                    padding: 10
                });

            } else {

                 $('a[href=' + hRt + ']').css({
                    padding: 0
                });
            }
        });
    });
});

- Cache your selectors: As a rule of thumb, if you use a selection more than once, you should cache it. What happens when you use $("someElem") is jQuery has to jump into the DOM and look through all elements that would match that selection. So you should really do a search only once, and save your results for future use. This way you can look and play with them whenever you want.  Ex.:

$("a[href=" + hRt + "]").css({
    padding: 10
});

//Should be like this:
var whichLink = $("a[href=" + hRt + "]"); //Saved my search to a variable, which I use later.
whichLink.css({
    padding: 10
});

//...

whichLink.css({
    padding: 0
});

- Save function calls: If you read the jQuery source code you'll see that shortcut methods like .click(), .scroll(), and etc. all reference the .on() method. All they do is basically call the .on() method with some parameters. Well why not just go straight to the meat and potatoes? Check this out:

$("#foo").click(function() {
    //Do your awesomeness
});

//That does the same thing as this:
$("foo").on("click", function() {
    //Do your awesomeness even awesomener.
});

//Or try this:

$(window).on("scroll", function () {
    //Wicked!
});

That just makes the syntax so easy to rememeber as well. If you're going to use jQuery on a regular basis, I recommend that you take some time and read through the source code of the methods you're using. To find them quickly just use CTRL+F and type methodName:. That should jump you straight to what you want to know. This way you can understand what and how you are doing things, and even find better ways to do them on your own. Also if you see something you think should be done better or differently, you know how it works and you can contribute to jQuery.

In your click functions you also might want to prevent the default browser action on a link, which is to direct the page to that link. Since you just want to perform something on your page and don't actually want the browser to leave the page you should prevent that action.
You can do it by passing in e for event and running e.preventDefault();. I see you've used return false; which does that, but if you want to read more on the difference between the two I would suggest [this article by Chris Coyier][1].

-Playing with visible elements: You're if statements from what I can tell are trying to detect scroll position and etc. I highly recommend you check out [this tiny plugin][2]. It basically detects if an element is visible or not at any given time. This may or may not help you out but I just thought I'd throw that out there.

-Performance Wise: Focus on the .scroll() event for now. The way you have it now, the code runs hundreds of times since it is called each time the window scrolls, even if the user isn't done scrolling. That's an increadible ammount of times your code will run for no reason. Not only that but then you run code on each element with the class of .dober - more code that gets run.
Now we don't want to do that since it can really slow down the browser, if not crash it all together. What you'll want to do is wait for when the user stops or is done scrolling, then run the code.

var $window = $(window); //Remember, if you use a selection more than once, you should cache it

$window.on(function() {
    //Here we check if there has been a call already
    //If the check is true that means the code was already called
    //So we cancel any previous calls, this way the code is only called once
    if(this.scrollEnd) clearTimeout(this.scrollEnd);

    //If you've made it here, the code hasn't been called, or the call has been canceled.
    this.scrollEnd = setTimeout(function() {
        $(this).trigger('scrollEnd'); //Call the actual code with a 500ms delay
    }, 500);
});

$window.on('scrollEnd', function() {
//This is a custom event that is triggered after the timeout
//This will only run on the last time the scroll method was called
    $('.dober').each(function () {
        var hRt = $(this).attr('id');
        var paddingAmt = 0; //Here I just slightly optimized your code

        if ($(this).offset().top <= $window.scrollTop()) {
            paddingAmt = 10;
            $('li a').css({ padding: 0 });
        }

        $('a[href=' + hRt + ']').css({
            padding: paddingAmt
        }, function(){ //Callback to set padding back to zero
            paddingAmt = 0;
        });
    });
});

[1]: http://css-tricks.com/return-false-and-prevent-default/
[2]: https://github.com/teamdf/jquery-visible/


Is_permutation() on sequence containers in O(n) complexity - follow-up This question is a continuation of my previous question:

Check is_permutation on a pair of same sized arrays.

I improved the implementation to generalize for all sequence containers. Please let me know how I can improve this implementation again.

#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<array>
#include<list>

template < typename T1 >
std::unordered_map< int, int > count_frequency( T1 first, T1 last )
{
    std::unordered_map< int, int > temp_unordered_map;
    auto temp_unordered_map_end = std::end( temp_unordered_map );
    while( first != last )
    {
        auto it_temp_unordered_map = temp_unordered_map.find( *first );
        if( it_temp_unordered_map == temp_unordered_map_end )
        {
            temp_unordered_map.emplace( *first, 1 );
        }
        else
        {
            ++( it_temp_unordered_map->second );
        }
        ++first;
    }
    return temp_unordered_map;
}

template < typename T1, typename T2 >
bool is_permutation( const T1 first1, const T1 last1, const T2 first2, const T2 last2 )
{
    if( std::distance( first1, last1 ) != std::distance( first2, last2 ) )
    {
        return false;
    }
    std::unordered_map< int, int > first_map = count_frequency( first1, last1 );
    std::unordered_map< int, int > second_map = count_frequency( first2, last2 );

    std::pair<std::unordered_map< int, int >::iterator,std::unordered_map< int, int >::iterator > myPair=
        std::mismatch( std::begin( first_map ), std::end( first_map ), std::begin( second_map ),
        []( std::pair< const int, int >& seed1, std::pair< const int, int > & seed2)
        { return seed1.second == seed2.second; }
        );

    return  myPair.first == first_map.end() && myPair.second == second_map.end();
}

int main()
{
    const std::array< int, 5> array1 { { 1, 3, 2, 4, 5 } };
    const std::array<int,4> array2 { { 1, 2, 4, 3 } };

    if( ::is_permutation( std::begin( array1 ), std::end( array1 ), std::begin( array2 ), std::end( array2 ) ) )
    {
        std::cout<< " Elements are permutation of each other\n";
    }
    else
    {
        std::cout<< " Elements are not permutation of each other\n";
    }

    const std::vector< int > vec1 { { 1, 3, 2, 4 } };
    const std::vector< int > vec2 { { 1, 2, 4, 3 } };

    if( ::is_permutation( std::begin( vec1 ), std::end( vec1 ), std::begin( vec2 ), std::end( vec2 ) ) )
    {
        std::cout<< " Elements are permutation of each other\n";
    }
    else
    {
        std::cout<< " Elements are not permutation of each other\n";
    }

    const std::list< int > list1 { { 1, 3, 2, 4 } };
    const std::list< int > list2 { { 1, 2, 4, 3 } };

    if( ::is_permutation( std::begin( list1 ), std::end( list1 ), std::begin( list2 ), std::end( list2 ) ) )
    {
        std::cout<< " Elements are permutation of each other\n";
    }
    else
    {
        std::cout<< " Elements are not permutation of each other\n";
    }
    return 0;
}

I would initially agree that the complexity of your solution is O(n), though, there are extreme cases where the performance of your count_frequency could be greater - unordered_map.emplace() is 'average case constant time, worst case linear', I don't believe a worst-case situation would happen for you.

Note that you have a very complicated equality-check comparing your two frequency-maps.... you have:

if( std::distance( first1, last1 ) != std::distance( first2, last2 ) )
{
    return false;
}
std::unordered_map< int, int > first_map = count_frequency( first1, last1 );
std::unordered_map< int, int > second_map = count_frequency( first2, last2 );

std::pair<std::unordered_map< int, int >::iterator,std::unordered_map< int, int >::iterator > myPair=
    std::mismatch( std::begin( first_map ), std::end( first_map ), std::begin( second_map ),
    []( std::pair< const int, int >& seed1, std::pair< const int, int > & seed2)
    { return seed1.second == seed2.second; }
    );

return  myPair.first == first_map.end() && myPair.second == second_map.end();

as far as I can tell, the size-check is redundant, and the rest can be simply:

template < typename T1, typename T2 >
bool is_permutation( const T1 first1, const T1 last1, const T2 first2, const T2 last2 )
{
    return count_frequency( first1, last1 ) == count_frequency( first2, last2 );
}

I put your code in this ideone, and the replacement code in this ideone here.


Updating certain values in text file So I need to update some certain values within text file based on actual values there. Any advice on making it more effective or just readable is appreciated.

Example text file:

Lalala
There is tons of text in this file log-12345sr
And somewhere within
There are log file names log-23456sr
Some more text here
I want to edit log file names within Java code
to change the log file names log-34567sr some text here as well
But I want to edit based on current value
For example add 100 to the number in the name
So log-45678sr
becomes log-45778sr
I can safely assume there is no more than one on a single line

My code:

public static void main(String[] args) throws Exception {
    doModification(new File("test.txt"));
}

public static ArrayList<String> findAllOccurrences(File file, String prefix, String suffix) throws IOException {
    ArrayList<String> occurrences = new ArrayList<>();
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while ((line = br.readLine()) != null) {
        if (line.contains(prefix) && line.contains(suffix)) {
            occurrences.add(line.split(prefix)[1].split(suffix)[0]);
        }
    }
    return occurrences;
}

public static HashMap<String,String> buildReplacementMap(ArrayList<String> values, Function<String, String> modification) throws Exception {
    HashMap<String,String> replacementMap = new HashMap<>();
    for(String value: values){
        replacementMap.put(value, modification.apply(value));
    }
    return replacementMap;
}

public static void doModification(File file) throws Exception {
    ArrayList<String> occurrences = findAllOccurrences(file, "log-", "sr");
    HashMap<String, String> replacementMap = buildReplacementMap(occurrences, (value) -> String.valueOf(Long.parseLong(value) - 100));
    String content = new String(Files.readAllBytes(file.toPath()));
    for (Map.Entry<String,String> pair : replacementMap.entrySet()){
        content = content.replaceAll(pair.getKey(), pair.getValue());
    }
    Files.write(file.toPath(),content.getBytes());
}

Text file after modification:

Lalala
There is tons of text in this file log-12445sr
And somewhere within
There are log file names log-23556sr
Some more text here
I want to edit log file names within Java code
to change the log file names log-34667sr some text here as well
But I want to edit based on current value
For example add 100 to the number in the name
So log-45778sr
becomes log-45878sr
I can safely assume there is no more than one on a single line

You could simplify with Regular Expressions:

Pattern pattern = Pattern.compile("log-(\\d+)sr");
Matcher matcher = pattern.matcher(input);
StringBuffer buffer = new StringBuffer();
while(matcher.find()) {
  Long value = Long.parseLong(matcher.group(1), 10);
  Long increased = value + 100;
  matcher.appendReplacement(buffer, increased.toString());
}
System.out.println(buffer.toString());


Task observer implementation I need help cleaning up this piece of code.

if is_complete == true
  #If there are time stamps get between time stamps
  if start_date && end_date
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NOT NULL and DATE(completed_date) between ? and ?", contact_id, start_date, end_date])
  else
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NOT NULL", contact_id])
  end
else
  #If there are time stamps get between time stamps
  if start_date && end_date
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NULL and DATE(completed_date) between ? and ?", contact_id, start_date, end_date])
  else
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NULL", contact_id])
  end
end

you can replace if is_complete == true with if is_complete
the only thing that changes is :conditions, tasks = ... should not be inside the if/else
the 3rd case is invalid: completed_date can't be NULL and within a certain range at the same time
use one conditional for the NOT in completed_date IS (NOT) NULL and one for the and DATE ..., and concatenate the sql string then. Then the nested if/else is gone.
the extra query arguments start_date and end_date depend only on start_date && end_date, so the distinctions should not be in the is_completed conditional.


Summing digits of an alphanumeric string I am going through the Java CodingBat exercises. Here is the one I have just completed:

  Given a string, return the sum of the digits 0-9 that appear in the string, ignoring all other characters. Return 0 if there are no digits in the string.

Here is my code:

public int sumDigits(String str) {

    StringBuilder strAppend = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {
        if (Character.isDigit(str.charAt(i))) {
            strAppend.append(str.charAt(i));
        }
    }

    int total = 0;
    String strDigits = strAppend.toString();

    for (int i = 0; i < strDigits.length(); i++) {
        total += Integer.parseInt(strDigits.substring(i, i+1));
    }

    return total;

}

My questions are:

Should I be using one for loop instead of two?
Is it correct to be converting to StringBuilder to avoid concatenating a string?
Is it right to convert from string to int towards the end of the method, or convert as the digits are found?

Your question is surprising in the sense that you use the somewhat obscure isDigit method (not many people are aware of that one), yet you do not use the similar Character.getNumericValue(...) method.

Using that method, you can remove the second loop (as you suspected). It also answers the second question - there is no need for a StringBuilder, or the int conversion:

int total = 0;
for (char c : str.toCharArray()) {
    if (Character.isDigit(c)) {
        total += Character.getNumericValue(c);
    }
}
return total;


Efficiency of this constantly running time processor for an HTML5 video control bar I built a custom HTML5 video control bar, and for each second, it updates two readings:

Time Elapsed
Time Remaining

in hh:mm:ss notation, like so:

Because of how often this function runs, I want it to be as efficient as possible.

I created this JS Fiddle to test benchmarks. It runs the timer normally, until you un-comment the benchmark and comment the casual running func. The commented function call runs this function 1,000,000 times and logs the speed via the console's timing utility.

I'm looking for best practices, efficiency, and general improvements.

Here's the code. For testing, it's been modified to run in a loop or at a set interval rather than being connected to a video.

/* Video Time Processing Benchmark Snippet */

var timeProgress = $("#time-progress"),
    timeRemaining = $("#time-remaining");

// Set mock video duration for testing
var duration = 5000;

// Convert numbers to double+ digit format (09, 99, 999)
function digitize(n) {
    return n > 9 ? "" + n : "0" + n;
}

// Convert seconds to hh:mm:ss
function secondsToHMS(seconds) {
    var numhours = digitize(Math.floor(((seconds % 31536000) % 86400) / 3600));
    var numminutes = digitize(Math.floor((((seconds % 31536000) % 86400) % 3600) / 60));
    var numseconds = digitize(Math.floor((((seconds % 31536000) % 86400) % 3600) % 60));
    return numhours + ":" + numminutes + ":" + numseconds;
}

// Process the elapsed and remaining times to two hh:mm:ss format
function processTime(currentTime) {
    var value = (100 / duration) * currentTime;
    var progressHMS = secondsToHMS(currentTime);
    var remainingHMS = "-" + secondsToHMS(duration - currentTime);
    timeProgress.html(progressHMS);
    timeRemaining.html(remainingHMS);
}

// Test time via interval or loop
function testTime(type, number) {
    if (type == "interval") {

        // If a number isn't provided, the default is every second (1000)
        if (!number) var number = 1000;
        var i = 0;

        // Set interval to run function
        setInterval(function(){
            currentTime = i;
            processTime(currentTime);
            i++;

            // Clear the interval when duration is reached
            if (i > duration) clearInterval(Int);
        }, number);
    }
    else if (type == "loop"){
        for (var i = 0; i < duration; i++){
            currentTime = i;
            processTime(currentTime);
        }
    }
}

// Use Int to set time for clearInterval() targetng
var Int = testTime("interval");

//Get benchamark on functon, vs optimized versions
/*
console.time("Benchmark");
    testTime("loop", 1000000);
console.timeEnd("Benchmark");
*/

If you're worried about performance, this should raise a red flag:

someJQueryObject = $("#some-id");
...
someJQueryObject.html(aPlainOldString);

.html(foo) is almost certainly slower than .innerHTML = foo, because .html() does a bunch of extra stuff, like checking if it can use innerHTML, trying to use innerHTML, catching errors if that fails and using a fallback, etc. Also, using innerHTML is probably slower than simply creating a Text node and updating its data property.

I'd suggest replacing timeProgress = $("#time-progress") with something like this:

var timeProgress = document.createTextNode('');

document.getElementById('time-progress').appendChild(timeProgress);

And replacing timeProgress.html(progressHMS); with this:

timeProgress.data = progressHMS;

This will be a significant performance improvement and will also eliminate the jQuery dependency. Using a large GP library like jQuery to select two elements and update their text content seems like overkill anyway.

Here's a jsPerf demonstrating the performance difference.


Merge sort in Clojure I made my own version of merge sort:

    (defn rsort[a]
      (cond
        (<= (count a) 1) a
        :else
          (let [half    (/ (count a) 2)
                [lh rh] (split-at half a)]
            (loop [res () slh (rsort lh) srh (rsort rh)]
              (cond
                (empty? slh) (into srh res)
                (empty? srh) (into slh res)
                :else
                  (if (< (first slh) (first srh))
                    (recur (cons (first slh) res) (rest slh) srh)
                    (recur (cons (first srh) res) slh (rest srh))))))))

Any suggestion how improve this code?

I tested with a couple of input values and for the most part, it seem
fine.  Note however, that the standard sort also works with
e.g. [1 nil] (with output [nil 1]) whereas this code breaks with an
exception during the comparison.

Code looks fine with a few minor issues:

The name should be merge-sort; rsort is not meaningful.
The values (first slh) and (first srh) are written down twice; the
compiler might optimise that away, but IMO it would be nicer to have a
separate let for them.
Emacs' clojure-mode indents the :else branch differently, dunno
about that.

Some suggestions:

Support the same signature as the standard sort.
Add a docstring explaining the function.
Add tests, possibly with randomised input as well.


Predicate testing for equality that returns the common element I'm going to try brute-forcing the solving of a Magic Square. To simplify the code later on, I wanted a function similar to =, but one that returns the common element if all the elements are equal and nil otherwise. This is unlike = which always returns either true or false. I'm calling it =? for lack of a better name.

Example:

(=? 1 2 1)
nil ; nil because they're not all the same

(=? 1 1 1)
1 ; Returns the common element of 1

Obviously, this function won't work well when nil may be the sole element in a collection, since it will return falsey even if all the elements are the same, but nil.

I thought that there must be some kind of core operation I could use here, but after a few minutes of thinking, I couldn't think of any. I ended up rolling my own function using loop. I'd like general advice on the function that I wrote, or potentially a more idiomatic way to write it that I'm missing. It looks exceedingly clunky to me; especially after I realized the need for the last-arg accumulator. A recursive solution would be nice, as I fear I'm missing something obvious here:

(defn =?
  "Checks if every supplied argument =s every other.
  Returns the common element if they're all the same, nil otherwise."
  [& args]
  (loop [[f-arg & r-args] (rest args)
         last-arg (first args)]
    (cond
      (nil? f-arg) last-arg
      (= f-arg last-arg) (recur r-args f-arg)
      :else nil)))

Soon after I posted this, I went for a walk and realized that this is the perfect opportunity to use reduce. I'm kind of embarrassed that I didn't see it originally, but this was my train of thought that lead me to what I'm much happier with.

First, I tried a simple reduction. This was pretty simple, although still a little verbose:

(defn =?2 [& args]
  (reduce (fn [acc n]
              (if (= n acc)
                n
                (reduced nil)))
          (first args)
          (rest args)))

I decided that this was probably simple enough to use a function macro for. Normally I don't like using them for reductions, but there's not much going on here:

(defn =?3 [& args]
  (reduce #(if (= % %2) % (reduced nil))
          (first args)
          (rest args)))

I don't like using explicit calls to first and rest, as I find they're usually neater when they're implicit in a deconstruction. I decided to deconstruct the arguments instead:

(defn =?4 [& [arg & rest-args]]
  (reduce #(if (= % %2) % (reduced nil))
          arg
          rest-args))

Then I checked what = uses, and found that it just uses multiple argument lists, so I tried that. This strikes me as the more idiomatic solution:

(defn =?5
  ([] nil)
  ([arg] arg)
  ([arg & args]
   (reduce #(if (= % %2) % (reduced nil))
           arg
           args)))

I'm torn between 4 and 5, but I think that both are a significant improvement.


Trait accessing variables of classes using it I just tried PHP Traits for the first time, to keep my code DRY :

<?php
namespace Acme\DemoBundle\Model;

trait CheckPermissionTrait
{
    protected function checkPermission($object_id)
    {
        $judge = $this->container->get('acme_judge');

        $user  = $this->container->get('security.context')->getToken()->getUser();

        if( !$judge->isPermitted($user, $object_id) ) {
            throw $this->createAccessDeniedException("Brabbel");
        }
    }
}

-

<?php
namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Acme\DemoBundle\Model\CheckPermissionTrait;

class SomeController extends Controller
{
    use CheckPermissionTrait;

    public function someAction(Request $request, $object_id)
    {
        $this->checkPermission($object_id);

        //do other stuff
    }
}

What making me a little nervous, is that the trait is accessing the container of the class using it, which means there is actually the requirement that the class using the trait needs to extend the Controller (Symfony\Bundle\FrameworkBundle\Controller\Controller) for the trait to work.

Is this normal when using traits or is it bad practice?

Though you now have seen the light, and know not to use traits in this way, I'm going ahead and post my review here anyway. I'll be updating it along the way, seeing as this is something I can rant on about for some time.
Your trait suffers from a couple of (severe) issues:

It constitutes both a breach of contract, and enforces a bad contract.
Traits requiring properties are like using global in a class
It's not a valid use-case for a trait. At all.
Its namespace is wrong

Now these are just the first things I could think of, each of which are problematic enough to ditch the trait as you rightfully did.
Allow me to explain, though, what these one-liners mean:
Breach of Contract + enforcing a bad one:
Classes define a contract. That's a given. If you pass an instance of class X to a function, you make a deal with that function. You're essentially saying "This object has this specific job, and you can call these methods on it, and/or access these properties". When you extend a class, it's important to respect the contract. You can add things, but never change the promises made by the base class.
If the base class' constructor, for example, expects 1 argument of the type array (enforced through type-hinting), then all of its children should either use the same constructor or, if they choose to override it, define a constructor that takes 1 array argument. They are allowed to loose the type-hint, but may not change it. They're free to add optional arguments, but can't force additional arguments to be passed to the constructor:
abstract class Base
{
    public function __construct(array $param)
    {}
}
class ValidChild extends Base
{}
class AnotherChild extends Base
{
    public function __construct(array $param, $opt = null)
    {}
}
class IffyButTheoreticallyFine extends Base
{
    public function __construct($param, array $opt = null)
    {}
}

These are all valid child classes, however: these are not. They are evil, but sadly commonplace:
class Bastard extends Base
{
    public function __construct()
    {
    }
}
class Ungrateful extends Base
{
    public function __construct(array $param = null)
    {}
}
class EvilTwin extends Base
{
    public function __construct(stdClass $param)
    {
        parent::__construct( (array) $param);
    }
}
class Psychopath extends Base
{
    public function __construct(PDO $db, array $parent = null)
    {
        if (!$parent) {
            $parent = [1, 2, 3];
        }
        parent::__construct($parent);
    }
}

Now, how does this apply to your case? Simple: A trait is a tool to reduce code-duplication. It's a nugget of often-needed functionality that a class (a contract) includes/uses to do its job. For a class to use a trait, the trait has no right to define that class' contract. A trait's relation to its user is, in some way, the same as that of a child's towards its parent: it's the child that inherits the contract, not the parent. Therefore, it must follow that any class, regardless of its job, has to be able to use a trait, without having to change its own contract and dependencies.
Your trait, then is not a valid use-case: all of its users are required, by definition, to add a $this->container property to its dependencies, which will of course have an impact on that class' contract and the contract of its children.
A new global in drag
I think it's safe to say that it's universally accepted that a class definition containing global $someVar is a tell-tale sign of bad code. A class is scoped, its methods are scoped and neither of them should rely on the global scope to function. The same applies to a trait: because it can be used in a variety of classes, a trait must be context (and scope) agnostic. If it requires a property to be present, the trait must define it. If that property has to be of a particular type, the only thing you could do is define a property, and enforce an abstract setter for it, which imposes type restrictions. However, this is unreliable, given that multiple traits can be used, it might cause conflicts with the user and the class itself has direct access to the property, too. Lastly: this approach brings us back to square one: a trait like this is no longer a trait.
This implies that a trait cannot have dependencies. If a trait has a dependency, it ceases to be a trait: it's either an abstract class, or an Interface, but definitely not a trait. There is, however a tiny sliver of grey-area here:
Whilst it's not my idea of best practice, one might argue that it's acceptable to write a trait, to be used in tandem with an Interface, for example: a single Interface that ensures data models are traversable, like the IteratorAggregate interface. In that case, a trait like this could perhaps be acceptable.
trait IteratorAggregateTrait
{
    public function getIterator()
    {
        if (!$this instanceof IteratorAggregate) {
            throw new \LogicException(
                sprintf(
                    '%s must implement IteratorAggregate to use %s',
                     get_class($this),
                     __TRAIT__
                )
            );
        }
        return new ArrayIterator($this);
    }
}

Valid use-case
For reasons I've explained above, it's clear that your example isn't something best handled with traits. It might be useful at this point to serve up a small, 100% valid example of a trait. Suppose you've got some models that represent either a DB record, user input (form data), or something else entirely. All of these models contain user information, including an email address. A model with setters is ideal to ensure that, whenever some data is gathered, that data is then validated (ie filter_var($email, FILTER_VALIDATE_EMAIL)). Because these classes represent different things (db record or form), they're likely to inherit from an abstract class already. Rather than duplicating the email setter, a trait can be used:
trait UserDataTrait
{
    public $email = null;
    public function setEmail($email)
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('bad email');
        }
        $this->email = $email;
        return $this;
    }
}

Wrong namespace
Just a little nit-pick: I don't like the fact that your trait is defined in the Model namespace, while it's pretty clear that it can't be used anywhere else but in the controller.

Update
Time for an update. While I stand (firmly) by what I've stated previously (traits not being in a position to impose a contract), there are certainly people who will argue that they can. Not in the least because PHP's trait construct enables you to declare abstract methods:
trait Evil
{
    protected $dependency = null;
    public function someMethod()
    {
        return $this->dependency->getValue();
    }
    abstract public function setDependency(SomeType $dep);
}

This trait, then, imposes a partial contract on its user: the class that uses the trait must define the setDependency method. So what's the problem, you might say? The problem is simple: traits were introduced to solve supposed problems that might require multiple inheritance, hence a class can use more than one trait, and it's possible for the class to resolve conflicts regarding method names by itself. So let's assume the trait above is being used, and you have a couple more traits lying around, one of which looks like this:
trait Pure
{
    public $dependency = null;
    public function setDependency(Container $container)
    {
        $this->dependency = $container;
        return $this;
    }
}

Now, imagine you have a class that uses both these traits (assume Evil::setDependency is not declared abstract here):
class FromHell
{
    use Pure, Evil {
        Pure::setDependency insteadof Evil;
    }
}

Congrats, the contract imposed by the trait is broken, along with its functionality, simply because the class has chosen to adhere to the contract imposed by Pure. It doesn't take a rocket scientist to realize that traits, whilst they can, in theory, impose a minimal contract, are not as potent at ensuring the contract is adhered to.
Now this was a simple example, but if you want a more plausible scenario: Assume 2 traits, A and B, both define a method logError, A::logError writes to a default log file, B is more generic, and expects you to pass a resource as an argument, or writes to stderr by default.
Because your project is rather large, you're dealing with multiple levels of inheritance and at some point, some classes end up implementing both traits. Of course, depending on what class it is, either A::logError is given a higher precedence, or B:logError. The latter is more likely to be used in workers/crons/backend code.
It's very likely that your project, seeing as you're relying on traits so much, contains code that looks like this:
$traits = class_uses($object);
if (isset($traits['A']))
{
    $object->logError('The error string');
}

Now if this object has chosen to override A::logError with B::logError, you'll probably waste a lot of time trying to work out why on earth logError doesn't write your error messages to the default log. In short:
Trait contracts are weak suggestions, and can be overridden easily
Back to the definition of abstract methods in a trait: I'll have to test it a bit more, but AFAIK, that's just bad design. Either an abstract class contains your abstract methods (because a class enforces a strong contract), or you implement the method in the class from the get-go. A trait is supposed to reduce code duplication, whereas an abstract method requires you to re-write the method's signature and implementation whenever you use the trait. If that's what you want, why bother using a trait in the first place?
The other issue I have with this is one I'll look into a bit more when I find the time, but classes can be composed out of 1 or more traits, and contain no other definitions of their own. That's fine, but what if we look at our 2 traits above (Pure and Evil). Is Pure::setDependency a valid implementation of the abstract Evil::setDependency method? If so, will that trait method be regarded as an implementation of the abstract method? If not, traits containing abstracts can't be used in classes that contain no definitions of their own, and therefore, such traits are special cases (because their usage is limited).
If Pure::setDependency is a valid implementation of the abstract method in Evil (Container being an alias of SomeType, or its parent class), and traits can be used to implement abstract trait methods, then another issue presents itself: maintenance HELL: Changing either one of these traits could break your code, depending on how, and where the traits are being used. You'll end up having to test all classes using both traits, whenever you change just one trait. When you look at it like that, I'd say some code duplication is the lesser of two evils.


Generic Template implementation of merge sort in C++ A few month ago I wrote several basic sort algorithm for educational purposes as generic as possible in C++. In a few days time I want to present some of that stuff in my class but before that I thought I show my implementation to you and listen to your comments of what do you find confusing or very readable.

Mergesort

template <typename I>
    void merge(I first, I mid, I last) {
        while (first != mid && mid != last) {
            auto iter = mid;
            first = std::upper_bound(first, mid, *mid);
            mid = std::upper_bound(mid, last, *first);
            std::rotate(first, iter, mid);
        }
    }

What did I do here? Very simple; I want to avoid to allocate any new memory actively myself and try to write readable algorithm with as few loops as possible.

Obviously, I could not use the 'standard' way implementing merge not very readable. I also needed an in-place looking variant. So I started at looking what I actually do if I try to merge something in itself, what mergesort does in the end.

According to the STL documentation, std::upper_bound does the following:

  Returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found.
  The range [first, last) must be at least partially ordered, i.e. partitioned with respect to the expression !(value < element) or !comp(value, element). A fully-sorted range meets this criterion.
  The first version uses operator< to compare the elements, the second version uses the given comparison function comp.

I call this function twice, first to receive an Iterator of the first part of my array which is greater than the Item in the middle and then for my middle part which is greater than the Item behind my first Iterator of my array. Then I rotate those two "newly build" ranges.

According to the documentation, std::rotate does the following:

  Performs a left rotation on a range of elements.
   Specifically, std::rotate swaps the elements in the range [first, last) in such a way that the element n_first becomes the first element of the new range and n_first - 1 becomes the last element.
   A precondition of this function is that [first, n_first) and [n_first, last) are valid ranges.

template< class ForwardIt >
void rotate( ForwardIt first, ForwardIt n_first, ForwardIt last );

The precondition is always fulfilled because our ranges are within the array we want to merge stuff. This will be repeated as long first is not mid and mid is not equal to last, otherwise we merged our ranges.

What follows is simply the the algo for merge sort using the above implementation of merge:

template <typename I>
    void mergesort(I first, I last) {
        auto&& size = std::distance(first, last);
        if (size < 2) {
            return;
        }

        auto&& mid = first + size / 2 + size % 2;

        mergesort(first, mid);
        mergesort(mid, last);
        merge(first, mid, last);
    }

Well, it's a bit curious to indent after template<...>, but at least you are consistent there.

In merge() I would mark the only variable const.

In mergesort() I would make both variables const auto. There's no reason to make them references.

And I would change the initialization of mid so mutable forward-iterators are good enough. In addition, you only really need to refer to size once, though I expect any half-way useable compiler to optimize it appropriately.

const auto mid = std::next(first, (size + 1) / 2);

Be aware that if you have random-access-iterators and first / mid are generally only moved a relatively small amount in merge each iteration, std::find_if (O(n)) would beat std::upper_boud (O(log(n))). Not that it matters, your in-place-merge will be quadratic in that case anyway.


Page auto refresh on update I've written a simple script to refresh the page when the page has been updated.

How it works:

The Javascript polls a PHP script and sends it the current URL and the current version, the PHP script then queries MySQL which returns the true version of the page.

Here is the PHP

if (isset($_GET['URL']) && isset($_GET['CurrentVersion'])) {

$URL = mysqli_real_escape_string($DBConnection, $_GET['URL']);
$CurrentVersion = mysqli_real_escape_string($DBConnection, $_GET['CurrentVersion']);

$Query = "SELECT ID, URL, CurrentVersion FROM PageUpdates WHERE URL = '$URL'";
$Query = $DBConnection->query($Query);

if ($Query->num_rows == 1) {
    $Row = $Query->fetch_assoc();
    if ($Row['CurrentVersion'] > $CurrentVersion) {
        echo "TRUE";
    } else {
        echo "FALSE";
    }
} else {
    echo "FALSE";
}
}

and here is the Javascript

CheckForUpdate();
function CheckForUpdate() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        if (this.responseText == "TRUE") {
            document.location.reload(true);
        } else {
            setTimeout(function() { CheckForUpdate() }, 50000);
        }
        console.log(this.responseText);
    }
};
xhttp.open("GET", "/IsPageUpdated.php?URL="+ window.location+"&CurrentVersion="+CurrentWebpageVersion, true);
xhttp.send();
}

CurrentWebpageVersion is defined in a script in the HTML so I can set it with PHP.

JAVASCRIPT

Calling function before defining it

Invoking CheckForUpdate() before actually defining it, while perfectly valid in JavaScript, is generally a bad practice and it makes code harder to follow. It can also cause troubles in some rare cases.

Style

Function names should follow camelCase convention.
Use strict equality / identity operator (===) instead of regular equality operator (==). That way no type conversion will be performed and following this practice, you are less likely to hurt yourself in the future.
Spaces around +.

onreadystatechange property

Use addEventListener() with readystatechange argument instead. That way you could define multiple listeners of that type if necessary.

setTimeout() function

Firstly, escaping CheckForUpdate() into anonymous function to pass it as an argument to setTimeout() is unnecessary. This

setTimeout(function() { CheckForUpdate() }, 50000);

could be simply written as

setTimeout(CheckForUpdate, 50000);

Lastly, instead of setting timeout at every function call, you could call setInterval() once, outside the function.

Encode

Use encodeURI() function to encode whatever you pass as URL parameters.

Approach of constant querying the server

Constantly querying the server to know whether update is necessary or not, is rather far from the best possible thing to do. It would be way better to be able to get the message directly from the server, once it is necessary. This is where WebSockets come in handy. After linked MDN (emphasis mine):

  WebSockets is an advanced technology that makes it possible to open an
  interactive communication session between the user's browser and a
  server. With this API, you can send messages to a server and receive
  event-driven responses without having to poll the server for a reply.

Respond with JSON (ᴀʀɢᴜᴀʙʟᴇ)

If you responded with {"update": true} instead of TRUE, you could use it later as if (JSON.parse(this.responseText).update) instead of if (this.responseText == "TRUE"). That way you could access values of response as properties of an object in the future. If this doesn't seem necessary, it may be an overkill, though.

Rewrite

After applying all the above suggestions (and more), the code could look like this:

function onUpdateStateChange() {
  if (this.readyState === 4 && this.status === 200) {
    if (JSON.parse(this.responseText).update) {
      return document.location.reload(true);
    }
    console.log(this.responseText);
  }
}

function checkForUpdate() {
  var request = new XMLHttpRequest(),
      address = '/IsPageUpdated.php?URL=' + window.location + '&CurrentVersion=' + CurrentWebpageVersion;

  request.open('GET', encodeURI(address), true);
  request.addEventListener('readystatechange', onUpdateStateChange);
  request.send();
}

setInterval(checkForUpdate, 50000);

PHP

Potential SQL injection

$URL = mysqli_real_escape_string($DBConnection, $_GET['URL']);
$Query = "SELECT ID, URL, CurrentVersion FROM PageUpdates WHERE URL = '$URL'";

Well, mysqli_real_escape_string() is not the preferred method of passing variables to SQL statements. You could hurt yourself, e.g. if you didn't explicitly defined character set to the right one. Use prepared statements and mysqli_prepare() instead.

Style

You have a few style problems, i.a. indentation and naming issues.


Red Black Tree Implementation I would like some feedback on my red black tree implementation. Anything is fine. I've debugged this and it seems to be working fine, however I may have missed something.

Basically, this is a red black tree that stores character strings as keys and the passage that contains those strings as values. Since these keys are able to be repeated, they form a linked list as well.

    TNODE *tree_add(TNODE *root, const KEY k, const VALUE v) {
        LNODE *lnode = NULL;
        if (root == NULL) {
                TNODE *node = talloc(k);
                lnode = lalloc(v);
                node->head = lnode;
                node->tail = lnode;
                node->is_red = true;
                return node;
        }
        if (strcmp(k, root->key) < 0) {
                root->left = tree_add(root->left, k, v);
        } else if (strcmp(k, root->key) > 0) {
                root->right = tree_add(root->right, k, v);
        } else {
                if (strcmp(k, root->key) == 0) {
                        lnode = lalloc(v);
                        root->tail->next = lnode;
                        root->tail = lnode;
                        root->tail->next = NULL;
                }
        }
        if (is_red(root->right) && !is_red(root->left)) {
                root = rotate_left(root);
        }
        if (is_red(root->left) && is_red(root->left->left)) {
                root = rotate_right(root);
        }
        if (is_red(root->left) && is_red(root->right)) {
                flip_colors(root);
        }
        return root;

}

Here are TNODE and LNODE:

    // LNODE is the data structure for a singly linked list.
typedef struct lnode {
  VALUE val;          // A pointer to the value stored in the linked list.
  struct lnode *next; // Pointer to the next item in the list; it should be NULL if there is no successor.
} LNODE;

typedef struct tnode {
  KEY key;             // Search key for this binary search tree node.
  struct tnode *right; // Right child.
  struct tnode *left;  // Left child.

  LNODE *head; // Head of the linked list storing the values for the search key.
  LNODE *tail; // Tail of the linked list storing the values for the search key.

  bool is_red; // Flag use only in red-black trees to denote redness.
} TNODE;

Here are some more functions: TALLOC, LALLOC, and rotate

    TNODE *talloc(const KEY k) {
        TNODE *tnode = malloc(sizeof(TNODE));
        if (tnode == NULL) {
                return NULL;
        }
        tnode->key = k;
        tnode->is_red = false;
        tnode->head = NULL;
        tnode->tail = NULL;
        tnode->right = NULL;
        tnode->left = NULL;
        return tnode;
}

LNODE *lalloc(const VALUE v) {
        LNODE *lnode = malloc(sizeof(LNODE));
        if (lnode == NULL) {
                return NULL;
        }
        lnode->val = v;
        lnode->next = NULL;
        return lnode;
}

TNODE *rotate_left(TNODE *h) {
        TNODE *x = h->right;
        h->right = x->left;
        x->left = h;
        x->is_red = h->is_red;
        h->is_red = true;
        return x;

}

TNODE *rotate_right(TNODE *h) {
        TNODE *x = h->left;
        h->left = x->right;
        x->right = h;
        x->is_red = h->is_red;
        h->is_red = true;
        return x;
}

void flip_colors(TNODE *h) {
        h->is_red = true;
        h->left->is_red = false;
        h->right->is_red = false;
}

This isn't quite a full review, but here goes anyway:

It looks like you're using 8-space indents. That's quite a lot. I think 4 is more common, but it is a matter of preference and it is consistent, so it's definitely not wrong
You have KEY, presumably a typedef of char*, but then you call strcmp on it. If you want it to be general across key types (which is a pretty good idea IMO), you should pass in a comparator function that takes two keys as arguments.
I'm going to assume that the other fields of TNODE exist for some reason, but is there a chance you could move them out to rbtree_t and leave TNODE smaller?
I don't know the naming conventions for types in C, so don't take this as implicit agreement or disagreement
talloc and lalloc probably don't need to be their own functions; malloc(sizeof(TNODE)) is probably sufficient