Regex to select the last components of a file path

Your regex has too many capturing groups.
Using (?:) makes it into a simple matching group, speeding up the regex since it doesn't have to store anything.

Since you are trying to get the part from the end of the string, anchor it there using $.

At the end, you have this: (\/)(\w+\.\w+).

This is really bad in 2 ways:

You are using 2 capturing groups.
You regex only allows files with letters. Spaces, underscores and others should de allowed too.

For version control, you have this: (\/)(\w\d-?\d).

This allows me to have a folder called t0-0 which makes no sense.
Be more strict about your match.

This is the regex I came up with:

\/(?:[vV][1-9]\d?(?:-\d)?\/)?[^\/]+\.[^\.]+$

It addresses all your issues.

Explaining each part:

(?:\/[vV][1-9]\d?(?:-\d)?\/)? matches the version number, if there is any.
1.1. No need for capturing groups.

1.2. It enforces that the folder starts with v or V with.

1.3. The version only can starts with 1-9 and can have any number or digits.

1.4. The version folder is still optional
[^\/]+\.[^\.]+$ matches the file name.
2.1. Again: No need for capturing groups.

2.2. The file can have ANY name.

2.3. The file can have ANY extension, but there must be one.
The whole string is matched to the end, which makes it easier for us to write it.


This might not be an improvement per se, but you can change this:

$(document).ready( function() {
    $('.flipper').each(function(e) {
        var flipper = new myFlipper($(this));
    })
});

To this:

$(function() {
    $('.flipper').each(function(e) {
        var flipper = new myFlipper($(this));
    });
});

The reason this works is $() is a shortcut for $(document).ready().

With JavaScript, it is usually recommended that you keep from cluttering the global namespace. You currently have everything contained in var myFlipper, which is good. But since you're using jQuery, you might as well use a jQuery plugin, which would allow you to do something like this:

$.fn.myFlipper = function () {
    //...
};

$(function() {
    $('.flipper').myFlipper();
});

This way, you aren't introducing another variable into the global namespace. Plus, the jQuery plugin architecture affords you some additional benefits, like syntax, etc.


Due to the nested and long conditions the code becomes hard to follow
at some points. Early returns prevent nesting of conditions.
Some code is duplicate (step 9)
Possibly some values could be overwritten by url-forging (depending on the server-configuration). (step 5)

I'll do a step-by-step refactoring here with some explanations.

Move everything in a function. This eases early-return.

function sendMail() {
    // your code here.
}

While not necessary, it's I like to invert the conditions so the static expression stands on the left side. This avoids accidental assignment in conditions. Avoids tricky to detect bugs (though most IDEs and codesniffer emit a warning).
Using the === operator for comparison avoids bugs to unforeseen casting

function sendMail() {
    if ('POST' !== $_SEVER['REQUEST_METHOD']) {
        return '';
    }

    if ($_SESSION['token'] !== $_POST['token']) {
        return '0';
    }
    // remaining code
}

What's the purpose of your output-cachting? I can't see any outputs being made? Trying to catch any errors? Hiding them is a bad idea, catch and handle them. If simply removed them.
You are using $_REQUEST instead of $_POST. Sure you do check if the request type. But this doesn't prevent anyone from submitting both, GET and POST values. And here lies a dangerous problem: If I send you a link to form.php?message=something this does get send to the server as well when you submit the form. Now GET and POST both having the key name collide. Depending on the variables_order the GET value I set overwrites your message. If you use $_POST to access your variables instead this issue can be prevented.
I have extracted a simple accessor function to check for existence of a $_POST variable and return else:

function getPostValue($key) {
    return isset($_POST[$key]) ? $_POST[$key] : null;
}

function sendMail() {
    if ('POST' !== $_SEVER['REQUEST_METHOD']) {
        return '';
    }

    if ($_SESSION['token'] !== $_POST['token']) {
        return '0';
    }

    $_SESSION['token'] = '';

    $name = getPostValue('name');
    $email = getPostValue('email');
    $message = getPostValue('message');
    $number = getPostValue('number');
    $date = getPostValue('date');
    $select = getPostValue('select');
    $radio = getPostValue('radio');
    $checkbox = getPostValue('checkbox');

    if (!isset($name, $email, $message, $number, $date, $select, $radio, $checkbox)) {
        $response = "Error";
    }
}

All those input validations go with early return again (snippet only):

    $spam_pattern = "/[\r\n]|Content-Type:|Bcc:|Cc:/i";
    if (!preg_match($spam_pattern, $name)
        || !preg_match($spam_pattern, $number)
        || !preg_match($spam_pattern, $date)
        || !preg_match($spam_pattern, $radio)
        || !preg_match($spam_pattern, $checkbox)
        || !preg_match($spam_pattern, $select)
        || !preg_match($spam_pattern, $message)) {
        return 'Invalid Request!';
    }

The $to variables and others you use as parameters for mail are only used once. Furthermore the $message variable is overwritten, removing the original content. Variable reuse makes stuff hard to track though. I just do this all as arguments in the mail function (snippet):

    $sendResult = mail(
        'support@loaidesign.co.uk',
        'New Message From: ' . $name,
        "Name:

           number: $number

           date: $date

           select: $select

           radio: $radio

           checkbox: $checkbox

           Email: $email

           Message: $message",
        "MIME-Version: 1.0 r\n Content-type: text/html; charset=utf-8 \r\n From: '.$email . '\r\n"
    );

All those returns have their html-markup in common. We sure can extract this into a common helper:

function getResponse($message, $isError) {
    return '' . $message . '';
}

Final remarks & further points of improvement:

Indention of three characters is unusual. Most times its two or four.
This can of course be further refactored: Especially creating local variables from $_POST is a point of repetation. Maybe it could be handled as an array. That'd make mass-checking (preg_match) easier: just loop over all input variables.
If desired, this could of course be moved into a dedicated mailer class
The functions depend on the global state ($_POST). A next step would be to pass the required input variables as argument (maybe an array :)). This would make this function reusable as well.
Returning formated strings limits reusability to HTML output. Throwing expections or error codes puts this into the responsibility of the caller, not the callee.

My final result:

function getPostValue($key) {
    return isset($_POST[$key]) ? $_POST[$key] : null;
}

function getResponse($message, $isError) {
    return '' . $message . '';
}

function sendMail() {
    if ('POST' !== $_SEVER['REQUEST_METHOD']) {
        return '';
    }

    if ($_SESSION['token'] !== $_POST['token']) {
        return '0';
    }

    $_SESSION['token'] = '';

    $name = getPostValue('name');
    $email = getPostValue('email');
    $message = getPostValue('message');
    $number = getPostValue('number');
    $date = getPostValue('date');
    $select = getPostValue('select');
    $radio = getPostValue('radio');
    $checkbox = getPostValue('checkbox');

    if (!isset($name, $email, $message, $number, $date, $select, $radio, $checkbox)) {
        $response = getResponse('Error', true);
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return getResponse('Invalid Email Address!', true);
    }

    $spam_pattern = "/[\r\n]|Content-Type:|Bcc:|Cc:/i";
    if (!preg_match($spam_pattern, $name)
        || !preg_match($spam_pattern, $number)
        || !preg_match($spam_pattern, $date)
        || !preg_match($spam_pattern, $radio)
        || !preg_match($spam_pattern, $checkbox)
        || !preg_match($spam_pattern, $select)
        || !preg_match($spam_pattern, $message)) {
        return getResponse('Invalid Request!', true);
    }

    $sendResult = mail(
        'support@loaidesign.co.uk',
        'New Message From: ' . $name,
        "Name:

           number: $number

           date: $date

           select: $select

           radio: $radio

           checkbox: $checkbox

           Email: $email

           Message: $message",
        "MIME-Version: 1.0 r\n Content-type: text/html; charset=utf-8 \r\n From: '.$email . '\r\n"
    );

    if (true === $sendResult) {
        return getResponse('Success! Your submission has been sent.', false);
    } else {
        return getResponse('Error! There was a problem with sending.', true);
    }
}


Go Code Review Comments

  Don't Panic

  Don't use panic for normal error handling. Use error and multiple
  return values.

func Make(object interface{}) string {
    payloadBytes, err := json.Marshal(object)
    if err != nil {
        panic(err)
    }
    payload := base64.StdEncoding.EncodeToString(payloadBytes)
    return payload + "." + sign(payload)
}

I'm going to exploit this, an exported function that panics, to crash your application.

func sign(s string) string {
    h := hmac.New(sha256.New, []byte("secret"))
    h.Write([]byte(s))
    return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

I'm going use a literal embedded in your executable, []byte("secret"), to break your authentication.


Here are some tips:

Use $.getJSON() to get JSON.

Also, name the first parameter json for clarity.

Note from documentation for jQuery.getJSON()

  JSONP

  If the URL includes the string "callback=?" (or similar, as defined by
  the server-side API), the request is treated as JSONP instead. See the
  discussion of the jsonp data type in $.ajax() for more details.

More information here

Old Code:

var url = 'https://api.twitter.com/1/statuses/show/' + id + '.json',
    karma;
$.ajax({
    url: url,
    type: 'GET',
    dataType:'jsonp',
    crossDomain: true,
    success: function(data) {
        display_karma(data.retweet_count);
    },
    error: function() {alert('fail');}
}));

New Code:

var url = 'https://api.twitter.com/1/statuses/show/' + id + '.json?callback=?';
$.getJSON( url, function (json) {
    display_karma(json.retweet_count);
}).error(function () {
    alert('fail');
});

Eliminate commented code. Use a source control system like git, svn, mercurial to keep track of changes.

Here's a good start for it

Old Code:

function start_get_karma() {
    var id;

    $('.tweetContainer').each(function(index,el) {
        //id = $(el).data(el, tweet_id);
        id = '248988915661410304';
        get_retweet(id);
    });
}

New Code:

function start_get_karma() {
    var id = '248988915661410304';
    $('.tweetContainer').each(function (index, el) {
        get_retweet(id);
    });
}

Function calls are expensive, so use a basic loop instead of each() when appropriate.

Old Code:

$('.tweetContainer').each(function (index, el) {
    get_retweet(id);
});

New Code A:

for(var i = 0; len = $('.tweetContainer').length; i < len; i++){
    get_retweet(id);
}

However, there's a problem. Making multiple calls to get_retweet() with the same static value doesn't make sense.  So just make one call.

New Code B:

if( $('.tweetContainer').length ){
    get_retweet(id);
}

Don't declare variables if they're only used once.

Old Code:

function display_karma(retweets) {
    var id, karma,
        el =$('.tweetContainer');
        id = '248988915661410304';
    karma = calc_karma(retweets);
    el.find('.tcPoints').text(karma);
}

New Code:

function display_karma(retweets) {
    var id = '248988915661410304';
    $('.tweetContainer').find('.tcPoints').text(calc_karma(retweets));
}

Have variable names give a hint to the type.

retweets sounds like a function or array. Try naming it retweet_amount or something similar.

Final Code:

function calc_karma(tweets) {
    return (tweets * 10) + 10;
}
function display_karma(retweet_amount) {
    $('.tweetContainer').find('.tcPoints').text(calc_karma(retweet_amount));
}
function get_retweet(id) {
    var url = 'https://api.twitter.com/1/statuses/show/' + id + '.json?callback=?';
    $.getJSON( url, function (json) {
        display_karma(json.retweet_count);
    }).error(function () {
        alert('fail');
    });
}
function start_get_karma() {
    var id = '248988915661410304';
    if( $('.tweetContainer').length ){
        get_retweet(id);
    }
}


Thou shalt not bruteforce.
Your algorithm exhibits a quadratic time complexity, and cannot be salvaged. You need a better one.
First observation you should make is that when you remove the peak, other peaks stay put. That alone is enough to see that rescanning the entire array is a waste of time.
More important observation is that once you remove the peak, the new peak may appear only in the position immediately adjacent to the peak being removed. Please prove this fact (or at least convince yourself that it is so). Also notice that the newborn peak would in general be smaller than the existing peaks, if any.
I hope it is enough to get you going.

As for the proper review:

Flat is better than nested. The condition list1.size() >= 2 better be reversed:
  if (list1.size() < 2) {
      // The list consists of a single element, which is a peak,
      // and it resides at index 0
      return 0;
  }
  // Proceed with a general case here
  ....

list1 looks like a strange name. There are no other lists, are there?


Comparing multiple variables and assigning new values respectively

Introduce a function:

var boundedIncrement = function(current, maximum) {
    return current === maximum ? 0 : current + 1;
};

Then use it:

if (forward) {
    counter = boundedIncrement(counter, listEnd);
    nextCounter = boundedIncrement(nextCounter, listEnd);
    prevCounter = boundedIncrement(prevCounter, listEnd);
}

No more logic duplication.

You could also close over listEnd if you wanted to have a single argumented function:

if (forward) {
    var boundedIncrement = function(current) {
         return current === listEnd ? 0 : current + 1;
    };
    counter = boundedIncrement(counter);
    nextCounter = boundedIncrement(nextCounter);
    prevCounter = boundedIncrement(prevCounter);
}


Even though your code works I have some comments regarding Erlang style and naming conventions:

Spaces after commas and empty lines between function definitions make the code a lot more readable.
Helper functions that do the actual work are usually named with the do_ prefix. Instead of ghelper I would have named that do_get.
Using lists:nth could greatly simplify your code. The standard library includes a lot of useful functions, I try to always check if there is an existing function for what I want to do and only if there's none then I implement it.


Handling data from an HTML table using jQuery

$(document).on('click', '#updateBtn', function () {    // See "Event Handler"
    var locations = [],                                // See "Unused Variable"
        rows = [],                                     // See "Improper Scope"
        content = {};

    $('.rowUpdate').each(function (i) {                // See "Exactly One" and "Parameters"
        var feed = [];

        $(this).find('td').each(function (j, v) {      // See "Parameters"
            var label = $(this).html();

            if (j == 0) feed = feed + label;           // See "Type Variance"
            if (j != 0) {
                var input = $("input", this),
                                                       // See "Wait, what?"
                    name = input.attr("name").substring(0, input.attr("name").length),
                    value = input.val();

                //alert(value);                        // See "Commented Code" and "Alert"
                content[name] = value;
                //alert(JSON.stringify(content));
            }
            if (j == 7) {
                                                       // See also "JSON"
                feed = feed + '=' + JSON.stringify(content);
            }
        });
        alert(feed);
        rows.push(feed);                               // See "Improper Scope"
    });
});

Event Handler -
You've attached the event listener to the document which is fine, but you've used an Id selector to filter it to. There can be only one element with in the document referenced by that Id.1 Unless the #updateBtn element is expected to be destroyed and recreated during the documents lifetime, it would be better to specify that element explicitly.

Unused Variable -
The locations variable is never referenced after it is instantiated, remove it.

Improper Scope -
The rows variable is pushed to, but never read from. If it is to be useful to other code it will need to be moved out of the event handler's scope.

The content variable is never used at this level of the scope, move its declaration to the narrowest scope required.

Exactly One -
According to the HTML snippet you've provided, the .rowUpdate contains the #updateBtn which forces me to assume means there will be only 1 .rowUpdate. Update the markup to indicate this element is special by setting the id instead of the class attribute.

Because we expect this .each function to be invoked once it can be flattened into the parent scope.

Parameters -
JavaScript does not allow functions to be overloaded by parameters.2 the i and v parameters are never used and can be removed. Parameters are essentially variable declarations and should be named accordingly. j would be better named index.

Type Variance -
feed is originally instantiated as an empty array, but you're now adding a string to it. I'm not sure what your intent is, but the effect will be to cast the empty array to an empty string and append label. This is only being done for the 0th element so a simple assignment will do.

Wait, what? - First, nearly every string literal in your code is enclosed in single quotes ('). Suddenly you've begun using double quotes ("). Javascript will allow either, but keep your code consistent.

I'm not sure what the purpose of the .substring method call when your arguments are the full length of the string. this can be removed.

Commented Code -
Remove code that is unused. Only comment out code for the purposes of debugging or experimenting and remove the comment (and code if necessary) when done.

Alert -
alert should not be used for debugging purposes. Use the console methods trace, debug, log, warn, etc..

JSON -
JSON is a format used for serializing data. It should be used to save, restore, and transfer data. Your code should never manipulate JSON directly. Instead use the objects serialized from the JSON string.

After modifying the code based on the review, I end up with something like this:

var rows = [];

$('#updateBtn').on('click', function {
    var feed = {},
        content = {},
        label = $('.rowUpdate td').first().html();

    $('tr.rowUpdate td input[type=text]', this).each(function(index, input) {
        var $input = $(input),
            name = $input.attr('name'),
            value = $input.val();

        console.debug('value', value);
        content[name] = value;
        console.debug('content', content);
    });

    feed[label] = content;
    console.debug('feed', feed);
    rows.push(feed);
});

Then use the actual objects from the rows array if being consumed in other javascript code or send the rows JSON to wherever it is consumed. If for some reason your consumer cannot be modified to use a proper object and relies on the broken JSON string originally in the method, change feed[label] = content to feed = label + '=' + JSON.stringify(content).


Some notes:

data as a name has been criticised elsewhere; I would simply say that any variable or property should be self-explanatory within context. a, b, and c should also have more descriptive names.
You don't need self.ip and self.port in the server - they are only used in the constructor. YAGNI.
You should default timeout to None and forward it directly to the socket configuration. Making your code have different timeout semantics from the socket library is probably just going to cause confusion.
Why return (res) instead of return res?


Ok, I tried to rearrange it a bit:

Corrected stop words (Should only contain lowercase words)
Used Jaccard method to calculate distances
Rearranged code structure
Rewrote it in Python3 with type annotations

You should now add an argument parser and that's basically it.
As far as I understood the task, the final goal was to remove same books.
Now you can play with a threshold argument to find out what strings should be treated the same.
import re
from typing import List, Callable, Set

from nltk.metrics.distance import jaccard_distance
from nltk.util import ngrams

def canonize(data: str) -> str:
    data = re.sub(r'[^\w\s]', ' ', data)  # replace punctuation with space
    data = re.sub(' +', ' ', data)  # replace multiple space with one
    return data.lower().strip()

def jaccard(book_a: str, book_b: str, n: int = 3) -> float:
    return 1 - jaccard_distance(set(ngrams(book_a, n)), set(ngrams(book_b, n)))

def filter_books(books: List[str],
                 book_filter_fun: Callable,
                 cmp_filter_func: Callable,
                 threshold: float = 0.3) -> Set[int]:
    excluded_indices = set()
    for one_book_offset, one_book in enumerate(books):
        if book_filter_fun(one_book):
            excluded_indices.add(one_book_offset)
        for another_book_offset, another_book in enumerate(books[one_book_offset + 1:], start=one_book_offset + 1):
            if {one_book_offset, another_book_offset} & excluded_indices:
                continue
            if cmp_filter_func(one_book, another_book) > threshold:
                excluded_indices.add(one_book_offset)
    return excluded_indices

if __name__ == '__main__':
    stopWords = {'i', 'a', 'about', 'an', 'are', 'as', 'at', 'be', 'by', 'com', 'for', 'from', 'how', 'in', 'is', 'it',
                 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'the'}

    with open('UnifiedBookList.txt') as fin:
        original_books = fin.readlines()

    canonized_books = list(map(canonize, original_books))

    excluded_indices = filter_books(
        canonized_books,
        lambda book: len(book.split()) < 2,  # book name should contain not less than 2 words
        jaccard,
    )

    with open('DuplicatesSorted.txt', 'w') as fout:
        for i, book in enumerate(original_books):
            if i in excluded_indices:
                continue
            fout.write(book)


Are private extension methods a bad thing to use?

In my opinion, extension methods are only a (pretty nice) syntactic sugar for a static helper method. Under the hood, the IL translates your extension method call to a call on the static method, so really it's just an other way to write methods.

The extension method do not have a private access to the type they are extending either, so changing a static method into an extension one will not break any encapsulation.

As for the private keyword, it is indeed the correct accessibility level since your method will not be used outside of your class.

According to MSDN's Guidelines, the major problem of extension methods is the following :

  When using an extension method to extend a type whose source code you cannot change, you run the risk that a change in the implementation of the type will cause your extension method to break.

Also, if someday IWebDriver defines a new method called "WaitForTimeout", your extension method won't be called anymore... But the risk is really pretty low.

So if you think readability is increased by using that extension method, use it - you won't violate any principles or break anything, see it as a nice syntactic sugar.


Sum up all odd numbers between 1 and 2n + 1

Random thoughts:

A comment that indicates what/where read_hex returns might be useful.
mov ebx, 2; mul ebx could probably be replaced with shl eax,1.
While div can be used to check for 'oddness', I believe it is an expensive solution.  How about bt?
In fact, why check for oddness every iteration of the loop?  Check once at the top and count by 2's.
If you aren't using mul/div, then you don't have to have values in specific registers.  This might help you avoid moving values from one register to another so much.

But my biggest piece of advice is to junk this whole approach and start over.

I've tried to calculate some solutions here (let me know if I've got this wrong):

n   result
0   1
1   4
2   9
3   16
4   25

Do you notice anything interesting about the numbers in the right-hand column?  Here's a hint, but before you hover over it, take a moment to try to puzzle it out yourself.  You'll feel better if you do.

   1*1 = 1, 2 * 2 = 4, 3 * 3 = 9, 4*4 = 16, 5 * 5 = 25

Or in other words:

   (n+1)2

With that in mind, there's a much faster/simpler way to calculate results, especially if n is big.


List of tuples generated through list comprehension

Using high-order functions is not much readable:

userRatings search = concatMap (\film ->
  map ((title film,) . snd)
    $ filter ((==search) . fst) $ ratings film)

You need {-# LANGUAGE TupleSections #-} to be able to write (title film,).

Another useful extension is NamedFieldPuns.

getUserRatings search database
  = [ (title,rate)
    | Film{title, ratings} <- database
    , (user,rate) <- ratings
    , search == user
    ]

Writing Film{title, ratings} instead of Film title _ _ ratings is not only a bit shorter, it also allows you to change/reorder fields in Film without updating getUserRatings.

Btw, in my opinion, splitting getUserRatings in several lines adds more readability than rewriting it somehow.


Share data between controllers with service

I think you're on the right track. Having a model object owned by a service and referenced from multiple scopes is good practice. Having more references to the same object in this was isn't a cost you should worry about.

However the example could be improved with clearer layout and more meaningful naming. I would suggest something like the following style.

angular.module('asideApp', ['ui.bootstrap', 'ngAside'])

  .service('AsideService', function ($timeout) {
    var model = {
      aside: null,
      text: null
    };

    function initAside(aside) { shared.aside = aside; }

    return {
      model: model,
      initAside: initAside
    };
  })

  .controller('MainController', function ($scope, $aside, AsideService) {
    $scope.shared = AsideService.model;

    $scope.openAside = function () {
      AsideService.initAside($aside.open({
          placement: 'right',
          templateUrl: 'PropertiesSidebar.html',
          size: 'lg',
          controller: 'AsideController'
        }));
    };
  })

  .controller('AsideController', function ($scope, AsideService) {
    $scope.shared = AsideService.model;
  });


Big-O complexity calculation for a merge and sort function

If N == number of input arrays and M == length of the longest input array then your outer while loop will run M times with the check condition being O(N) so your outer loop is O(MN). The inner loop runsNtimes and the heap insert isO(log(N))so your inner body isO(Nlog(N)). Resulting in a total complexity of O(M * N^2 * log(N))

Some review:

I find the entire code very confusing and hard to read. You keep track of different properties for the same array in disjoint helper arrays (indices and endOfArray) while they should be combined in a single state object.

Also your input is Object[] while obviously you expect a list of int[] so why not express that in your parameter directly like: List<int[]> input.

Your result is a non-generic ArrayList so it's really hard to know what the exact return type of the elements is. Reading through the code it looks like the elements get returned as strings which is probably very confusing for the user - why on earth would a method to which I pass a list of integer arrays return the merged result as an array of strings?

If I read your intention correctly then you want to merge the input arrays, remove all duplicates and return the result ordered. You can write that very nicely with LINQ:

public List<int> MergeLists(List<int[]> lists)
{
    return lists.SelectMany(l => l) // flatten into single collection
                .Distinct()         // remove duplicates
                .OrderBy(x => x)    // sort the result
                .ToList();          // build result list
}

Assuming all N arrays have the same maximum length M then the complexity should be:

Distinct() is in the order of O(N * M)
OrderBy() is in the order of O(N * M * log(N * M))
ToList() is in the order of O(N * M)

Which means the resulting complexity is O(N * M * log(N * M) so you have cut it down to linear in terms of number of input arrays and the code is significantly shorter, easier to read and maintain and very likely to contains fewer bugs.


I have modified your code. The logic is same as you have done. You do not need to create those Integer. Read about Autoboxing. If the input array is large, you will see performance hit for creating Integer. Note that Integer is a class, and not a primitive type in java.

public static void main(String[] args) {
    int[] arr={10,20,10,2,11,10,32,15,15,10,10};
    HashMap<Integer,Integer> result = new HashMap<Integer,Integer>();

    for(int element : arr)
      {
        if(result.containsKey(element))
          {
            result.put(element, result.get(element) + 1);
          }
        else
          {
            result.put(element, 1);
          }
      }
    System.out.println(result);
  }


Spring autowiring in managed beans with support for serialization - is this safe?

Handler is too generic name for a class. Try to find something more descriptive (which doesn't force readers to check the implementation if they want to know what the class does), SerializationHandler, for example.
In Java classes could have only one superclass. If you make it an abstract superclass you can't have another one which might be cumbersome in some cases.

  Inheritance is appropriate only in circumstances where the subclass really is a
  subtype of the superclass. In other words, a class B should extend a class A only if
  an “is-a” relationship exists between the two classes. If you are tempted to have a
  class B extend a class A, ask yourself the question: Is every B really an A? If you
  cannot truthfully answer yes to this question, B should not extend A. If the answer
  is no, it is often the case that B should contain a private instance of A and expose a
  smaller and simpler API: A is not an essential part of B, merely a detail of its
  implementation.

Source: Effective Java, Second Edition, Item 16: Favor composition over inheritance

I'd use composition with a helper class:

@ManagedBean
@RequestScoped
public class Index implements Serializable {
    private static final long serialVersionUID = 1L;

    @Autowired
    SampleService ss;

    public String hello() {
        return ss.sayHello();
    }

    @PostConstruct
    private void init() {
        WireHelper.wireObject(this);
    }

    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
        ois.defaultReadObject();
        WireHelper.wireObject(this);
    }
}

public final class WireHelper {
    public static void wireObject(Object object) {
        Spring.appCtx.getAutowireCapableBeanFactory().autowireBean(this);
    }
}

If you stay with the original implementation: you don't necessarily need implements Serializable here since Handler already implements that interface:

public class Index extends Handler implements Serializable {
    ...
}


Conditionally deleting rows in a worksheet

You have fallen prey to a common temptation: writing a script. The problem with a script, is that it feels clunky and wrong, a bit like macro-recorder code does.

What is this code achieving?

Public Sub DeleteRandom()

Is it deleting random rows? Naming is hard. But it's worth it. Take the time to name things properly. Is it deleting non-essential rows? Then how about..

Public Sub DeleteNonEssentialRows()

So, back to the original question: what is this code achieving?

Turn off screen updating (and set calculation mode to manual?), for performance
Hide status bar and page breaks (for... what for?)
Iterate rows in the used range of Sheet2...
...delete unwanted rows
Copy headers to Sheet1
Restore status bar and page breaks
Restore screen updating

What's the copy headers to sheet1 doing there? Is that part of deleting non-essential rows? No! It's a completely separate concern, and one could argue it's an undesirable side-effect of calling the DeleteRandom procedure: if the calling code wants to copy headings to sheet1, let the calling code do it.

Make a procedure responsible for toggling screen updating, status bar and page breaks (and calculation mode?).. although I seriously question why you would want to hide the status bar at any time - this feels rather surprising, especially since you could instead be using it to convey some "Please wait..." message to the user so they know your code is running and Excel isn't frozen.

Make another procedure responsible for copying the headers from Sheet2 over to Sheet1, and get that concern out of this DeleteRandom procedure.

Now tackle the elephant in the room: make a function responsible for determining whether a row should be deleted or not.

Private Function IsNonEssentialRow(ByVal sheet As Worksheet, ByVal rowIndex As Long) As Boolean

End Function

Notice the sheet parameter: this function is going to work off a worksheet reference, and avoid another big problem with your current code: you're relying on Select and completely assume the active sheet is the sheet you need to be working with - and it might not be - or it could - or the user might have selected another sheet between two executing lines of code - regardless, your code relies on implicit references to Application.ActiveSheet, and that's bad.

Every time you call an unqualified Cells function, you make an assumption.

Keep a reference to your worksheet:

Dim sheet As Worksheet
Set sheet = ThisWorkbook.Worksheets("Sheet2")

...

If sheet.Cells(r, "C") <= 0 Then

Don't refer to them by index - the user is always free to reorder them!

Even better - sheets have a code name, which is basically a global-scope object reference that's ready to use - use it!

if Sheet2.Cells(r, "C") <= 0 Then

Select your sheet in the Project Explorer, and then hit F4 to access the properties toolwindow, and look for the CodeName property of your worksheet; give it a meaningful name, and then you can use that identifier in your VBA code.

Now, back to IsNonEssentialRow. The code should speak for itself - comments are good, but self-documenting code is better.

Dim amountPaid As Decimal
amountPaid = sheet.Cells(rowIndex, "C").Value

Dim compoundCode As Integer
compoundCode = sheet.Cells(rowIndex, "AE").Value

Dim claimType As String
claimType = sheet.Cells(rowIndex, "L").Value

Dim claimStatus As String
clainStatus = sheet.Cells(rowIndex, "J").Value

Dim categoryCode As String
categoryCode = sheet.Cells(rowIndex, "S").Value

Dim preAuth As String
preAuth = sheet.Cells(rowIndex, "N").Value

Dim groupId As String
groupId = sheet.Cells(rowIndex, "AD").Value

Now this looks like a bunch of very related values, doesn't it? How about encapsulating it into a type?

Private Type TRowItem
    AmountPaid As Decimal
    CompoundCode As String
    ClaimType As String
    ClaimStatus As String
    CategoryCode As String
    PreAuth As String
    GroupId As String
End Type

And now you can do this:

Dim item As TRowItem
item.AmountPaid = sheet.Cells(rowIndex, "C").Value
item.CompoundCode = sheet.Cells(rowIndex, "AE").Value
item.ClaimType = sheet.Cells(rowIndex, "L").Value
item.ClaimStatus = sheet.Cells(rowIndex, "J").Value
item.CategoryCode = sheet.Cells(rowIndex, "S").Value
item.PreAuth = sheet.Cells(rowIndex, "N").Value
item.GroupId = sheet.Cells(rowIndex, "AD").Value

Now that you've read everything you needed from the worksheet (once!), you're ready to start evaluating:

Dim result As Boolean

result = result Or item.AmountPaid <= 0
result = result Or item.CompoundCode = vbNullString
result = result Or CInt(item.CompoundCode) >= 2 'todo: define magic number 2
result = result Or item.ClaimType <> "P"
result = result Or StringMatchesAny(item.ClaimStatus,"CAC","OVR","PWE")
result = result Or StringMatchesAny(item.CategoryCode,"D","I","M","N","O","P","Q","R","S")
result = result Or item.PreAuth <> 0
result = result Or Not StringMatchesAny(item.GroupId,"DS","GM","HP","LP")

IsNonEssentialRow = result

For this to work you'll need a little helper function, StringMatchesAny, which returns True if a given string matches any of a specified bunch of values, and returns as soon as it finds a match:

Public Function StringMatchesAny(ByVal source As String, ParamArray values()) As Boolean

    Dim find As String, i As Integer, found As Boolean

    For i = LBound(values) To UBound(values)
        find = CStr(values(i))
        found = (source = find)
        If found Then Exit For
    Next

    StringMatchesAny = found

End Function

Then you could further refine the validation logic to return as soon as one of the rules evaluates to True, but I'll leave that to the reader.

With that validation logic out of the way, your DeleteNonEssentialRows procedure can focus on its task - the final code could look something like this (assuming some ToggleWaitMode(Optional ByVal wait As Boolean = True) procedure is implemented in another module):

Option Explicit
Private Type TRowItem
    AmountPaid As Decimal
    CompoundCode As String
    ClaimType As String
    ClaimStatus As String
    CategoryCode As String
    PreAuth As String
    GroupId As String
End Type

Public Sub DeleteNonEssentialRows()

    ToggleWaitMode

    Dim r As Long
    For r = Sheet2.UsedRange.Rows.Count To 1 Step -1
        If IsNonEssentialRow(Sheet2, r) Then
            Sheet2.Rows(r).EntireRow.Delete
        End If
    Next

    ToggleWaitMode False

End Sub

Private Function IsNonEssentialRow(ByVal sheet As Worksheet, ByVal rowIndex As Long) As Boolean

    Dim item As TRowItem
    item.AmountPaid = sheet.Cells(rowIndex, "C").Value
    item.CompoundCode = sheet.Cells(rowIndex, "AE").Value
    item.ClaimType = sheet.Cells(rowIndex, "L").Value
    item.ClaimStatus = sheet.Cells(rowIndex, "J").Value
    item.CategoryCode = sheet.Cells(rowIndex, "S").Value
    item.PreAuth = sheet.Cells(rowIndex, "N").Value
    item.GroupId = sheet.Cells(rowIndex, "AD").Value

    Dim result As Boolean

    result = result Or item.AmountPaid <= 0
    result = result Or item.CompoundCode = vbNullString
    result = result Or CInt(item.CompoundCode) >= 2 'todo: define magic number 2
    result = result Or item.ClaimType <> "P"
    result = result Or StringMatchesAny(item.ClaimStatus,"CAC","OVR","PWE")
    result = result Or StringMatchesAny(item.CategoryCode,"D","I","M","N","O","P","Q","R","S")
    result = result Or item.PreAuth <> 0
    result = result Or Not StringMatchesAny(item.GroupId,"DS","GM","HP","LP")

    IsNonEssentialRow = result

End Function

Or better yet, do like @Worker suggested and add the row to a range to delete in a single step.


Calculating a Score in VBA based on selected ShapeStyle. Is there a better/shorter way to do this?

You deleted this before I could answer on SO:

Option Explicit
Sub Lead_Score()

    Dim shp As Shape
    Dim RelScore As Long
    Dim QualScore As Long
    For Each shp In ThisWorkbook.Sheets(1).Shapes 'change (1) for your sheet name.
        RelScore = MyRelScore(shp)
        QualScore = MyQualScore(shp)
    Next shp
    Dim Score As Long
    Score = RelScore + QualScore
    Debug.Print Score

End Sub
Private Function MyRelScore(shp As Shape) As Long

    Select Case shp.Name
        Case "CustomerButton", "VendorButton"
            If shp.ShapeStyle = 34 Then MyRelScore = 0
        Case "ProspectButton"
            If shp.ShapeStyle = 34 Then MyRelScore = 15
        'Case ...
    End Select

End Function
Private Function MyQualScore(shp As Shape) As Long

    Select Case shp.Name
        Case "SuspectButton"
            If shp.ShapeStyle = 34 Then MyQualScore = 5
        Case "QualifiedButton"
            If shp.ShapeStyle = 34 Then MyQualScore = 15
        Case "NonQualifiedButton"
            If shp.ShapeStyle = 34 Then MyQualScore = 0
        'Case ...
    End Select

End Function


You have excessive, unnecessary comments.  You wrote your code clean enough that you don't need them.

for (x = 2; x <= Math.sqrt(i); x++) {
  if (i % x == 0) {prime = false}
}

You are wasting your time here.  Once you know the value is not a prime, you do not need to continue looping.  This will reduce your time greatly:

for (x = 2; x <= Math.sqrt(i); x++) {
  if (i % x == 0) {
    prime = false;
    break;
  }
}

if(prime){ array.push(i); factor(number/i, i); }

I'm not sure why you continue finding all the small factors when only the largest prime factors are needed.  In fact, if you are going to do it manually looping over each number, you should start high and work toward the smaller numbers.  A better way to do it, however, would be to use the Sieve of Eratosthenes, as mentioned in the comments on your post.


The Utility class should keep track of its own activation state, otherwise calling .activate() multiple times on the same instance (without calling .deactivate() in between) might cause some problems; also, in the current code, calling .addUtil() after .activate() leaves the instance in a limbo state, where the method name is added to this.utils but isn't actually available on the aided class's prototype, even though the instance is activated. I can imagine this leading to some frustrating debugging on a more complex project. I'd suggest that calling .addUtil() on an activated Utility instance should either immediately activate the added function, or throw an Error (this sounds more consistent with your approach).

(also, as a side note, I wouldn't call this syntactic sugar. Sugar is just simpler way of writing something. e.g. { ...obj } is sugar for Object.assign({}, obj); it doesn't actually add new functionality, which your code certainly does)


ReactJs stateWrapper for nested state objects

In general, React disapproves playing with tis internal lifecycle function such has render or setState has it may cause unexpected behavior later on in your app.

Everything that you put in a Component's state is only readable by this component, and nothing else. As the docs will also tell you, the state may only be modified by the setState function, as it will avoid unexpected behaviors in the re-rendering process.

If some components need to modify what each others are going to render, then the values determining the ouput of their render function should be stored in their first common parent component.

A working live implementation :

class Test extends React.Component {
 constructor(props) {
  super(props)
  this.state = {}
 }

 setText = (source, dest) => event => {
  this.setState({
   [dest]: `Received text: Component n°${source + 1} set my text`,
   [source]: 'I got clicked!'
   })
 }

 render() {
  return (

    {[1, 2, 0].map((dest, index) => <WrappedComponent onClick={this.setText(index, dest)} text={this.state[index]}/>)}

  );
 }

}

class WrappedComponent extends React.Component { //I left this component stateful for future modifications

 render() {
  const { text, onClick } = this.props
  return (

{text || 'No one defined my text (yet)'}

  )
 }
}

ReactDOM.render(<Test/>, document.getElementById('root'))

Here every component's text is stored in their parent component dynamically.


checkIn(id, renter){...}
checkOut(id, renter){...}

You're not actually checking in the id of a book. You're checking in a book. So I would suggest accepting an instance of a book and get the ID from it instead of passing in an ID. You're already doing it for renter, passing in the renter instance, so it shouldn't be different.

this.books = [];

I would suggest using an object {} instead of an array. One problem with using an array, and the ID as index is that you unknowingly increase the length of the array. If you check the length of an empty array after doing this.books[100] = new Book(...), you'll see that it's 101. The array stretched to 101 elements and left gaps in between.

If the book is checked out, you can either null its entry in the object or delete it altogether with delete. It also makes getIndex unnecessary as you can simply access the object directly with id as key.

throw "Book Already Checked In";

I would suggest throwing an instance of Error instead of a string. Error-catching code will most likely expect an instance of Error and not a string. You also lose out on extra information that comes with an instance of Error. Lastly, not OOP-ish. :P

checkOut(id, renter){
  ...
  var dateFormat = require('dateformat');

Dependencies should be done outside anything. Behavior depends on the loader used. If you used RequireJS this would try to resolve dateformat, and load it on the fly. Other module loaders may inline the code, causing this function to bloat.

this.currentRenter = null;
this.checkOutDate = null;

The book shouldn't be aware of its renter. All it should be describing is the book itself.

If you want something like a library card, then I suggest making a property libraryCard that holds an array of LibraryCardRecord objects, each containing the date of checkout and the id of the renter at that date.

  It does not feel right setting a instance variable without a setter or returning a instance variable without a getter.

It's overkill, but it's a good practice to always use a getter and setter. While it's meaningless in the world of all-public JavaScript, it allows you to do intermediate operations before setting or getting. ES6 does have special syntax for getters and setters.


If implementing your own version of a standard routine such as atoi(), some form of explanation (comment) is needed.  For example, is this supposed to be a drop in replacement for atoi()?  Are some aspects deliberately not implemented?  Do you have space restrictions that prevent you from using the standard?  Do you know that certain string combinations will not exist?  This type of information is helpful to anyone reading your code so that they can put things into context.

For the remainder of this review, I shall be assuming that it is meant as an exact replacement for atoi().

The header file limits.h is included, but I do not see any current reason for it to be there.
IS_ASCII_DIGIT() should not be using the magic numbers of 48 and 57.  Values such as '0' and '9' are preferred.
It is customary to surround the macro arguments with parentheses.  This helps to ensure that the argument is evaluated as a whole to cover the case where the argument is a complex expression.
Instead of using IS_ASCII_DIGIT(), I would recommend using isdigit().  This would require including the header file ctype.h.
atoi() is supposed to return an int.  Your routine returns a long.  This indicates either a misnamed routine or an incorrect return value.
The contents of buffer parameter do not change.  It would be better to declare it as a 'const char *'.
There is nothing preventing the dereferencing a NULL pointer.
There is no accounting for white space at the beginning of the string.
There is no accounting for the '+' character at the start of the integer sequence.
There is no accounting for values that are too large or too small to represent.
The standard atoi() routine does not exit or print any message upon a detected error; neither should yours.

For additional information on atoi(), please refer to the following pages:

http://pubs.opengroup.org/onlinepubs/009695399/functions/atoi.html
http://pubs.opengroup.org/onlinepubs/009695399/functions/strtol.html

Hope this helps.


The only real change that pops out at me without touching the record datatypes is to make indexesToInclude an array, you're evaluating it over and over again in that seq comprehension each time. Since it's an array and lookups are fast, and you know its size, you might as well pre-allocate it instead of using a comprehension which will be much faster. Then do a mapi over the rows, and just look up if you want that index in the array.

type Table =
    {
        Rows : string list list
        OnlyColumns : string list option
    }
    member internal x.FilteredRows =
        match x.OnlyColumns with
        | None -> x.Rows
        | Some xs ->
            let headers = List.head x.Rows |> List.toArray
            let isIncluded = Array.init (headers.Length) (fun hi -> xs |> List.exists (fun lv -> lv = headers.[hi]))
            x.Rows
            |> List.map (fun row -> row |> List.mapi (fun i v ->  (isIncluded.[i], v))
                                        |> List.filter fst |> List.map snd)

The most important thing here is that we're no longer indexing into a list (almost always a bad idea in F#), which costs O(n) where n is the index you're indexing into. If you do this every time it gets very expensive!


Procedural way

I usually suggest doing it in a way such that you don't have to perform to many checks. Also, I think that iterating on cells and updating the contour when you find a mine is logically simpler than detecting adjacent mines for each cell.

I will not write code for you (you are trying to learn something in the end), but I will outline the overall algorithm, and offer an object-oriented approach to the problem - which has smaller checks than your current solution and is substantially more readable.

Phase 1: corners

Write, for each corner, a single if statement. If it is a mine, update the three surrounding cells if they are not mines.

Phase 2: borders (- corners)

Iterate over the four borders (with 4 for loops), updating the 5 adjacent cells if they are not mines.

Phase 3 (final): the center of the board

For each cell in the center, if it is a mine, update all 8 surrounding cells if they are not mines.

Object-oriented way

Let every cell be an instance of a class Cell¹. A Cell knows (and exposes) whether it is a mine or not. It also has a public method incrementNeighborCounter()².

Done.

Really, we're done. (Yes, you need to implement Cell, but the essential part of programming [designing] has been done already, and you seem capable of writing the code of Cell).

How does it work? You go through the board once, using the pattern described in the "Procedural way" above. But you don't check if a cell is a mine or not before telling it to increment its counter (because that has been delegated to how a Cell presents itself [mines can even count their neighboring mines too now]), you just call incrementNeighborCounter() and move ahead. Part of the logic is now in Cell and your code is simpler, lighter on the brain and less likely to contain bugs.

¹ - It could be an Interface or an Abstract Class, just don't go overboard and add unnecessary complexity.

² - Name it whatever you feel like, this is not an exact science. Just try to be descriptive and use the name as documentation.

Just in case you are wondering, a very simple Cell implementation could use a boolean for being a mine or not and an integer for counting how many mine neighbors it has.


Wrapper functions for terminal capabilities

A few quick comments:

You should declare all internal functions and variables static to avoid polluting the global namespace. (You'd do this in a C++ program as well, but would probably use an unnamed namespace. I'm not sure what the D equivalent is).
Since you have state (implicitly and explicitly via BackupProperties) I'd recommend using an object oriented approach exposing an opaque pointer to maintain it, even if there is only one Terminal instance it's (IMO) a better approach. Otherwise you should at least ensure that TerminalMakeRaw isn't called twice without corresponding calls to TerminalReset.
You should also consider that at some point you'll probably want to have callbacks of some sort to notify the users of your library when/if the window size changes and so on.


A program with a function that converts a string of digits into an integer value

is this code efficient ?

No.  Rather than using the unnecessary powe(), lent(),

simply scale by 10 each operation; and
use - '0'.

.
char sn[20];
//scanf("%s",sn);
if (scanf("%19s", sn) == 1) {
  int z = 0;
  for (int i = 0; sn[i] >= '0' && sn[i] <= '9'; i++) {
    z = z*10 + (sn[i] - '0');
  }
  printf("%d",z);
}

Even better code would detect overflow and maybe use unsigned and/or wider types.


I think what greybeard is getting at in the comments is that you could get away with squishing these images much more than you presently are. It sounds like you're basically using the reduced versions as thumbnails, but these "thumbnails" are almost twice the width (over three times the area) of a standard HD monitor.

Dropping basewidth to 1920 (or possibly much lower still) seems like a good idea. Contrary to greybeard, I think your JPEG "quality" setting is fine, but you could play around with different variations of smaller-vs-larger and crisp-vs-compressed.

A minute of googling suggests that PIL is in fact the normal choice for image handling. Maybe there's something better, but I'll suppose not. Given that the originals are large (50MB? more?), it may simply be that there's a lot of work to be done. That said, there are some things you can try.

General hardware: Given that this is a heavy task, you may have some luck just running the same code on a fancier computer. This is an expensive option; even if you feel like throwing money at the problem still do plenty of research first.
Storage hardware: One possible bottleneck is the hard drive you're reading from and writing to. If you can easily try the task against a different (faster or slower) harddrive while keeping everything else the same, that may be informative.
Memory: Does you computer have a lot of RAM? Is that memory available for this python script to use? If you have a way of making half the currently available memory unavaliable, check if that makes the process twice as slow.
Memory leaks: I see the line im = Image.open(filename), and looking at the docs suggests that you should probably have a call to load or more likely close someplace.
Parallelism: Your computer probably has multiple processor cores. It's hard to say if or how well this script is using all of those cores. If you try running your script twice at the same time (against non-overlapping target sets), how much slower is each concurrent process?
It's not clear if ANTIALIAS is a valid option to the resize method in the 3.x version. Try NEAREST.
Oh hey there's a thumbnail function that affects the way the file is read from disk!. Playing around with the underlying draft function may also be helpful.

And because this is code review:

Move your format and quality constants up to the same place as basewidth.


Without some sample inputs I can only really comment on how the code reads, less on how it runs.

First, this should really be a few functions, I'll indicate below where might be good places to separate the code.
Why import os and os.path? Just import os then call os.path.<something>
You don't need to wrap i, captcha_image_file in brackets when using enumerate(); enumerate() also takes an optional start argument; so, using f-strings as well, you can write:

for count, captcha_image_file in enumerate(captcha_image_files, 1):
    print(f"[INFO] processing image {count}/{len(captcha_image_files)}")

count typically indicates starting from 1, where pos or index would indicate starting from 0. Avoid using short, non-descriptive variables like i.

The "Hack" can be shortened nicely with a ternary operator:

contours = contours[0] if imutils.is_cv2() else contours[1]

I would separate the block immediately following this into a function, which would yield, rather than append to a list. This will be faster, cleaner, and get rid of dummy variables.
I would use itemgetter rather than a lambda function here, entirely a style choice, though.
Contrary to what I said earlier, I actually think using x, y, w, h is fine here as they are commonly understood to be the x and y directions, width and height.
Again, this last block (for letter_bounding_box, letter_text ...) should be its own function.
Really, I think this whole piece of code should be a class, the globals can then be class variables, and you can have three methods. You can then have a main() function which calls these methods and keeps track of which file you're on etc. This main() should sit inside:
if __name__ == '__main__':
Overall comments are good, somewhat excessive in parts but better than too sparse.

The bulk of the improvements would come from separating out your code into readable methods. Functions / methods should generally have one clear purpose. This also has the advantage of making generators easier to use as you can easily yield rather than constantly making lists.


Logging leads when interactions happen for a contact

I'm not sure how you intend to use this class, but the call method is very fishy. This method seems to do one of three things: convert_lead, activate_lead or stale_lead. The choice of which of them should actually be executed is made in the options argument during object construction.

This is not very easy to understand from reading the code, and I can't really see the reasoning behind it. Is it an implementation of a Command pattern? that is not very ruby-like.

Since all this class actually does is quite basic delegation (@lead.converted!, @lead.stale! or @lead.active!) I would consider foregoing this class altogether, and simply doing the action. It is unnecessarily long and convoluted, and hides more than explains what it does.

From your comment below I understand that LeadGeneration should be a Service Object. It is true that service objects may have a single method called call, as is suggested in this blog post:

  Service objects are responsible for retrieving and/or manipulating
  data — essentially any work that needs to be done that you might have
  put in a controller or model object before. They typically only have
  one method, which I like to define as “#call” (they're usually named
  something like PictureCreationService, so naming the method #create
  would seem redundant).

But note, though, the reason a single method call is allowable - it is apparent from the class name exactly what the method should do.
If your service object was called LeadConversionService, then a call method would be good enough.

Being a service object, it is even more important than usual in ruby for the class to be small and transparent.

If you want to go to the extreme SRP suggested in the quote above, you'd have three classes, each with #call and #allowed? methods:

class LeadConversionService
  def initialize(lead)
    @lead = lead
  end

  def call
    @lead.converted!
  end

  def allowed?
    !@lead.new_record?
  end
end

OR, you could be a little less extreme, and decide the LeadGeneration (or maybe LeadLifeCycleService?) is a good enough scope, and let it have three method:

class LeadLifeCycleService
  def initialize(lead)
    @lead = lead
  end

  def convert!
    raise LifeCycleException if @lead.new_record?
    @lead.convert!
  end

  def activate!
    @lead.active!
  end

  def stale!
    raise LifeCycleException if @lead.new_record?
    @lead.stale!
  end
end

Writing this solution makes it obvious again, that this service doesn't do much, since it only delegates (so it doesn't even save code in your model...). All it does is validates pre-conditions to your actions, which may be better handled by a state-machine, as @Flambino suggested.


Solution for swapping ArrayList data members with another

In Solution 3, assuming you initialize mp31 and mp32 to null, you can replace this

//Check if we found track 1
if(vectorMain.contains(mp31)){
    //Set temp var new track number
    mp31.setTrackNo(t2);
}

With:

//Check if we found track 1
if(mp31 != null) {
    //Set temp var new track number
    mp31.setTrackNo(t2);
}

There is really no need to check if the arraylist contains the object since you used the get(...) method on the arraylist to get it in the first place. Therefore, you know that if the object has been initialized (is not null), the arraylist contains the object.

Also, I would change the method signature for getMainIndex to also take the list to search in as an argument to the method. In that case, you don't need to have two methods (with probably a lot of duplicated code) getMainIndex and getFavIndex can be the same method, getIndexInList(int trackNumber, List<MP3Track> list).

I am not sure how your getMainIndex method works at the moment, but I assume the code mp31 = vectorMain.get(getMainIndex(t1)); within the loop is the same thing as mp31 = track;. Therefore, you can replace this entire loop:

for(MP3Track track : vectorMain){
    if(track.getTrackNo() == t1){
        //If track 1 found assign it to temp var
        mp31 = vectorMain.get(getMainIndex(t1));
    }
    if(track.getTrackNo() == t2){
        //If track 2 found assign it to temp var
        mp32 = vectorMain.get(getMainIndex(t2));
    }
}

With either:

for(MP3Track track : vectorMain){
    if(track.getTrackNo() == t1){
        //If track 1 found assign it to temp var
        mp31 = track;
    }
    if(track.getTrackNo() == t2){
        //If track 2 found assign it to temp var
        mp32 = track;
    }
}

Or:

int index = getMainIndex(t1);
if (index != -1)
    mp31 = vectorMain.get(index);
index = getMainIndex(t2);
if (index != -1)
    mp32 = vectorMain.get(index);

As for Solution 2, this code here does not guarantee uniqueness of trackNo if two songs have the same title:

for(MP3Track track : vectorMain){
    if(track.getTrackNo() == t1){
        s1 = track.getTitle();
    }
    if(track.getTrackNo() == t2){
        s2 = track.getTitle();
    }
}

for(MP3Track track : vectorMain){
    if(track.getTitle().equals(s1)){
        track.setTrackNo(t2);
    }
    if(track.getTitle().equals(s2)){
        track.setTrackNo(t1);
    }
}

What you are essentially doing here is that you first scan through the list to get the title of the matching songs, and then you search for their title to change their track number. Why not change their track number within the first loop? You don't need all the three loops you have in Solution 2. Instead, search through vectorMain once and change the track numbers there, then search through vectorFav and change it there.

Some other comments:

I am not sure about how exactly you are using these two vectors and your MP3Track objects, or your trackNumber values. It seems to me as if whenever you swap track numbers, you do it in both of the lists. Therefore, perhaps you should use the same object references in both of the list. Don't create new MP3Track objects to place in vectorFav, you can re-use the same objects. That way, it will be enough to search only the vectorMain for the tracks, because it's the same object it will also update in vectorFav. As I said, I don't know exactly how you are using the trackNumber values so this might fit for you at the moment, but if it doesn't fit then you might want to change your design of the project.

As far as I have seen of the usage of getMainIndex and getFavIndex, you only use those methods to first get the index in the list, and then get the MP3Track object itself. Consider returning an MP3Track (the object itself) instead of an int (the index of the object in the list). Then you should also rename the method to reflect this change in behavior.


Selection sort review. Does it look good?

You don't need two arrays, it works with one too, simply swap the
values. This needs less memory.
According to this:

int i, high = 0, k, j = 9, store;

j is always one less than the size of the array. Don't use magic numbers, use the constant.
If you want to reuse this selection_sort it would be adviseable to
add a parameter for the size, so you don't need the global constant.
In the inner loop you also iterate through the array parts which also have been sorted. (This may also be the reason you choose to use two arrays)
The result may be wrong if you'd only have negative values in the array (due high = 0)

Here my improved implementation:

void selection_sort(int *num, size_t size)
{
    size_t k, i, j, store; // for indexes
    int high, swap; // for values

    // no need to sort if the array is short enough
    if(size <= 1) return;

    high = INT_MIN; // set the highest number to the minium
    j = size - 1;

    for(k = 0; k < size; k++, j--)
    {
      for(i = 0; i <= j; i++)
      {
         if(num[i] >= high)
         {
             high = num[i];
             store = i;
         }
      }

      // swap the highest number with the number at the last position
      // in the array
      swap = num[j];
      num[j] = num[store];
      num[store] = swap;
      high = INT_MIN; // reset the highest number
    }
}

There is also a similar implementation on Wikipedia


What is the fastest way to record the names of each file in a directory?

Calling realloc in every iteration makes the code really slow. Algorithmically it is in \$\mathcal O(n^2)\$ since realloc already has complexity \$\mathcal O(n)\$. Plus, you are calling it interleaved with malloc for the name of the directory entries.
The performance of your program depends very much on the specific memory allocator. It might be very fast or very slow, probably somewhere between \$n\$ and \$n^2\$.
To fix this, you should use the well-known pattern of having a triplet (pointer, length, capacity) to represent the growing buffer of directory entries.
Ideally you define a separate struct for this, together with an append function. That way, the function that reads the directory entries doesn't have to fiddle with realloc directly.


Have I prepared this prepared statement well?

Single line if statements combined with column aligned spacing:

Never ever do this. Never. A quick glance at the code you posted looks like this:

function wyswietl($rekord, $tabela) {
    $lacz = lacz_bd();

    if (!$zap_preparowane = $lacz->prepare("SELECT {$rekord} FROM {$tabela} where email = ?"))
    if (!$zap_preparowane->bind_param("s",$_SESSION['prawid_uzyt']))
    if (!$zap_preparowane->execute())
    if (!$zap_preparowane->store_result())
    if (!$zap_preparowane->bind_result($binded_result))
        while ($zap_preparowane->fetch()) {
             echo $binded_result;     //htmlspecialchars? printf("%s ?
        }
    $zap_preparowane->free_result();
    $zap_preparowane->close();

    $lacz->close();
}

My first thought was "why are all these if statements chained together with no indentation?". Then I noticed the horizontal scrollbar. Now, I see that the code does something much different. You should not make someone reading your code have to work this hard to know what the code is doing.

On top of that, I don't like the use of single line if statements and column aligned spacing, in general. Single line if statements lead to people missing the executed line because a line for the if clause and a line for the true clause is so much more prevalent. Column aligned spacing is easy enough to write the first time. But when you have to come back and edit the code, you might have to make changes to lines just to maintain the spacing.

Repeated code:

The code that prints the error message is repeated code. You can easily make it a function.

function log_error($zap_preparowane, $header) {
  echo $header ." nieudane: (" . $zap_preparowane->errno . ") " . $zap_preparowane->error;
}

Now if you want to change how the errors are handled, it is easily done in one place.

The error handling doesn't stop execution of the code. If you fail to properly prepare the SQL statement, it is unlikely that anything else will execute correctly.


Console calculator, takes a string as input (like: 2+3*4-1+3) and outputs the result

Some quick observations:

Don't use using namespace std
Prefer using \n over std::endl
Prefer prefix over postfix
You're mixing C and C++ here. Use <cstring>/<string> (depending on what you need) instead of string.h. For input have a look at the C++ I/O library
Some of your code is windows only ( system("pause") and system("cls") )
Don't define more than one variable per line
Comparing floats with ==/!= might be unsafe
There are several (probably unwanted) type conversions which you can catch by enabling warnings in your compiler of choice
Putting all the code into the main function makes this hard to read. It's better to split it up into functions
Try to avoid overly short variable names. They should always express intent to make reading the code easier.


Command to measure CPU time and RAM usage of process while making sure it does not go over certain ressource limitation

Command="$3"
for (( i=4 ; i<="$#"; i++)); do
    Command="${Command} ${!i}"
done
# …
${Command} &

Much cleaner to just reference the end of the $@ array directly.  Since you're running the commands later, and would like to keep quoting intact, use an array:
declare -a Command=( "${@:3}" )

"${Command[@]}" &

# Break if the process has stopped running
if [[ ${mem} == "" ]]; then
    break
fi

The idiomatic way to test for process existence is with kill -0, as in:
 kill -0 $pid || break

Since $mem is a number, or empty, an arithmetic test is good too:
(( mem )) || break

if [ "${mem}" -gt "${MemoryPeak}" ]; then
    MemoryPeak=$mem
fi

if [ "${MemoryPeak}" -gt "${MaxMemory}" ];then
    #echo "process consumed too much memory"
    kill ${pid}
    break
fi

Prefer parentheses over single brackets (or double brackets) for arithmetic operations:
 (( MemoryPeak = ( mem > MemoryPeak ? mem : MemoryPeak ) ))

 if (( MemoryPeak > MaxMemory )); then # etc.

 # If it consumed too much CPU time, then kill

You're measuring wallclock time, not CPU time.  There's also some slop:  timeBefore is recorded when the script collects it, which might not be close to the binary invocation time.  Better to read the times and cputimes values from ps, and calculate with those:
 MaxElapsed= # …
 MaxCPU= # …
 # …
 read mem dt ct <<< $( ps --no-headers -o rss,etimes,cputimes -p$pid )
 # …
 if (( dt > MaxElapsed || ct > MaxCPU )); then # …

timeAfter=$(date +"%s")
timeUsage=$((timeAfter - timeBefore))

See timing comments above.  If you make the outer loop condition kill -0 $pid, you can simply reference $dt here.

Putting it all together:
 MaxMemory=$1 MaxElapsed=$2 MaxCPU=$3 Command=( "${@:4}" ) MemoryPeak=0
 "${Command[@]}" & pid=$!
 while kill -0 $pid; do
    read mem dt ct <<< $( ps --no-headers -o rss,etimes,cputimes -p$pid )
    (( mem )) || break
    (( MemoryPeak = ( mem > MemoryPeak ? mem : MemoryPeak ) ))
    (( MemoryPeak > MaxMemory || dt > MaxElapsed || ct > MaxCPU )) && kill $pid && wait $pid  # loop conditional will break for us
done
echo "MEM $MemoryPeak ELAPSED $dt CPU $ct"


let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext!

The type annotations are not necessary, the Swift compiler can infer
the type automatically:

let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext!

request.returnsObjectsAsFaults = false

This makes no sense here because you don't want to access
any properties of the returned objects. On the contrary, only the
managed object ID is needed to delete objects and no properties need
to be fetched at all, so this should be replaced by

request.includesPropertyValues = false

to increase the performance.

I prefer to cast the return value from the fetch request immediately

let incidents = try context.executeFetchRequest(request) as! [NSManagedObject]

this makes both the type annotation : AnyObject and the cast
as! NSManagedObject obsolete.

You have to decide how an error should be handled, but I would
at least print some message when running in debug mode

} catch let error as NSError {
    debugPrint(error)
}

to detect possible problems.

Starting with iOS 9, objects can be deleted directly in the store
without loading them into memory.
This would look like this:

func deleteIncidents() {
    let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDel.managedObjectContext!
    let coord = appDel.persistentStoreCoordinator

    let fetchRequest = NSFetchRequest(entityName: "Incidents")
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    do {
        try coord.executeRequest(deleteRequest, withContext: context)
    } catch let error as NSError {
        debugPrint(error)
    }
}

There is a catch (!) however: Existing objects already loaded into
the managed object context are not automatically removed, and
doing so it a bit tricky. See https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/ for more information.


Well, first of all the description is wrong.
strbin_to_dec() should be strbin_to_i(), because it parses a base-2-number, instead of converting it to base-10.

Next, refrain from using your own defines as much as possible, if there is an appropriate type already.

Third, assuming correct input is generally naive. Assuming corrupted or malicious input is far wiser.
Your code breaks if any character is neither 0 nor 1, or if the number is too big for an unsigned.

Finally, it's more straight-forward to parse from beginning to end, only needs a single pass, and is probably due to both reasons slightly more efficient, if you really care. Still, what input you get might be important to the determination.

Regarding your question whether byte-operations are faster than wider operations, probably only on 8bit-microcontrollers or the like.
Still, micro-optimisations are hard to do correctly, and have hardly any significant effect, especially if you don't know what to optimise for: Source clarity (should be the default), source size, compiled code size, code throughput, memory bandwidth, ...
Let's hope you chose the right optimisation-options, or the point is moot anyway.


How to prevent SQL injection PHP and MySQL?

So, you want to defend against possible injection attacks. That's great. But I struggle to understand why you're bothering to escape all parameters in various ways, but then let the whole thing down by not using the easiest, fastest and rather safe tool you have: prepared statements.

First off, are prepared statements 100% safe, all of the time? No, I'm not going to postulate that. Simply because I don't have a solid basis (as in proof) that it is.
Have I seen injection attacks of the first order that managed to circumvent the security gotten from prepared statements? Nope. Never. So, as long as you're not using mysqli_multi_query, don't use user-data in tandem with data gotten from another query and you don't allow yourself to get bogged down in endless sub-queries or JOIN queries without aliases, you should be pretty safe.

So, first step in defending against inject: use prepared statements.

Now, look at what you're doing with your data:

$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysqli_real_escape_string($db_conx, $email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
$password = md5($password);

Email:
What's wrong with how you process the email? A couple of things.

stripslashes: can potentially change email addresses that are perfectly valid! However unusual an email address is, you have the responsibility to write code that can handle valid input.
This is a valid email address: "very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com, believe it or not. stripslashes, then, is NOT an option. See other wacky email addresses here.
striptags: I take it that, from the example here, and on the wiki I linked to, it's self-evident that this function call is right out, for the same reasons.

What to do, then? Simple. PHP comes with an email validator function out of the box, simply use that:

if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
    $email = $_POST['email'];
else
    //error.

If you want to be lenient towards your users, which I'd encourage, you can add a sanitation call to this code. If the email address posted contains invalid chars, then notify the user and ask him/her if he meant to write a valid version of the address:

if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{//not the !<-- not valid
    echo $_POST['email'], ' is not a valid email address. Did you mean: ',
        filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);//<-- sanitize
}

Password:
What's wrong with the password? A few things.

first off: you're going to hash the password. An md5 hash is guaranteed to contain only hex chars (0-9a-f). These chars pose no risk at all in terms of injection.
If you want to inform the user about him/her using an "invalid" password, however, a regex can come in handy. However, the one you're using now is not going to work!
preg_replace: You are not replacing what you thing you are. In PHP, a regex has to be delimited by special chars (for example: /a/ matches a). Of course, delimiters like [ and ] are allowed, too. That means that PHP doesn't interpret your pattern as a character class, but rather.

It is translated to this:

preg_replace('/^A-Za-z0-9/', '', $string);

You're matching the beginning of the string, followed by the literal string: A-Za-z0-9. This will be replaced, the rest is left as is.
Just test:

echo preg_replace("[^A-Za-z0-9]", '', 'Hello World!');

Which should replace the space and exclamation mark. The actual output, however, is: Hello World!.
I take it you were actually going for something along the lines of:

echo preg_replace('/[^A-Za-Z0-9]/', '', 'Hello World!');

Which echoes HelloWorld. But actually, it's a good thing this code doesn't work. You're actually prohibiting users from entering a safer password. Which pass, according to you (and according to common sense) would be most likely to be cracked using a simple dictionary attack:

mySimplePass
//or
|\/|y=5!mpL3_P@55

Allow complex passes, you have no reason not to.

md5: Ok, it's good to see you're hashing passwords. It really is. But md5 is deemed unsafe. Collisions have been spotted in the wild, and thus it's likely that there are several passwords that will be accepted as valid for a single hash.
sha1 is a safer option, but best switch to blowfish.

Another niggle when using hash functions is: never simply hash the pass. use salt. If I were to create a dummy account, and at some point saw the hash you were using, I could figure out what type of hashing algorithm you are using, and I would know you're not using salt.
In that case, all I need is to see someone elses salt and set my machine to work, generating random strings and computing the hash. For every match I find, I have access to another users' account on your site.

Couple this to your policy of forcing people to use weak passes and you must admit, you have a huge security problem on your hands.
In case you don't know what I mean by salt:

$hash = sha1($pass, 'S0me->53cr3t<>5tr!~');

That way, I'd first have to generate random strings, in the off chance I find the salt, which is of unknown length, can contain any char, and even when I get a matching hash (in case of md5 especially), I could be dealing with a false positive (collision...).

Moving on: Like I said: use prepared statements, instead of just stringing arguments into a query string, for starters. Then, do away with the mysqli_num_rows call. All your code is contained within a while loop. If there are no results to be found, the loop body won't be executed. Instead, I'd simply write a single query:

$stmt = mysqli_prepare(
    $db_conx,
    'UPDATE members
        SET lastlogin=NOW()
    WHERE email = ?
      AND password = ?'
);
//after validation, of course
mysqli_stmt_bind_param($stmt, 'ss', $email, $pass);
mysqli_stmt_execute($stmt);
if (mysqli_affected_rows($db_conx))
{
    mysqli_stmt_close($stmt);//<-- CLEAN UP AFTER YOURSELF!
    //update was successful
}

Of course, this code doesn't select username, first and last name from the table. If you want to do so, then you'll have to keep the second query, still.

There, too, your code can be improved on. SELECT * is something that can, and should be avoided as much as possible: only SELECT what you need!
If the supplied email and pass are valid, you already have that data, so there's no reason to query for it again. You only need 4 fields: the id, user-, first- and last name.
Not only is selecting what you need easier on your server, it makes life of the people who end up maintaining your code (and that includes you, yourself) a lot easier if ever something needs to be changed/added a couple of weeks from now:

$stmt = mysqli_prepare(
    $db_conx,
    'SELECT id, username, firstname, lastname
     FROM members
     WHERE email = ?
       AND password = ?'
);
mysqli_bind_param($stmt, 'ss', $email, $pass);
if (!mysqli_stmt_execute($stmt))//returns false on success
    throw new RuntimeException('Failed to execute statement');
//get the result first
$result = mysqli_stmt_get_result($stmt);
//or $row = mysqli_fetch_assoc($result)
if ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
    $_SESSION['id'] = $row['id'];//and so on
    //AND CLEAN UP!!
    mysqli_free_result($result);
    mysqli_stmt_close($stmt);
}

As you can see, the mysqli_* extension offers a lot of powerful features, and tools. In return, it does require you to take care of a couple of things: freeing the results, closing the statements when you're done playing with them etc...
It takes some getting used to at first, but it's not that hard, really.

If you find this a bit too wearisome (can't blame you if you do), then take a look at the alternative extension PDO.
It offers a cleaner, less verbose API. The trade-off: it's OO-only (IMO, a good thing), slightly less powerful and marginally slower, but not as if you'd notice. Other things are far more likely to be the bottleneck.


Computer tries to guess your inputted number

You can simplify this:
    do
        guess = rand() % highRange + 1;
    while (guess <= lowRange);

Why not get a value in the correct range then add lowRange.
    // I did not check the maths there
    // may be an off by one error in this
    // Please verify the range is correct.
    guess = rand() % (highRange + 1 - lowRange);
    guess += lowRange;

I am not complain about you using rand() in this extremely simple example code. But you should note that:

rand() is not very random.
rand() % x not all values in the range [0-x) are equally probably.

Please have a look at the C++ standard random number generator (you are using the C version).
http://www.cplusplus.com/reference/random/

You use the correct C++ header files:
#include <cstdlib>
#include <ctime>

This puts all the functionality in the std namespace. Though it allows implementations to also add a definition in the global namespace (though this is optional). But this optional bit is what allows it to compile on your system (but you can't assume it would work everywhere).
So the functions you use should be prefixed with std::.
std::srand(static_cast<unsigned int>(std::time(0)));
^^^^^                                ^^^^^

....
std::rand() % highRange
^^^^^


This code seems much better than before, so congrats. Here are a few more things to adjust:

Move your main game loop into a function and call it in an if block like this:

if __name__ = "__main__":
    #call your main function

This is so that people (including yourself) importing your module don't immediately get a chess window popping up.
You factored out the Piece baseclass from all of the pieces, simplifying that code quite a bit. This is good! But now you should finish the job of merging the different coloured pieces into the same class. They are extremely close to identical. You can pass in all of the values that distinguish them (colour, position, etc.) in the __init__ method when you initialize them.
At this point, with the number of global variables and global functions operating on those variables, you should group them into a GameState object to encapsulate them.
I will second the recommendations to replace numbers that are clearly constants with variables to improve readability, as well as follow the style guidelines in PEP 8.

Beyond that, I think the changes we're looking at are either implementation specific (you would do it differently depending on what this is supposed to accomplish, and what your goals are), are too minor to bring up one by one, or down to personal coding style.


4 solutions to leetcode 202. Happy Number have almost same performance

Solution #2:

class Solution2:
    def isHappy(self, n):
        # ...
        while n != 1:
            if n in s: return False
            # ...

    return n == 1

You are looping while n != 1, without any break statements. There is no need to test n == 1 at the return statement at the end.  Just return True.

Solution #3 returns None if 0 is given as input, instead of returning True or False.

Solution #4 becomes an endless loop if 0 is given as input.

Are there any other stopping conditions other that n == 0, n == 1 or n == 4?  It isn't clear that all unhappy numbers result in a loop containing the value 4, so the validity of this approach is in question.

Update: Actually Wikipedia provides a clear argument that unhappy numbers will arrive in a loop containing the value 4, so this approach is valid, but should included a comment with a link to that proof.

In all your solutions, your loop is testing at least two conditions, such as both n != 1 and n is s.  Why not initialize s to contain a 1 (or even just leave it as an empty set), and then only test n in s.  No special cases.

def is_happy(n):
    s = { 1 }

    while n not in s:
        s.add(n)
        n = sum(i * i for i in map(int, str(n)))

    return n == 1

Update:

Since Wikipedea has proof that all positive unhappy numbers end in the sequence 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → ..., and happy numbers end in the sequence 1 → 1 → ..., you can create a set of these termination values (including 0 → 0 → ...), and no longer needed to maintain the set of "seen" values.  By using all numbers in the unhappy loop, we can terminate the search up to 8 iterations earlier over just checking for n == 1 and n == 4.

def is_happy(num):
    # See https://en.wikipedia.org/wiki/Happy_number#Sequence_behavior
    terminal = { 0, 1, 4, 16, 20, 37, 42, 58, 89, 145 }

    while num not in terminal:
        num = sum(i * i for i in map(int, str(num)))

    return n == 1

Finally:

follow the PEP-8 standards (avoid mixedCase function/method names),
Stop writing classes!


Those poor knights.... what did they do to deserve that?

But, there is a mathematical treat that allows this problem to be solved in O(1) time, and space.

What does that mean? Well, it means that solving the problem for 1 knight takes just as long (and just as much memory) as solving it for 10, or 1000, or 1000000000000000 knights. How is this possible?

There's a pattern that emerges when you study this problem. If there is 1 knight, then knight 1 survives. If there's 2, then knight 1 survives, and, if we map this out for say the first 32 knights, we get:

1 -> 1
2 -> 1
3 -> 3
4 -> 1
5 -> 3
6 -> 5
7 -> 7
8 -> 1
9 -> 3
10 -> 5
11 -> 7
12 -> 9
13 -> 11
14 -> 13
15 -> 15
16 -> 1
17 -> 3
18 -> 5
19 -> 7
20 -> 9
21 -> 11
22 -> 13
23 -> 15
24 -> 17
25 -> 19
26 -> 21
27 -> 23
28 -> 25
29 -> 27
30 -> 29
31 -> 31
32 -> 1

Note that, at the powers-of-2, the surviving knight skips back to knight 1. Also, between the powers, the surviving knight increments by 2 (and is always odd).

The pattern is also easy to enumerate - find the largest power of 2 that's less than (or equal to) the count. Find how many knights there are after that power, double it, and add one.

It would look like this:

import math

def low_power(input):
    return 1 << int(math.floor(math.log(input, 2)))

def survivor(count):
    return 1 + 2 * (count - low_power(count))

So, calling survivor(16) will return 1. survivor(60) returns 57.

But, you can do crazy numbers now too, like survivor(98765432123456789) is 53415676171057707

See this code running on ideone: Knights

Note that you have now confirmed you are using Python 3.4. Python 3.1 introduced the bit_length() method. This makes the determination of the power much easier (from a programming perspective - bitlength can be thought of as an implementation of the log2):

def low_power(input):
    return 1 << (input.bit_length() - 1)

The same code running bit_length in python 3 is shown here in ideone (also contains correct parenthesis for python 3 print statements).


Override setContentView instead of a different onCreate that receives the layout id.

public class BaseActivity {

    protected void setContentView(Int layoutResID) {
        super.setContentView(layoutResID);
        ButterKnife.bind(this);
    }

}

Overriding this makes it more consistent (no custom onCreate) with the android style, I think.

I dont see any problem of using it, its cool since everytime you create a new activity its already there so just add @BindView and it works.

Other alternative is not using ButterKnife but Kotlin and Kotlin Extensions, take a look.

https://kotlinlang.org/docs/tutorials/android-plugin.html


You can simplify (and sometimes speed up) things like this

try:
    a = memcache.get('ads')
except KeyError:
    a = Ad.all().filter('modified >',
                            start).filter('published =',
                True).order('-modified').fetch(count)
    memcache.set('ads', a)

It's (often) slightly faster in Python to avoid the if statement.

After measuring that with timeit, you should rename the variable a.  That's a poor name.


Nothing would make a reviewer happier than help you jam the networks of an innocent neighborhood. (sarcasm)

Mutually exclusive conditions

Can line match Address, Channel, etc at the same time? If not, then the multiple [[ ... ]] are needlessly evaluated, and it would be better to rewrite them using elifs:

    if [[ "$line" =~ Address ]]; then
        m=${line##*ss: }
    elif [[ "$line" =~ Channel ]]; then
        chn=${line##*nel }
        chn=${chn:0:$((${#chn}-1))}
    elif
        ...

Avoid multiple statements on a single line

Multiple statements on a single line like this can be hard to read:

mac+=($m);essid+=($e);channel+=($chn);level+=($lvl)

It's better to split this line to have just one statement per line.
That way the code will be nicely readable from top to bottom,
without having to carefully read sideways too.

Conditions on non-empty values

A non-empty string is falsy in Bash,
so instead of [[ "$network" != "" ]] you can write:

[[ "$network" ]]

Simpler parameter expansion

An easier way to chop off the last letter of a string is using parameter expansion:

chn=${chn%?}

Function declaration style

Instead of this:

function scan {

The recommended style to declare functions is this:

scan() {


Using twitter4j to fetch usernames that retweeted me

General Notes

Follow Java naming conventions.  Class names should have EachWordCapitalized, and variable and method names should be inCamelCase.  Also, class names should be nouns, and method names should be verbs.
For collections, the overarching interface is usually used.  (i.e., List<String> names = new ArrayList<String>();)  Not really that important in my view, but it adds some style points according to some authorities.
Most of the int literals should be true constants.  So for example, you would have private static final long WAIT_TIME = 12000; at the top of your class, and then call Thread.sleep(WAIT_TIME).  It doesn't matter for this small application, but for large-scale projects this will allow you to change the setting globally just by modifying this one value.  Otherwise, you'll be doing a lot of digging through your code, and you're guaranteed to forget to change that one spot it mattered most.  Every.  Single.  Time.
Why are you bothering to convert the ArrayList<String> into a String[] before returning it?  You may as well just change the return type of the method to List<String>.  In general, it's best to avoid primitive arrays and use these data structures.  And they can also be used in the enhanced for loop in your main method.
You should hardly ever swallow Exceptions and do nothing about them.  Again, it's pretty trivial in this case and doesn't really matter, but if you're looking to develop good programming habits, start logging and doing safety checking and all that now.  It'll make your life a lot easier down the road.

Also, this method name made me die a little on the inside: getjoereddingtonTwitter()


Schema.org

Assuming that the Thing represents your organization/business on each page of your site, you should try to find a more specific type, e.g., TravelAgency as you point out in the comments.
Every Schema.org type is also implicitly a Thing, so every type can use the basic properties from Thing.

The description property is not for the full content, but only for a "short description" (of the TravelAgency in your case, so it would likely always be the same).

In the same way would the value of the image property have to show an image of the TravelAgency, not just any image.

And the url property would be for the URL of the item, i.e., the TravelAgency, so it would always be the same URL (typically the URL of the home page), no matter on which page.

That said, if you want to have an item that represents each page (and not the business all these pages belong to), you probably want to use WebPage (or one of its sub-types) in addition.

Microdata

Syntactically, your Microdata is fine.

HTML5

Your HTML5 is fine, too, apart from a small error: You have a closing </a> tag after the link element. You probably want to either use link (i.e., the link is invisible) or a (i.e., the link is visible).


A simple Insertion Sort implementation in Java

this code is not commented
strikingly, it does not even have doc comments
given at least two classes from the same coder that do essentially the same thing, there should be an 'interface' - look for one you can use (if as a template), especially from the Java API
SECOND_NUMBER_INDEX is close to meaningless
as a "genuine" constant, SECOND_NUMBER_INDEX should be static
int[] sort(int[] numbers) would then not use any instance (data) members and should be a class/static method instead of an instance one
if iterations was called ordered or sorted, the condition of the outer loop read close to a loop invariant
having found the first element no bigger than currentNumber, continuing to index 0 isn't called for - just place currentNumber and break the inner loop, no need for newIndex

Use a foreach-loop in main().


unit-testing / mocking a class which contains functionality which depends on itself

I'm not sure if you need GetSettingByIdentifierOrCreateIfDoesNotExist declaration in your interface... Do you have special use cases where GetSetting<T> is not enough?

If I'm right and all you need is just GetSetting<T> method then you can go ahead and make GetSettingByIdentifierOrCreateIfDoesNotExist method private, thus you'll make it an implementation specific that doesn't need to be tested separately, you'll test it by testing GetSetting<T>.

If you do need GetSettingByIdentifierOrCreateIfDoesNotExist method, then I would go with a different approach: since GetSetting<T> is just an additional feature on top of GetSettingByIdentifierOrCreateIfDoesNotExist, you can remove it from ISettingsManager interface and rewrite as an extension method like this:

public interface ISettingsManager
{
    SettingData GetSettingByIdentifierOrCreateIfDoesNotExist(Enum identifier);
}

public static class SettingsManagerExtensions
{
    public static T GetSetting<T>(this ISettingsManager manager, Enum identifier)
    {
        var setting = manager.GetSettingByIdentifierOrCreateIfDoesNotExist(identifier);
        return (T)setting.Value;
    }
}