Posting data to endpoints Here's the code I am trying to refactor. The same Http client is being used in each nested try with resource. I don't understand the rationale behind nesting client.execute() calls.
The code tries to Post data to an endpoint if resource is missing and retries to Post to a backup endpoint if earlier call fails
public void makeSeveralApiCalls() throws Exception {
  try (final CloseableHttpClient client = HttpClients.createDefault()) {
    try (final CloseableHttpResponse response = client.execute(httpGetUri())){
      if (response.getStatusLine().getStatusCode() == 404) {
        // Resource not found, Post data to Microservice A
        try (final CloseableHttpResponse nestedResponse = client.execute(httpPostToMicroserviceA())) {
          if (resp.getStatusLine().getStatusCode() == 201) {
            LOGGER.info("Success");
          } else {
            // Microservice A could not consume data, log error response
            final String responseString = EntityUtils.toString(resp.getEntity());
            LOGGER.debug("Error response: " + responseString);
            // Try to Post to Microservice B
            try (final CloseableHttpResponse subResponse = client.execute(httpPostToMicroserviceB())) {
              if (resp.getStatusLine().getStatusCode() == 201) {
                LOGGER.info("Success");
              } else {
                // Is this exception propagated to the caller?
                throw new RuntimeException("Very bad unrecoverable state");
              }
          }
       }
    }
  }
}

Is this a valid way to call multiple executes on the same HTTP client in a nested fashion. Is it better to separate out each client.execute() call?

First of all you should split up this method into smaller ones. The inline comment give you a perfect sign what should be extracted.
Also *try with resource" can handle more than one resource in a single statement.
public void makeSeveralApiCalls() throws Exception {
  try (final CloseableHttpClient client = HttpClients.createDefault();
       final CloseableHttpResponse response = client.execute(httpGetUri());
      ){
      if (response.getStatusLine().getStatusCode() == 404) {
        // Resource not found
        postDataToMicroserviceA(client, response);
       }
    }
}

private void postDataToMicroserviceA(CloseableHttpClient client, CloseableHttpResponse response){
  try (final CloseableHttpResponse nestedResponse = client.execute(httpPostToMicroserviceA())) {
          if (resp.getStatusLine().getStatusCode() == 201) {
            LOGGER.info("Success");
          } else {
            // Microservice A could not consume data,
            logErrorResponse(client, response);
          }
  }
}

private void logErrorResponse(CloseableHttpClient client, CloseableHttpResponse response)
            final String responseString = EntityUtils.toString(resp.getEntity());
            LOGGER.debug("Error response: " + responseString);
            // Try to Post to Microservice B
            try (final CloseableHttpResponse subResponse = client.execute(httpPostToMicroserviceB())) {
              if (resp.getStatusLine().getStatusCode() == 201) {
                LOGGER.info("Success");
              } else {
                // Is this exception propagated to the caller?
                throw new RuntimeException("Very bad unrecoverable state");
              }
}

Of cause this could be optimized a bit more if you find a more generalized solution to merge postDataToMicroserviceA() and logErrorResponse(), since basically they do the same...


Further optimization of file transfer over FIFO on linux? For learning purposes I'm writing a very simple mqueue based file transfer server. Below is a thread function that takes care of an incoming request:

static void * handle_client_request(const char *request_string) {
    char request_pathname[_part_delim_alloc_size],
         request_fifo_name[_part_delim_alloc_size];

    bool parse_ret = parse_mqueue_request_string(request_string, (char *[]) {request_pathname, request_fifo_name});
    if(!parse_ret) {
        fprintf(stderr, PROGNAME ": error parsing mqueue request string: %s\n", request_string);
        free(request_string);
        return NULL;
    }

    fprintf(stdout, PROGNAME ": received new request: (%s, %s) -- handling\n", request_pathname, request_fifo_name);

    // open requested file for reading
    int file_fd = open(request_pathname, O_RDONLY);
    if(file_fd == -1) {
        perror(PROGNAME ": error opening requsted file");
        free(request_string);
        return NULL;
    }

    // construct full FIFO path
    char full_fifo_path[strlen(FIFO_STORAGE_PATH) + strlen(request_fifo_name) + 1];
    strcpy(full_fifo_path, FIFO_STORAGE_PATH);
    strncat(full_fifo_path, request_fifo_name, 11);

    // open FIFO for writing only -- this may block until client also opens the FIFO
    int fifo_fd = open(full_fifo_path, O_WRONLY);
    if(fifo_fd == -1) {
        perror(PROGNAME ": failed opening FIFO for writing");
        close(file_fd);
        free(request_string);
        return NULL;
    }

    void *buf = malloc(DEFAULT_BUFSIZE); // 128 KiB, 2^17 bytes
    if(!buf) {
        perror(PROGNAME ": failed allocating buffer");
        close(file_fd);
        close(fifo_fd);
        free(request_string);
        return NULL;
    }

    size_t bread;
    while((bread = read(file_fd, buf, DEFAULT_BUFSIZE)) > 0) {
        // read call complete, "bread" bytes are now in "buf"
        ssize_t bwritten = write(fifo_fd, buf, bread);

        if(bwritten == -1) {
            // failed writing the batch of bytes received
            fprintf(stderr, PROGNAME ": failed writing to FIFO - request aborted (%s): %s\n", full_fifo_path, strerror(errno));
            free(buf);
            free(request_string);
            close(file_fd);
            close(fifo_fd);
            return NULL;
        }

        /* fprintf(stdout, PROGNAME ": read %lu bytes of data and wrote %ld bytes of data\n", bread, bwritten); */
    }

    fprintf(stdout, PROGNAME ": done processing request (%s, %s) last bread: %lu\n", request_pathname, request_fifo_name, bread);

    close(file_fd);
    close(fifo_fd);
    free(buf);

    return NULL;
}

Its purpose is to transfer a local file (that the client requests) over a FIFO that the client connects to.

The size of the buffer for read(2) and write(2) I've decided on is 128KiB. Increasing it doesn't seem to have an positive effect on performance.

I am wondering - are there any trivial (or not so trivial) optimizations I could apply to this function to gain an ever so slight increase in performance?

Const

I consider

const char *request_string

and

free(request_string);

to be in conflict. If the contract for this function is that it is responsible for freeing the string it was given, it should not be const. Conversely, if you really think it should be const, shift responsibility of freeing it onto the caller.

Stack allocation

In C terms, support for dynamic stack allocation of the kind seen in

char full_fifo_path[strlen(FIFO_STORAGE_PATH) + strlen(request_fifo_name) + 1];

is relatively new. If I were you I would be concerned that a hostile caller could pass a huge string in request_string, which parses into a huge request_fifo_name and blows the stack. As long as you take care to free the memory yourself through the various return paths in this function, I would consider malloc safer.


Java Calculator with GUI I've wrote a calculator in Java with a GUI using swing.
Here are the classes:

Control.java:

public class Control {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        Gui gui = new Gui(calculator);
        gui.setVisible(true);
        boolean exit = false;
        while(!exit) {

        }
    }
}

Gui.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Gui extends JFrame {
    Calculator calculator;
    public Gui(Calculator calculator) {
        this.calculator = calculator;
        //The frame
        setSize(400, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        //Panel for Text-output
        JPanel textPanel = new JPanel();
        textPanel.setPreferredSize(new Dimension(400,70));
        JTextField textfield = new JTextField("");
        textfield.setPreferredSize(new Dimension(380,70));
        textfield.setHorizontalAlignment(JTextField.RIGHT);
        textPanel.add(textfield);
        add(textPanel, BorderLayout.NORTH);

        //Panel for buttons
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new java.awt.GridLayout(4, 5));
        buttonPanel.setPreferredSize(new Dimension(380, 280));

        //Buttons
        String[] buttonText = {
            "7", "8", "9", "+", "<-", "4", "5", "6", "-", "(", "1", "2", "3",
            "*", ")", "0", ",", "C", "/", "="
        };
        JButton button[] = new JButton[20];
        for(int i = 0; i < 20; i++) {
            button[i] = new JButton(buttonText[i]);
            button[i].addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    for(int i = 0; i < 20; i++) {

                        if(event.getSource() == button[i]) {

                            //Delete last character button
                            if(i == 4) {
                                String text = textfield.getText().toString();
                                text = text.substring(0, text.length()-1);
                                textfield.setText(text);
                            }

                            //Delete all button
                            else if(i == 17) {
                                textfield.setText("");
                            }

                            //"="-button
                            else if(i == 19) {
                                String text = textfield.getText().toString();
                                String output = "";
                                try {
                                    output = calculator.calculate(text);
                                }
                                catch (Exception ex) {

                                }
                                textfield.setText(output);
                            }

                            //other buttons
                            else {
                                String text = button[i].getText().toString();
                                String fieldText = textfield.getText().toString();
                                textfield.setText(fieldText + text);
                            }

                        }
                    }
                }
            });
            buttonPanel.add(button[i]);
        }

        add(buttonPanel, BorderLayout.SOUTH);
    }
}

Calculator.java:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class Calculator {
    public String calculate(String text) throws Exception {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
        Object sol = scriptEngine.eval(text);
        String solution = sol + "";
        return solution;
    }
}

What do you think about it? Do you have any suggestions on improving the code?

Control.java

I don't like this name as it's not specific. I'd suggest 'CalculatorApp' instead.

You don't need the inifinite loop. The application will already continue until the user closes the program.

// you can remove all of this:
boolean exit = false;
while(!exit) {
}

Calculator.java

If you didn't write the program, would you know what Calculator.calculate(String) does? The naming is very ambiguous and the code itself looks very complicated (thankfully the heavy complicated, heavy lifting is done by an external library). You should add a javadoc to both the class & method at the very least.

You could have done this entire assignment without JavaScript. You may have gotten more learning out of it if you didn't use ScriptEngine. To me it seems hacky. I do give you bonus points for cleverness, though.

Gui.java

You have 2 unused imports (Level & Logger)

Avoid using wildcards (.*) in your imports. It clutters the local namespace and It makes it harder to tell which libraries are doing what. It will also cause a compiler error when there are two classes with the same name.

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

If you're using an IDE you should see a warning about your class not having a serialversionUID. You can allow your IDE to auto-generate one for you:

private static final long serialVersionUID = 1L;

Avoid magic numbers & magic strings Your class would be easier to maintain & read if you used static variables declared at the top. E.G:

private static final int WIDTH = 400;
private static final int HEIGHT = 400;
...
//The frame
setSize(WIDTH, HEIGHT);

No need to count the number of values in an array yourself, instead use array.length. This will make maintenance easier as you don't have to re-count the values every time:

JButton button[] = new JButton[buttonText.length];
for(int i = 0; i < buttonText.length; i++) {

Alternatively use a 'for-each' loop since you don't need the index.

'17' should definitely be a variable here, as it's currently unreadable. Same goes for your other magic strings/variables:

else if(i == 17) {

This is probably one of, if not the worst thing you can possibly do. You may not think it matters now but trust me, this is a really bad habit and the best way to use good practices is to never learn the bad ones.  Please use a throws declaration if you don't want to handle errors:

catch (Exception ex) {
}


Correct use of procs in Ruby I wrote a Ruby gem to analyse strings for word length, word density, and a few more hand methods...

The Counter class accepts a filter (String). The class will remove any words from the original string that you include in the filter. Spec:

  it "removes words passed in the filter" do
    counter = Counter.new("That was magnificent, Trevor.", filter: "magnificent")
    expect(counter.words).to eq(%w[That was Trevor])
  end

I added a feature that allows you to send in a Regexp filter instead of a string. It's my first use of Procs, and I'm sure it can be done better. It's not very readable, and probably not efficient.

  it "it accepts a regexp filter" do
    counter = Counter.new("That was magnificent, Trevor.", filter: /magnificent/i)
    expect(counter.words).to eq(%w[That was Trevor])
  end

def initialize(string, options = {})
  @options = options
  @char_count = string.length
  # Here I split the wrongs from the string, then call reject to
  # remove any words that meet the filter criteria
  @words = string.scan(regex).reject { |word| filter.call(word) }
  # ...
end

# The filter method checks to see if the filter is a string or a Regexp
# It returns a proc object that acts according.
def filter
  filters = @options[:filter]
  if filters.is_a?(String)
    f = filters.split.collect { |word| word.downcase }
    Proc.new { |w| f.include?(w.downcase) }
  elsif filters.is_a?(Regexp)
    Proc.new { |w| w =~ filters }
  else
    Proc.new {}
  end
end

As you can see, it looks a bit messy compared to the original methods:

def initialize(string, options = {})
  @options = options
  @char_count = string.length
  @words = string.scan(regex).reject { |word| filter.include? word.downcase }
  # snip...
end

def filter
  if filters = @options[:filter]
    filters.split.collect { |word| word.downcase }
  else
    []
  end
end

For the sake of brevity I have not included the enter class, but you can see it here (65 lines). And here is a gist of my proposed changes. Only the initialise and filter methods change.

Moving a decision into code that gets executed earlier, with later code merely telling an object to "do whatever it is we decided earlier" is one of the techniques of confident programming.  It's often a good idea, and I think it is well applied here.

Is there a better name for the filter option?

There may be a more descriptive name for the option than "filter."  The trouble is that "filter" might be interpreted as "here are the things I want", instead of "here are the things I don't want."

A less ambiguous name for this option might be "except," "reject", or "exclude".  You get the idea.

Similarly, you might consider renaming the instance method @filter.

Set proc in constructor

Uri is correct that it is better, if you are going to do this, to create the proc just once.  He does so using lazy evaluation.  You might also consider just setting it in #initialize:

def initialize(string, options = {})
  @filter = filter_proc(options[:filter])
  ...
end

# Your filter method, renamed, and made to take an argument
def exclude_proc(filter)
  if filter.is_a?(String)
  ...
end

Use type coercion methods

Rather than testing the option's class, consider testing whether the object responds to a coercion method that converts it to that class.  So, instead of:

if filter.is_a?(String)
  # the code that converts a string to a proc

you would do this:

if filter.respond_to?(:to_str)
  filter = filter.to_str
  # the code that converts a string to a proc

String responds to #to_str, so filters of those types will continue to work fine.  But now the caller can pass in, as well as a String, any object that responds to #to_str.

By the way: We use #to_str instead of #to_s because #to_s will convert pretty much anything to a string.  #to_str only converts to a string objects which wish to be treated like strings.

You can use the same idea for regular expressions, but you cannot do it the same way.  The convention is that an object that responds to #to_regexp can be treated as a Regexp, but for some strange reason Regexp does not respond to #to_regexp.  Instead, you have to use Regexp.try_convert:

elsif Regexp.try_convert(filters)
  filters = Regexp.try_convert(filters)
  Proc.new { |w| w =~ filters }

If given a Regexp, .try_convert will return it.  If given an object that responds to #to_regexp, .try_convert will return the result of that method.  Otherwise, it returns nil.

Consider allowing procs

It's trivial to allow the caller to pass in a callable object, such as a method:

counter = Counter.new("That was magnificent, Trevor.",
                      filter: method(:exclude_word?))

or a lambda:

counter = Counter.new("That was magnificent, Trevor.",
                      filter: ->(word) { foo(word) || bar(word) })

In the code that makes the proc:

...
elsif filter.respond_to?(:to_proc)
  filter.to_proc
...

By allowing this, you give the caller the ability to make decisions that don't fit comfortably in a list of words or a regular expression.

Consider allowing arrays

Once you've made method filter take an argument, you can use a bit of recursion to allow it to take arrays of filters:

def filter_proc(filter)
  if filter.respond_to?(:to_a)
    filter_procs = Array(filter).map(&method(:filter_proc))
    Proc.new do |w|
      filter_procs.any? { |p| p.call(w) }
    end
  ...
end

Interestingly, nil responds to #to_a with an empty array.  That works out fine, because the the result of #any? on an empty array is false.

The caller may now pass in an array of words:

Counter.new("That was magnificent, Trevor.",
            filter: ["That", "was"])

An array of regular expressions sill also work:

Counter.new("That was magnificent, Trevor.",
            filter: [/That/, /was/])

Also, since Enumerable responds to #to_a, the possibilities are endless.  This makes the API flexible enough that the caller can do anything needed, but still rational enough to understand and reason about.  Best of all, it's done pretty simply.

Catch incorrect filter types

If the caller passes in a filter type that the code does not understand, it acts as though there is no filter.  Consider raising an exception instead:

def filter_proc(filter)
  if ...
  ...
  else
    raise ArgumentError, "Incorrect filter type"
  end
end

Use require_relative for spec_helper

In the spec, consider using require_relative to load the spec_helper:

require_relative '../spec_helper'

This will allow the spec to be run no matter what the current directory is.

Consider using lambdas instead of procs

Everything you are doing here with procs can be done with lambdas, and more concisely.  For example, this:

Proc.new { |w| w =~ filter }

could be expressed as:

lambda { |w| w =~ filter }

or, using the "stabby" operator:

->(w) { w =~ filter }


Longest common subsequence solution I've seen this today on a mock interview and wanted to give it a try. I'd love to hear some feedback from you guys. This is my second attempt at the problem, initially I had a mess of if/else towers and nested loops.

/*
 * Write a function that takes two strings s1 and s2 and returns the
 * longest common subsequences of s1 and s2.
 *
 * Examples:
 * s1: ABAZDC s2: BACBAD  result: ABAD
 * s1: AGGTAB s2: GXTXAYB result: GTAB
 * s1: aaaa   s2: aa      result: aa
 * s1: aaaa   s2: ''      result: ''
 */
public class LongestSubsequence {

  public static void main(String[] args) {
    LongestSubsequence ls = new LongestSubsequence();

    assertEquals("ABAD", ls.solve("ABAZDC", "BACBAD"));
    assertEquals("GTAB", ls.solve("AGGTAB", "GXTXAYB"));
    assertEquals("aa", ls.solve("aaaa", "aa"));
    assertEquals("", ls.solve("aaaa", ""));
    assertEquals("ABAD", ls.solve("BACBAD", "ABAZDC"));
    assertEquals("aaaa", ls.solve("bcaaaa", "aaaabc"));
    assertEquals("aaaa", ls.solve("bcaaaade", "deaaaabc"));
  }

  private String solve(String s1, String s2) {
    if (s1.length() == 0 || s2.length() == 0) {
      return "";
    }

    String subSeq1 = getLongestSubsequence(s1, s2);
    String subSeq2 = getLongestSubsequence(s2, s1);
    return (subSeq1.length() >= subSeq2.length() ? subSeq1 : subSeq2);
  }

  private String getLongestSubsequence(String first, String second) {
    String retValue = "";
    int currentIndex = 0;
    for (int remaining = first.length(); retValue.length() < remaining; remaining--) {
      StringBuilder firstWorker = new StringBuilder(first.substring(currentIndex));
      StringBuilder secondWorker = new StringBuilder(second);
      StringBuilder possibleSequence = new StringBuilder();
      while (firstWorker.length() > 0 && secondWorker.length() > 0) {
        String ch = firstWorker.substring(0, 1);
        int firstIndex = secondWorker.indexOf(ch);
        if (firstIndex != -1) {
          possibleSequence.append(ch);
          secondWorker.delete(0, firstIndex + 1);
        }
        firstWorker.delete(0, 1);
      }
      if (possibleSequence.length() > retValue.length()) {
        retValue = possibleSequence.toString();
      }
      currentIndex++;
    }

    return retValue;
  }

}

Bug
Your program fails on this test:
ls.solve("abddc", "acddb");

Your program finds "ab" and "ac" as the longest subsequences, but the actual answer should be "add".
The problem is that your algorithm is greedy, and it will always use any match, even if the match skips over a part that would produce a better answer.  In my test case, the b in the first string matches the b at the end of the second string, thereby  skipping over the dd in the middle.


Primitive ArrayList Implementation I have implemented a primitive ArrayList class in C++ as part of an attempt to learn about data structures and their optimizations. It currently has:

Constructor/destructor
Overloaded [] operator
bool insert()
bool remove()
short LinearSearch()
short BinarySearch()

insert and remove return a bool indicating success or failure. insert can accept a negative number to insert from the end towards the front (-2 is the 2nd to last element); by default, insert is called with index = 1. The search functions return a short indicating the index, or -1 if it is not found.

It uses templates to allow for multiple types of data stored, but I am currently only concerned with number and boolean data types to be stored. If you have any tips or optimizations regarding the current functions, or operators/other functions that I should consider, please tell me. Thank you for your help.

Code:

#include <cstdlib> // for calloc/malloc

namespace structures {
    template<typename T> class ArrayList {
        private:
            T* pointer;
        public:
            ArrayList(unsigned short len = 10);
            ~ArrayList();
            T& operator[](unsigned short index);
            const T& operator[](unsigned short index) const;
            unsigned short length;
            bool insert(const T& element, short index = -1);
            bool remove(unsigned short index);
            short LinearSearch(const T& element) const;
            short BinarySearch(const T& element) const;
    };

    template<typename T> ArrayList<T>::ArrayList(unsigned short len) {
        length = 0;
        pointer = (T*)calloc(len, sizeof(T));
    }

    template<typename T> ArrayList<T>::~ArrayList() {
        free(pointer);
    }

    template<typename T> T& ArrayList<T>::operator[](const unsigned short index) {
        if (index > length) throw;
        return pointer[index];
    }

    template<typename T> const T& ArrayList<T>::operator[] (const unsigned short index) const {
        if (index > length || index < 0) throw;
        return pointer[index];
    }

    template<typename T> bool ArrayList<T>::insert(const T& element, short index) {
        if (index > (short)length) return false;
        if (index < 0) index = length + index + 1;
        if (length == sizeof(*pointer)/sizeof(T)) {
            pointer = (T*)realloc(pointer, 2 * sizeof(*pointer)/sizeof(T));
        }
        if (index == length || index == -1) pointer[index] = element;
        else {
            for (short i = length; i > index; --i) {
                pointer[i] = pointer[i-1];
            }
            pointer[index] = element;
        }
        ++length;
        return true;
    }

    template<typename T> short ArrayList<T>::LinearSearch(const T& element) const {
        for (short i = 0; i < length; ++i) {
            if (pointer[i] == element) return i;
        }
        return -1;
    }

    template<typename T> short ArrayList<T>::BinarySearch(const T& element) const{
        short left = 0;
        short right = length - 1;
        short middle = (length - 1) / 2;
        while (true) {
            if (left > right) return -1;
            if (element == pointer[middle]) return middle;
            if (element > pointer[middle]) left = middle + 1;
            else right = middle - 1;
            middle = (left + right) / 2;
        }
    }

    template<typename T> bool ArrayList<T>::remove(unsigned short index) {
        if (index > length || index < 0) return false;
        for (; index < length; ++index) {
            pointer[index] = pointer[index + 1];
        }
        --length;
        return true;
    };
}

pointer = (T*)calloc(len, sizeof(T));

Say what?  I’m used to getting people to stop using “naked new”, but this is C memory management!  Why would you do that?  You are not initialing any of the T objects you allocated room for.  That may work for ints and other primitive types, but in general you are looking at a boom when you subsequently access an element.

unsigned short

Why use this for the size type?  At the very least, abstract it as a member type, normally called size_type.  The usual default type for this is std::size_t but there is a movement to switch to signed types for new containers.

   if (index > length) throw;

Throw what?  This will crash since throw by itself is only allowed when there is a current exception being handled.

Your insert and remove take (signed) shorts, which conflicts with your use of unsigned for indexes.  Besides not being able to represent all the values, you will have problems comparing them, which is exactly what you do in the first line.

To provide for the negative number indexing feature, either use the same approach as Eric Neibler (end - 5 rather than -5) or use the signed type for your length, as suggested earlier.

Your insert is re-allocating memory, which is not what I’m expecting.  You are implementing a vector class, not an array class (which is fixed length).  So why?  What’s wrong with std::vector?

LinearSearch, BinarySearch:  Don’t write these members.  Instead, allow std::find etc. (as well as all other algorithms) to work with your container.

You re-allocate upon inserting, but not when deleting.  But you don’t keep track of how much slack space you have.


Is my use of CSS inheritance clean enough for these sprites? I have a set of links with background images on this CodePen.

I am seeking feedback to see if I did this the most optimal way. For example, I made a sprite so that I can just load one image. And I leveraged inheritance so that I did not have to assign every containing div a class. Just used a child selector and for the individual buttons, I used :nth-of-type to pass the background image.

Tell me your thoughts if this could use improvement.

HTML

      Dentist

      Patient

      Lab

CSS

.introSelect { text-align:center; }
.introSelect div {
  display:inline-block;
  position: relative;
  text-align: center;
  background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/bruxzir-user-sprites_1.png') no-repeat;
  width: 90px;
  height: 90px;
}
.introSelect div:nth-of-type(1) {
  background-position: 0 -180px ;
}
.introSelect div:nth-of-type(2) {
  background-position: -90px -180px;
}
.introSelect div:nth-of-type(3) {
  background-position: -180px -180px;
}

.introSelect a {
  display:block;
  text-decoration: none;
}
.introSelect span {
  background-color: rgba(152, 216, 242, 0.7);
  color: #444;
  font-weight: bold;
  letter-spacing: 1px;
  position: absolute; bottom: 0; left: 0; right: 0;
}

There hasn't been a good reason to use extra elements such as spans for purposes of hiding text in the last 10 years.  If you need to support very old browsers, negative indentation is the simplest method.  Otherwise, there's plenty of clean, modern techniques to choose from.

.foo {
    text-indent: -100em;
}

http://nicolasgallagher.com/css-image-replacement-with-pseudo-elements/
http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/

There's not really a good reason to use nth-child here.  You'd be better off using self-documenting class names.  If the order of the images need to be adjusted, then you don't have to make modifications in multiple places (markup and CSS).

.introSelect .dentist {
  background-position: 0 -180px ;
}
.introSelect .patient {
  background-position: -90px -180px;
}
.introSelect .lab {
  background-position: -180px -180px;
}


Find if items in a list of list matches to another list We have two lists:

l=["a","b","c"]
s=[["a","b","c"],
["a","d","c"],
["a-B1","b","c"],
["a","e","c"],
["a_2","c"],
["a","d-2"],
["a-3","b","c-1-1","d"]]
print l
print s

Now, I am try to see if each 2nd-level list of s has fuzzy match to any of items in list l:

matches=list()
matchlist2=list()
print s2
for i in range(len(s)):
    matches.append([])
    for j in range(len(s[i])):

        for x in l:
            if s[i][j].find(x)>=0:
                print s[i][j]
                matches[i].append(True)

                break
        else:
            matches[i].append(False)

    matchlist2.append(all(x for x in matches[i]))
print matches
print matchlist2

This gives me what was intended. But I am not happy with how it has so many loops. I am also working with pandas and if there is pandas solution that will be great to. In pandas, there are just two columns of two dataframes.

[[True, True, True], [True, False, True], [True, True, True], [True, False, True], [True, True], [True, False], [True, True, True, False]]

[True, False, True, False, True, False, False]

Extract this into functions

You are doing one well defined thing (finding fuzzy matches), so this should be at least one function, but I suggest more because you are returning two results.

Write automatic tests

Re-factoring is very hard without tests, re-running and checking the input manually is very time consuming, an automatic test runs in milliseconds.

Use the list comprehensions and zip

You are basically checking the single-dimensional list (xs) against each row of the two-dimensional list (matrix) and seeing which elements are contained and which are not. This can be expressed very easily in code.

def fuzzy_matches(xs, matrix):
    """
    >>> list(fuzzy_matches(["a","b","c"], [["a", "b43", "x"], ["w", "b", "5cfg"]]))
    [[True, True, False], [False, True, True]]
    """
    return ([i in j for i, j in zip(xs, line)] for line in matrix)


Consecutive whitespace reduction I pursued an according algorithm with an absolute best performance, the following class embodies the solution.

Any comment is welcome.

class TextCompressor
{
    private const char Seperator = '\x20';

    private StringBuilder builder;

    public TextCompressor()
    {
        this.builder = new StringBuilder();
    }

    public string Compress(string str)
    {
        int offset = 0;
        int end = str.Length - 1;

        for (int i = 0; i < end; i++)
        {
            if (Char.IsWhiteSpace(str[i]))
            {
                if (i != offset)
                {
                    if (str[i] == Seperator)
                    {
                        if (!Char.IsWhiteSpace(str[i + 1]))
                        {
                            i++;

                            continue;
                        }

                        builder.Append(str, offset, (i - offset) + 1);
                    }
                    else
                    {
                        builder.Append(str, offset, i - offset);
                        builder.Append(Seperator);
                    }
                }

                offset = i + 1;
            }
        }

        if (offset != 0)
        {
            builder.Append(str, offset, str.Length - offset);

            return Char.IsWhiteSpace(str[end]) ? Release().TrimEnd() : Release();
        }

        return Trim(str);
    }

    private static string Trim(string s)
    {
        return (s.Length != 0 && (Char.IsWhiteSpace(s[0]) || Char.IsWhiteSpace(s[s.Length - 1]))) ? s.Trim() : s;
    }

    private string Release()
    {
        string s = builder.ToString();

        builder.Length = 0;

        return s;
    }
}

Compress vs. Regex.Replace

.. using \s{2,}

String: "   The   quick    brown     fox      jumps       over        the         lazy          dog.   "

1.97017 * (10 times faster)
19.333874

String: "The quick brown fox jumps over the lazy dog."

0.485821 * (16 times faster)
8.049062

The good stuff

Your code looks neat and is pretty fast.

Remarks

I would second that the name Separator isn't chosen well and would like to suggest SpaceChar which is more obvious.

Review

The biggest problem I see is the missing null check for the parameter of the public method Compress. Throwing an ArgumentNullException instead of getting a NullReferenceException is better.

The Trim(string s) method doesn't buy you much. Saving some Ticks this way is a optimization which comes with less readable code. Just a call to string.Trim() is sufficient.

Initializing the StringBuilder like @Shelby115 suggested in his answer won't save you a lot but it is a good habit to do so. If you know how big the buffer of the StringBuilder can increase you should use that knowledge. With the default constructor the StringBuilder's internal buffer has a size of 16 which is doubled each time it is reached.

Instead of having this method in the TextCompressor class which implies that it compresses some text I would suggest making this an extension method.

I would like to suggest using a char [] instead of a StringBuilder and change the arrow code to something like this:

public static class StringExtensions
{
    public static string ReplaceMultipleWhiteSpaceWithSpace(this string str)
    {
        return str.ReplaceMultipleWhiteSpaceWithSeparator('\x20');
    }

    public static string ReplaceMultipleWhiteSpaceWithSeparator(this string str, char separator)
    {
        if (str == null) { throw new ArgumentNullException(str); }
        if (str.Length == 0) { return str; }

        int end = str.Length;
        int destinationOffset = 0;
        bool foundWhiteSpace = true;
        char current = separator;
        char[] destination = new char[end];

        for (int i = 0; i < end; i++)
        {
            if (Char.IsWhiteSpace(str[i]))
            {
                if (foundWhiteSpace) { continue; }

                foundWhiteSpace = true;
                current = separator;
            }
            else
            {
                foundWhiteSpace = false;
                current = str[i];
            }
            destination[destinationOffset] = current;
            destinationOffset++;
        }

        int newSize = foundWhiteSpace
            ? IndexOfLastNonWhithSpaceChar(destination, destinationOffset)
            : destinationOffset;

        Array.Resize(ref destination, newSize);

        return new string(destination);

    }
    private static int IndexOfLastNonWhithSpaceChar(char[] values, int startIndex)
    {
        if (startIndex >= values.Length) { startIndex = values.Length - 1; }
        for (int i = startIndex; i >= 0; i--)
        {
            if (!Char.IsWhiteSpace(values[i]) && values[i]!='\0')
            {
                return i +1;
            }
        }
        return startIndex;
    }
}

Some numbers

You mentioned in your question that you have measured the performance and provided some numbers, which are unfortunately missing a unit. I couldn't compare them to my numbers so I just measured your method and my method.

For both scenarios each benchmarked method first does a warm-up phase for 5000 ms and then it is called 10000 times and returns the average of StopWatch.ElapsedTicks which is then converted to milliseconds.

Passed in a string with Length of 7368 containing 4124 white space characters.

Yours: 0,0289723431498079 ms
Mine: 0,0308240396927017 ms
Other: 0,110759507042254 ms
Passed in a string with Length of 1591488 containing 890784 white space characters.

Yours: 6,70626021126761 ms
Mine: 7,66718351472471 ms
Other: 42,3948242637644 ms

So, what is Other? It is only taking 42 ms for the second scenario which is IMO fast enough for such a task. It's very simple:

string.Join(" ", str.Split().Where(s => s.Length > 0));


JSON Schema Validation helper method This is what I wrote to validate JSON to the given schema.

public void validateJsonSchema(ObjectNode jsonSchema, ObjectNode json) throws InvalidRequestException {

    String errorMessage = null;

    if (json != null) {

        if(jsonSchema == null) {
            errorMessage = "json exist in request but there is no schema to validate it against";
        }
        else {
            try {
                JsonSchema jsonSchema = JsonSchemaFactory.byDefault().getJsonSchema(jsonSchema);
                ProcessingReport processingReport = jsonSchema.validate(json);

                if (!processingReport.isSuccess()) {

                    StringBuilder sb = new StringBuilder();
                    processingReport.forEach(jsonError -> sb.append(String.format("[%s] ", jsonError)));

                    errorMessage = String.format("json validation failed. Errors: %s", sb.toString());
                }

            } catch (ProcessingException e) {
                errorMessage = String.format("json validation threw ProcessingException. Error Message: %s", e.getMessage());
            }
        }
    }

    if (errorMessage != null) {
        throw new InvalidRequestException(errorMessage);
    }

}

Here are few things that I had in my mind while writing this code:

I don't want to return anything from the method. Schema is either valid or invalid. In case of invalid, I just throw an exception. Since it's part of a Helper class, I think it's okay to put some business logic (throwing exception) with in this code.
I like 1 point of return or 1 point of exception throwing. Thats why I am using errorMessage to capture any error and if it exists, throw it at the end. By this approach, the code readability is much better.
The jsonSchema and json both are optional. In case if json doesn't exist, there is no point of getting into validation.

Contrary to Julien Rousé and you, I'm rather against the "1 point of return" policy. It doesn't make it more readable. It might make it a bit easier to formally prove correctness of the code, but I have never seen someone do that outside of an academic context.

As it is now, when looking at what would happen if the json == null you'd first encounter the if(json != null) line. Then you scroll down 20 or more lines to find the end of that if block finding that there's no else block. But the method doesn't end here yet. There's another if (message != null) line where I forgot if I had encountered any initialisation in the meantime so I have to go over the entire method again to see if it is null or not ...

Compare that with a method that starts with:

public void validateJsonSchema(ObjectNode jsonSchema, ObjectNode json) throws InvalidRequestException {
    if (json == null) {
        return;
    }

By writing in this "return as early as possible" style, you immediatly see that empty json objects are always valid. If at some point it's clear what the result of the method should be, then I want that to be clear explicitly at that point. I don't want to tire myself constantly looking up and down the method to see if I didn't miss anything (for example: was this message really still null when we got here?).

That's why I would prefer to structure the method like this:

public void validateJsonSchema(ObjectNode jsonSchema, ObjectNode json) throws InvalidRequestException {
    if (json == null) {
        return;
    }

    if(jsonSchema == null) {
        throw new InvalidRequestException("json exist in request but there is no schema to validate it against");
    }

    try {
        JsonSchema jsonSchema = JsonSchemaFactory.byDefault().getJsonSchema(jsonSchema);
        ProcessingReport processingReport = jsonSchema.validate(json);

        if (!processingReport.isSuccess()) {

            StringBuilder sb = new StringBuilder();
            processingReport.forEach(jsonError -> sb.append(String.format("[%s] ", jsonError)));

            throw new InvalidRequestException(String.format("json validation failed. Errors: %s", sb.toString()));
        }

    } catch (ProcessingException e) {
        throw new InvalidRequestException(String.format("json validation threw ProcessingException. Error Message: %s", e.getMessage()));
    }
}

I'd say this is more readable and especially easier to find out what the result is of the special cases. Not that I had any trouble reading/understanding your code ofcourse. I just prefer the way that takes a little bit less effort to understand completely.


Cache of shared observables (Rx) So the idea is to maintain a cache of shared Observables - accessible by a key - which if not present will produce one using the given factory.

The underlying shared Observable is accessed via an Observable created on each invocation of get - this is in order to be able to maintain ownership of the shared Observable and enforce when and how subscribe/unsubscribe is called on it.

When a subscriber is subscribed to an external Observable, then it looks up or created the underlying Observable, and subscribes to it.

When a subscriber is unsubscribed, if there are no more subscriptions on the underlying Observable, then it is removed from the cache.

If the underlying shared Observable terminates, then it is removed from the cache. I believe doOnTerminate is called before the onComplete/onError methods of subscribers, meaning that it will not be possible to subscribe to an Observable which has just terminated, and receive nothing in response.

It's written in Kotlin, but if need be I can port to Java.

I'd appreciate validation that what I've said above is true, and any edge cases I may have missed. Additionally, if there are any suggestions for making this non-blocking, without the chance of duplicating Observables for the same key, or having unmanaged references, then I'd be keen to listen.

package streams

import rx.Observable
import rx.observers.Subscribers.from
import rx.subscriptions.Subscriptions
import java.util.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock

/**
 * Shares a number of underlying observables
 * Unsubscribes from and removes the source observable from the cache if there are no binding subscriptions to it,
 * or if the source observable terminates
 */
class SharedObservableCache<K, T>(private val factory: (K) -> Observable<T>) {

    private val sharedObservables = HashMap<K, Observable<T>>()
    private val lock = ReentrantLock()

    operator fun get(key: K): Observable<T> {
        return Observable.create<T>(
                { subscriber ->

                    val bindingSubscriber = from(subscriber)
                    lock.withLock {
                        getSharedObservable(key).subscribe(bindingSubscriber)
                    }

                    subscriber.add(Subscriptions.create(
                            {
                                lock.withLock {
                                    bindingSubscriber.unsubscribe()
                                }
                            }))
                })
    }

    private fun getSharedObservable(key: K): Observable<T> {
        return sharedObservables.getOrPut(key,
                {
                    factory.invoke(key)
                            // Occurs before calls to onComplete/onError to subscribers
                            // Removed at this point so as not to allow a subscriber to subscribe to a terminating observable
                            .doOnTerminate { lock.withLock { sharedObservables.remove(key) } }
                            // Locked by unsubscription of binding subscriber
                            .doOnUnsubscribe { sharedObservables.remove(key) }
                            .share()
                })
    }
}

For your methods that only return a single expression, I would use the single expression syntax operator fun get(key: K) = Observable.create<T> (same for getSharedObservable). If you want to still have keep the explicit return type, you can do that, too.

For methods that take a lambda as the last parameter, the style guide recommend to put the lambda outside of the parans. I also would format it to have the first curly brace on the same line, resulting in

operator fun get(key: K) = Observable.create<T> { subscriber ->

    val bindingSubscriber = from(subscriber)
    lock.withLock {
        getSharedObservable(key).subscribe(bindingSubscriber)
    }

    subscriber.add(Subscriptions.create {
        lock.withLock {
            bindingSubscriber.unsubscribe()
        }
    })
}

same for getSharedObservable


Handling request errors in snap with haskell I'm currently taking a look at Snap with Haskell. I'm pretty new to Haskell and functional programming in general and am working out the best way to handle errors. Currently I have something like this

createReport :: Handler b Api ()
createReport = do
report <- readRequestBody 65536
modifyResponse $ setHeader "Content-Type" "application/json"
case (decode report :: Maybe Report) of
  Just x -> do
    execute "INSERT INTO \"Reports\" (name) VALUES (?)" [name x]
    -- Do some other stuff and return a response
  Nothing -> badRequest

badRequest :: Handler b Api()
badRequest = do
 modifyResponse . setResponseCode $ 400
 writeLBS "Bad Request"

I'm really wondering if this is the best way to go about errors or is there a better way to handle errors, specifically within Snap. Also any other comments you may have would be great.

Full code here https://github.com/elliotstokes/report-generator

What's "bad" about the request?

Giving a generic failure response isn't terribly useful to the poor soul who has to deal with handling the errors when interfacing with your API.  Why did it fail?  You're only catching the case where the response either is or isn't valid JSON, but what about other kinds of failure?

One thing you might want to look at is Digestive Functors, if you haven't already.  You can use it to do some of your error handling (eg. the value for FieldB is out of the specified range, etc.).  There's a Digestive Functors Aeson library that will let you send your JSON result through the form.  I don't do much with passing around JSON data myself, so this might be a bit more than you need.

The database can fail, too

You've only handled the case where decoding your JSON request can fail, not the database portion.  When it comes to the database, there are 4 basic outcomes to a query:

Success: Results
Success: No results
Failure: Constraint Violations (errors caused by the user)
Failure: SQL errors (errors caused by the developer)

So for queries that can fail (any time you run an insert/update/delete query), you'll want to make sure you're catching the Constraint Violations.  PostgreSQL Simple has a convenient function in Database.PostgreSQL.Simple.Errors (catchViolation) specifically for that (though if you're using the PostgreSQL Simple snaplet rather than using PostgreSQL Simple directly, you'll have to roll your own because the type signatures are incompatible).

Snap Extras might be right for you

There's another package called snap-extras that contains useful functions like reading the response as JSON or responding with JSON.  I know some people aren't too fond of it since it has a lot of dependencies, but I tend to use some of the other modules in it, so it's convenient for me.

If not, you can easily copy/paste just the parts you need into your own project.


Check if all objects have the property value of all other objects I have a list of objects. These objects have a processname, amount and a date. I need every object to have all dates (if it doesnt exist add a new one with amount 0). So if I have 2 processnames: 'Inflate' and 'Deflate' and they have different dates: 'Inflate':12-01-2017 and 'Deflate': 13-01-2017. I need them to have the other object's dates.

I have the following code but it feels devious:

        HashSet<Date> dates = new HashSet<>();
        HashSet<String> processes = new HashSet<>();

        //Get all the unique values from the objects. processAmounts is the list of objects
        for (ProcessAmount processAmount : processAmounts) {
            dates.add(processAmount.getDate());
            processes.add(processAmount.getProcessName());
        }

        //Loop through processnames
        for (String s : processes) {
            //Loop through all the unique dates
            for(Date date : dates) {
                //loop through the objects we have and check if the date exists.
                boolean dateFound = false;
                for(ProcessAmount processAmount : processAmounts) {
                    if(processAmount.getProcessName() != null && processAmount.getProcessName().equals(s)) {
                        if(processAmount.getDate().equals(date)) {
                            dateFound = true;
                        }
                    }
                }

                //If the date is not found add a new object with amount 0
                if(!dateFound) {
                    processAmounts.add(new ProcessAmount(date, 0, s));
                }
            }
        }

It might be a bit unclear for some people so if you don't understand I will try to explain it another way.

From the question and the comment I'd argue that your object model needs refactoring. There should be an Action object (you might come up with a better name...) tat contains the date and both of the processes Inflate and Deflate (not having a date themselves).

However...

This is how I would approach this by avoiding to iterate processAmounts excessively

public void fixMissingProcesses(){
    Map<String,Map<Date,ProcessAmount>> processesPerName = separateProcessesByName();
    List<String> processNames = new ArrayList<>(processesPerName.keySet());
    for(int i=1;i<processNames.length();i++)
      for(int j=0;j<i;j++)
         addMissingProcesses(processNames.get(i),processNames.get(j), processesPerName);
}

private void separateProcessesByName(){
    Map<String,Map<Date,ProcessAmount>> processesPerName = new HasMap<>();
    for (ProcessAmount processAmount : processAmounts) {
      if(null!=processAmount.getProcessName()){
         Map<Date,ProcessAmount> processesPerDate=  processesPerName.getOrDefault(processAmount.getProcessName(),new HashMap<>());
         processesPerDate.put(processAmount.getDate(),processAmount);
         processesPerName.put(processAmount.getProcessName(),processesPerDate)
      }
    }
    return processesPerName;
}

private void addMissingProcesses(String sourceProcessName, String targetProcessName, Map<String,Map<Date,ProcessAmount>> processesPerName);
    for(Date checkDate: processesPerName.get(sourceProcessName).keySet()){
       if(!processesPerName.get(targetProcessName).containsKey(checkDate)){
         processAmounts.add(new  ProcessAmount(checkDate, 0, targetProcessName)
       }
    }
}


Populating monthly report with new data each month This code basically checks a cell for the current date and then fills out the report by finding that date and placing the correct values in the correct places. It works fine I just know that I am going to need to build something similar for many other reports so I am hoping to update, streamline and improve in any way I can.

 Sub Copy_Data()
        Dim Data As Worksheet
            Set Data = ThisWorkbook.Worksheets("Data")
        Dim Turnover2017 As Worksheet
            Set Turnover2017 = ThisWorkbook.Worksheets("2017 Turnover")      '*************** Edit Year Number here upon creation of next year's tab
        Dim FindDate As Date
            FindDate = Data.Range("FindDate").Value
        Dim HCRNG As Range
        Dim NTRNG As Range
        Dim PTRNG As Range
        Dim X As Integer
        Dim HCNUM As Integer
        Dim NTNUM As Integer
        Dim PTNUM As Integer

        For X = 1 To 11
            '******* This  block scoops data from the Data tab
            HCNUM = Data.Range("B2").Offset(X, 0).Cells.Value
            NTNUM = Data.Range("C2").Offset(X, 0).Cells.Value
            PTNUM = Data.Range("D2").Offset(X, 0).Cells.Value
                With Turnover2017.Range("A:AM")      '*************** Edit Year Number here upon creation of next year's tab
                    Set HCRNG = .Find(What:=(FindDate), _
                        After:=Range("A1"), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False, _
                        SearchFormat:=False)
                            HCRNG.Offset(X, 2).Cells.Value = HCNUM   '******** This updates the appropriate column based on the date determined in Data G2 aka. range "FindDate"
                            HCRNG.Offset(X + 15, 2).Cells.Value = HCNUM   '******** This updates the appropriate column based on the date determined in Data G2 aka. range "FindDate"
                    End With
                With Turnover2017.Range("A:AM")      '*************** Edit Year Number here upon creation of next year's tab
                    Set NTRNG = .Find(What:=(FindDate), _
                        After:=Range("A18"), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False, _
                        SearchFormat:=False)
                            NTRNG.Offset(X, 1).Cells.Value = NTNUM     '******** This updates the appropriate column based on the date determined in Data G2 aka. range "FindDate"
                    End With
                With Turnover2017.Range("A:AM")      '*************** Edit Year Number here upon creation of next year's tab
                    Set PTRNG = .Find(What:=(FindDate), _
                        After:=Range("A1"), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False, _
                        SearchFormat:=False)
                            PTRNG.Offset(X, 1).Cells.Value = PTNUM    '******** This updates the appropriate column based on the date determined in Data G2 aka. range "FindDate"

                     End With

        Next X

    End Sub

Let me start with a number of general guidelines that can make your code more maintainable and more reusable. After that I will give some more specific advise regarding your code.

General Guidelines

Good variable names are one of the best ways to document what your code is doing. If someone else ever reads your code, he will be very grateful in case the variable names actually tell him what the variables are. This might actually also apply to yourself coming back to code after a few month. In the case of FindDate you are already using a good name. However, I have absolutely no idea what PTNUM is.
Try to follow the single responsibility principle. In short it states that a unit of your code, e.g. a procedure, should do one and only one thing. This leads to shorter more focused procedures that are easy to understand. Combined with good naming, this makes nearly all comments unneccesary. Admittedly, often it is rather hard to get this principle really right.
Do not use magical numbers, like e.g. 1 and 11 in your code. Either declare a constants minVerticalOffset and maxVerticalOffset or even pass these as parameters.
Do not hard-code configuration all over the place. Your comments show that you have to adjust the code in several places every year. Instead you should rather extract all but the configuration into a parametrized procedure that you call from Copy_Data.
Explicitely declare the scope of procedures and variables, i.e. declare them as Private, Public or Friend.
Declare you variables close to where you actually use them. I know that this contradicts with old coding conventions for VBA, but having the declaration right before its use makes it clear of what type the variable is without any need of a naming convention.
Rather VBA specific, use Long in favor of Integer if you do not specifically want to limit the range to that of an integer. As explained in the answer to this SO question every Integer is internally converted to a Long anyway on any halfway modern system.

Specific Advice

As I hinted at already above, the variable names in all caps could use some work. E.g. the variable X could be renamed to verticalOffset.
Getting more specific regarding point 4 above, it might be of great use for reusability to extract the body of the procedure into its own (private) procedure with three parameters:  TurnoverSheet As WorkSheet, FindDate As Date, DataSheet As worksheet. The names might need a little work, though. The parameters would then be passed in when calling the procedure from Copy_Data.
Most probably, your code contains a hard to see bug. Inside the with blocks, the Range(AddressString) is not prefixed with a dot. Thus, it refers to the range on the active sheet. This means that this procedure only works when called from the sheet Turnover2017.
Your three With blocks all refer to the same variable. Hence, they can be combined into one and even be pushed outside the For loop.
When using Range.Find you should always consider the possibility that there is no search result. In this case Nothing is returned. This would lead to runtime errors whan trying to call anything on it. So, you might want to test the result range for Is Nothing.
From your code I get the impression that you first only want to search in the first row, then  only in the 18th row and then only in the first column. If this is the case, then you should actually use the appropriate ranges. (This would also make the use of the optioanl parameter SearchOrder obsolete, which contains the very subtle difference between the first and third search.)
The performance could be improved by pushing the searches out of the For loop. Your searches are independent of the value of X. So, at the moment, you are performing the same work for each value of this variable. If you have really large worksheets, this wastefulness can be a problem.
After pushing the searches out of the For loop, you can eliminate the loop alltogether. To do this wyou have to load the three sets of data each into a two dimensional array by assigning the Value property, or better Value2 property, of the the corresponding ranges to a Variant variable. (See this blog post for why to use Value2.) Then the values can be assigned to the target ranges by setting the Value property of the top left cell of the target range to the corresponding array. This is much faster then itterating over the cells because accessing the worksheet is rather slow.


Car store implementation using abstract factory I'm studying design patterns and I made this car store implementation. Although I'm confident that the idea is right, I'm not confident that the implementation is good. I would like you to check it out and give me some advice.

It doesn't have tests, and I'm using an abstract class with a private method.

Car:

<?php namespace Pattern\AbstractFactory;

interface Car {

}

CarFactory:

<?php namespace Pattern\AbstractFactory;

use InvalidArgumentException;

abstract class CarFactory {

  private $sports = [];
  private $family = [];

  function __construct(array $sports, array $family)
  {
    $this->sports = $sports;
    $this->family = $family;
  }

  public function makeSportsCar($name)
  {
    return $this->makeCar($this->sports, $name);
  }

  public function makeFamilyCar($name)
  {
    return $this->makeCar($this->family, $name);
  }

  private function makeCar(array $cars, $name)
  {
    if (! isset($cars[$name]))
    {
      throw new InvalidArgumentException('You tried to make a nonexistent car');
    }

    return new $cars[$name];
  }
}

CarStore:

<?php namespace Pattern\AbstractFactory;

class CarStore {

  private $factory;

  function __construct(CarFactory $factory)
  {
    $this->factory = $factory;
  }

  public function orderSportsCar($name)
  {
    return $this->factory->makeSportsCar($name);
  }

  public function orderFamilyCar($name)
  {
    return $this->factory->makeFamilyCar($name);
  }

}

Chevrolet:

<?php namespace Pattern\AbstractFactory\Factory;

use Pattern\AbstractFactory\CarFactory;

/**
 * @codeCoverageIgnore
 */
class Chevrolet extends CarFactory {

  private $sports = [
    'miray' => 'Pattern\AbstractFactory\Car\Sport\Miray'
  ];

  private $family = [
    'equinox' => 'Pattern\AbstractFactory\Car\Family\Equinox'
  ];

  function __construct()
  {
    parent::__construct($this->sports, $this->family);
  }

}

Equinox:

<?php namespace Pattern\AbstractFactory\Car\Family;

use Pattern\AbstractFactory\Car\Family;

class Equinox implements Family {

}

Evos:

<?php namespace Pattern\AbstractFactory\Car\Sport;

use Pattern\AbstractFactory\Car\Sport;

class Evos implements Sport {

}

Family:

<?php namespace Pattern\AbstractFactory\Car;

use Pattern\AbstractFactory\Car;

interface Family extends Car {

}

Ford:

<?php namespace Pattern\AbstractFactory\Factory;

use Pattern\AbstractFactory\CarFactory;

/**
 * @codeCoverageIgnore
 */
class Ford extends CarFactory {

  private $sports = [
    'evos' => 'Pattern\AbstractFactory\Car\Sport\Evos'
  ];

  private $family = [
    'galaxy' => 'Pattern\AbstractFactory\Car\Family\Galaxy'
  ];

  function __construct()
  {
    parent::__construct($this->sports, $this->family);
  }

}

Galaxy:

<?php namespace Pattern\AbstractFactory\Car\Family;

use Pattern\AbstractFactory\Car\Family;

class Galaxy implements Family {

}

Miray:

<?php namespace Pattern\AbstractFactory\Car\Sport;

use Pattern\AbstractFactory\Car\Sport;

class Miray implements Sport {

}

Sport:

<?php namespace Pattern\AbstractFactory\Car;

use Pattern\AbstractFactory\Car;

interface Sport extends Car {

}

use protected instead of private

by making $sports and $family protected you could just override them within the child classes without having to use parrent::__construct.

interface vs abstract

why Interface for Car? It is not wrong or something but since you are asking for feedback i would recommend to use an abstract class for Car and extend it for implementations of car like Galaxy. You should ask yourself "what other object than specific cars would implement the interface "car" afaik no one.

But if you would have an Interface like ABS you could ask questions like "does instance of car implement ABS" which sounds more like the real world you are trying to model

separation of sport && family cars

i dont know why you separate them like this, it looks like you could simplify the code a lot without this kind of separation.

my simplified take:

    <?php
namespace Car {

    abstract class Car
    {
    }

    class Shop
    {
        private $factory;

        public function __construct(\Car\Factory\Factory $factory)
        {
            $this->factory = $factory;
        }

        public function orderCar($name)
        {
            return $this->factory->makeCar($name);
        }
    }

abstract class Ford extends Car {}
class Mustang extends Ford {}

}
namespace Car\Factory{
abstract class Factory {

    protected $cars = array();
    abstract public function makeCar($name);
}

class Ford extends \Car\Factory\Factory {

    protected $cars = array("Mustang" => '\Car\Mustang');
    public function makeCar($name) {
        if (!isset($this->cars[$name])) {
            throw new \InvalidArgumentException(sprintf("%s %s \n", "invalid car name", $name));
        }

        return new $this->cars[$name];
    }

}
}
namespace App {

use Car\Factory\Ford as FordFactory;
use Car\Shop;

try {
    $fac = new FordFactory();
    $shop = new Shop($fac);
    $car = $shop->orderCar('Mustang');
    var_dump($car);

    if ($car instanceof \Car\Ford) {
        echo "real deal \n";
    }
} catch (\Exception $e) {
    print_r($e->getMessage());
}
}


Group a list of products and services I'm working with a third part service of my client that is providing me a list of products and services, which is a little bit of a mess.

The list will return all of the services for the product but the product repeats itself, for example:

The product A has the service A and the product A also has the service B so, when i receive the list i will get two products A with services A and B

What i need to do is to group all of the products to get only one with all of it's services and i have done so but i'm worried about performance because i think my solution isn't the 'best' one:

var productsNormalized = products.Data.AsEnumerable().Select(x => new ProdutoSSO
{
    CodigoServico = int.Parse(string.IsNullOrEmpty(x["CodigoServico"].ToString()) ? "0" : x["CodigoServico"].ToString()),
    CodigoPeca = int.Parse(string.IsNullOrEmpty(x["CodigoPeca"].ToString()) ? "0" : x["CodigoPeca"].ToString()),
    CodigoFamilia = int.Parse(string.IsNullOrEmpty(x["CodigoFamilia"].ToString()) ? "0" : x["CodigoFamilia"].ToString()),
    Familia = x["Familia"].ToString(),
    Servico = x["Servico"].ToString(),
    Peca = x["Peca"].ToString(),
    Hash = x["Hash"].ToString(),
    Valor = decimal.Parse(string.IsNullOrEmpty(x["Valor"].ToString()) ? "0" : x["Valor"].ToString())
})
.GroupBy(x => new { x.CodigoPeca, x.CodigoFamilia, x.Familia, x.Peca })
.Select(x => new ProdutoGroup
{
    Produto = new Produto
    {
        CodigoPeca = x.Key.CodigoPeca,
        CodigoFamilia = x.Key.CodigoFamilia,
        Familia = x.Key.Familia,
        Peca = x.Key.Peca
    },
    Servicos = x.Select(y => new ProdutoServico
    {
        CodigoServico = y.CodigoServico,
        Hash = y.Hash,
        Servico = y.Servico,
        Valor = y.Valor
    }).ToList()
});

Is there a better way to achieve this or this is as good as it gets?

There are some improvemants possible but they are rather of technical nature then about performance as I don't think you can do much about it until you have measured it either with benchmarks or a profiler.

products.Data.AsEnumerable()

This looks like you are working with a DataTable, aren't you? If the data comes from a database then you should group it on the server.

CodigoServico = int.Parse(string.IsNullOrEmpty(x["CodigoServico"].ToString()) ? "0" : x["CodigoServico"].ToString()),
CodigoPeca = int.Parse(string.IsNullOrEmpty(x["CodigoPeca"].ToString()) ? "0" : x["CodigoPeca"].ToString()),
CodigoFamilia = int.Parse(string.IsNullOrEmpty(x["CodigoFamilia"].ToString()) ? "0" : x["CodigoFamilia"].ToString()),

You should create a helper extension or function for such lines, it's pretty ugly to repeat it so many times. Even two times is already too many.

.GroupBy(x => new { x.CodigoPeca, x.CodigoFamilia, x.Familia, x.Peca })

You are grouping by the same properties as the object has that you create in the next step:

Produto = new Produto
{
  CodigoPeca = x.Key.CodigoPeca,
  CodigoFamilia = x.Key.CodigoFamilia,
  Familia = x.Key.Familia,
  Peca = x.Key.Peca
},

Instead of doing this twice you should implement the IEquatable<Produto> interface on this object and use this instance as a key so that you only have a single new.

Servicos = x.Select(y => new ProdutoServico
{
  CodigoServico = y.CodigoServico,
  Hash = y.Hash,
  Servico = y.Servico,
  Valor = y.Valor
}

You can replace this with Servicos = x if you use another overload of GroupBy and project each item right away.


Using an Array of Objects to Store Quiz Questions/Answers For a quiz web app, I decided the best way to store quiz questions, answers, and other user data related to the question was to use an array of objects for the quiz. I'm not sure if this is the best way to go about it since static information such as the questions and answers will be mixed with user data.

Each object in the array contains the quiz question, answer, if the user has enabled the question, and if the question has already been asked during the quiz session.

During a quiz session I wish to ask all questions that are enabled and haven't been asked yet. My script works but I am concerned it is inefficient (with a bank of 1000+ questions)? Is it alright to store user data with my quiz questions? Will this make adding additional questions down the road more difficult? Can I improve what I have or should I look for a different approach?

My script: JS Bin: http://jsbin.com/owehix/1/edit

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

How you're making the questions really looks ugly. How about this way?

var quiz = [{
    question: "Montgomery",
    answer: "Alabama",
    enabled: false,
    asked: 0
},{
    question: "Juneau",
    answer: "Alaska",
    enabled: true,
    asked: 0
}, {} /* ... */ ];

// Now instantiate every quiz
quiz = quiz.map(function(el) {
    return new quizConstructor(el.question, el.answer, el.enabled, el.asked);
});

Now if you're not doing anything more with your quizConstructor object, you can just as well use plain objects. (What's done before instantiating every quiz up there.)


TrackBar volume control This changes the application's volume through the Trackbar (1-100, 1% to 100%):

public static class NativeMethods
{
    //Winm WindowsSound
    [DllImport("winmm.dll")]
    internal static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);
    [DllImport("winmm.dll")]
    internal static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);
}

private void trackBar1_Scroll(object sender, EventArgs e)
{
    uint CurrVol = ushort.MaxValue / 2;
    NativeMethods.waveOutGetVolume(IntPtr.Zero, out CurrVol);
    ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
    int NewVolume = ((ushort.MaxValue / 100) * trackBar1.Value);
    uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
    NativeMethods.waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
    label1.Text = Convert.ToString("Volume: " + trackBar1.Value + "%");
}

Is it possible to make String.Format use multiple arguments/values?

For example:

 String Status = String.Format("Current Buffer: {0}", waveProvider.BufferedDuration.Milliseconds, TimesBufferClear) + " Clear: " + TimesBufferClear.ToString() + " Ping: " + PingReply + " Buffer: " + SendStream.BufferMilliseconds;

There, I would like to use it on everything, as they all work pretty much the same. But if I have to write String.Format every time, it will take up much more space.

Is this code okay, or can it be improved?

There isn't much to review in 6 lines of code. But oh well.

Native methods return error codes, so it is good practice to handle those codes somehow, not just ignore them. For example, if method reports, that there is no sound driver or no sound card or w/e, it makes sense to notify user somehow. Write warning in the status bar of your window or something.
It is meaningless to initialize CurrVol, since its value will be overriden anyway, wont it? And, if its your real code, you dont have to recieve current volume in order to set it to begin with.
Convert.ToString should be refactored to String.Format("Volume: {0}%", trackBar1.Value);. More complex example:

var status = String.Format("Current Buffer: {0} Clear: {1} Ping: {2} Buffer: {3}", waveProvider.BufferedDuration.Milliseconds, TimesBufferClear, PingReply, SendStream.BufferMilliseconds);


Quaternion and Vector3 transfomation Math hi I have made and AI for my enemies which works perfectly but a particular section of code is repetitive and I feel that it can be optimised

void ChangeDirection()
    {
        if (movement == Vector3.left)
            transformModel.rotation = Quaternion.Euler(0, 270, 0);
        else if (movement == Vector3.right)
            transformModel.rotation = Quaternion.Euler(0, 90, 0);
        else if (movement == Vector3.back)
            transformModel.rotation = Quaternion.Euler(0, 180, 0);
        else if (movement == Vector3.forward)
            transformModel.rotation = Quaternion.Euler(0, 0, 0);
    }

the enemy will be in a tight corridor where only the following movements are possible i.e enemy can only move the vector3. right, left, back and forward. thus the code works without any issues,
however, the code is repetitive and I want the enemy to move in whichever its movement vector will be.

here is the rest my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMovement2 : MonoBehaviour
{
    public float speed;
    public Vector3 movement;
    public Animator animator;
    private GameObject gameManager;

    void Start()
    {

        movement = Vector3.back;
        gameManager = GameObject.FindWithTag("GameController");

    }
    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Wall")
        {

            CorrectPosition(new Vector3(1, 1, 1));
            movement = Vector3.zero;

        }
    }

    public Transform transformModel;
    void ChangeDirection()
    {
        if (movement == Vector3.left)
            transformModel.rotation = Quaternion.Euler(0, 270, 0);
        else if (movement == Vector3.right)
            transformModel.rotation = Quaternion.Euler(0, 90, 0);
        else if (movement == Vector3.back)
            transformModel.rotation = Quaternion.Euler(0, 180, 0);
        else if (movement == Vector3.forward)
            transformModel.rotation = Quaternion.Euler(0, 0, 0);
    }
    void CorrectPosition(Vector3 CorrectPositionOF)
    {
        Vector3 posNow = transform.position;
        if (CorrectPositionOF.x == 1)
            posNow.x = Mathf.RoundToInt(gameObject.transform.position.x);
        if (CorrectPositionOF.y == 1)
            posNow.y = Mathf.RoundToInt(gameObject.transform.position.y);
        if (CorrectPositionOF.z == 1)
            posNow.z = Mathf.RoundToInt(gameObject.transform.position.z);
        transform.position = posNow;
    }
    public LayerMask whatIsWall;
    private Vector3[] direction = { Vector3.left, Vector3.forward, Vector3.back, Vector3.right };
    void FixedUpdate()
    {
        GetComponent<Rigidbody>().velocity = movement * speed;
        animator.SetFloat("runningSpeed", GetComponent<Rigidbody>().velocity.magnitude);
        for (int i = 0; i < direction.Length; i++)
        {
            RaycastHit hit;
            if (Physics.Raycast(transform.position, direction[i], out hit, 18, 0 << 11 | 1 << 8 | 1 << 9)
                && hit.collider.gameObject.tag == "Player"
                && movement == Vector3.zero)
            {
                movement = direction[i];
                ChangeDirection();
                return;
            }
        }

    }
}
```

If you want DRY the KISS way, I suggest substituting the if-chain..

if (movement == Vector3.left)
    transformModel.rotation = Quaternion.Euler(0, 270, 0);
else if (movement == Vector3.right)
    transformModel.rotation = Quaternion.Euler(0, 90, 0);
else if (movement == Vector3.back)
    transformModel.rotation = Quaternion.Euler(0, 180, 0);
else if (movement == Vector3.forward)
    transformModel.rotation = Quaternion.Euler(0, 0, 0);

..with a lookup map:

var rotationsEulerY = new Dictionary<Vector3, int>
{
    {Vector3.left, 270}, {Vector3.right, 90}, {Vector3.back, 180}, {Vector3.forward, 0}
};

void ChangeDirection()
{
    transformModel.rotation = Quaternion.Euler(0, rotationsEulerY[movement], 0);
}

You could do something similar for CorrectPosition using a predefined map of guard conditions and assignor actions.


Memoized Collatz sequence Here is one of my programs that utilized memoization and array to improve performance and memory usage. The performance seems satisfactory but the memory usage is ridiculous and I can't figure out what's wrong:

{-# LANGUAGE BangPatterns #-}
import Data.Functor
import Data.Array (Array)
import qualified Data.Array as Arr
import Control.DeepSeq

genColtzArr n = collatzArr
    where collatzArr = Arr.array (1, n) $ take n $ map (\v -> (v, collatz v 0)) [1..]
          collatz 1 !acc  = 1 + acc
          collatz !m !acc
              | even m    = go (m `div` 2) acc
              | otherwise = go (3 * m + 1) acc
              where go !l !acc
                      | l <= n    = let !v = collatzArr Arr.! l in 1 + acc + v
                      | otherwise = collatz l $ 1 + acc

collatz here means this guy. This function is supposed to receive a number n, and then return an array indexing from 1 to n, and in which each cell contains the length of the link from the index to 1 by applying Collatz formula.

But the memory usage of this method is so high. Here is the profiler result (ghc option -prof -fprof-auto -rtsopts, run time option +RTS -p, n == 500000):

total alloc = 730,636,136 bytes  (excludes profiling overheads)

COST CENTRE              MODULE  %time %alloc

genColtzArr.collatz      Main     40.4   34.7
genColtzArr.collatz.go   Main     25.5   14.4

COST CENTRE                      MODULE                    no.     entries  %time %alloc   %time %alloc

      genColtzArr                Main                      105           1    0.0    0.0    74.7   72.1
       genColtzArr.collatzArr    Main                      106           1    8.0   20.8    74.7   72.1
        genColtzArr.collatzArr.\ Main                      107      500000    0.9    2.2    66.8   51.3
         genColtzArr.collatz     Main                      109     1182582   40.4   34.7    65.9   49.1
          genColtzArr.collatz.go Main                      110     1182581   25.5   14.4    25.5   14.4

Please note that -O2 is not a desired answer. I want to figure out what's the problem in this program and in general, how should I spot time and memory inefficiencies in Haskell code.  Specifically, I have no idea why this code, with tail recursion and bang pattern, can consume so much memory.

UPDATE1:

the same code with -s produces this:

   1,347,869,264 bytes allocated in the heap
     595,901,528 bytes copied during GC
     172,105,056 bytes maximum residency (7 sample(s))
         897,704 bytes maximum slop
             315 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0      2408 colls,     0 par    0.412s   0.427s     0.0002s    0.0075s
  Gen  1         7 colls,     0 par    0.440s   0.531s     0.0759s    0.1835s

  INIT    time    0.000s  (  0.000s elapsed)
  MUT     time    0.828s  (  0.816s elapsed)
  GC      time    0.852s  (  0.958s elapsed)
  RP      time    0.000s  (  0.000s elapsed)
  PROF    time    0.000s  (  0.000s elapsed)
  EXIT    time    0.004s  (  0.017s elapsed)
  Total   time    1.684s  (  1.791s elapsed)

  %GC     time      50.6%  (53.5% elapsed)

  Alloc rate    1,627,861,429 bytes per MUT second

  Productivity  49.4% of total user, 46.4% of total elapsed

so it takes 300 meg. that is still too large.

It doesn't use 300 megabytes of heap, it peaks at a little over 20 megabytes. Total allocation is not peak allocation and Haskell has cheap short-lived allocations so total alloc isn't always a good heuristic for GC time or steady-state heap usage. The heap profiling stuff is giving data designed for tuning code rather than for analytics and total alloc is often more helpful when comparing code for overall memory usage.

Here's a screenshot from a memory profile:

I don't think it necessarily bit you here, but in future, add explicit types to functions you are benchmarking. See here for an example of why you want to do that.

Here's the command I wrote to profile your code:

$ rm -f collatz
$ stack ghc -- -prof -fprof-auto -rtsopts -O2 collatz.hs -o collatz
$ ./collatz +RTS -hc -p
$ hp2ps collatz.hp
$ evince collatz.ps

Last bits are just converting the hp heap profiling data to a postscript file and then I'm opening it in my PDF reader.


Email-sending class for GAE Please review this:

class KoolDailyReminderAfterWeek(webapp2.RequestHandler):
    def get(self):
        logging.info('sending reminders')
        timeline = datetime.now () - timedelta (days = 7)
        edge = datetime.now () - timedelta (days = 8)
        ads = Ad.all().filter("published =", True).filter("added <", timeline).filter("url IN", ['www.koolbusiness.com']).filter("added >", edge).fetch(99999)
        for ad in ads:
            logging.info('sending reminder to %s', ad.name)
            if ad.title:
                subject= ad.title
            else:
                subject = 'Reminder'
            message = mail.EmailMessage(sender='Kool Business <info@koolbusiness.com>', subject=subject)
            message.body = """
            Hello!
Now your ad %s has been out for a week. If you already have sold your product you can remove your ad.

Some advice to promote your ad:
Change + Renew the ad and it will be on top of the list. You can also change text and price.
Change the ad if you only want to lower the price or change the ad text
Renew so that the ad will be on top if the list.

Best regards,
Koolbusiness.com
            """  % (ad.key().id(),ad.title)
            message.html = """

            Hello!
Now your ad %s has been out for a week. If you already have sold your product you can remove your ad.

Some advice to promote your ad:
Change + Renew the ad and it will be on top of the list. You can also change text and price.
Change the ad if you only want to lower the price or change the ad text
Renew so that the ad will be on top if the list.

Best regards,
Koolbusiness.com

            """  % (ad.key().id(),ad.title)
            message.to=ad.email
            message.send()
            logging.info('sent email to: ' +ad.email)

YAML

 - description: daily mailout
   url: /report/dailyafterweek
   schedule: every 24 hours

Background

I'm not familiar with that framework, so I can only provide some general points:

You can rewrite the if statement to subject = ad.title or 'Reminder' (see here).
You are a bit inconsistent with spacings (before and after =, ,, (), etc.), and string formatting (your second and third logging.info)
I'd recomment spreading both those chained filters and overly long strings over multiple lines.
Maybe you could use some helper method to derive the HTML version of the message from the plain-text version or vice versa?


Increase performance in an R function using a vectorized approach Goal

Write an R function to generate probabilities modeled by the following equation (IRT; 2 Parameter Logistic Model):

Data

set.seed(1)
a = runif(10, 1.5, 3)
b = rnorm(10, 0, 1)
theta = rnorm(10000000)
# the output of the implementation should result in
# a matrix with 100 mil. rows and 10 columns

Implementation

Strategy A

# the implementation of the equation
computeProbability = function(theta, b, a) {
    x = exp(1) ^ (a * (theta - b))
    return(x / (1 + x))
}

strategy.A = function(theta, b, a) {
    n.rows = length(theta)
    n.cols = length(b)

    prob_mtx = matrix(nrow = n.rows, ncol = n.cols)

    for(i in 1:n.rows)
    {
        prob_mtx[i, ] = computeProbability(theta[i], b, a)
    }
    return(prob_mtx)
}

Strategy B

strategy.B = function(theta, b, a) {
   return(t(sapply(theta, computeProbability, b = b, a = a)))
}

Strategy C

strategy.C = function(theta, b, a) {
    return(1 / (1 + exp(-sweep(outer(theta, b, "-"), 2, a, "*"))))
}

Timings

    # Strategy A        |       # Strategy B        |       # Strategy C
                        |                           |
 user  system elapsed   |    user  system elapsed   |   user  system elapsed
64.76    0.27   65.08   |   82.01    0.91   82.93   |   7.81    0.64    8.46

Question: Strategy C is by far the most efficient way, but how can I make it even faster?

Your strategy C is probably already nearly optimal. Here is an Rcpp based solution to squeeze out some additional seconds

library('Rcpp')
cppFunction(includes = '#include <math.h>',
            code = 'Rcpp::NumericMatrix strategy_rcpp(const Rcpp::NumericVector& theta,
                                                      const Rcpp::NumericVector& b,
                                                      const Rcpp::NumericVector& a) {
  const int n = theta.size();
  const int m = a.size();
  if (m != b.size())
      Rcpp::stop("a and b must have equal length");
  const double e = exp(1.0);
  Rcpp::NumericMatrix ret(n, m);
  for (int j = 0; j < m; ++j) {
      for (int i = 0; i < n; ++i) {
         ret(i, j) = 1.0 / (1.0 + pow(e, -a[j] * (theta[i] - b[j])));
      }
  }
  return ret;
}')

Benchmarks with your data:

library('microbenchmark')
microbenchmark(times = 1,
               strategy.C(theta, b, a),
               strategy_rcpp(theta, b, a)
)

Unit: seconds
                       expr       min        lq      mean    median        uq
    strategy.C(theta, b, a) 10.996822 10.996822 10.996822 10.996822 10.996822
 strategy_rcpp(theta, b, a)  6.921705  6.921705  6.921705  6.921705  6.921705


Methods to check form validity and to count invalid form fields I have two these methods. Their loops are pretty similar. I'd like to refactor it to avoid duplicate nested loops. How could I do that?

@Override
public boolean isValid() {
    for (final FormSection formSection : getFormSections()) {
        for (final Component fieldComponent : formSection) {
            boolean isFieldValid = ((Field)fieldComponent).isValid();
            if(!isFieldValid){
                return false;
            }
        }
    }
    return true;
}

private int countErrors() {
    int errorAmount = 0;
    for (final FormSection formSection : getFormSections()) {
        for (final Component fieldComponent : formSection) {
            boolean isFieldValid = ((Field)fieldComponent).isValid();
            if(!isFieldValid){
                errorAmount++;
            }
        }
    }
    return errorAmount;
}

I've tried to use interface but it doesn't look good.

interface FieldHandler {
    boolean process(AtomicInteger number);
}

@Override
public boolean isValid() {
    return handleTextFieldsInTabs(new FieldHandler() {
        @Override
        public boolean process(AtomicInteger number) {
            return false;
        }
    }, null);
}

boolean handleTextFieldsInTabs(FieldHandler fieldHandler, AtomicInteger number) {
    for (final FormSection formSection : getFormSections()) {
        for (final Component fieldComponent : formSection) {
            boolean isFieldValid = ((Field)fieldComponent).isValid();
            if(!isFieldValid && !fieldHandler.process(number)) {
                return false;
            }
        }
    }
    return true;
}

private int countErrors() {
    final AtomicInteger errorAmount = new AtomicInteger(0);
    handleTextFieldsInTabs(new FieldHandler() {
        @Override
        public boolean process(AtomicInteger number) {
            number.incrementAndGet();
            return true;
        }
    }, errorAmount);
    return errorAmount.intValue();
}

If you are using Google's guava, I would suggest:

@Override
public boolean isValid() {
  // Firstly, flat your Iterable<Iterable<Component>> getFormSections()
  // into Iterable<Component>.
  // Then we use a Predicate to check whether there is any match.
  return Iterables.all(
    Iterables.concat(getFormSections()), validComponents());
}

@Override
public int countErrors() {
   return Iterables.size(
      Iterables.filter(Iterables.concat(getFormSections()), Predicates.not(validComponents()));

}

// - Positive names is always preferable
// - This method is static simply because it does not access to any instance varibles. It is easier to extract it out into another class.
private static Predicate<Component> validComponent() {
  new Predicate<Component>() {
      @Override
      public boolean apply(Component input) {
        return // your logic here
      }
    };
}


Format python data structures in HTML no dependencies My poorly written tests suggests that the module works as intended. I fear this is to good to be true. I don't known how to write unit tests for this. I'm new to writing tests and I think this module would be hard for a unit test master to test.

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

SINGLETONS = [
    'area',
    'base',
    'br',
    'col',
    'command',
    'embed',
    'hr',
    'img',
    'input',
    'keygen',
    'link',
    'meta',
    'param',
    'source',
    'track',
    'wbr'
]

# Constants.
SP = ' '
EMPTY = ''

def is_singleton(tag):
    return tag in SINGLETONS

def not_singleton(tag):
    return is_singleton(tag) == False

def html_attributes(**kw):
    # 'attrs' is the elements attributes.
    # Iterate over the keys and values of the kw dict
    # and transform them into a string of html
    # attributes. Two html attribute keys are
    # Python keywords 'class' and 'id' to set
    # the id and class of and element use:
    # cls for class and '_id' for 'id.'
    attrs = EMPTY
    n_attrs = len(kw)
    for key, value in zip(kw.keys(), kw.values()):
        if key == 'cls':
            key = 'class'

        if key == '_id':
            key = 'id'

        if n_attrs > 1:
            attrs += '{}="{}"{}'.format(key, value, SP)
        else:
           attrs += '{}="{}"'.format(key, value)
    return attrs.rstrip(SP)

def tagify(tagname, data=EMPTY, **kw):
    if isinstance(data, str):
        data = data.replace('\n', '
')
    attrs = html_attributes(**kw)

    if not attrs:
        opentag = '<{}>'.format(tagname)
    else:
        opentag = '<{}{}{}>'.format(tagname, SP, attrs)

    if not_singleton(tagname):
        closetag = '</{}>'.format(tagname)
    else:
        closetag = None

    if not closetag:
        return '{}'.format(opentag)

    if data:
        return '{}{}{}'.format(opentag, data, closetag)
    else:
        return '{}{}'.format(opentag, closetag)

def tag(tagname, **deco_kw):
    '''
    Decorate a functions output with html by
    passing it through tagify.
    '''
    def deco(func):
        def wraps(*args, **kw):
            content = func(*args, **kw)
            return tagify(tagname, content, **deco_kw)
        return wraps
    return deco

def tests():
    '''
    This is a temporary function for
    testing the module.
    Please dont include this in any reviews.
    '''
    @tag('li', cls='link', _id='list-item')
    def link(name, **kw):
        return tagify('a', name, **kw)

    @tag('article', cls='main', _id='spam')
    def paragraph(content, **kw):
        return tagify('p', content, **kw)

    print(link(__name__, src=__file__))
    print(paragraph(list(range(10)), _id='monty'))

if __name__ == '__main__':
    tests()

test() output

__main__

[0, 1, 2, 3, 4]

The better way to do this would be to use  html_lib, but short of that, here are a few suggestions.

not_singleton is useless. Just use not singleton.

Use kw.items instead of  zip(kw.keys(), kw.values()).

Don't use SP, use '  '.


Find the inverted value of the string How can this be optimized?

$text = "reverseesrever"; // Reverse and esrever
$b = false;

for($i = 0; $i < strlen($text); $i++) {
    if($text[$i] !== $text[strlen($text) - 1 - $i]) {
        $b = true;
        break;
    }
}

echo ($b) ? "YES" : "NO"; // result: NO.

The title of the question is confusing. The code seem to check if the text is not the same if you read it backward. For example, it $b will be true for "hello" and false for "level". In other words, you're checking if some text is NOT a palindrome. I think you should change the title to better reflect what the code is doing.

Things to improve:

It's enough to iterate until strlen($text) / 2, no need to go all the way until the end
To avoid re-calculating the length of the string, it's better to calculate it once before the loop and reuse it
Wrap the whole thing in a function to make it easier to reuse and to test
The !== is unnecessary, a simple != would do

For example:

function isPalindrome($text) {
    $length = strlen($text);
    for ($i = 0; $i < $length / 2; $i++) {
        if ($text[$i] != $text[$length - 1 - $i]) {
            return false;
        }
    }
    return true;
}

function test_isPalindrome($text) {
    printf("isPalindrome(%s) -> %s\n", $text, isPalindrome($text) ? 'YES' : 'NO');
}

test_isPalindrome("reverseesrever");
test_isPalindrome("hello");
test_isPalindrome("aba");
test_isPalindrome("aa");
test_isPalindrome("ab");

Outputs:

isPalindrome(reverseesrever) -> YES
isPalindrome(hello) -> NO
isPalindrome(aba) -> YES
isPalindrome(aa) -> YES
isPalindrome(ab) -> NO


Encode message by alphabets I am trying to resolve below problem to improve my skill. I would appreciate it if someone improve my code in a better way.
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.
#include <stdio.h>
#include <stdlib.h>

#define MIN_ALPH 1
#define MAX_ALPH 26

//return number of possible encode methods
int encode(unsigned int num)
{
    int count=0;
    unsigned int ddigit;

    //encode by 2 digits
    for(int i=10; i<=num; i*=10)
    {
        ddigit = (num % (i*10)) / (i/10);
        if (ddigit >= MIN_ALPH && ddigit <= MAX_ALPH)
            count++;
    }

    //extra count for the single digit encoding since all digits are non-zero
    return ++count;
}

int main(void)
{
    /*Given the mapping a = 1, b = 2, ... z = 26, and an encoded message,
    count the number of ways it can be decoded.
    For example, the message '111' would give 3,
    since it could be decoded as 'aaa', 'ka', and 'ak'.
    You can assume that the messages are decodable.
    For example, '001' is not allowed.*/

    printf( "result: %d\n",  encode(512));
    printf( "result: %d\n",  encode(542));
    printf( "result: %d\n",  encode(112));

}

The terminology is a bit sloppy - I would call the operation of going from digits back to alphabetic characters decoding rather than encoding - and our function isn't really either of those: it's counting.  (I'm guessing that you're not a native English speaker, so don't take this criticism too harshly!).

The interface is surprising: accepting an integer type greatly limits the maximum length of input, and we could return an unsigned type as result:
unsigned int count_decodings(const char *input);

As a hint, it is safe to convert a character to digit by subtracting '0' (C guarantees that the digits 0..9 have consecutive encodings, regardless of the host environment's character coding).

The algorithm produces incorrect results:
This comment is not justified:
//extra count for the single digit encoding since all digits are non-zero
return ++count;

Some digits may indeed be zero - for example, 10 and 201 can each be decoded exactly one way.  That should suggest some extra testing you could (and should) do.

It's good that we have some tests in main(); I would go further and make the tests self-checking.  Instead of merely printing the results, we should compare against the expected values, and return EXIT_SUCCESS only if all the tests pass.  There are several libraries available to help with unit testing like this, or you could could do it quite simply:
int failures = 0;
failures += count_decodings("10") != 1;
failures += count_decodings("11") != 2;
// more tests here

We don't have any indication of which tests have failed, and what their expected and actual results were.  We could create macros to help here (which is exactly what the unit-testing frameworks provide for us).