Printing out relative date from current time Here is some code of mine that prints out the relative date according to the current time:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (int argc, char *argv[])
{
  int i = 1;
  struct tm date = {0};
  char relativeDays[80];

  char* temp = strtok(argv[1], "/");
  while(temp != 0)
  {
    switch(i++)
    {
                case 1:
                        date.tm_mon  = atoi(temp) - 1;
                        break;
                case 2:
                        date.tm_mday = atoi(temp);
                        break;
                case 3:
                        date.tm_year = atoi(temp) - 1900;
    }
    temp=strtok(NULL, "/");
  }
  i = (int) difftime(time(NULL), mktime(&date))/86400;
  sprintf(relativeDays, "%d", abs(i));
  if (i > 0) printf("%s\n", strcat(relativeDays, " days ago."));
  else if (i < 0) printf("%s\n", strcat(relativeDays, " days from now."));
  else printf("Today\n");
  return 0;
}

Sample input and output:

$ ./date 12/8/2013
2 days ago.
$ ./date 12/10/2013
Today
$ ./date 12/24/2013
13 days from now.

Any thoughts on how to improve the code, specifically how to make it shorter?

I've commented your code:

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

int main(int argc, char *argv[])
{
    int i = 1;
    struct tm date = {0};
    char relativeDays[80];

Check For Proper Input

    if(argc != 2)
    {
        printf("Two arguments required!\n");
        return -1;
    }

    char *temp = strtok(argv[1], "/");

temp will be NULL if empty.  Also, add a break after case 3: for consistency.  If you think you'll need to handle unexpected cases, use default at the end.

    while(temp != NULL)
    {
        switch(i++)
        {
            case 1:
                date.tm_mon  = atoi(temp) - 1;
                break;
            case 2:
                date.tm_mday = atoi(temp);
                break;
            case 3:
                date.tm_year = atoi(temp) - 1900;
                break;
            default:
        }

Be consistent with spacing.

        temp = strtok(NULL, "/");
    }

Add comments so people know what your intentions are.  Why are you dividing by 86400?

    i = (int)difftime(time(NULL), mktime(&date)) / 86400;
    sprintf(relativeDays, "%d", abs(i));

Use spaces to make everything more readable.

    if(i > 0)
        printf("%s\n", strcat(relativeDays, " days ago."));
    else if(i < 0)
        printf("%s\n", strcat(relativeDays, " days from now."));
    else
        printf("Today\n");

    return 0;
}

Edit:

This while block can be changed to the following. Though it doesn't change the operation, it may improve the aesthetics.

while(temp != NULL)
{
    int num = atoi(temp);
    switch(i++)
    {
        case 1:
            date.tm_mon = num - 1;
            break;
        case 2:
            date.tm_mday = num;
            break;
        case 3:
            date.tm_year = num - 1900;
            break;
        default:
            printf("Unexpected input. Blowing up now!\n");
            break;
    }

    temp = strtok(NULL, "/");
}


Checking number of of columns in a row I have a own made grid system and made a jQuery function for that to check if there are not too many columns in each row. If so, delete the HTML code of the row.

Normally in my grid system, there fits 12 columns in 1 row, but I can change that.

In HTML, I've written them like this:

...

...

...

...

...

...

...

...

...

...

...

...

In this jQuery function, im checking the number of each [class*="size-"] and counting them up.

    function validateRowWidths() {
        $('.row').each(function (index) {
            var row = $(this),
                columns = 0;
            row.children('[class*="size-"]').each(function () {
                var eachSizeNumber = Number($(this).attr('class').match(/\d+$/)[0]);
                columns += eachSizeNumber;
            });

            row.children('[class*="offset-"]').each(function () {
                var eachSizeNumber = Number($(this).attr('class').match(/\d+$/)[0]);
                columns += eachSizeNumber;
            });

            row.children('[class*="push-"]').each(function () {
                var eachSizeNumber = Number($(this).attr('class').match(/\d+$/)[0]);
                columns += eachSizeNumber;
            });

            row.children('[class*="pull-"]').each(function () {
                var eachSizeNumber = Number($(this).attr('class').match(/\d+$/)[0]);
                columns += eachSizeNumber;
            });

            console.log(columns);

            if (columns > 12) {
                $(this).remove();
                console.log("Row " + (index + 1) + " is has to many colums in it. Remove one or more columns or make them narrower.");
            }
        });
    }

For all the grid extensions such as offset, push or pull i have to write that same each function again.

The HTML markup for the grid extensions looks like this:

...

...

...

...

...

...

...

...

...

...

Can I do this in a better way?

You could try:

Using Multiple selectors
Moving the calculation logic to a function so that you can re-use it elsewhere or refactor/change in a single place if the need be.

Applying this you get something like the following:

row.children('[class*="size-"],[class*="offset-"],[class*="push-"],[class*="pull-"]').each(function () {
            columns += getCurrentSize(this);
        });

 function getCurrentSize(element){
     return Number($(element).attr('class').match(/\d+$/)[0]);
 }

However, if you want each class to be evaluated separately, as mentioned in the comments, you could first try adding these elements to an array and then perform a common action on them. Something like -

var uniqueClassColumns = [];
uniqueClassColumns.push($('[class*="size-"]'));
uniqueClassColumns.push($('[class*="offset-"]'));
uniqueClassColumns.push($('[class*="push-"]'));
uniqueClassColumns.push($('[class*="pull-"]'));

uniqueClassColumns.each(function () {
                columns += getCurrentSize(this);
            });

     function getCurrentSize(element){
         return Number($(element).attr('class').match(/\d+$/)[0]);
     }


Remove anagrams from vector I was asked to solve the following exercise:

Given an input vector<string>, I have to find the anagrams and return a vector<string> with only the strings that are not an anagram from other strings in the vector.

Example:

Input vector:

"code","doce","framy","frame","sad","cat","frema"

Output:

"code","framy","sad","cat"

Here, the anagram "frame" == "frema" is removed. All words which are anagrams from one another are removed.

My solution is to sum the ASCII values from the strings, if two strings are equal, then I sort it to check for equality.

#include <iostream>
#include <bits/stdc++.h>
#include <algorithm>    // std::sort

using namespace std::chrono;
using namespace std;

int sumASCII(string input) {

    int i;
    int sum = 0;
    int size = input.size();

    for( i = 0; i < size; i++) {

        sum+=(int)input[i];
    }

    return sum;
}

int sortStringAndCompare(string &a, string &b)
{
   sort(a.begin(), a.end());
   sort(b.begin(), b.end());
   return a.compare(b);
}

vector<string> funWithAnagrams(vector<string> &text) {

    bool anagram = false;
    int i;
    int size = text.size();
    int sumCurr = 0;
    int sumPrev = 0;
    int k = 0;
    int originalSize = 0;

    string copyA;
    string copyB;

    vector<string> originalStrings;

    originalStrings.push_back(text[0]);

    for( i = 1 ; i < size;  i++ ) {
        sumCurr = sumASCII(text[i]);
        originalSize = originalStrings.size();

        for( k = 0; k < originalSize; k++ ) {

            if(originalStrings[k].size() == text[i].size() ) {
                sumPrev = sumASCII(originalStrings[k]);

                if(sumPrev == sumCurr) {// means it found a possible anagram.

                    copyA = originalStrings[k];
                    copyB = text[i];
                    if(sortStringAndCompare(copyA,copyB) == 0)
                    {
                        anagram = true;
                        break;
                    }
                }
                else
                    anagram = false;
            }
            else {
                anagram = false;
            }

        }
        if(!anagram) {
            originalStrings.push_back(text[i]);
            }
    }

    return originalStrings;
}

int stringCompare(std::string a,std::string b)
{
    return a.compare(b);

}

void print(std::vector<string> const &input)
{
    int size = input.size();
    printf("[ ");
    for (int i = 0; i < size; i++) {
        std::cout << input.at(i) << ' ';

        if(i < (size-1))
            printf(",");
    }

    printf(" ]");
}

int main() {

    printf("TEST STARTED\n");
    vector<string> input{"doceframe","code", "doce","ecod","framer","frame", "frema","cat","sad"};
    vector<string> out;

    // Get starting timepoint
    auto start = high_resolution_clock::now();
    out = funWithAnagrams(input);
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);

    cout << "Time taken by function: " << duration.count() << " microseconds" << endl;
    printf("\n \n");
    print(out);
    printf("\n");

    printf("TEST ENDED\n");

    return 0;

}

My program is not the best in terms of memory, i shall improve it. But my task, at the moment, is to develop the fastest algorithm possible. How can I improve it?

You are on the right track, but the code does need a lot of attention.

Never go for #include <bits/stdc++.h>

Same goes for using namespace std; Both will lead you into a lot of trouble for zero gain. Only include what you need and use proper qualifications

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

Note that I also sorted the includes alphabetically so it is easy to see what is already included
You should pass by value whenever it is possible. However std::string is no such case. Luckily we have std::string_view since C++17 so you should almost always prefere this to passing a std::string, e.g

int sumASCII(const std::string_view input) {
    int i;
    int sum = 0;
    int size = input.size();

    for( i = 0; i < size; i++) {
        sum+=(int)input[i];
    }

    return sum;
}

Same for all the other functions. Your strings are stored in the original vector so there is no possibility for a dangling reference. That said you should definitely read up on ownership and view-like types
Use a formatter. Your formatting is highly unregular. You should pick a clang-format style you are comfortable with and use that everywhere.
Use range-based loops when possible

int sumASCII(const std::string_view input) {
    int sum = 0;
    for (const char character : input) {
        sum += (int)character;
    }
    return sum;
}

Do not use C-style casts. C++ has a wide variety of specialized casts that do what they are supposed to do and not more. In the above case static_cast is sufficient

int sumASCII(const std::string_view input) {
    int sum = 0;
    for (const char character : input) {
        sum += static_cast<int>(character);
    }
    return sum;
}

Use the proper algorithms

The STL provides a wide range of algorithms that is not only incredibly powerfull but also is often highly optimized and correct with respect to various corner cases.

int sumASCII(const std::string_view input) {
    return std::accumulate(std::begin(input), std::end(input), 0);
}

Note that you might want to test this with proper warnings.
Consider const correctness.

One of the most difficult parts of programming is keeping all the moving parts in your head. The more explicit you are about what is immutable the easier it is to reason about the code. So use const whenever possible and cbegin and cend too. (Even if in this case it does exactly the same it provides additional information to the reader)

int sumASCII(const std::string_view input) {
    return std::accumulate(std::cbegin(input), std::cend(input), 0);
}

Keep control flow as simple as possible.

Another hard part of software engineering is keeping track of control flow. Try to minimize indentations as much as possible to keep the code clean and easily readable. As an example this is what you wrote

for( i = 1 ; i < size;  i++ ) {
    sumCurr = sumASCII(text[i]);
    originalSize = originalStrings.size();
    for( k = 0; k < originalSize; k++ ) {
        if(originalStrings[k].size() == text[i].size() ) {
            sumPrev = sumASCII(originalStrings[k]);
            if(sumPrev == sumCurr) {// means it found a possible anagram.
                copyA = originalStrings[k];
                copyB = text[i];
                if(sortStringAndCompare(copyA,copyB) == 0)
                {
                    anagram = true;
                    break;
                }
            }
            else
                anagram = false;
        }
        else {
           anagram = false;
        }

    }
    if(!anagram) {
        originalStrings.push_back(text[i]);
    }
}

It is hard to keep track of the different conditions in thi loop and what it actually does so lets try to simplify it with some early returns:

for( i = 1 ; i < size;  i++ ) {
    anagram = false;
    sumCurr = sumASCII(text[i]);
    originalSize = originalStrings.size();
    for (const string_view newString : originalStrings) {
        if(newString.size() != text[i].size() ) {
            continue;
        }

        sumPrev = sumASCII(newString);
        if(sumPrev != sumCurr) {
            continue;
        }

        copyA = originalStrings[k];
        copyB = text[i];
        if(sortStringAndCompare(copyA,copyB) == 0) {
            anagram = true;
            break;
        }
    }

    if(!anagram) {
        originalStrings.push_back(text[i]);
    }
}

I hope you agree that this is much easier to read.
Think about the proper data structures.

You are searching for a reoccuring pattern. This is usually done via an associative container. The STL knows std::unordered_map and std::map. You should use those.

The first thing you need is a container of histograms,. You wantunique ones so you should go for a set

std::unordered_set<someHistogramThing> histograms;

The second thing you want to do is to count the characters in the string. Again a map is the simplest solution

std::unordered_map<char, std::size_t> charCount;

Lets have a look at how we get there;

std::unordered_map<char, std::size_t> countCharacters(const std::string_view input) {
    std::unordered_map<char, std::size_t> charCount;
    for (const char character : input) {
        charCount[character]++;
    }
    return charCount;
}

For any word this gives us a histogram of the occurences of characters in that word. Two words are an anagram if they have the same histogram. So lets see if we can put it together.

std::vector<std::string> removeAnagrams(const std::vector<std::string>& input) {
    std::vector<std::string> result;
    std::unordered_set<std::unordered_map<char, std::size_t>> histograms;
    for (const std::string& newWord : input) {
        const auto[it, notAnagram] = histograms.insert(countCharacters(newWord));
        if (notAnagram) {
            result.push_back(word);
        }
    }
}

Usetype aliases to give your data structures better names

using CharacterHistogram = std::unordered_map<char, std::size_t>;
using HistogramSet = std::unordered_set<CharacterHistogram>;

If we put that all together we get

#include <string>
#include <string_view>
#include <vector>
#include <unordered_map>
#include <unordered_set>

using CharacterHistogram = std::unordered_map<char, std::size_t>;
using HistogramSet = std::unordered_set<CharacterHistogram>;

CharacterHistogram countCharacters(const std::string_view input) {
    CharacterHistogram charCount;
    for (const char character : input) {
        charCount[character]++;
    }
    return charCount;
}

std::vector<std::string> removeAnagrams(const std::vector<std::string>& input) {
    std::vector<std::string> result;
    HistogramSet histograms;
    for (const std::string& newWord : input) {
        const auto[it, notAnagram] = histograms.insert(countCharacters(newWord));
        if (notAnagram) {
            result.push_back(word);
        }
    }
}


Validating search parameters in an Angular $scope I am using the following function to make a specific filter passing the $scope.searchParams in this way:

<tbody ng-repeat="user in users | customFilter:searchParams "> ...

$scope.updateSearch = function() {

    var searchParams = {},
      loginArr = [],
      nameArr = [],
      statusArr = [],
      accountsArr = [],
      profileArr = [];

    if($scope.search.name !== undefined && /\S/.test($scope.search.name)){
      //$scope.tags.push({ text: 'Nombre: ' + $scope.name });
      nameArr.push($scope.search.name);
      searchParams['name'] = nameArr;
    }
    if($scope.search.login !== undefined && /\S/.test($scope.search.login)){
      //$scope.tags.push({ text: 'Nombre: ' + $scope.name });
      loginArr.push($scope.search.login);
      searchParams['login'] = loginArr;
    }
    if($scope.search.status !== undefined && /\S/.test($scope.search.status)){
      //$scope.tags.push({ text: 'Nombre: ' + $scope.name });
      statusArr.push($scope.search.status);
      searchParams['merchant.status'] = statusArr;
    }
    if($scope.search.accounts !== undefined && /\S/.test($scope.search.accounts)){
      //$scope.tags.push({ text: 'Nombre: ' + $scope.name });
      accountsArr.push($scope.search.accounts);
      //accountsArr.push('500092');
      searchParams['merchant.accounts'] = accountsArr;
    }
    if($scope.search.profiles !== undefined && /\S/.test($scope.search.profiles)){
      //$scope.tags.push({ text: 'Nombre: ' + $scope.name });
      accountsArr.push($scope.search.profiles);
      searchParams['merchant.accounts'] = accountsArr;
    }
    $scope.searchParams = searchParams;
  };

In this case I have to filter based on 5 fields ('login','name','status','account' and 'profile'). This is not optimum if I need 10 or more fields to filter. How can I do this more generic?

If you can wrap your arrays into an object and keep their names in line with the search attributes, you can have:

<tbody ng-repeat="user in users | customFilter:searchParams "> ...

$scope.updateSearch = function() {

//  Uncomment to test the following block in console:
//  var $scope = {search: {login:'log1', status:'status0'}};

    var searchParams = {},
      arr = { // Initialise arrays (if needed?)
        login: [],
        name: [],
        status: [],
        accounts: [],
        profiles: []
      };

    Object.keys($scope.search).forEach(
      e => {if(/\S/.test($scope.search[e])) {
        arr[e].push($scope.search[e]);
        searchParams[e] = arr[e];
      }}
    );

    $scope.searchParams = searchParams;
  };

If you definitely need renaming:

<tbody ng-repeat="user in users | customFilter:searchParams "> ...

$scope.updateSearch = function() {

//  Uncomment to test the following block in console:
//  var $scope = {search: {login:'log1', status:'status0'}};

    var searchParams = {},
        loginArr = [],
        nameArr = [],
        statusArr = [],
        accountsArr = [],
        profileArr = [];

    function mapSearch(src, arr, sTgt) {
      if(src !== undefined && /\S/.test(src)) {
        arr.push(src);
        searchParams[sTgt] = arr;
      }
    }

    mapSearch($scope.search.name    , nameArr    , 'name');
    mapSearch($scope.search.login   , loginArr   , 'login');
    mapSearch($scope.search.status  , statusArr  , 'merchant.status');
    mapSearch($scope.search.accounts, accountsArr, 'merchant.accounts');
    mapSearch($scope.search.profiles, profileArr , 'merchant.profiles');

    $scope.searchParams = searchParams;
  };


My own expandable list in Python I have written my own expendable list in Java.
LinkedList in Java
 Now I tried to write that thing in Python. Did I have used the elements of the python language properly?

class Node:
    def __init__(self):
        self.object = None
        self.nextNode = None

    def hasObject(self):
        return self.object != None

    def hasNextNode(self):
        return nextNode != None

class LinkedList:
    def __init__(self):
        self.startNode = Node()

    def getEmptyNode(self):
        currentNode = self.startNode
        while currentNode.hasObject():
            currentNode = currentNode.nextNode
        return currentNode

    def insert(self, obj):
        emptyNode = self.getEmptyNode()
        emptyNode.object = obj
        emptyNode.nextNode = Node()

    def getNumberOfElements(self):
        currentNode = self.startNode
        numberOfElements = 0
        while currentNode.hasObject():
            numberOfElements += 1
            currentNode = currentNode.nextNode
        return numberOfElements

    def getNodeByIndex(self, index):
        currentNode = self.startNode
        for i in range(index):
            currentNode = currentNode.nextNode
        return currentNode

    def get(self, index):
        node = self.getNodeByIndex(index)
        return node.object

    def delete(self, index):
        if index == 0:
            startNode = self.getNodeByIndex(1)
            return

        # if index equals last available index
        if index == (self.getNumberOfElements) - 1:
            nodeBefore = self.getNodeByIndex(index - 1)
            nodeBefore.nextNode = None

        nodeBefore = self.getNodeByIndex(index - 1)
        nodeBehind = self.getNodeByIndex(index + 1)
        nodeBefore.nextNode = nodeBehind

linkedList = LinkedList()
linkedList.insert("Hello")
linkedList.insert("How are you")
linkedList.insert(3)
linkedList.insert("I feel fine")
print(linkedList.getNumberOfElements())
print(linkedList.get(2))

for i in range(linkedList.getNumberOfElements()):
    print(linkedList.get(i))

Just some random things I noticed while looking over your code:

The way you're handling additions is a little odd to me. You seem to be continually maintaining an "empty node" at the end of the list, then when you add, you iterate to that node, replace its content then give it a new, empty node. Why not just have nextNode remain None, then iterate while currentNode.hasNextNode() to find the last node? Something like:

def getLastNode(self):
    currentNode = self.startNode
    while currentNode.hasNextNode():
        currentNode = currentNode.nextNode
    return currentNode

def insert(self, obj):
    newNode = Node()
    newNode.object = obj

    lastNode = self.getLastNode()
    lastNode.nextNode = newNode

From my experience, this is a far more typical set up. This also has the miniscule benefit of using slightly less memory, since you're no longer keeping one more node than needed in memory at all times. This also does away with the need for the hasObject method.

The definition of getNumberOfElements is completely impractical for most applications. You can assume for most, if not all data structures (besides maybe lazy lists), that a size method will run in O(1) time. Iterating the entire list every time you want to get the size has the opportunity to bring your application to a crawl; especially if the user of the class isn't aware that getNumberOfElements is O(n).

Just give your class a n_nodes field, and increment/decrement it in the appropriate methods:

def insert(self, obj):
    newNode = Node()
    newNode.object = obj

    lastNode = self.getLastNode()
    lastNode.nextNode = newNode

    self.n_nodes += 1 # Here

Then change getNumberOfElements to something like:

def size(self):
    return self.n_nodes

You can now get the size of the list nearly instantly instead of requiring a full iteration. The only drawback is you need to take care to properly manage n_nodes in all the methods that can change the size of the list.

Python isn't my main language, but I'm pretty sure snake_case is idiomatic Python. Coming from Java, you're probably more used to camelCase, but adhering to conventions is important for allowing other people to read your code easier. One thing you need to adjust to when writing in multiple languages is remembering what conventions the language you're writing uses. Clojure, my main language, uses dash-case; but this isn't even valid in many languages (like Python). I've gotten yelled at many times on Stack Overflow when answering questions in languages I don't use often because I forgot to adjust my naming conventions, and end up using either unidiomatic, or outright illegal names.

It would likely simplify your life if you gave the Node constructor the ability to directly set nextNode and object fields:

def __init__(self, newObject = None, newNextNode = None):
    self.object = newObject
    self.nextNode = newNextNode

That will save you a couple lines in the few places by just directly passing the object:

def insert(self, obj):
    newNode = Node(obj)

    # No longer needed!
    # newNode.object = obj

    lastNode = self.getLastNode()
    lastNode.nextNode = newNode

    self.n_nodes += 1

The "start node" of a linked list is more typically referred to as the "root".

def delete(self, index):
    if index == 0:
        startNode = self.getNodeByIndex(1)
...

Could probably be written more cleanly as simply

def delete(self, index):
    if index == 0:
        startNode = startNode.nextNode
...

For efficiency, you might also want to maintain a lastNode field. Right now, to get to the last node, you're needing to iterate the entire list, which is quite expensive. If you just keep a reference to the last node when you do an insertion, you can just use that reference instead of needing to iterate.

if index == (self.getNumberOfElements) - 1:

Is broken. You need to call the method.


Find the longest word's length The challenge is simple:

  Return the length of the longest word in the provided sentence.

The solution is just as simple:

function findLongestWord(str) {
  arr = str.split(' ');
  size = 0;
  for (var s in arr) {
    if (arr[s].length > size) {
      size = arr[s].length;
    }
  }
  return size;
}

However, I vaguely remember you're not supposed to use for..in in JavaScript unless absolutely necessary. What would be the more idiomatic approach for this loop?

First, I'd not name the function findLongestWord as you're not looking for the longest word, but the length of the longest word. Try getLongestWordLength instead.

You're forgetting var for your variables. This makes them shoot up to the global scope and be declared there, and we don't want that to happen. For ES6, there's also let.

for-in is only advisable on objects, and even on objects you guard it with hasOwnProperty. That's because it iterates through prototype properties (things other than the array elements or instance properties). A regular loop (for or while) while incrementing an index until length would be better. But there's an even better approach...

You can create a map of lengths by using map on your split string, returning the length of the strings. Then you use Math.max to get the largest number in the array of lengths. We can use the spread operator (...) to spread the array as arguments to Math.max.

function getLongestWordLength(str){
  return Math.max(...(str.split(' ').map(s => s.length)));
}

The above is ES6 syntax. The ES5 equivalent would look like the following. One notable difference, aside from the more verbose map is the use of apply to provide Math.max with a dynamic set of arguments.

function getLongestWordLength(str) {
    return Math.max.apply(Math, str.split(' ').map(function (s) {
        return s.length;
    }));
}

document.write(getLongestWordLength('The quick brown fox jumps over the lazy doge'));


Parsing: Entity Classes to DTO I'm building a GWT application for GAE, using JDO for Datastore access. I use and Entity class for data mapping, so it contains lots of Persistence annotations:

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class AppointmentEntity implements Serializable {

    private static final long serialVersionUID = 1L;
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;
    @Persistent
    private String firstName;
    @Persistent
    private String lastName;
    @Persistent
    private String DNI;
    @Persistent
    private Date appointmentDate;
    @Persistent
    private String attendant;
    @Persistent
    private String treatment;
    @Persistent
    private String details;
    @Persistent
    private Date nextAppointment;
    @Persistent(serialized = "true")
    private DownloadableFile file;

    //getters and setters...

Because of GWT and JDO nature, i can't use this Entity classes in my presentation layer; so there's a need of passing Entity Object attributes to the corresponding DTO, which is a POJO that has the same attributes of the Entity class:

public class AppointmentDTO implements Serializable {

    private static final long serialVersionUID = 1L;
    private Long id;
    private String firstName;
    private String lastName;
    private String DNI;
    private Date appointmentDate;
    private Date nextAppointmentDate;
    private String attendant;
    private String treatment;
    private String details;

    //getters and setters...

To do the Job of mapping attributes i make a Wrapper class that handles it, but it doesn't feel quite right to me. Does anyone have a better approach?

public class AppointmentWrapper {

    private List<AppointmentEntity> entitiesList;

    public AppointmentWrapper(List<AppointmentEntity> appointmentEntities) {
            entitiesList = appointmentEntities;
    }

    public List<AppointmentDTO> getDTOList() {
            List<AppointmentDTO> dtoList = new ArrayList<AppointmentDTO>();

            for (AppointmentEntity entity : entitiesList) {
                    AppointmentDTO dto = new AppointmentDTO();

                    dto.setId(entity.getId());
                    dto.setFirstName(entity.getFirstName());
                    dto.setLastName(entity.getLastName());
                    dto.setAppointmentDate(entity.getAppointmentDate());
                    dto.setNextAppointmentDate(entity.getNextAppointment());
                    dto.setAttendant(entity.getAttendant());
                    dto.setDetails(entity.getDetails());
                    dto.setDNI(entity.getDNI());
                    dto.setTreatment(entity.getTreatment());
                    dtoList.add(dto);
            }
            return dtoList;
    }
}

There is this concerning GWT and GAE objects. If that doesn't work for you, I would rather have a class of public static methods that does the conversions rather than sticking it into some kind of "wrapper class" that contains object states. For example,

public final class JDOEntityUtil {

   static public AppointmentDTO toDTO(AppointmentEntity entity) {
       AppointmentDTO dto = new AppointmentDTO();
       dto.setId(entity.getId());
       dto.setFirstName(entity.getFirstName());
       dto.setLastName(entity.getLastName());
       dto.setAppointmentDate(entity.getAppointmentDate());
       dto.setNextAppointmentDate(entity.getNextAppointment());
       dto.setAttendant(entity.getAttendant());
       dto.setDetails(entity.getDetails());
       dto.setDNI(entity.getDNI());
       dto.setTreatment(entity.getTreatment());
       return dto;
   }

   static public AppointmentEntity toEntity(AppointmentDTO dto) {
       AppointmentEntity entity = new AppointmentEntity();
       entity.setId(dto.getId());  /* or however you want to construct this */
       entity.setFirstName(dto.getFirstName());
       entity.setLastName(dto.getLastName());
       entity.setAppointmentDate(dto.getAppointmentDate());
       entity.setNextAppointmentDate(dto.getNextAppointment());
       entity.setAttendant(dto.getAttendant());
       entity.setDetails(dto.getDetails());
       entity.setDNI(dto.getDNI());
       entity.setTreatment(dto.getTreatment());
       return entity;
   }
}


Variadic Functions in NASM Win64 Assembly Simple variadic function implementation in NASM Assembly. When implemented like I have below:

sum.asm

;; bits 64
default rel

extern printf

section .text
    global main
    global sum
main:
    sub     rsp, 40
    mov     r9d, 3
    mov     r8d, 2
    mov     edx, 1
    mov     ecx, 3
    call    sum
    lea     rcx, [fmt]
    mov     edx, eax
    call    printf
    xor     eax, eax
    add     rsp, 40
    ret
sum:
    sub     rsp, 24
    test    ecx, ecx
    mov     qword [rsp+28H], rdx
    lea     rdx, [rsp+28H]
    mov     qword [rsp+30H], r8
    mov     qword [rsp+38H], r9
    mov     qword [rsp+8H], rdx
    jle     .end
    lea     eax, [rcx-1H]
    lea     rcx, [rsp+rax*8+30H]
    xor     eax, eax
.recurse:
    add     eax, dword [rdx]
    add     rdx, 8
    cmp     rdx, rcx
    jnz     .recurse
    add     rsp, 24
    ret
.end:
    xor     eax, eax
    add     rsp, 24
    ret

%macro str 2
    %2: db %1, 0
%endmacro

section .rdata
    str "%d", fmt

We can change how many variables are being given to the function without having to change the amount of memory being allocated to the function itself.

main:
    sub     rsp, 72
    mov     dword [rsp+30H], 6
    mov     dword [rsp+28H], 5
    mov     dword [rsp+20H], 4
    mov     r9d, 3
    mov     r8d, 2
    mov     edx, 1
    mov     ecx, 6
    call    sum
    lea     rcx, [fmt]
    mov     edx, eax
    call    printf
    xor     eax, eax
    add     rsp, 72
    ret

There are no comments in the code since what I'm doing should be pretty self-explanatory. Any advice and all topical comments on optimizing the code and its performance, as well as standard conventions, is appreciated!

Compiled as follows using VS2017 x64 Native Tools Command Prompt:

> nasm -g -f win64 sum.asm

> cl /Zi sum.obj msvcrt.lib legacy_stdio_definitions.lib

mov     qword [rsp+8H], rdx

Why would you store this value at all? You never use the stored value afterwards!

You can easily dismiss all of the local storage for the sum routine. No need for sub rsp, 24 nor add rsp, 24 instructions. Also, why 24 bytes when all you use are the middle 8 bytes? The same happens in main where you reserve 40 bytes when all you use are the middle 24 bytes! The alternative main evens wastes 24 bytes this way.

You can avoid the separate .end code by clearing the accumulator very early and jumping to the one RET you really need.

lea     eax, [rcx-1H]
lea     rcx, [rsp+rax*8+30H]

You can calculate this upper limit in just one instruction. Absorb the decrement by 1 operation into the displacement of the LEA:

lea     rcx, [rsp + rcx*8 + 28h]

And since by the time of this calculation the RDX register already points at [rsp + 28h] you could simply write:

lea     rcx, [rdx + rcx*8]

Applying these changes:

sum:
    xor     eax, eax
    test    ecx, ecx
    jle     .end
    mov     [rsp + 10h], rdx    ; 1st arg for sure (ECX=1+)
    mov     [rsp + 18h], r8     ; maybe 2nd arg
    mov     [rsp + 20h], r9     ; maybe 3rd arg
    lea     rdx, [rsp + 10h]    ; lower limit
    lea     rcx, [rdx + rcx*8]  ; upper limit
.more:
    add     eax, dword [rdx]
    add     rdx, 8
    cmp     rdx, rcx
    jb      .more
.end:
    ret

When comparing memory addresses like in your code cmp rdx, rcx, it would be best to not check for equality but rather for excess. Provided the step is non-zero, checking for the 'below' condition will happen eventually while checking for the 'equal' condition might never happen at all (if there's an error in the program of course...).

An even simpler solution uses the ECX register as a counter (like it was on input):

sum:
    xor     eax, eax
    test    ecx, ecx
    jle     .end
    mov     [rsp + 10h], rdx    ; 1st arg for sure (ECX=1+)
    mov     [rsp + 18h], r8     ; maybe 2nd arg
    mov     [rsp + 20h], r9     ; maybe 3rd arg
    lea     rdx, [rsp + 10h]    ; lower limit
.more:
    add     eax, dword [rdx]
    add     rdx, 8
    sub     ecx, 1
    jnz     .more
.end:
    ret

  We can change how many variables are being given to the function without having to change the amount of memory being allocated to the function itself.

True, but the caller still has to reserve - somewhat mysteriously - those 24 bytes that correspond to the 3 arguments passed via registers EDX, R8D, and R9D.
I think it would be simpler to either pass all values on the stack or pass a pointer (in RDX) to a buffer holding all of those values. In both cases the count remains in ECX.
Next code combines it all:

    sub     rsp, 48
    mov     rdx, rsp
    mov     dword [rdx + 40], 6
    mov     dword [rdx + 32], 5
    mov     dword [rdx + 24], 4
    mov     dword [rdx + 16], 3
    mov     dword [rdx + 8], 2
    mov     dword [rdx], 1
    mov     ecx, 6
    call    sum
    ...

sum:
    xor     eax, eax
    test    ecx, ecx
    jle     .end
.more:
    add     eax, dword [rdx]
    add     rdx, 8
    sub     ecx, 1
    jnz     .more
.end:
    ret


Excel sheet code is taking too much time I have an Excel sheet with lot of rows with data. I am separating it into 2 sheets with some condition satisfies.

This is taking too much time.  How can I improve the speed?  Please suggest any changes to my code.

Dim bmver As Object(,) = New Object(i20, 36) {}
Dim bmhor As Object(,) = New Object(i20, 36) {}

Dim ik As Integer = 0
Dim ij As Integer = 0
With oWs

    For i As Integer = 2 To i20 - 1
        If (.range("E" & i).value = .range("L" & i).value) Then

            For j As Integer = 0 To 36
                bmhor(ij, j) = .cells(i, j + 1).value
            Next
            ij = ij + 1
        End If

    Next

    For k As Integer = 2 To i20 - 1
        If (.range("C" & k).value = .range("J" & k).value) Then

            For j1 As Integer = 0 To 36
                bmver(ik, j1) = .cells(k, j1 + 1).value
            Next
            ik = ik + 1
        End If

    Next

End With
oWs = oBook.Worksheets("beamhor")
oWs.activate()
Dim r6 As Range = oWs.Range("A2").Resize(bmhor.GetLength(0), 37)
r6.Value2 = bmhor

With oWs

    .Range("A2:AE" & i20).Sort(Key1:=.range("E2"), Order1:=Excel.XlSortOrder.xlAscending, _
         Key2:=.range("L2"), Order2:=Excel.XlSortOrder.xlAscending, _
          Key2:=.range("C2"), Order2:=Excel.XlSortOrder.xlAscending, _
         Key2:=.range("J2"), Order2:=Excel.XlSortOrder.xlAscending, _
           Orientation:=XlSortOrientation.xlSortColumns, _
             Header:=Excel.XlYesNoGuess.xlNo, _
           SortMethod:=XlSortMethod.xlPinYin)

End With
oWs = oBook.Worksheets("beamver")
oWs.activate()
Dim r7 As Range = oWs.Range("A2").Resize(bmver.GetLength(0), 37)
r7.Value2 = bmver
With oWs

    .Range("A2:AE" & i20).Sort(Key1:=.range("E2"), Order1:=Excel.XlSortOrder.xlAscending, _
                  Key2:=.range("L2"), Order2:=Excel.XlSortOrder.xlAscending, _
                 Key2:=.range("C2"), Order2:=Excel.XlSortOrder.xlAscending, _
                   Key2:=.range("J2"), Order2:=Excel.XlSortOrder.xlAscending, _
                   Orientation:=XlSortOrientation.xlSortColumns, _
                  Header:=Excel.XlYesNoGuess.xlNo, _
                 SortMethod:=XlSortMethod.xlPinYin)

End With

Excel interoperability is inherently slow - you have the .NET runtime talking to a COM object model through COM interop, there's a performance penalty just for doing that.

Hence, you should strive to reduce the number of times you're accessing the worksheet cells, be it to read or to write.

Before going into the algorithm, I'd like to point out the naming issues. Bad names make the code harder to read and longer to parse. Typing code is 20% of the job - the other 80% is spent reading code, so when the first 20% makes a good job at being readable, the 80% can be more productive.

Avoid single-letter identifiers (for-loop variable is ok though) and disemvoweling. Use comments - don't write code that assumes the reader is also looking at the worksheet in question: name things so that we know what columns C, E, J and L are, or comment to that effect.

Now. We have two loops, both iterating from 2 To i20 - 1. Round one would be to merge them:

For i As Integer = 2 To i20 - 1

    If (.range("E" & i).value = .range("L" & i).value) Then

        For j As Integer = 0 To 36
            bmhor(ij, j) = .cells(i, j + 1).value
        Next

        ij = ij + 1

    End If

    If (.range("C" & i).value = .range("J" & i).value) Then

        For j As Integer = 0 To 36 'I'd believe identifier j can be reused here
            bmver(ik, j) = .cells(i, j + 1).value
        Next

        ik = ik + 1

    End If

Next

Just doing that has reduced the number of iterations by half. Now these two blocks look awfully similar. Let's see if we can extract a method here:

Sub NameMe(Value1 As String, Value2 As String, Row As Long, TheWorksheet As Worksheet, TheArray As Object(,))

    Dim Counter As Integer
    If (Value1 = Value2) Then

        For i As Integer = 0 To 36
            TheArray(Counter, i) = TheWorksheet.Cells(Row, i + 1).Value
        Next

        Counter += 1

    End If

End Sub

Then the loop can look like this:

Dim ValueForColumnE As String
Dim ValueForColumnL As String
Dim ValueForColumnC As String
Dim ValueForColumnJ As String

For i As Integer = 2 To i20 - 1

    ValueForColumnE = .range("E" & i).Value.ToString()
    ValueForColumnL = .range("L" & i).Value.ToString()
    ValueForColumnC = .range("C" & i).Value.ToString()
    ValueForColumnJ = .range("J" & i).Value.ToString()

    NameMe ValueForColumnE, ValueForColumnL, i, ows, bmhor
    NameMe ValueForColumnC, ValueForColumnJ, i, ows, bmver

Next


Push Notifications - save token id into a database using Asynchronous Request based on this answer I modified my code. Is this the correct approach now?

   func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    var userId = "001" //I just use it as USER number 1

    let token = deviceToken.hexString()

        var postBody = NSString(format: "user=%@&token=%@", userId, token)
        var endBody = NSURL(string: "http://www.myServer.com/api/v1.0/register.php")
        var request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)

        request.HTTPMethod = "POST";
        request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

        var response: NSURLResponse?
        var error: NSError?

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
            (response, data, error) -> Void in

            if data != nil {
                println("data: \(response)")

            } else {

                println("failed: \(error.localizedDescription)")
            }
        }
  }

   extension NSData {
func hexString() -> String {
    // "Array" of all bytes:
    let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
    // Array of hex strings, one for each byte:
    let hexBytes = map(bytes) { String(format: "%02hhx", $0) }
    // Concatenate all hex strings:
    return "".join(hexBytes)
    }
   }

First of all I think you could improve indenting (use Xcode built-in tool) and spaces.

Second thing you had 2 useless local variables.

And, most important, IMO you should create a struct or a class as your API client wrapper. Even if you have one simple method for now.

Here is a very simplified example.

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    var userId = "001" //I just use it as USER number 1
    let token = deviceToken.hexString()

    let apiClient = MyRESTAPI(userId: "001")
    apiClient.setUserToken(token) {
        result in
        switch result {
        case .Ok(let response):
            println("data: \(response)")
        case .Error(let error):
            println("failed: \(error.localizedDescription)")
        }
    }
}

    struct MyRESTAPI {
        enum Result {
            case Error(NSError)
            case Ok(NSURLResponse)
        }

        let userId:String

        func setUserToken(token:String, completion:(Result -> Void)) {
            var postBody = NSString(format: "user=%@&token=%@", self.userId, token)
            var endBody = NSURL(string: "http://www.myServer.com/api/v1.0/register.php")
            var request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)

            request.HTTPMethod = "POST";
            request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
                (response, data, error) -> Void in

                if data != nil {
                    completion(MyRESTAPI.Result.Ok(response))
                } else {
                    completion(MyRESTAPI.Result.Error(error))
                }
            }
        }
    }

    extension NSData {
        func hexString() -> String {
            // "Array" of all bytes:
            let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
            // Array of hex strings, one for each byte:
            let hexBytes = map(bytes) { String(format: "%02hhx", $0) }
            // Concatenate all hex strings:
            return "".join(hexBytes)
        }
    }


MST Kruskal's algorithm in Python I have this code for finding MST for undirected weighted graph, currently works for graphs with maximum 10 vertices. How can I update the code to scale for larger graphs?

# Python program for Kruskal's algorithm to find Minimum Spanning Tree
# of a given connected, undirected and weighted graph

from collections import defaultdict

#Class to represent a graph
class Graph:

    def __init__(self,vertices):
        self.V= vertices #No. of vertices
        self.graph = [] # default dictionary to store graph

    # function to add an edge to graph
    def addEdge(self,u,v,w):
        self.graph.append([u,v,w])

    # A utility function to find set of an element i
    # (uses path compression technique)
    def find(self, parent, i):
        if parent[i] == i:
            return i
        return self.find(parent, parent[i])

    # A function that does union of two sets of x and y
    # (uses union by rank)
    def union(self, parent, rank, x, y):
        xroot = self.find(parent, x)
        yroot = self.find(parent, y)

        # Attach smaller rank tree under root of high rank tree
        # (Union by Rank)
        if rank[xroot] < rank[yroot]:
            parent[xroot] = yroot
        elif rank[xroot] > rank[yroot]:
            parent[yroot] = xroot
        #If ranks are same, then make one as root and increment
        # its rank by one
        else :
            parent[yroot] = xroot
            rank[xroot] += 1

    # The main function to construct MST using Kruskal's algorithm
    def KruskalMST(self):

        result =[] #This will store the resultant MST

        i = 0 # An index variable, used for sorted edges
        e = 0 # An index variable, used for result[]

        #Step 1:  Sort all the edges in non-decreasing order of their
        # weight.  If we are not allowed to change the given graph, we
        # can create a copy of graph
        self.graph =  sorted(self.graph,key=lambda item: item[2])
        #print self.graph

        parent = [] ; rank = []

        # Create V subsets with single elements
        for node in range(self.V):
            parent.append(node)
            rank.append(0)

        # Number of edges to be taken is equal to V-1
        while e < self.V -1 :

            # Step 2: Pick the smallest edge and increment the index
            # for next iteration
            u,v,w =  self.graph[i]
            i = i + 1
            x = self.find(parent, u)
            y = self.find(parent ,v)

            # If including this edge does't cause cycle, include it
            # in result and increment the index of result for next edge
            if x != y:
                e = e + 1
                result.append([u,v,w])
                self.union(parent, rank, x, y)
            # Else discard the edge

        # print the contents of result[] to display the built MST
        print "Following are the edges in the constructed MST"
        for u,v,weight  in result:
            #print str(u) + " -- " + str(v) + " == " + str(weight)
            print ("%d -- %d == %d" % (u,v,weight))
 g = Graph(14)
 g.addEdge(0, 1, 7)
 g.addEdge(0, 3, 3)
 g.addEdge(1, 2, 3)
 g.addEdge(1, 4, 2)
 g.addEdge(2, 5, 2)
 g.addEdge(3, 4, 3)
 g.addEdge(3, 6, 2)
 g.addEdge(4, 5, 5)
 g.addEdge(4, 7, 7)
 g.addEdge(5, 8, 3)
 g.addEdge(6, 7, 3)
 g.addEdge(6, 9, 1)
 g.addEdge(7, 8, 7)
 g.addEdge(7, 10, 3)
 g.addEdge(9, 12, 4)
 g.addEdge(9, 10, 1)
 g.addEdge(10, 11, 6)
 g.addEdge(10, 13, 7)
 g.addEdge(11, 12, 6)
 g.addEdge(11, 14, 2)
 g.addEdge(12, 13, 4)
 g.addEdge(13, 14, 5)

 g.KruskalMST()

Why do you assume this code is limited to 10 vertices? This code comes from: http://www.geeksforgeeks.org/greedy-algorithms-set-2-kruskals-minimum-spanning-tree-mst/

But you have an error in use:

 g = Graph(14)

Defines a graph with 14 vertices but then you used 0-14 which is 15 vertices. Either use:

 g = Graph(15)

Or remove all the edges with vertex 14.


Making a simple call to a server Earlier this year, before I learnt about Code Review Stack Exchange, I gave this answer in response to a question about how to combine ASP.NET, jQuery, and JSON:

I keep thinking that there must be a better way to handle the JSON than just using escaped string literals, but I'd like to know for sure.

urlToHandler = 'handler.ashx';
jsonData = '{ "dateStamp":"2010/01/01", "stringParam": "hello" }';
$.ajax({
                url: urlToHandler,
                data: jsonData,
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json',
                success: function(data) {
                    setAutocompleteData(data.responseDateTime);
                },
                error: function(data, status, jqXHR) {
                    alert('There was an error.');
                }
            }); // end $.ajax

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";

        DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]);
        string stringParam = (string)Request.Form["stringParam"];

        // Your logic here

        string json = "{ \"responseDateTime\": \"hello hello there!\" }";
        context.Response.Write(json);
    }

You are correct. There is a better way. Starting in .NET 3.5, there is a JavaScriptSerializer class that can be used for simplifying JSON responses. It can be found in the System.Web.Script.Serialization namespace (System.Web.Extensions assembly)

First, you'd need to make a model to represent your response:

public class SimpleResponse {
    public string responseDateTime { get; set; }

    public SimpleResponse() {
          responseDateTime = "hello hello there!";
    }
}

...Then in your handler:

 public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "application/json";
     var json = new JavaScriptSerializer();

     context.Response.Write(
         json.Serialize(new SimpleResponse())
     );
 }

Here is the result:

{"responseDateTime":"hello hello there!"}

In an ASP.NET MVC application this is more trivial. Just return a JsonResult from your controller:

public JsonResult Index()
{
    return Json(new SimpleResponse());
}


Transforming http request into linq query I wrote something that has probably done thousands of times:
a function that takes a parsed http query as input and return a linq query.

Any input is appreciated.

public IList<Lead> GetLeads(NameValueCollection nvc)
{
    IQueryable<MyContext> queryBase = QueryBase();

    foreach (string key in nvc)
    {
        const string format = "dd-MM-yyyy";

        if (nvc[key] == "all")
            continue;

        //case where an array of possible values is sent
        const string regex = "\\[.*\\]";

        Expression<Func<MyContext, bool>> predicate = c => false;

        string[] values = nvc[key].Split(',');
        foreach (string value in values)
        {
            Expression<Func<MyContext, bool>> predicateTemp;
            DateTime date;
            switch (Regex.Replace(key, regex, ""))
            {
                case "nature":
                    string value1 = value;
                    predicateTemp =
                        c => c.Typologies.NatureDemande == value1;
                    break;
                case "departementCode":
                    string value2 = value;
                    predicateTemp = c => c.Geographies.DepartementCode == value2;
                    break;
                case "start":
                    String start = value;
                    date = DateTime.ParseExact(start, format, null);

                    DateTime date1 = date;
                    predicateTemp = c => c.Temps.Date >= date1;
                    break;
                case "end":
                    String end = value;
                    date = DateTime.ParseExact(end, format, null);

                    DateTime date2 = date;
                    predicateTemp = c => c.Temps.Date <= date2;
                    break;
                default:
                    predicateTemp =
                        c => true;
                    break;
            }
            predicate = OrElse(predicate, predicateTemp);
        }

        queryBase = queryBase.Where(predicate);
    }

    //query all leads
    IQueryable<Lead> query = (from x in queryBase
                              select new Lead
                                  {
                                      id = Convert.ToInt32(x.Leads.DemandeWeb_FK),
                                      lng = Convert.ToDouble(x.Leads.longitudeClient.Replace(",", ".")),
                                      lat = Convert.ToDouble(x.Leads.latitudeClient.Replace(",", ".")),
                                      temps = Convert.ToInt32(x.Leads.GeolocDureeTrajetDistrib),
                                      distance = Convert.ToInt32(x.Leads.GeolocDistanceRouteDistrib),
                                      nature = x.Typologies.NatureDemande,
                                      type = x.Distributeurs.DistribType,
                                      reseau = x.Distributeurs.ReseauDistributeur,
                                      instance = x.Demands.IdInstance,
                                      distribution = Convert.ToInt32(x.Distributeurs.DistribIdPointDeVente),
                                  });

    return query.ToList();
}

Here's a stab at making it a tad more performant while simplifying the syntax a bit:

//case where an array of possible values is sent
private const string MyRegex = "\\[.*\\]";

private static readonly Regex replacer = new Regex(MyRegex, RegexOptions.Compiled);

public IList<Lead> GetLeads(NameValueCollection nvc)
{
    var queryBase = QueryBase();

    foreach (var key in nvc.Cast<string>().Where(key => nvc[key] != "all"))
    {
        // case where an array of possible values is sent
        Expression<Func<MyContext, bool>> predicate = c => false;

        foreach (var value in nvc[key].Split(','))
        {
            const string Format = "dd-MM-yyyy";
            Expression<Func<MyContext, bool>> predicateTemp;
            var localValue = value;

            switch (replacer.Replace(key, string.Empty))
            {
                case "nature":
                    predicateTemp = c => c.Typologies.NatureDemande == localValue;
                    break;
                case "departementCode":
                    predicateTemp = c => c.Geographies.DepartementCode == localValue;
                    break;
                case "start":
                    predicateTemp = c => c.Temps.Date >= DateTime.ParseExact(localValue, Format, null);
                    break;
                case "end":
                    predicateTemp = c => c.Temps.Date <= DateTime.ParseExact(localValue, Format, null);
                    break;
                default:
                    predicateTemp = c => true;
                    break;
            }

            predicate = this.OrElse(predicate, predicateTemp);
        }

        queryBase = queryBase.Where(predicate);
    }

    // query all leads
    return queryBase.Select(x => new Lead
    {
        id = Convert.ToInt32(x.Leads.DemandeWeb_FK),
        lng = Convert.ToDouble(x.Leads.longitudeClient.Replace(",", ".")),
        lat = Convert.ToDouble(x.Leads.latitudeClient.Replace(",", ".")),
        temps = Convert.ToInt32(x.Leads.GeolocDureeTrajetDistrib),
        distance = Convert.ToInt32(x.Leads.GeolocDistanceRouteDistrib),
        nature = x.Typologies.NatureDemande,
        type = x.Distributeurs.DistribType,
        reseau = x.Distributeurs.ReseauDistributeur,
        instance = x.Demands.IdInstance,
        distribution = Convert.ToInt32(x.Distributeurs.DistribIdPointDeVente),
    }).ToList();
}


Refactoring a class hierarchy to remove subclasses I have the following class inheritances hierarchy:

First the abstract parent class:

<?php
abstract class SegmentParserAbstract{
/** @var ParserResult */
protected $_result;
protected $_invalidSegmentMessage;
protected $_segmentRegex;
protected $_segment;

abstract protected function createSegmentObject();
public function __construct() {
    $this->_result = new ParserResult();
}
public function setSegment($Segment) {
    $this->_segment = $Segment;
}
/**
 * Function will parse the Segment  by validating the input string.
 * If valid it will create the Segment Object in the result array with no errors.
 * If invalid it will populate the result array with the error, but no object will be created.
 */
public function parse() {
    if ($this->isValidSegment()) {
        $this->createSegmentObject();
    } else {
        $this->createErrorMessage();
    }
    return $this->_result;
}
protected function isValidSegment() {
    $matchesFound = preg_match($this->_segmentRegex, $this->_segment);
    return ($matchesFound > 0);
}
protected function createErrorMessage() {
    $this->_result->addError(array($this->_invalidSegmentMessage . $this->_segment));
}
}
?>

The first child:

<?php
class GsParser extends SegmentParserAbstract {
    const SUPPLIER_ID_INDEX = 2;
    const GROUP_HEADER_INDEX = 6;
    protected $_invalidSegmentMessage= 'Invalid GS segment: ';
    protected  $_segmentRegex="/^GS\*IN\*\w{2,15}\*\w{2,15}\*(\d{6}|\d{8})\*\d{4}\*\d{1,9}\*X\*\d{1,12}$/";

    protected function createSegmentObject() {
        $elements = explode('*', $this->_segment);
        $gs = new Gs();
        $gs->setSupplierId($elements[self::SUPPLIER_ID_INDEX]);
        $gs->setGroupReference($elements[self::GROUP_HEADER_INDEX]);
        $this->_result->setSegment($gs);
    }
}
?>

The second child:

<?php
class IsaParser extends SegmentParserAbstract {
    const SUPPLIER_ID_INDEX = 6;
    protected $_invalidSegmentMessage= 'Invalid ISA segment: ';
    protected $_segmentRegex="/^ISA\*00\*.{10}\*00\*.{10}\*ZZ\*.{15}\*ZZ\*.{15}\*\d{6}\*\d{4}\*U\*.{5}\*\d{9}\*[0-1]\*[PT]\*>$/";

    protected function createSegmentObject() {
        $elements = explode('*', $this->_segment);
        $isa = new Isa();
        $isa->setSupplierId($elements[self::SUPPLIER_ID_INDEX]);
        $this->_result->setSegment($isa);
    }
}
?>

Now I'll be having about nearly 16 other parsers extending the same abstract class SegmentParserAbstract with only differing in the implementation of createSegmentObject() and the number of constants (which might have different names of course).

Somehow I feel that I can remove all sub classes and only keep the parent class and make it a concrete class that can be configured to work on any Segment provided it knows its regular expression and the data that needs to be extracted and the resulting object type.

Any help?!

Edit: As David pointed out in the comments, I am completely wrong about constructors in the abstract classes. I hid the (ir)relevant section to avoid confusion and attempted to edit the rest of the post so it fit the new context. In case I missed something, Abstract classes CAN have constructors because they CAN'T be instantiated therefore any references to the init() method that may be left over should be assumed to be parent::__construct() instead. Thank you again David.

  Abstract classes can not, or rather should not, be instantiated. Therefore they should never have a constructor. If you want to have a shared "constructor" there are a couple different things you can do. The easiest method is to create an init()-like function and call that in your real constructors.  Another method is to extend an actual class. Since you don't seem to be trying to instantiate this class, as some who use "abstract constructors" are wont to do, then I think the first solution should be adequate, though I should add that the init() method should not be public to avoid "accidental" reinstantion.

    protected function init() {
        $this->_result = new ParserResult();
    }

Abstract classes are still classes. Therefore anything defined in it is still defined in its children. Thus, redefining properties should actually be handled in construction, because, if I'm remembering this correctly, redefining them in the children actually throws warnings. Either way, the better place is in construction.

public function __construct() {
    $this->_invalidSegmentMessage = 'Invalid GS segment: ';
    $this->_segmentRegex = "/^GS\*IN\*\w{2,15}\*\w{2,15}\*(\d{6}|\d{8})\*\d{4}\*\d{1,9}\*X\*\d{1,12}$/";

    parent::__construct();
}

So, there are a few principles being violated in your createSegmentObject() method. The first, and most obvious, is the "Don't Repeat Yourself" (DRY) principle. This can be observed by how similar all these methods are. If we take into account the Inversion of Control (IoC) Principle as well, then we can see that it is violating both of these principles. IoC is something I've never really thought about before, so I don't feel entirely comfortable explaining it. Google it if you're not sure what it is, I'll be reading up on it more myself after this post. I think you began to notice something was amiss, which is why you added it to the abstract class, you just didn't go quite far enough with it. The third principle, which is making this a little more difficult to see, is that this method also violates the Single Responsibility Principle. This method should be concerned with creating a segment, not creating AND setting. Leave that for after you call the method. If we try setting it immediately then we can't extend it.

//abstract class
protected function createSegmentObject( Segment $segment ) {
    $elements = explode('*', segment);

    $segment->setSupplierId( $elements[ self::SUPPLIER_ID_INDEX ] );
    $this->segment = $segment;
    $this->elements = $elements;
}

//extending class
protected function createSegmentObject( Segment $segment ) {
    parent::createSegmentObject( $segment );

    $this->segment->setGroupReference( $this->elements[ self::GROUP_HEADER_INDEX ] );
}

//usage
if ($this->isValidSegment()) {
    $this->createSegmentObject();
    $this->_result->setSegment( $this->segment );
}

In case you are curious, createSegmentObject( Segment $segment ) is assuming that your "segments" are using a common interface or abstract class and that it is called "Segment". If you are not using one of these, then I would seriously think about doing so. Assuming for now that you are, then we can declare the parent class as the common denominator and type hint our parameters for it. This will ensure that any object passed to the above method must be a type of Segment and will be able to produce the expected results every time, else PHP will throw errors.

So, we've just eliminated most of the need for multiple classes. The only thing holding us back are these unique properties and the occasional extensions. The interesting thing about these classes is that the properties are very structured and unique. So what do we do when we have a common data structure that needs to be saved and reused? If we create a database with each row denoting a segment and each field a property, then we can construct our segments by calling that specific row in the database. Of course, we should inject these parameters into our constructor to avoid our class becoming dependent. I'll leave the database implementation to you, but here's the constructor:

public function __construct( $id, $group, $type, $regex ) {
    $this->_supplierIdIndex = $id;
    $this->_groupHeaderIndex = $group;
    $this->_invalidSegmentMessage = "Invalid $type segment: ";
    $this->_segmentRegex = $regex;

    parent::_construct();
}

That leaves us with just extensions holding us back now. We could create an elaborate comparison table and pick and choose when to use what, or we can automate the process and use a factory pattern. Again, I'm going to leave this up to you, for multiple reasons, but the main one being that I haven't played with factories yet and wouldn't be sure where to begin. Besides, without the rest of the subclasses I couldn't begin.

I believe some of this is what Saul linked to, but I just skimmed over it. I did spy something about a factory in there, so maybe much of this is the same, but it lacked a lot of the explanations that I felt were necessary. Hopefully this helps.


Recursion with char[] in c# I am trying to learn recursion and have a question involving an array that needs to be reversed. I am focusing on c# but the language probably doesn't matter a whole lot because my function is not using any libraries.
Here is my code:
char[] ReverseString(char[] s, int i = 0)
{
    char[] x = s;
    char temp = s[i];
    s[i] = s[s.Length - (i + 1)];
    s[s.Length - (i + 1)] = temp;

    i++;
    if (i < (s.Length) / 2)
    {
        ReverseString(s, i);
    }
    return x;
}

Any suggestions on how I should improve my function (maybe time complexity or using libraries (nuget packages)) is appreciated as well.

Honestly, this is not a very good problem to do recursively, just pick another problem. Here's a better one: take in an integer, and print the sum of the digits.
Some general feedback:

ReverseString returns something, but you ignore its return value
You make x, but it's a shallow copy of s -- modifying x and s do the same thing, and returning them would do the same thing. Just don't declare 'x' at all.
See how short you can make this. It's not good general advice, but it can be good advice when learning recursion.

One last tip when learning recursion: next time, try to do it without modifying a single variable. Just use expressions and return values. Again, it's not always how you should write real code, but it will help you learn faster.


Java split a string into ArrayList I want to split the following String into java ArrayList

"[\"1-72\",\"1-111\",\"1-4\"]"

I had wrote a very rough solution but not sure how to enhance it:

String sample = "\"[\"1-72\",\"1-111\",\"157f9d3dfb4-4\"]\"";
sample =  sample.replaceAll("\"", "");      //to replace double quote
sample = sample.replaceAll("\\[", "").replaceAll("\\]","");    //to replace open and close square bracket
List<String> sampleList= Arrays.asList(sample.split(","));
sampleList.forEach(System.err::println);

There are many encoding formats that could lead to this string. One of them is JSON. So instead of writing the splitting code yourself, you should use one of the many existing JSON parsers. Have a look at the awesome-java project at GitHub to find one.

Then, your code should become as simple as:

JSONArray sampleList = JSON.parseArray(sample);


"The Ministry of Truth" challenge I'm trying to solve Codeeval's The Ministry of Truth challenge, and have hit 97.5% - is anyone able to spot where my code is missing the last 2.5%? The percentage indicates that one or more of their test cases is failing.
Here's the question - I've used the original wording because I'm worried if I give my version of the problem then it'll be one that misses that 2.5% edge case:

Challenge Description:
It's 1984, and you are working as an official at the Ministry of Truth. You have intersected a message subjected to Big Brother's doctrine.
Your task is to delete letters from certain "utterances" in order to replace them with an "utterance" approved by the Ministry.
A "word" is a single sequence of Latin letters, and an "utterance" is a sequence of multiple words and spaces.
To compare two "utterances," you have to replace all blocks of spaces with one space. Utterances are considered to be identical when resulting expressions match.
One line contains two different expressions separated by semicolon ';'. The first expression is the original utterance, and the second one is the utterance you want to get.
If you cannot fulfill the order, print a single line «I cannot fix history». Otherwise, output the original utterance by replacing the letters that must be erased with underscore and by replacing all blocks of white spaces with a single white space.
Sample input lines:

Higher meaning;Hi mean
this is impossible;im possible
twenty   two minutes;two minutes
Higher meaning;e

Sample output lines:

Hi____ mean___
I cannot fix history
______ two minutes
____e_ _______

Here's the code so far (Python 3):

import sys
import re

with open(sys.argv[1], 'r') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue

        original, target = line.split(';')

        # Replace contiguous spaces with one space
        original = re.sub(r"\s+", " ", original)

        # Split target into targets
        targets = target.split()

        redacted, current_target, i, not_possible, space_next = '', 0, 0, False, False
        while i < len(original):
            if not space_next and current_target is not None and targets and len(targets) > 0 and len(original) >= i+len(targets[current_target]) and original[i:i+len(targets[current_target])] == targets[current_target]:
                redacted += targets[current_target]
                i += len(targets[current_target])

                if current_target < len(targets)-1:
                    current_target += 1
                    space_next = True
                else:
                    current_target = None

            elif original[i] == ' ':
                 redacted += ' '
                 space_next = False
                 i += 1
            else:
                redacted += '_'
                i += 1

        print('I cannot fix history' if current_target is not None else redacted)

For the overall program structure, I suggest:

Using fileinput instead of explicitly using sys.argv[1].  Your program would automatically switch between sys.stdin and the named file.
Breaking out the redaction logic into its own function, because each line is a self-contained problem with well-defined inputs and outputs.

To perform the redaction, I suggest using regular expressions, since this is just a pattern-matching problem.  You've used the re module already, so you might as well go all the way.

import fileinput
import re

def redact(original, target):
    matched = False
    def replacement(m):
        matched = True
        s = list(m.string)
        for g in range(1, 1 + len(m.groups())):
            for i in range(m.start(g), m.end(g)):
                s[i] = ' ' if s[i] == ' ' else '_'
        return ''.join(s)

    # Replace contiguous spaces with one space
    original = re.sub(r"\s+", " ", original)
    pattern = re.compile(
        '^(.*?)' +
        '( .*?|.*? )'.join(re.escape(c) for c in target.split(' ')) +
        '(.*?)$'
    )
    result = pattern.sub(replacement, original)
    return 'I cannot fix history' if matched else result

if __name__ == '__main__':
    for line in fileinput.input():
        line = line.strip()
        if not line:
            continue
        print(redact(*line.split(';', 1)))


Explosion animation plugin for a game I have been writing a small particle plugin since I want to learn how physics works for games. Now I have tried to get this as clean as I possible could but  It feels something is missing. Am I repeating too much code? Could this be improved in any way such as in performance?

https://jsfiddle.net/zdufwLv6/

new explodeLayer({
  particles: 17, xSpread: 5, ySpread: 20, colorIndex: 3, radius: 0, radiusMax: 100, x: 0, y: 0
})

function explodeLayer(obj) {
  var self = this;
  this.elem = document.getElementsByTagName('div');
  this.particle = [];
  this.radius = obj.radius;
  this.color = ['red', 'yellow', 'cyan', 'orchid']
  this.interval = 2 * Math.PI / obj.particles;

  this.init = function() {
    this.create();
    this.blast();
  }

  this.create = function() {
    for(var i = 0;  i < obj.particles; i++) {
      document.body.appendChild(document.createElement('div'));
      this.elem[i].style.background = this.color[obj.colorIndex];
      this.particle.push(new this.Properties(this.interval * i, obj.x, obj.y));
      this.updatePosition(i);
    }
  }

  this.Properties = function(angle, x, y) {
    this.angle = angle;
    this.x = x;
    this.y = y;
    this.vy = y;
    this.vx = y;
  }

  this.updatePosition = function(index) {
    this.elem[index].style.left = this.particle[index].x + 'px';
    this.elem[index].style.top = this.particle[index].y + 'px';
  }
    this.move = function() {
    for(var i = 0;  i < this.particle.length; i++) {
      this.particle[i].vy += 0.4;
      this.particle[i].x += this.particle[i].vx;
      this.particle[i].y += this.particle[i].vy;
      this.updatePosition(i);
     }
    requestAnimationFrame(function() {
      self.move.call(self);
    });
  }
  this.blast = function() {
    for(var i = 0;  i < this.particle.length; i++) {
      this.particle[i].x = Math.round(window.innerWidth) / 2 + this.radius * Math.cos(this.particle[i].angle);
      this.particle[i].y = Math.round(window.innerHeight) / 2 + this.radius * Math.sin(this.particle[i].angle);
      this.particle[i].vx = obj.xSpread * Math.cos(this.particle[i].angle);
      this.particle[i].vy = obj.ySpread * Math.sin(this.particle[i].angle);
      this.updatePosition(i);
    }
    requestAnimationFrame(function() {
      self.move.call(self);
    });
  }

  this.init();
}
html, body { background: rgb(30, 30, 30)}
div { padding: 8px; position: absolute; border-radius: 100%}

I would suggest moving out your animation loop to a separate system, and that your object at least have a render and update method (sort of an interface). That way, you have a centralized way to control the render loop, you're objects don't have to worry about the render loop while keeping the knowledge of how to render and update inside the object.

let objects = [];

// Render loop
function renderLoop(){
  requestAnimationFrame(renderLoop);
  objects.forEach(object => object.update());
  objects.forEach(object => object.render());
}

// Add objects
objects.push(new ExplodeLayer());
objects.push(new ExplodeLayer());
objects.push(new ExplodeLayer());
objects.push(new ExplodeLayer());

// Start loop
renderLoop();

explodeLayer is a constructor. It's a convention that constructors have the first letter of words in capital letters. It should be ExplodeLayer.

Also suggesting you move requestAnimationFrame call as the first call in the render loop. That way, scheduling the next frame won't be blocked by slow code before it and you're assured that the next callback is ready to be called regardless of slowdowns in code.

this.updatePosition = function(index) {
  this.elem[index].style.left = this.particle[index].x + 'px';
  this.elem[index].style.top = this.particle[index].y + 'px';
}

This is probably better when done in canvas for better performance, but I understand that there is an itch to do it in the DOM :D However, you can further improve performance by using CSS3 transforms, specifically the translate3D transforms. They have the advantage of being hardware-accelerated (the GPU does the work), making them smoother than normal.

Lastly, your explode layer is... a layer. It's comprised of particles. Suggesting you create a separate class for a single particle. That way, your explode layer can focus on being a layer (calculating position, managing particles, etc.), while particles can focus on how an individual particle renders (textures, colors etc.).


Stack using linked List I have this problem with my interview. I was asked to implement a stack using a linked list.

Gist

#!python

from linkedlist import LinkedList

# Implement LinkedStack below, then change the assignment at the bottom
# to use this Stack implementation to verify it passes all tests
class LinkedStack(object):

    def __init__(self, iterable=None):
        """Initialize this stack and push the given items, if any."""
        # Initialize a new linked list to store the items
        self.list = LinkedList()
        if iterable is not None:
            for item in iterable:
                self.push(item)

    def __repr__(self):
        """Return a string representation of this stack."""
        return 'Stack({} items, top={})'.format(self.length(), self.peek())

    def is_empty(self):
        """Return True if this stack is empty, or False otherwise."""
        return self.list.is_empty()
        # TODO: Check if empty

    def length(self):
        """Return the number of items in this stack."""
        return self.list.size
        # TODO: Count number of items

    def push(self, item):
        """Insert the given item on the top of this stack.
        Running time: O(1) – Just does an append, which is O(1)"""
        self.list.append(item)

def peek(self):
    """Return the item on the top of this stack without removing it,
    or None if this stack is empty."""
    if self.is_empty():
        return
    return self.list.get_at_index(self.length() - 1)

def pop(self):
    """Remove and return the item on the top of this stack,
    or raise ValueError if this stack is empty.
    Running time: O(n) – It will always loop through whole list before
    finding the item at the end"""
    if self.is_empty():
        raise ValueError("Cannot pop from an empty stack")
    item = self.peek()
    self.list.delete(item)
    return item

My code passed the following 6 tests. I make sure that my code works a pretty comprehensive following unit test cases, and it passed against all test cases, so the code seems to be working fine.

#!python

from LLstack import Stack
import unittest

class StackTest(unittest.TestCase):

    def test_init(self):
        s = Stack()
        assert s.peek() is None
        assert s.length() == 0
        assert s.is_empty() is True

    def test_init_with_list(self):
        s = Stack(['A', 'B', 'C'])
        assert s.peek() == 'C'
        assert s.length() == 3
        assert s.is_empty() is False

    def test_length(self):
        s = Stack()
        assert s.length() == 0
        s.push('A')
        assert s.length() == 1
        s.push('B')
        assert s.length() == 2
        s.pop()
        assert s.length() == 1
        s.pop()
        assert s.length() == 0

    def test_push(self):
        s = Stack()
        s.push('A')
        assert s.peek() == 'A'
        assert s.length() == 1
        s.push('B')
        assert s.peek() == 'B'
        assert s.length() == 2
        s.push('C')
        assert s.peek() == 'C'
        assert s.length() == 3
        assert s.is_empty() is False

    def test_peek(self):
        s = Stack()
        assert s.peek() is None
        s.push('A')
        assert s.peek() == 'A'
        s.push('B')
        assert s.peek() == 'B'
        s.pop()
        assert s.peek() == 'A'
        s.pop()
        assert s.peek() is None

    def test_pop(self):
        s = Stack(['A', 'B', 'C'])
        assert s.pop() == 'C'
        assert s.length() == 2
        assert s.pop() == 'B'
        assert s.length() == 1
        assert s.pop() == 'A'
        assert s.length() == 0
        assert s.is_empty() is True
        with self.assertRaises(ValueError):
            s.pop()

if __name__ == '__main__':
    unittest.main()

.pop() in a stack can be \$O(1)\$ with a proper implementation of linked list.


Navigation controller in Swift I was looking for a way to write this code shorter and still get the same result. Can this be achieved?

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if indexPath.row == 0 {
        print("connection status pressed")

        print("get")

        let connectionStatusSelectorViewController = ConnectionStatusSelector()
        //profileEditor.user = self.user
        navigationController?.pushViewController(connectionStatusSelectorViewController, animated: true)

    }else{
        if indexPath.row == 1 {
            print("account type pressed")

            let AccountSelectorViewController = AccountTypeSelector()

            navigationController?.pushViewController(AccountSelectorViewController, animated: true)

        }else{
            if indexPath.row == 2 {
                print("gender type pressed")

                let GenderSelectorViewController = GenderTypeSelector()
                navigationController?.pushViewController(GenderSelectorViewController, animated: true)

            }else{
                if indexPath.row == 3 {
                    print("service type pressed")

                    let serviceSelectorViewController = ServiceTypeSelector()
                    navigationController?.pushViewController(serviceSelectorViewController, animated: true)

                }else{
                    if indexPath.row == 4 {
                        print("distance pressed")

                    }else{
        print("nothing")
}
}
}
}
}
}

One simple thing that would clean this up is to use the else if keyword. So you would do:

if indexPath.row == 0
{
    // code here
}
else if indexPath.row == 1
{
    // code for 1 here
}
else if indexPath.row == 2
{
    // code for 2 here
}
else if indexPath.row == 3
{
    ...etc.
}

This eliminates the nesting and the excessive number of closing curly braces at the end.

You could also remove the intermediate values. So one of the bodies of the "if" statement might look like this:

if indexPath.row == 2
{
    print("gender type pressed")
    navigationController?.pushViewController(GenderTypeSelector(), animated: true)
}


Filtering a list of customers in Java based on three criteria Let's assume that you need to filter customers based on 3 criteria:

name
tags assigned to customer
customer's location

For some reasons you have to do it directly in your program code, without database queries or PL/SQL for that matter.
Which of these two solutions do you find better in any terms? (e.g code readability, performance, cleanliness)

First example

public List<Customer> filterStepbyStep(List<Customer> customers,
                                       String searchString,
                                       List<Tag> selectedTags,
                                       List<LocationId> selectedLocations) {
    List<Customer> filteredCustomers = new ArrayList<Customer>(customers);
    boolean searchStringNotEmpty = searchString != null && !searchString.trim().isEmpty();
    boolean locationsNotEmpty = selectedLocations != null && selectedLocations.size() > 0;
    boolean selectedTagsNotEmpty = selectedTags != null && selectedTags.size() > 0;

    filteredCustomers.removeIf(customer -> {
        boolean valid = true;

        //searchString
        if (valid && searchStringNotEmpty) {
            valid = customer.name.contains(searchString);
        }

        //locations
        if (valid && locationsNotEmpty) {
            valid = selectedLocations.stream().anyMatch(locationId -> locationId.equals(customer.locationId));
        }

        //tags
        if (valid && selectedTagsNotEmpty) {
            boolean tagValid = false;
            for (Tag selectedTag : selectedTags) {
                for (Tag customerTag : customer.getTags()) {
                    if (selectedTag == customerTag) {
                        tagValid = true;
                        break;
                    }
                }
                if (tagValid) {
                    break;
                }
            }
            valid = tagValid;
        }

        return !valid;
    });

    return filteredCustomers;
}

Second example

public List<Customer> filterWithLambda(List<Customer> customers,
                                       String searchString,
                                       List<Tag> selectedTags,
                                       List<LocationId> selectedLocations) {
    List<Customer> filteredCustomers = new ArrayList<Customer>(customers);
    boolean searchStringNotEmpty = searchString != null && !searchString.trim().isEmpty();
    boolean locationsNotEmpty = selectedLocations != null && selectedLocations.size() > 0;
    boolean selectedTagsNotEmpty = selectedTags != null && selectedTags.size() > 0;

    filteredCustomers.removeIf(customer -> {
        return (searchStringNotEmpty && !customer.name.contains(searchString))
                || (locationsNotEmpty && !selectedLocations.stream().anyMatch(locationId -> locationId.equals(customer.locationId)))
                || (selectedTagsNotEmpty && !selectedTags.stream().anyMatch(selectedTag ->
                      customer.getTags().stream().anyMatch(customerTag ->
                        selectedTag == customerTag)));
    });

    return filteredCustomers;
}

For me second example is more readable, I can immediately see that customer gets filtered out (removed) if any of 3 operands of OR operator is true.
On the other hand repeating if(valid) for each property in first example does not seem too clean to me. I also find it tiresome and tedious to follow valid variable. Having this kind of state with valid variable is IMO error-prone.
The only reason I can see, that one would prefer first example is not being familiar with lambda expressions.

I've created small repl.it to try these approaches out.

If you can think of better way of doing this, than two above examples, then please feel free to post it here.

As far as which is easier to read, there isn't a clearly correct answer. The second is more shorter, but more cramped. I personally prefer code with a little more whitespace, such as the first example. Others prefer code that's more succinct. Which is more readable is probably a question to ask your coworkers.

Marking variables as final will clue the reader in that they don't change once assigned.

In camelCase, the method name should be filterStepByStep.

Both methods use lambdas, so the name filterWithLambda is misleading.

In recent versions of Java, you don't need to specify the type on the right hand side of a generic assignment. You can just use <>.

You can get rid of 'valid' by returning false early.

The equals check for locations can be cleaned up using customer.locationId::equals, or, better, by just using contains.

The check on tags can be cleaned up using Set operations.

I would consider renaming the variables to matchCustomerName, matchLocation, and matchTags to make the checks read more cleanly.

If you were to make all these changes, your code might look more like:

public static List<Customer> filterStepByStep(
        final List<Customer> customers,
        final String searchString,
        final List<Tag> selectedTags,
        final List<LocationId> selectedLocations) {

    final List<Customer> filteredCustomers = new ArrayList<>(customers);
    final boolean matchCustomerName = searchString != null && !searchString.trim().isEmpty();
    final boolean matchLocation = selectedLocations != null && selectedLocations.size() > 0;
    final boolean matchTags = selectedTags != null && selectedTags.size() > 0;

    filteredCustomers.removeIf(customer -> {
        if (matchCustomerName && !customer.name.contains(searchString)) {
            return true;
        }

        if (matchLocation && !selectedLocations.contains(customer.locationId)) {
            return true;
        }

        if (matchTags) {
            final Set<Tag> matchedTags = new HashSet<>(selectedTags);
            matchedTags.retainAll(customer.getTags());
            return matchedTags.isEmpty();
        }

        return false;
    });

    return filteredCustomers;
}

public List<Customer> filterWithLambda(
        final List<Customer> customers,
        final String searchString,
        final List<Tag> selectedTags,
        final List<LocationId> selectedLocations) {

    final List<Customer> filteredCustomers = new ArrayList<>(customers);
    final boolean matchCustomerName = searchString != null && !searchString.trim().isEmpty();
    final boolean matchLocations = selectedLocations != null && selectedLocations.size() > 0;
    final boolean matchTags = selectedTags != null && selectedTags.size() > 0;

    filteredCustomers.removeIf(customer -> {
        return (matchCustomerName && !customer.name.contains(searchString))
                || (matchLocations && !selectedLocations.contains(customer.locationId))
                || (matchTags && !selectedTags.stream().anyMatch(customer.getTags()::contains));
    });

    return filteredCustomers;
}


Finding similarities between images I've posted here before and got pretty helpful reviews. How does my code look now? To keep it really helpful, I just copied this from the middle of one of my projects.

 <?php

  function findSimilarityBetweenImages($imagePathA, $imagePathB, $accuracy){

    //if images are png
    $imageA = imagecreatefrompng($imagePathA);
    $imageB = imagecreatefrompng($imagePathB);

    //if images are jpeg
    //$imageA = imagecreatefromjpeg($imagePathA);
    //$imageB = imagecreatefromjpeg($imagePathB);

    //get image resolution
    $imageX = imagesx($imageA);
    $imageY = imagesy($imageA);

    $pointsX = $accuracy*5;
    $pointsY = $accuracy*5;

    $sizeX = round($imageX/$pointsX);
    $sizeY = round($imageY/$pointsY);

    //Compare the color of each point while looping through.
    $y = 0;
    $match = 0;
    $num = 0;
    for ($i=0; $i < $pointsY; $i++) {
      $x = 0;
      for($n=0; $n < $pointsX; $n++){

        $rgba = imagecolorat($imageA, $x, $y);
        $colorsa = imagecolorsforindex($imageA, $rgba);

        $rgbb = imagecolorat($imageB, $x, $y);
        $colorsb = imagecolorsforindex($imageB, $rgbb);

        if(colorComp($colorsa['red'], $colorsb['red']) && colorComp($colorsa['green'], $colorsb['green']) && colorComp($colorsa['blue'], $colorsb['blue'])){

          $match ++; //Match between points.
        }
        $x += $sizeX;
        $num++;
      }
      $y += $sizeY;
    }
    //A similarity or percentage of match between the two images.
    $similarity = $match*(100/$num);
    return $similarity;
  }

  function colorComp($color, $c){
    //To see if the points match
    if($color >= $c-2 && $color <= $c+2)
    {
      return true;
    }
    else
    {
      return false;
    }
  }

?>

Since your question is about coding style, consider to adhere to PSR-2.

Your color comparision function is bloated. 'If the expression is true, then return true, else, if the expression is false, then return false.' Just return the expression.

return ($color >= $c-2 && $color <= $c+2);

Next, I'd make the literal '2' variable, and add some DocBlock documentation:

/**
 * Check if two color components are similar
 *
 * @param  int  $color  The first color component's value
 * @param  int  $c      The second color component's value
 * @param  int  $dist   The maximum difference for two values to be considered equal
 *
 * @return boolean  True, if the color components are similar.
 */
function colorComp($color, $c, $dist)
{
    return ($color >= $c-$dist && $color <= $c+$dist);
}


Using Booleans to Manage State I'm in the middle of writing my own little bullet shooter game much in the style of Touhou. Everything works fine so far but I'm disliking certain aspects of my code. Take this function for showing and unshowing the title screen:

    private function runIntro() : void
    {
        if (introFadeInTitle_ && aliceIntroTxt.alpha < 1)
            aliceIntroTxt.alpha += 0.02;
        else if (introFadeInTitle_)
        {
            var timer : Timer = new Timer(1000);
            timer.addEventListener(TimerEvent.TIMER, function() {
                timer.stop();

                introFadeInBtns_  = true;
            });
            timer.start();

            introFadeInTitle_ = false;
        }
        else if (introFadeInBtns_ && startBtn.alpha < 1)
        {
            startBtn.alpha   += 0.02;
            optionsBtn.alpha += 0.02;
        }
        else if (introFadeInBtns_)
        {
            introFadeInBtns_ = false;

            gameState = GameState.READY;
        }

        if (introFadeOutBtns_ && startBtn.alpha > 0)
        {
            startBtn.alpha   -= 0.02;
            optionsBtn.alpha -= 0.02;
        }
        else if (introFadeOutBtns_)
        {
            var timer : Timer = new Timer(500);
            timer.addEventListener(TimerEvent.TIMER, function() {
                timer.stop();

                introFadeOutTitle_ = true;
            });
            timer.start();

            introFadeOutBtns_ = false;
        }
        else if (introFadeOutTitle_ && aliceIntroTxt.alpha > 0)
            aliceIntroTxt.alpha -= 0.02;
        else if (introFadeOutTitle_)
        {
            var timer : Timer = new Timer(500);
            timer.addEventListener(TimerEvent.TIMER, function() {
                timer.stop();

                introFadeOutBg_ = true;
            });
            timer.start();

            introFadeOutTitle_ = false;
        }
        else if (introFadeOutBg_ && introBg.alpha > 0)
            introBg.alpha -= 0.02;
        else if (introFadeOutBg_)
        {
            introFadeOutBg_;

            gameState = GameState.RUNNING;
        }
    }

At a glance, it's just a bunch of if-else-if statements that check whether or not a given object has faded out and what the current state of the animation is. I feel that this if-else-if chain is alright for a rather short function like this, but I do have more complicated states that I wish to show (for example a ready-set-go splash before the fight begins) that would just balloon this kind of structure into an unholy mess.

What is the best way to deal with this code?

If ActionScript supports enums use an enum instead of the many booleans. If not, use a string with one constant for every state. It's also better than the booleans. For example:

...
else if (state == FADE_INT_ASDF) {
   state = CODE_OF_NEXT_STATE;
   gameState = GameState.READY;
}
...

If the logic was more complicated it would be worth implementing the State pattern.

If the booleans were replaced to an enum/string constants you can create a new setTimer function which could remove some code duplication:

private function setTimer(int timeout, IntroState/String newState) : void {
    var timer : Timer = new Timer(timeout);
    timer.addEventListener(TimerEvent.TIMER, function() {
        timer.stop();
        state = newState;
    });
    timer.start();
}