Expressing current time with natural language def current_time():
    '''Returns a tuple containing (hour, minute) for current local time.'''
    import time
    local_time = time.localtime(time.time())
    return (local_time.tm_hour, local_time.tm_min)

(hour,minute) = current_time()

def ishtime(hour, minute):
    import random

    Starting_str = ['it is','its',"it's","Current time is"]

    h_str = ['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve']

    mid_str = ['almost','nearly','roughly','maybe']

    Ex = ['Exactly' , 'Perpectly' ,'']

    m_str = ['ten','twenty','thirty','fourty','fifty']

    End_str = ['in the morning','in the afternoon','in the evening','at night']

## - define random strings

    Head = Starting_str[int(random.random()*4)]

    Mid = mid_str[int(random.random()*4)]

    Hour = h_str[(int(hour)-1)%12]

    if round(int(minute),-1) == 0 or round(int(minute),-1) == 60:
        Rand_m_str = ''
    else:
        Rand_m_str = m_str[int((round(int(minute),-1)/10))-1]

## -define for final ex)its , it's , almost, one two three..

    if int(hour)>=6 and int(hour)<13:
        Ending = End_str[0]

    elif int(hour)>=13 and int(hour)<19:
        Ending = End_str[1]

    elif int(hour)>=19 and int(hour)<=23:
        Ending = End_str[2]

    elif int(hour)>=0 and int(hour)<6:
        Ending = End_str[3]

## - define 'ending str' ex) in the morning

    if minute == 0 or minute == 00:
        Result = "%s %s 'o clock %s" %(Head,Hour,Ending)

    elif minute%10 == 0:
        Result = "%s %s %s after %s %s" %(Head,Ex[int(random.random()*4)],Rand_m_str,Hour,Ending)

    elif round(int(minute),-1) == 0 or round(int(minute),-1) == 60:
        Result = "%s %s %s%s %s" %(Head,Mid,Rand_m_str,Hour,Ending)

    else:
        Result = "%s %s %s minute after %s %s" %(Head,Mid,Rand_m_str,Hour,Ending)

    return Result

print ishtime(hour,minute)

I did this job.. how could i make it simpler?

Python supports double-ended inequalities:

End_str = ['at night', 'in the morning','in the afternoon','in the evening']

if 0 <= hour < 6:
    Ending = End_str[0]
elif 6 <= hour < 13:
    Ending = End_str[1]
elif 13 <= hour < 19:
    Ending = End_str[2]
elif 19 <= hour < 24:
    Ending = End_str[3]

I've changed 23 to 24 for consistency and rearranged the members of End_str.  I don't see how hour should be anything other than an integer, so I've removed the casts.

if minute == 0 or minute == 00 is redundant, since 00 is exactly the same as 0.

I would expect noon and midnight to be handled as special cases.


An efficient way to order content in controller [Spring Boot] My code works as intended. CategoryController class has getAllCategories method, which tells ContentOrderMap class to map differently ordered categories to their respective OrderType enum.
The intention is whenever @RequestParam(defaultValue = "DEFAULT") OrderType categoriesOrderType changes from DEFAULT, to lets say, POST_COUNT_DESC, I would get differently ordered categories in my view.
My concern is if this is an efficient way of dealing with multiple ways of ordering my content. Previously I had a bunch of if statements in my controller and they would take care of getting and assigning information to model based on request param. This didn't seem very scalable since my controller method would get very big and would contain logic, which I think should not be there.
I'm having trouble correctly wording my problem and issues since I am new to this, if anything is not clear enough, I will gladly reword or explain.
Controller:
@Controller
@RequestMapping("/categories")
public class CategoryController {

private CategoryService categoryService;
private ContentOrderMap orderMap;

public CategoryController(CategoryService categoryService, ContentOrderMap orderMap) {
    this.categoryService = categoryService;
    this.orderMap = orderMap;
}

@GetMapping("/all")
    public String getAllCategories(@RequestParam(defaultValue = "0") int pageNumber, Model model, @RequestParam(defaultValue = "DEFAULT") OrderType categoriesOrderType) {
        orderMap.mapCategoriesToOrderType(pageNumber);
        Page<Category> categories = orderMap.categoriesByOrderType.get(categoriesOrderType);
        int pageCount = categoryService.getAllCategories(pageNumber).getTotalPages();
        model.addAttribute("orderType", categoriesOrderType);
        model.addAttribute("categories", categories.getContent());
        model.addAttribute("pageNumber", pageNumber);
        model.addAttribute("hasNextPage", categories.hasNext());
        model.addAttribute("pageCount", pageCount);
        return "categories";
    }
}

ContentOrderMap class
public Map<OrderType, Page<Category>> categoriesByOrderType = new HashMap<>();

public void mapCategoriesToOrderType(int pageNumber) {
        categoriesByOrderType.put(OrderType.DEFAULT, categoryService.getAllCategories(pageNumber));
        categoriesByOrderType.put(OrderType.POST_COUNT_DESC, categoryService.getAllCategoriesByPostCountDesc(pageNumber));
        categoriesByOrderType.put(OrderType.POST_COUNT_ASC, categoryService.getAllCategoriesByPostCountAsc(pageNumber));
        categoriesByOrderType.put(OrderType.FOLLOWER_COUNT_DESC, categoryService.getAllCategoriesByFollowersCountDesc(pageNumber));
        categoriesByOrderType.put(OrderType.FOLLOWER_COUNT_ASC, categoryService.getAllCategoriesByFollowersCountAsc(pageNumber));
        categoriesByOrderType.put(OrderType.POST_DATE_DESC, categoryService.getAllCategoriesByNewestPost(pageNumber));
        categoriesByOrderType.put(OrderType.POST_DATE_ASC, categoryService.getAllCategoriesByOldestPost(pageNumber));
    }

CategoryService
all of the methods seen above are more or less identical in service class, they only differ in their naming, so I am going to add only one of them for brevity's sake
public Page<Category> getAllCategoriesByPostCountDesc(int pageNumber) {
        Pageable pageable = PageRequest.of(pageNumber, 4);
        return categoryRepository.findAllOrderByPostCountDesc(pageable);
    }

In case its needed, I add an example of how categoryRepository looks
@Query(value = "SELECT c.* FROM category c LEFT JOIN review r ON c.id = r.category_id GROUP BY c.id ORDER BY COUNT(*) DESC",
            countQuery = "SELECT COUNT(*) FROM CATEGORY",
            nativeQuery = true)
    Page<Category> findAllOrderByPostCountDesc(Pageable pageable);

Well, you found a workable solution.
One thing that strikes out at me is, that you expose the inner structure of your
ContentOrderMap by accessing orderMap.categoriesByOrderType.get(categoriesOrderType) directly.
The inner map categoriesByOrderType is an implementation detail, which you should not make
known in the public interface. Rather give ContentOrderMap a direct method which returns the page (and while we are at it: change the name, as nobody should care about the class being or containing a map.)
A problem remains, which is: changes will not be local at one place. When you add a new OrderType,
you have to extend the OrderType enum and the ContentOrderMap and the CategoryRepository.
Frankly, you'll not find a way to solve this problem in a 100% clean way, as it concerns the interface
(i.e. the REST service), and the database, so if you assemble your actual definition of a type and
the data storage effect it has in one place, you will have mixed responsibilities in that place.
However, if you think this mixing of responsibilities is bearable (everything is a tradeoff in software
engineering ;-)) you might think about harnessing the power of the java enum, which can implement an
interface. Something along the lines of:
public enum OrderType {
    DEFAULT("select c.* from whatever order by whatever"),
    POST_COUNT_DESC("select c.* from whatever order by something else"),
    ....;

    private final String query;

    private OrderType(String query) {
        this.query = query;
    }

    public String getQuery() {
        return query;
    }
}

This way, you only have to extend the enum, pass the constant on into your repository, and then do
whatever you need to do with the contained query.
Another alternative is, using your container. I'm not using spring, but there must be something along
the lines of a CDI Instance<>, which gives you a list of all implementations of a given interface.
In a CDI world, you could declare an interface:
public interface OrderHandler {
    public boolean handlesType(String orderType); // no enum, in the end REST sends you a string anyway
    public Page<Category> getResult(Pageable pageable);
}

Then write your different implementations of these interfaces, and get all of them via:
@Inject
Instance<OrderHandler> orderHandlers;

...

for (OrderHandler orderHandler : orderHandlers) {
    if (orderHandler.handlesType(myParameter)) {
        orderHandler.getResult(...);
    }
}

As I said, there must be something equivalent in spring.


ADDREV - Adding Reversed Numbers I've finished ADDREV challenge but I'm still not happy with my current solution. How can I still make my solution efficient without using the built-in std::reverse() function?

  The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.

  Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros.

  ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).

  Input

  The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.

  Output

  For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.

#include<string>
#include<iostream>

int reverse(int num);
int main() {
int n, a, b;

scanf_s("%d", &n);
while (n--) {
    std::cin >> a;
    std::cin >> b;
    //reverse the two number
    int sum = reverse(a) + reverse(b);
    sum = reverse(sum);

   //convert sum to string in order to remove zeroes
    std::string sumString = std::to_string(sum);
    sumString.erase(0, sumString.find_first_not_of('0'));
    std::cout << sumString;
}
    system("PAUSE");
    return 0;
}

int reverse(int num) {
   std::string r = std::to_string(num);
   std::string tmp;
   for (int i = r.length(); i >= 0; i--)
     {
       tmp = tmp + r.substr(i, 1);
     }
  return std::stoi(tmp);
}

Here's one way to reverse numbers without converting to strings and/or using std::reverse.  As per the challenge, this deals with only positive integers.

int RevNum( int num )
{
    int outVal = 0;
    while ( num > 0 )
    {
        int temp = num % 10;
        outVal = ( outVal * 10 ) + temp;
        num /= 10;
    }
    return outVal;
}

Because the number starts and stays as a number, zeros are automatically handled properly.


LeetCode 1638: Count Substrings That Differ by One Character I'm posting a solution for LeetCode's "Count Substrings That Differ by One Character". If you'd like to review, please do. Thank you!
Problem

Given two strings s and t, find the number of ways you can choose a
non-empty substring of s and replace a single character by a different
character such that the resulting substring is a substring of t. In
other words, find the number of substrings in s that differ from some
substring in t by exactly one character.
For example, the underlined substrings in "computer" and "computation"
only differ by the 'e'/'a', so this is a valid way.
Return the number of substrings that satisfy the condition above.
A substring is a contiguous sequence of characters within a string.

Example 1:

Example 2:

Constraints:

1 <= s.length, t.length <= 100
s and t consist of lowercase English letters only.

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

static const size_t getCounts(
    const char *source,
    const char *target,
    size_t s_index,
    size_t t_index
) {
    size_t counter = 0;
    size_t prev = 0;
    size_t curr = 0;

    while (s_index < strlen(source) && t_index < strlen(target)) {
        ++curr;

        if (source[s_index] != target[t_index]) {
            prev = curr;
            curr = 0;
        }

        counter += prev;
        ++s_index;
        ++t_index;
    }

    return counter;
}

static const int countSubstrings(
    const char *source,
    const char *target
) {
    size_t counters = 0;

    for (size_t s_index = 0; s_index < strlen(source); ++s_index) {
        counters += getCounts(source, target, s_index, 0);
    }

    for (size_t t_index = 1; t_index < strlen(target); ++t_index) {
        counters += getCounts(source, target, 0, t_index);
    }

    return counters;
}

int main() {
    printf ("%i \n", countSubstrings("aba", "baba"));
    printf ("%i \n", countSubstrings("ab", "bb"));
    printf ("%i \n", countSubstrings("a", "a"));
    printf ("%i \n", countSubstrings("abe", "bbc"));
    printf ("%i \n", countSubstrings("abeaskdfjpoirgfjifjwkdafjaksld",
                                     "fqowuerflqfdjcasdjkvlfkjqheofkjsdjfasldkf"));
    return 0;
}

Outputs:
6
3
0
10
1314

It looks nice, and you got the right algorithm.
Still, there are problems and additional ideas:

The const-qualifier on the two functions return-value is ignored. Didn't your compiler warn?

Denoting the start of a string-slice by pointer to start of the whole string and offset into it is cumbersome and inefficient. Just give a pointer to the start of the slice.

You are playing Shlemiel The Painter with all four strlen()-calls in your loops. The compiler might be able to hoist it four you, or it might not.
If it cannot, at least those in countSubstrings() are cheaper by some constant factor than the calls to a fixed getCounts(), and thus don't influence your codes big-oh.
But those in getCounts() turn the function from linear to quadratic, and thus the algorithm from quadratic to cubic.
What I don't get is why you ask for the strings length at all.
Just substitute !s[n] for strlen(s) == n.

Either int is always big enough, and should be used throughout, or it isn't,
and you have to play it safe by using size_t.

By the way, the problem is symmetric in its two arguments. That can be used.

And that was all I found.
static int getCounts(const char* a, const char* b) {
    int prev = 0;
    int curr = 0;
    int r = 0;
    for (; *a && *b; r += prev) {
        ++curr;
        if (*a++ != *b++) {
            prev = curr;
            curr = 0;
        }
    }
    return r;
}

static int manyCounts(const char* a, const char* b) {
    int r = 0;
    while (*a)
        r += getCounts(a++, b);
    return r;
}

int countSubstrings(const char * a, const char * b) {
    return !*a ? 0 : manyCounts(a + 1, b) + manyCounts(b, a);
}


jQuery animation procedural approach, suggestions need I'm kinda worried that the way I did my animation intro is a bit too heavy and is not optimized. Please review and let me know your thoughts.

$(document).ready(function() {

    introIconFirst();

    function introIconFirst() {
        $('h2.ribbon').css({
            'marginTop': '+30px',
            'opacity': '0'
        }).animate({
            marginTop: '0',
            opacity: '1'
        }, 1500, 'easeOutElastic', introIconSecond());
    }

    function introIconSecond() {
        $('#ico_website').rotate('0deg').css({
            'top': '+900px',
            'opacity': '0'
        }).animate({
            top: '50px',
            opacity: '1'
        }, {
            queue: false,
            duration: 1100,
            easing: 'easeOutElastic'
        }).animate({
            rotate: '-30deg'
        }, 1000, 'easeOutElastic', introIconThird());
    }

    function introIconThird() {
        $('#ico_rails').css({
            'top': '+900px',
            'opacity': '0'
        }).delay(300).animate({
            top: '145px',
            opacity: '1'
        }, 1400, 'easeOutElastic', introIconFourth());
    }

    function introIconFourth() {
        $('#ico_plane').css({
            'left': '255px',
            'top': '90px',
            'opacity': '0'
        }).delay(800).animate({
            top: '18px',
            left: '299px',
            opacity: '1'
        }, 600, 'linear');
    }

});

Looks good, though I prefer to keep the $(document).ready() as clean as possible, by only making calls and not definitions. Makes DOM management a bit easier.


Checking if a checker can move Imagine a game of Checkers, but you can move left right up down instead of diagonally. I have made an array to store liberties (available moves) and use if statements to update if a checker can move there.

Checkers can share liberties:

So the little black squares are liberties.

Here's my ugly if statement to update:

function updateLiberties(x, y, color)
{
    liberties[x][y] = 'None';

    if (color == 'white')
    {
        if (liberties[x + 1][y] == 'clear')
        {
            liberties[x + 1][y] = color;
        }
        else if (liberties[x + 1][y] == 'black')
        {
            liberties[x + 1][y] = 'both';
        }

        if (liberties[x - 1][y] == 'clear')
        {
            liberties[x - 1][y] = color;
        }
        else if (liberties[x - 1][y] == 'black')
        {
            liberties[x - 1][y] = 'both';
        }

        if (liberties[x][y + 1] == 'clear')
        {
            liberties[x][y + 1] = color;
        }
        else if (liberties[x][y + 1] == 'black')
        {
            liberties[x][y + 1] = 'both';
        }

        if (liberties[x][y - 1] == 'clear')
        {
            liberties[x][y - 1] = color;
        }
        else if (liberties[x][y - 1] == 'black')
        {
            liberties[x][y - 1] = 'both';
        }
    }

    if (color == 'black')
    {
        if (liberties[x + 1][y] == 'clear')
        {
            liberties[x + 1][y] = color;
        }
        else if (liberties[x + 1][y] == 'white')
        {
            liberties[x + 1][y] = 'both';
        }

        if (liberties[x - 1][y] == 'clear')
        {
            liberties[x - 1][y] = color;
        }
        else if (liberties[x - 1][y] == 'white')
        {
            liberties[x - 1][y] = 'both';
        }

        if (liberties[x][y + 1] == 'clear')
        {
            liberties[x][y + 1] = color;
        }
        else if (liberties[x][y + 1] == 'white')
        {
            liberties[x][y + 1] = 'both';
        }

        if (liberties[x][y - 1] == 'clear')
        {
            liberties[x][y - 1] = color;
        }
        else if (liberties[x][y - 1] == 'white')
        {
            liberties[x][y - 1] = 'both';
        }
    }
}

So a liberty can either be None (a checker is on it), clear (nothing is on it), black, white or both.

Any chance I make this look a little neater?

Well, to start with, there is 99% the same code, repeated twice. This is a very bad code smell. You need to turn the repeated code part into a function, like

function checkLiberties (color, otherColor) {
    if (liberties[x + 1][y] == 'clear') {
        liberties[x + 1][y] = color;
    } else if (liberties[x + 1][y] == otherColor) {
        liberties[x + 1][y] = 'both';
    }

    if (liberties[x - 1][y] == 'clear') {
        liberties[x - 1][y] = color;
    } else if (liberties[x - 1][y] == otherColor) {
        liberties[x - 1][y] = 'both';
    }

    if (liberties[x][y + 1] == 'clear') {
        liberties[x][y + 1] = color;
    } else if (liberties[x][y + 1] == otherColor) {
        liberties[x][y + 1] = 'both';
    }

    if (liberties[x][y - 1] == 'clear') {
        liberties[x][y - 1] = color;
    } else if (liberties[x][y - 1] == otherColor) {
        liberties[x][y - 1] = 'both';
    }
}

and then just call it twice, as

checkLiberties("black", "white");
checkLiberties("white", "black");

After this step, you need to check the same thing inside the function. Where you can spot a pattern in the code, try to turn into a function. I am sure the four chunks inside can become one.


Loop through List multi-threading to ping hostnames I am new to Multi-threading. I have had a go at writing some code that loops through an ArrayList, gets a hostname and then pings the hostname. If the hostname is not pingable it adds the hostname to a list returned by the method.

I am very new to multi-threading so I was just wondering if someone could give me a hand with improving this. For example I've heard that you can pass an ArrayList to Runnable but I can't find any good examples on how to do this yet.

Please note that I am using Java 5.

private ArrayList<String> pingNonReplicatingRegisters (
    Collection<RegisterReplicationSynchTime> nonReplicatingRegisters) throws IOException {

    final ArrayList<String> nonPingableRegisters = new ArrayList<String>();

    int nThreads = 15;
    final ExecutorService es = Executors.newFixedThreadPool(nThreads);

    for(RegisterReplicationSynchTime nonReplicatingRegister : nonReplicatingRegisters){

        final String registerHostName = nonReplicatingRegister.getRegisterName();

        es.execute(new Runnable(){
            public void run(){
                boolean status = false;
                Socket socket = null;
                PingBean pngBean = new PingBean();

                try {
                    SocketAddress socketAddress = new InetSocketAddress(registerHostName, 139);
                    socket = new Socket();
                    socket.connect(socketAddress, 1000); //1secs
                    status = true;
                    socket.close();
                } catch (IOException ex) {

                }
                finally {
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (PortUnreachableException e) {
                            socket = null;
                            System.err.println("Got an " + e);
                        } catch (UnknownHostException e) {
                            // TODO Auto-generated catch block
                            socket = null;
                            System.err.println("Got an " + e);
                        } catch (IOException e) {
                            socket = null;
                        }
                    }
               }// finally
               /* return status */
               if (!status) {
                   nonPingableRegisters.add(registerHostName);
               }
           }
        });
   }// for
   try {
       es.shutdown();
       es.awaitTermination(60, TimeUnit.SECONDS);
       List<Runnable> pending = es.shutdownNow();

       if (!pending.isEmpty()) {
           System.err.println("Pending threads: " + pending);
       }

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return nonPingableRegisters;
}

I think what you are looking for is the Callable<T> interface:

  A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.

Instead of having to pass around a thread-safe Collection to gather your non-pingable servers, you can call ExecutorService.invokeAll(Collection) to get a List<Future<T>>, which you can then retrieve the results.

First, I'll suggest having an implementation of Callable<T>:

public class Ping implements Callable<String> {

    private final String hostname;

    public Ping(String hostname) {
        this.hostname = hostname;
    }

    public String call() {
        // ... try to ping server
        // assume the results are stored in a boolean
        return isPingable ? "" : hostname;
    }

}

And then you can construct your Collection<Ping> to submit to the ExecutionService:

List<Ping> pingTasks = new ArrayList<Ping>(nonReplicatingRegisters.size());
for (RegisterReplicationSynchTime nonReplicatingRegister : nonReplicatingRegisters) {
    pingTasks.add(new Ping(nonReplicatingRegister.getRegisterName()));
}
// or use invokeAll(Collection, long, TimeUnit) for an explicit timeout
List<Future<String>> taskResults = es.invokeAll(pingTasks);
List<String> results = new ArrayList<String>();
for (Future<String> taskResult : taskResults) {
    try {
        String output = taskResult.get();
        if (!output.isEmpty()) {
            results.add(output);
        }
    } catch (InterruptedException e) {
        // handle accordingly
    } catch (ExecutionException e) {
        // handle accordingly
    }
}


A GapHelper static class to create unique (non-existing) size restricted names I am working with a 3th party library which has following interface defined for a processing task:

public interface IProcessor {
    void Execute( FileContent fileContent );
}

Such an IProcessor gives me the possibility to change the FileContent before it gets written to the database. For legacy reasons, and for integration reasons with an unnamed ERP, its unique identifiers are string identifiers which have a limitation in length, and they are padded on the left with padding char '0'.

Names will therefore always have the form of 00100 or 02301 or 10179 for a 5 digit identifier.

Sometimes, we need to add new content inside the fileContent.Components, but we are not allowed to change the existing identifiers. Theoretically any number of items could be added to the components, but for the question at hand, I simplified it to just adding 20 items.

The existing identifiers do not have any order to them, nor can I be sure that the highest number inside the string would be lower than the theoretical maximum number for this identifier.

To handle this addition, I thought I could use a IEnumerator<string> function (not class) as an iterator, that creates the next number starting from the theoretical minimum value to the theoretical maximum value, and throw when it exceeds the maximum value.

public static class GapHelper {
    public static IEnumerator<string> GetNextName( int maxSize, IEnumerable<string> items, Func<int, string> transform ) {
        var maxLength = (long)Math.Pow( maxSize, 10 );
        var hashSet = new HashSet<string>( items );
        for (var i = 0; i < maxLength; i++) {
            var text = transform(i);
            if (hashSet.Contains( text )) {
                continue;
            }
            yield return text;
        }
        throw new ArgumentOutOfRangeException( "Iteration exceeded maximum numbers of items at " + maxSize );
    }

    public static IEnumerator<string> GetNextName( int maxSize, IEnumerable<string> items) {
        return GetNextName( maxSize, items, i => i.ToString().PadLeft( maxSize, '0' ) );
    }
}

and this would be used inside such an IProcessor in the following way:

public class ProcessingTask : IProcessor {
    public void Execute( FileContent fileContent ) {
        using (var nameGenerator = GapHelper.GetNextName( 5, fileContent.Components.Select( c => c.Name ) ) ) {
            for (var i = 0; i < 20; i++) {
                nameGenerator.MoveNext();
                fileContent.Components.Add( new Component {
                    Name = nameGenerator.Current, Content = "Foo"
                } );
            }
        }
    }
}

What I cannot change:

How the processor is called, and with which parameters
How the file is processed afterwards, and might have been processed before
My bracket positioning, we have them at the end of each line
I am aware I didn't add documentation to the methods

A full simplified example can be found in this dotnetfiddle.

I am interested in how this code looks from maintainability perspective, and what other potential options I might have overlooked. I am also curious if having an IEnumerator<string> implemented as a method rather than a class makes a big difference, either for this implementation or from an iterator perspective.

Possible Bug

Since Func<int, string> transform is not guarded against collisions (different int values may yield the same string result), the next line is wrong. It only checks for unique elements in the already available data items, not in the new results fetched from transform.

 if (hashSet.Contains( text )) {

This could be solved by trying to add each element to the set instead:

if (!hashSet.Add( text )) {

LINQ

Furthermore, I would use an IEnumerable to allow for some LINQ chaining.

public static IEnumerable<string> GetNextName(
  int maxSize, IEnumerable<string> items, Func<int, string> transform) {

So we could just call:

public class ProcessingTask : IProcessor {
    public void Execute( FileContent fileContent ) {
        GapHelper.GetNextName(5, fileContent.Components
            .Select(c => c.Name)).Take(20).Select(x
                => new Component { Name = x, Content = "Foo" })
            .ToList().ForEach(fileContent.Components.Add);
    }
}

Which yields better readability. Also a fun fact about disposing an enumerator from the initial code:

 using (var nameGenerator = // ..


A geometry Sector Solver, Value finder for my calculator's micropython I made a program for my calculator for A levels that acquires the value of the angle and radius of a sector and gives:

Area of Sector
Area of inner Triangle
Arc Length
Chord Area
Chord Length
Sector Perimeter

I need some advice on compacting and making it more efficient, it would be also nice to have some coding tricks.

Disclaimer: my calculator uses micropython which lacks alot of functions, and modules however some functions from math work, check the documentary about it to confirm.

from math import pi, sin

def input_pi_replacer(prompt):
    return float(eval(input(prompt).replace("pi", str(pi))))

def stopper():
    stop_or_continue = input("Stop?: ")
    if stop_or_continue == "x":
        raise SystemExit

print("Sector Quantities\nCalculator:\n")
C_Factor = 0
Area = 0
B = 0
while True:
    C_Factor = 0
    Area = 0

    Unit = ""
    # + = degrees , - = radians
    while Unit not in ['+', '-']:
        Unit = input("For Deg, enter '+',\nFor Rad, enter '-'\n: ")
        if Unit == "+":
            C_Factor = pi/180
            break
        elif Unit == "-":
            C_Factor = 180/pi
            break
        elif Unit == ".":
            raise SystemExit
    # R = Radius, A = theta/angle in deg/rads, C_Angle = Converted Angle, C_Factor = Conversion Factor of Angle

    R = input_pi_replacer("\nEnter Radius: ")
    A = input_pi_replacer("Enter Theta/Angle: ")

    if Unit == "+":
        C_Angle = A * C_Factor
        Angle_In_Deg = A
    elif Unit == "-":
        C_Angle = A
        Angle_In_Deg = A * C_Factor

    print()
    Sector_Area = 1/2 * (R**2) * C_Angle
    Triangle_Area = 1/2 * (R**2) * sin(C_Angle)
    Arc_Length = R * C_Angle
    Chord_Area = Sector_Area - Triangle_Area
    Chord_Length = 2 * R * sin(C_Angle/2)
    Perimeter_Sector = 2 * R + Arc_Length
    print("Area of Sector\n= ", Sector_Area)
    print("Area of inner Triangle\n= ", Triangle_Area)
    print("Arc Length\n= ", Arc_Length)
    print("Chord Area\n= ", Chord_Area)
    print("Chord Length\n= ", Chord_Length)
    print("Sector Perimeter\n= ", Perimeter_Sector)
    print()
    stopper()

Naming

Variable and function names should be snake_case, not This_Format or This. Uppercase and PascalCase are reserved for class names.

Checking inside lists vs strings

If you're checking for a single character, it's better to use a string rather than a list. Have a look:

if unit in "+-":
    ...

The walrus operator

If you're using python-3.8 you can use the walrus operator. It's another way of saying assignment expressions. It's a way to assign a variable within an expression. In your case, you can utilize the walrus operator to assign input to a variable, and use that. Have a look:

while unit := input("For Degrees, enter '+',\nFor Radians, enter '-'\n: "):
    if unit in "+-":
        ...

So unit is assigned whatever the output of the input  call is.

Unneeded function

If your function is simply an input call, you don't really need it. Just put it at the end of the while loop.

Ternary operators

You can use these to greatly shorten the length of your code. It's an easier way to assign values based on conditions. Take a look at the final code to see what I'm saying.

f-strings

You should use f"" to directly implement variables in your strings. It's a cool feature that keeps you from having to + or call a .format on your strings. Have a look:

print(f"Area of Sector = {sector_area}")
print(f"Area of inner Triangle = {triangle_area}")
...

Final code

After all these suggestions, you code would look something like this:

from math import pi, sin

def input_pi_replacer(prompt):
    return float(eval(input(prompt).replace("pi", str(pi))))

print("Sector Quantities Calculator:\n")
while True:

    while unit := input("For Degrees, enter '+',\nFor Radians, enter '-'\n: "):
        if unit in "+-.":
            if unit == ".":
                raise SystemExit
            c_factor = (pi / 180) if unit == "+" else (180 / pi)
            break

    radians = input_pi_replacer("\nEnter Radius: ")
    angle = input_pi_replacer("Enter Theta/Angle: ")

    c_angle = angle * c_factor if unit == "+" else angle

    print()
    sector_area = 1 / 2 * (radians ** 2) * c_angle
    triangle_area = 1 / 2 * (radians ** 2) * sin(c_angle)
    arc_length = radians * c_angle
    chord_area = sector_area - triangle_area
    chord_length = 2 * radians * sin(c_angle / 2)
    perimeter_sector = 2 * radians + triangle_area

    print(f"Area of Sector = {sector_area}")
    print(f"Area of inner Triangle = {triangle_area}")
    print(f"Arc Length = {arc_length}")
    print(f"Chord Area = {chord_area}")
    print(f"Chord Length = {chord_length}")
    print(f"Sector Perimeter = {perimeter_sector}")
    print()

    if input("Stop?: ").lower() == "x":
        raise SystemExit


Bloom filter implementation using a BitArray I am following the Wikipedia definition of the Bloom filter. My implementation uses the BitArray I created here. Here is an alternative implementation by Ilya Grigorik.

# n = Number of items in the filter
# p = Probability of false positives, float between 0 and 1 or a number indicating 1-in-p
# m = Number of bits in the filter
# k = Number of hash functions

require_relative '../bitarray/bit_array'
require 'digest'

class BloomFilter

  def initialize k: 1, m: 10
    @k = k
    @m = m
    @n = 0
    @b = BitArray.new
  end

  # Probability of a false positive based on formula in wikipedia
  def false_positive_rate
    fp_rate = (1-(1-1/@m.to_f)**(@k.to_f*@n.to_f))**@k.to_f
    p fp_rate
    fp_rate.round(2)
  end

  def insert item
    @n += 1
    @k.times do |n|
      hash_val = Digest::MD5.hexdigest( item.to_s + n.to_s ).to_i(16)
      position = hash_val % @m
      @b.set position
    end
    self
  end

  def include? item
    @k.times do |n|
      hash_val = Digest::MD5.hexdigest( item.to_s + n.to_s ).to_i(16)
      position = hash_val % @m
      return @b.get(position) == 1
    end
    return false
  end

end

The test:

require 'minitest/autorun'
require_relative 'bloom_filter'

class BloomFilterTest < MiniTest::Unit::TestCase

  # Verified probability formula and tests from http://hur.st/bloomfilter?n=1&p=0.01
  def test_stats
    assert_equal 0.01, BloomFilter.new(k: 7, m: 10).insert("a").false_positive_rate
    b = BloomFilter.new(k: 2, m: 29)
    10.times { |n| b.insert(n) }
    assert_equal 0.25, b.false_positive_rate
  end

  def test_include
    b = BloomFilter.new(k: 2, m: 100)
    b.insert "The Trumpet of the Swan"
    assert_equal true, b.include?("The Trumpet of the Swan")
    refute b.include?("E. B. White")
  end

end

You're using assert_equal to compare something with true - which is exactly what the basic assert method already does. Just like you use refute to check that something's false, assert checks that something's true.
You might want to check that \$k ≤ m\$. Doesn't really make sense otherwise. (Of course it doesn't really make sense for \$k\$ to equal \$m\$ either, as adding just 1 item would set every bit right away, but at least that's technically valid.)
In this case, I'm OK with using single-letter variables like k and m, since that appears to be conventional enough, and they're hard to give simple, yet descriptive names. However, I'd also add copious comments to explain exactly what the heck they mean. I had to go to Wikipedia to find out. (Edit: Sorry, comments already there, just not by the #initialize method, where I expected them to be.)
p fp_rate - don't leave print calls in final code (unless that code's purpose is to print, of course).
Why does #false_positive_rate round its output? Rounding is a presentation concern; the rate just is what it is, decimals and all. I'm thinking you're maybe rounding so it passes your tests, but in that case you're writing your code backwards.
Your #include? method is broken. It'll return (from the method; not just the block) at the first bit it checks - it won't check all of them. So if the first bit it checks is zero, you get false - which is correct! But if the first bit is 1, you immediate get true even though none of the other k-1 bits have been checked.
This also means that your false positive rate is at best

$$1 - (1 - \frac{1}{m})^n$$

because \$k\$ is effectively always 1 when checking. But if \$k\$ is higher, then we'd be setting more bits than we're checking, so the bit array fills up faster.
For instance, if \$k = 2\$ and \$m = 4\$ (extreme values; just for illustration), then the first item (call it \$A\$) we insert should set half of the bits in the bit array. That should (if my math is correct) give a false positive rate of ~19% after adding that one item: There's a 19% chance that another item, \$B\$, will match the same 2 bits. But if we only check 1 bit, then the false positive rate is essentially 50%, since half the bits in the array are set.

Making only only minimal changes, you could do this:

@k.times do |n|
  hash_val = Digest::MD5.hexdigest( item.to_s + n.to_s ).to_i(16)
  position = hash_val % @m
  return false if @b.get(position).zero?
end
true

Now, it'll only return if a bit is zero, otherwise it'll keep going.
But your hashing logic is flawed too, I'm afraid. There's no guarantee that it'll return \$k\$ unique bit positions (for \$k > 1\$). It's possible (though unlikely) that you'll calculate \$k\$ MD5 hashes that are all cleanly divisible by (i.e. are multiples of) \$m\$. In that case, you'd just get the bit position zero \$k\$ number of times and end up setting a single bit. It's a similar situation to the one above, since again, the false positive rate rises.
If, for example, \$k = 2\$ and \$m = 4\$ again, and we've added item \$A\$ which (correctly) set 2 bits, we should have that 19% false positive rate when checking \$B\$. But if the hash for \$B\$ works out so that it's just 1 bit instead of 2, then we're back to a 50% false positive rate since it's only that 1 bit that would have to match, rather than 2 separate bits.

Frankly, I don't know enough about creating robust hashing functions to offer a good solution to this. I'll continue and I'll provide alternative code for different things, but it all includes this basic flaw (except in the addendum at the end). The code I provide here won't fix that; it's there to illustrate other aspects of the code.
You've duplicated the logic for hashing items. Duplication is always bad, but this is a prime example of why: If the two pieces of code aren't exactly identical, the whole thing stops functioning. I'd extract the hashing logic into a separate, private method that returns an array of bit positions

 def item_bit_positions item
   @k.times.map do |n|
     hash = Digest::MD5.hexdigest("#{item}#{n}").to_i(16)
     hash % @m
   end
 end

You'll note that I'm using string interpolation; IMO it's clearer than manually calling to_s and concatenating. The results the same, though, but that result may not be what you want (see below)
Using MD5 and then discarding a bunch of stuff really feels like overkill. Ruby already maintains a hash for anything that inherits from Object (i.e. everything). It's what's used to check for object equality, and it's hexadecimal number you see printed if you print an object that doesn't have a #to_s method.
#hash is just a (signed) integer. You could do something like:

 def item_bit_positions item
   @k.times.map { |n| item.hash % (@m-n) }
 end

(Again, this is just as flawed [edit: Actually, it's more flawed, see below] as your current implementation (it can return fewer than \$k\$ positions); it's just here to illustrate how #hash can be used.)

The above does not require digest. It does however require that \$k ≤ m - 1\$, or you'll get a divide-by-zero error.

Note, though, that unlike MD5 which will always produce the same output for a given input, #hash is simply a number generated at runtime, so it'll be different each time you run the code. This could make testing tricky, since you're also dealing with something that can produce false positives. (One solution to this might be to stub out #hash on the items you're inserting.)

Using #hash also changes the behavior somewhat since it's now about object-wise equality - not string-wise equality. In your implementation, the string "foo" and the symbol :foo would be treated as one and the same, since both have the same string representation, and you're converting everything to a string to calculate the MD5 hash. But using #hash there's no such collision.
You're using your BitArray class, but I'd be tempted to just re-roll some of the same logic here, since it doesn't take much, and the implementation can be more specific. You can do everything with integers and bitwise manipulation.

class BloomFilter
  # This reader is mostly here for test purposes,
  # which isn't too pretty, I'm afraid. At least
  # it's a pretty harmless addition
  attr_reader :bit_array

  # TODO: Explain what k and m mean!
  def initialize(k = 1, m = 10)
    k, m = k.to_i, m.to_i
    raise RangeError, "k must be smaller than m" if k >= m
    raise ArgumentError, "k and m must be positive integers" if k < 1
    @k = k
    @m = m
    @bit_array = 0
  end

  def insert(item)
    @bit_array |= digest(item)
    self
  end

  def include?(item)
    hash = digest(item)
    @bit_array & hash == hash
  end
  alias_method :member?, :include?

  private

  # WARNING: This method is flawed! See answer
  def digest(item)
    hash = item.hash
    @k.times.map do |n|
      bit = (hash % (@m-n))
      2**bit
    end.inject(&:|)
  end
end

gem 'minitest'
require 'minitest/autorun'

class BloomFilterTest < Minitest::Test
  def test_initialize_with_valid_args
    assert BloomFilter.new(1, 2)
  end

  def test_initialize_with_invalid_args
    assert_raises RangeError do
      BloomFilter.new(2, 2)
    end
  end

  def test_initialize_with_negative_args
    assert_raises ArgumentError do
      BloomFilter.new(-2, 2)
    end
  end

  def test_insert_uses_the_items_hash
    item = mock_item(123)
    instance = BloomFilter.new
    instance.insert(item)
    item.verify
  end

  def test_insert_changes_the_bit_array
    instance = BloomFilter.new
    previous = instance.bit_array
    instance.insert(Object.new)
    refute_equal previous, instance.bit_array
  end

  def test_include_uses_the_items_hash
    item = mock_item(123)
    instance = BloomFilter.new
    instance.include?(item)
    item.verify
  end

  def test_include_returns_true_for_member
    item = mock_item(123, 2)
    instance = BloomFilter.new
    instance.insert(item)
    assert instance.include?(item)
  end

  def test_include_returns_false_for_nonmember
    member = mock_item(123)
    non_member = mock_item(122)
    instance = BloomFilter.new(3, 10)
    instance.insert(member)
    refute instance.include?(non_member)
  end

  # An intentionally failing test
  def test_digest_always_sets_k_bits
    k = 3
    item = mock_item(720) # multiple of 10, 8 and 9
    instance = BloomFilter.new(k, 10)
    hash = instance.send(:digest, item) # testing private method
    assert_equal k, count_bits(hash), "Note: This test intentionally fails!"
  end

  # A helper method (mock object factory)
  def mock_item(hash, calls = 1)
    mock = Minitest::Mock.new
    calls.times { mock.expect(:hash, hash) }
    mock
  end

  def count_bits(number)
    count = 0
    until number == 0
      count += (number & 1)
      number = number >> 1
    end
    count
  end
end

A thing I've noticed in you past few questions: You're writing tests which is great, but you're writing the barest minimum of tests. For instance, you're not testing #insert at all, and your test for #include? doesn't include an edge case as the one mentioned above where 2 items shared the same first bit - but not all of them.

Basically, you should have a higher test-to-code ratio. It's not uncommon to have way more test code than implementation code; in fact that's something to aim for.

Addendum: This is an interesting topic, actually. Not usually my cup of tea (I suck at theoretical stuff like this), but I got nerd sniped.

I've also realized that my hash implementation is even more flawed than I thought: Even if it manages to set \$k\$ bits (which isn't guaranteed), their distribution isn't random. Since I'm using modulo @m - n, only the first iteration has a chance of setting the highest bit. Boo, me, boo.

Anyway, as I said, I don't know of a way to construct a hash function that will always set exactly \$k\$ bits with random distribution, and I'm not smart enough to work one out - but I can think of a hack.

If \$m\$ is simply defined to be some multiple of \$k\$, then we can do something like this:

If we say that \$k = 4\$ and our multiplier \$f = 8\$ (just as an example), then \$m = k \cdot f = 32\$. So we have an array that's 32 bits long, or - to put it another way - we have 4 arrays that are each 8 bits long.

We can then do something like this (using #hash for simplicity):

mask = 0
k.times do |n|
  hash = calc_hash(n, item) # calculate a big 'ol hash (assume this method exists)
  mask = mask << f          # shift our current mask f places
  mask |= 2**(hash % f)     # set a bit somewhere in the lower f places
end

mask will now contain exactly 4 "set" bits - one in each of its 4 "sections". Even if 2**(hash % f) is the same for each iteration, it'll still end up in different places, since we shift the mask.

This will not have the same false positive rate as a proper hashing function, but at least it'll be predictable. But it will be slightly worse overall.

In essence, what we have are four Bloom filters, each set to \$k = 1\$ and \$m = f\$. So (if my math is correct, which is not something to rely on) our false positive rate should be the regular rate for one such filter, but to the power of 4. Or, in mathematical terms:

$$(1 - (1 - \frac{1}{f})^{n})^{k}$$

(I think that's correct but I may be completely wrong)


Converting a string to an Integer in C I'm learning C and one of the questions I've been asked is converting a string to an integer. The code I've written supports converting from a string in any base up to 16/hex to an integer. There is no  over/underflow checking and it does not support lowercase hex.

int ASCIIToInteger(char *x, int base)
{
    //Each element is the ASCII for it's index.
    int ASCIICodes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  _Bool negative = 0;
    int count = 0, output = 0;
    if (x[0] == '-')
    {
        negative = 1;
        count = 1;
    }
    else if (x[0] == '+')
    {
        count = 1;
    }
    do
    {
        for (int i = 0; i < base; i++)
        {
            if (ASCIICodes[i] == (int)x[count])
            {
                output = output * base + i;
                break;
            }
        }
        count++;
    } while (x[count] != 0);

    if (negative == 1)
    {
        return ~output + 1;
    }
    return output;
}

Can I please get some advice regarding any possible issues or "rookie mistakes" I may have made?

Avoid mysterious bit-shifting
return ~output + 1;

Is the same as:
return - (output + 1) + 1;

And as:
return - output;

But the last one is way more obvious than the first one.
Do not hide variable declarations
int ASCIICodes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  _Bool negative = 0;

If I look at the above line, the least thing in my mind is that a variable is defined after that list.
If a user has a small screen or a big font size he will be very puzzled when he will see you use negative without seeing its definition.
Just use a newline, they are free:
int ASCIICodes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
_Bool negative = 0;

Make variables as local as possible
I used x++ to express that I will skip the first character:
if (x[0] == '-')
{
    negative = true;
    x++;
}
else if (x[0] == '+')
{
    x++;
}

This allows me to make count local.
Using for loops when practical
The outer of your loops is a do while, but looking around I found all three components of a for loop, just shuffled into the code.
A for loop will give it more organization:
for (int count = 0; x[count] != 0; count++)
{
    for (int i = 0; i < base; i++)
    {
        if (ASCIICodes[i] == x[count])
        {
            output = output * base + i;
            break;
        }
    }
}

Simplify the initial conditional
Assigning a boolean to negative directly and using a || conditional looks shorter and simpler:
We go from:
_Bool negative = 0;
int count = 0, output = 0;
if (x[0] == '-')
{
    negative = 1;
    count = 1;
}
else if (x[0] == '+')
{
    count = 1;
}

to:
bool negative = x[0] == '-';

if (x[0] == '-' || x[0] == '+')
{
    x++;
}

While preserving identical functionality.
it's vs its

... How to choose between it's and its?
This is actually really easy, do you mean "it is" or not?

Use it's when you mean it is.
// Each element is the ASCII for it's index.

Here you should write its because you mean possession, intended as a property of the element.
Saying that:
// Each element is the ASCII for it is index.

Makes no sense.
So the correct comment will be:
// Each element is the ASCII for its index.


Good Unit Tests when ReSharper bugs for null checks I have the latest version of ReSharper installed and I am trying to write a Unit Test for my MVC controller. I need the Unit Test to:

  Ensure the ViewModel passed to the View is of the correct type.

So here is what I have at the moment:

public void Create_HasCorrectViewModelType()
{
    // arrange
    var controller = new DraftController(_draftFacade);
    // act
    var viewResult = controller.Create() as ViewResult;
    var viewModel = viewResult.Model as DraftViewModel;
    // assert
    Assert.IsInstanceOfType(viewModel.GetType(), typeof(DraftViewModel));
}

I have issues with this, and would like to know your thoughts on the matter.

the arrange makes sense. I am arranging / setting up my controller.
Only the first line in the act seems logical to me. But me trying to grab the ViewModel isn't really an Act is it? Sounds like // arrange again!
ReSharper complains that I am not doing null checks on viewResult and viewModel.

I can go with ReSharper's recommendation, then my test becomes:

public void Create_HasCorrectViewModelType()
{
    // arrange
    var controller = new DraftController(_draftFacade);
    // act
    var viewResult = controller.Create() as ViewResult;
    var viewModel = viewResult?.Model as DraftViewModel;
    // assert
    if (viewModel != null) Assert.IsInstanceOfType(viewModel.GetType(), typeof(DraftViewModel));
}

Now ReSharper is happy, but then my Unit Test don't seem clean anymore! I feel like there are too many paths that can be taken for that one unit test.

Anyone else bugged by this? What can I do to improve this? Or is this the best I'm going to get?

Any help would be greatly appreciated.

Asserting

if (viewModel != null) Assert.IsInstanceOfType(viewModel.GetType(), typeof(DraftViewModel));

You should use another assert and not an if
Assert.IsNotNull(viewModel);

Resharper even suggests this option:

Test name

Create_DraftFacade_ViewResultWithDraftViewModel

You might also want to reconsider the naming of your tests. Usually we use this pattern

TestedMethod/Property_TestData/Case_ExpectedResult


Particles moving around a Perlin Noise field I made this sketch in Processing (basically Java) that consists of a bunch of particles moving around a Perlin Noise field. Each particle is aware of the position of one other particle and this creates a rope like effect. The sketch is intended to be aesthetic, like a screensaver, and I in that way it might be difficult to judge the efficiency of the code.

Nevertheless, I'm hoping that there is something that I'm doing wrong stylistically that could be pointed out.

    int emergenceInterval = int(random(75, 100));
    float a, freq = 0.05;
    float alphDelta, alphAccel, alphSpringing = 0.0009, alphDamping = 0.98, alphX, maxAlph;
    int pAmt = int(random(2000, 4000));
    Particle p[] = new Particle[pAmt];

    void setup() {
      background(0);
      size(1000, 500);
      for (int i = 0; i < pAmt; i++) {
        p[i] = new Particle(random(width), random(height), i);
      }
    }

    void draw() {
      if(frameCount % emergenceInterval == 0) {
       if(maxAlph == .05) maxAlph = 1;
       else maxAlph = .05;
      }
      a += freq;
      fill(50, findAlpha() * 255);
      rect(0, 0, width, height);
      runParticles();
    }

    void runParticles() {
      for (Particle _p : p) {
        Particle lastP = _p;
        if (_p.index != 0) lastP = p[_p.index - 1];
        _p.update(450, lastP.pos, abs(pow(sin(radians(a)), 3)));
        point(_p.pos.x, _p.pos.y);
        _p.vel.x = 1;
      }
    }

    float findAlpha() {
      if (!(alphAccel < 0)) alphDelta = width - alphX;
      else alphDelta = 0 - alphX;
      alphDelta *= alphSpringing;
      alphAccel += alphDelta;
      alphAccel *= alphDamping;
      alphX += alphAccel;
      float alph = (alphX * (maxAlph * abs(pow(sin(radians(a)), 2))))/width;

      if(alphX > width) alphAccel *= -1;
      else if(alphX < 0) alphAccel *= -1;
      return alph;
    }

  class Particle {

  int index;
  float theta;
  float stride;
  float maxSpeed = 5;
  float maxChaos = 10;
  PVector accel, vel, pos;

  Particle(float startX, float startY, int index) {
    this.index = index;
    accel = new PVector(0, 0);
    vel = new PVector(0, 0);
    pos = new PVector(startX, startY);
  }

  void update(float stride, PVector target, float chaos) {
    this.stride = stride;
    stroke(50*(noise(pos.x)),0,50*(noise(pos.x)), noise(pos.x, pos.y) * 255);
    accel = noiseDir(chaos);
    accel.add(followDir(target));
    if (pos.x > width) pos.x = 0;
    if (pos.y > height) pos.y = 0;
    if (pos.y < 0) pos.y = height;
    vel.add(accel);
    float speed = noise(pos.x, pos.y) * maxSpeed;
    vel.limit(speed);
    pos.add(vel);
  }

  PVector noiseDir(float chaos) {
    theta = abs(noise(pos.x, pos.y)) * 180;
    float x = pos.x + stride * cos(theta);
    float y = pos.y + stride * sin(theta);
    PVector dir = new PVector(x - pos.x, y - pos.y);
    dir.normalize();
    dir.mult(chaos * maxChaos);
    return dir;
  }

  PVector followDir(PVector target) {
    PVector dir = new PVector(target.x - pos.x, target.y - pos.y);
    dir.normalize();
    dir.mult(5);
    return dir;
  }
}

(1). From the point of style I'd recommend you not to mix the level of details in a function. For example.

Instead of writing something like this:

void setup() {
  background(0);
  size(1000, 500);
  for (int i = 0; i < pAmt; i++) { // this is bad
    p[i] = new Particle(random(width), random(height), i);
  }
}

You should write something like this. The same is applicable for other functions.

void setup() {
  background(0);
  size(1000, 500);
  fillArray(); // there goes the loop and it's load easier to read.
}

(2). As for naming conventions I'd recommend you to use a verb as a first part for the function's name. Code like this looks unusual.

background(0);
size(1000, 500);

(3). You should be consistent with names for your variables. For example in your update() function you can see a mix of full and short names like stride, target, chaos vs accel, vel, pos. It really makes me think a lot more about names than I should.

(4).If you have to call this "normalize()" method a lot after construction of the object I'd recommend to think about adding this method to consturctor for example with the flag called "shouldNormalize".

PVector dir = new PVector(x - pos.x, y - pos.y);
dir.normalize();

vs

PVector dir = new PVector(x - pos.x, y - pos.y, true);
//or make it to normalize the vector by default and pass false when you don't need it
//but I guess that you should normalize it quite often after creation

(5). I would strongly recommend to make Particle class immutable. It would save you from a lot of hacks like this and make your code cleaner:

 void update(float stride, PVector target, float chaos) {
 this.stride = stride;
 ... }


R function for a timer with a beep I wrote a quick timer function that depends on the beepr package to provide the sound effect at the end of the time.  I've never used a while-loop before, so I don't know if there's a more elegant way to write this (i.e., one that doesn't require repeating the same line of code twice?).  I'd appreciate knowing if there is a better way:

timer <- function(interval, units) {
require(beepr)
t0 <- Sys.time()
stopwatch <- round(as.double(difftime(Sys.time(), t0, u = units)))
while(stopwatch < interval){
  stopwatch <- round(as.double(difftime(Sys.time(), t0, u = units)))
  }
beep(2)
}

timer(5, "secs")

To avoid repeating code, you could have used:

done <- FALSE
while(!done){
  done <- round(as.double(difftime(Sys.time(), t0, u = units))) >= interval
}

Note however that a for loop is quite taxing on your CPU. Instead, you should use the friendlier Sys.sleep function. It takes a number of seconds as input:

timer <- function(num_sec) {
   Sys.sleep(num_sec)
   if (require(beepr)) beep(2) else message("DONE!")
}

Notice how I improved your code regarding the use of require, since you had not accounted for the possibility that your user does not have the beepr package installed. If you want to make the beepr package a requirement, then calling library(beepr) is prefered to require(beepr), the blog here https://yihui.name/en/2014/07/library-vs-require/ offers a nice explanation.

If you absolutely want your function to allow to pass "minutes", "days", etc. (though I would stay away from it), you can do:

timer <- function(interval, units = c("secs", "mins", "hours", "days", "weeks")) {
   units <- match.arg(units)
   num_sec <- interval * switch(units, secs = 1, mins = 60, hours = 3600,
                                       days = 86400, weeks = 604800)
   Sys.sleep(num_sec)
   if (require(beepr)) beep(2) else message("DONE!")
}


SQL Server - Iterate, aggregate, and insert I'm trying to find an efficient way to aggregate data for reporting. Let's say I need to aggregate the following data in 5-second intervals:

CREATE TABLE RawData
(
    Result                          FLOAT,
    CaptureTime                     DATETIME
);
INSERT INTO RawData VALUES
(2.3, '2018-04-01 00:00:00'),
(2.5, '2018-04-01 00:00:01'),
(2.8, '2018-04-01 00:00:02'),
(2.8, '2018-04-01 00:00:03'),
(3.4, '2018-04-01 00:00:04'),
(5.1, '2018-04-01 00:00:05'),
(2.2, '2018-04-01 00:00:06'),
(4.1, '2018-04-01 00:00:07'),
(4.3, '2018-04-01 00:00:08'),
(5.9, '2018-04-01 00:00:09'),
...

The aggregated data will be stored in another table:

CREATE TABLE AggregateData
(
    Result                          FLOAT,
    StartCaptureTime                DATETIME,
    EndCaptureTime                  DATETIME
);

As an example: if my aggregate function is SUM, the data in AggregateData would be:

+--------+----------------------+---------------------+
| Result |   StartCaptureTime   |    EndCaptureTime   |
+--------+----------------------+---------------------+
|  13.8  | 2018-04-01 00:00:00  | 2018-04-01 00:00:05 |
|  21.6  | 2018-04-01 00:00:05  | 2018-04-01 00:00:10 |
+--------+----------------------+---------------------+

The best solution that I've come up with uses a loop:

CREATE PROCEDURE [dbo].[spPerformAggregateCalculation]
    @UpdateIntervalSeconds          INT,
    @StartTime                      DATETIME,
    @EndTime                        DATETIME
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @RunningStartTime       DATETIME = @StartTime;
    DECLARE @RunningEndTime         DATETIME = DATEADD(SECOND, @UpdateIntervalSeconds, @RunningStartTime);
    DECLARE @AggregateValue         FLOAT;

    WHILE @RunningStartTime < @EndTime
    BEGIN
        SELECT @AggregateValue =
        (
            SELECT SUM(Result)
            FROM RawData
            WHERE CaptureTime >= @RunningStartTime AND CaptureTime < @RunningEndTime
        );

        INSERT INTO AggregateData VALUES
            (@AggregateValue, @RunningStartTime, @RunningEndTime);

        SELECT
            @RunningStartTime = @RunningEndTime,
            @RunningEndTime = DATEADD(SECOND, @UpdateIntervalSeconds, @RunningEndTime);
    END
END

EXEC spPerformAggregateCalculation
    @UpdateIntervalSeconds = 5,
    @StartTime = '2018-04-01 00:00:00',
    @EndTime = '2018-04-01 00:00:10'

Is there a more efficient way to get this data? I'll be performing more complex aggregations on millions of rows on a daily basis, so every bit helps.

P.S. In case "increase your interval" is offered as a suggestion, my data will actually be aggregated in much larger intervals than 5 seconds; I just whittled the problem down for the example.

Update

Below was my final solution, based dnoeth's answer:

CREATE PROCEDURE [dbo].[spPerformAggregateCalculation]
    @UpdateIntervalSeconds          INT,
    @StartTime                      DATETIME,
    @EndTime                        DATETIME
AS
BEGIN
    SET NOCOUNT ON;

    WITH cte AS
    (
        SELECT
            -- Adjust each CaptureTime to the beginning of the interval.
            DATEADD(SECOND, -DATEDIFF(SECOND, @StartTime , CaptureTime) % @UpdateIntervalSeconds, CaptureTime) as StartCaptureTime,
            Result
       FROM RawData
       WHERE CaptureTime >= @StartTime
    )
    INSERT INTO AggregateData
    SELECT
        SUM(Result),
        StartCaptureTime,
        DATEADD(SECOND, @UpdateIntervalSeconds, StartCaptureTime)
    FROM cte
    GROUP BY StartCaptureTime
    ORDER BY StartCaptureTime;
END

There's no need for a cursor or recursion, both are not really performant for larger amounts of data.

Simply adjust the CaptureTime to the start of each interval.

declare @UpdateIntervalSeconds integer = 5;
declare @minTime datetime = (select min(CaptureTime) from RawData);
-- if you want to start at exactly `00` instead of `01`,`02` etc.
-- you can modify `@minTime` using another DATEADD/DATEDIFF

with cte as
 ( select
      -- adjust each CaptureTime to the begin of an interval
      DATEADD(SECOND, -DATEDIFF(SECOND, @minTime , CaptureTime) % @UpdateIntervalSeconds, CaptureTime) as StartCaptureTime
     ,Result
   from RawData
 )
select StartCaptureTime
  ,DATEADD(SECOND, @UpdateIntervalSeconds, StartCaptureTime) AS EndCaptureTime
  ,sum(Result)
from cte
group by StartCaptureTime
order by StartCaptureTime


Project Euler Retreat Now I am doing Project Euler number 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

This is my code, which runs in 0 milliseconds:

static void Main(string[] args)
{
    Stopwatch s = new Stopwatch();
    s.Start();

    int sumNums = 0;

    for(int i = 0; i < 1000; i++)
    {
        if (i % 3 == 0 || i % 5 == 0) { sumNums += i; }
    }

    s.Stop();

    Console.WriteLine(sumNums);
    Console.WriteLine(s.ElapsedMilliseconds);
}

I also have this version, which also runs in 0 milliseconds.  In fact, running both methods in the same timer together results in 0 milliseconds:
static void Main(string[] args)
{
    Stopwatch s = new Stopwatch();
    s.Start();

    int sumNums = 0;

    for (int i = 0; i < 1000; i += 3)
    {
        sumNums += i;
    }

    for (int i = 0; i < 1000; i += 5)
    {
        sumNums += i % 3 == 0 ? 0 : i;
    }

    s.Stop();

    Console.WriteLine(sumNums);
    Console.WriteLine(s.ElapsedMilliseconds);
}

What could be improved, and which version is better?

I don't have a C# compiler, but I think the 2nd version will be faster if you drop the i % 3 in the 2nd loop, let it sum all the multiple of 5, and then make another pass to remove the multiples of 15.
And since the summing of 3, 5, 15 are repetitive, I'd introduce a helper function, like this:

static int sumOfMultiples(int x, int limit)
{
    int sum = 0;
    for (int i = x; i < limit; i += x)
    {
        sum += i;
    }
    return sum;
}

Then in Main, you could write:

int max = 1000;
int sumNums = sumOfMultiples(3, max) + sumOfMultiples(5, max) - sumOfMultiples(15, max);

But of course, the suggestion of @VikasGupta in comments is the best,
to use pure math instead of looping, rewriting the helper as:

static int sumOfMultiples(int x, int limit)
{
    int n = (limit - 1) / x;
    return x * n * (n + 1) / 2;
}


SQL trigger to log when employee records are updated I am learning TSQL (SQL in general for that matter), and I wrote this trigger that inserts logs about updated employees into the tblEmployeeAudit table.

When I was looking at the end result my eyes hurt.
The trigger was super simple, yet super long (for something which is so simple), it seemed as if a 10-year-old rascal wrote it. Does anyone know if I can make this any better/shorter, and/or How to avoid repeating same line of code 100 times? Here's the code.

Alter TRIGGER tr_tblEmployee_ForUpdate
ON tblEmployee
FOR UPDATE

AS
declare @id int
declare @Name nvarchar(50)
declare @GenderID int
declare @Salary int
declare @City nvarchar(50)
declare @DepartmentID int
declare @ManagerID int
declare @DateOfBirth datetime

declare @Nameol nvarchar(50)
declare @GenderIDol int
declare @Salaryol int
declare @Cityol nvarchar(50)
declare @DepartmentIDol int
declare @ManagerIDol int
declare @DateOfBirthol datetime

BEGIN
    Select @id = employeeid from inserted

    Select @Name = Name
          ,@GenderID = GenderID
          ,@Salary = Salary
          ,@City = City
          ,@DepartmentID = DepartmentID
          ,@ManagerID = ManagerID
          ,@DateOfBirth = DateOfBirth
    From Inserted

    Select @Nameol = Name
          ,@GenderIDol = GenderID
          ,@Salaryol = Salary
          ,@Cityol = City
          ,@DepartmentIDol = DepartmentID
          ,@ManagerIDol = ManagerID
          ,@DateOfBirthol = DateOfBirth
    From deleted

    Select * from deleted
    Select * from inserted
    Insert into tblEmployeeAudit2 values(
    'Employee with ID ='
    + str(@id)
    + ' changed Name from ' + cast(@Nameol as nvarchar(50)) + ' to ' + cast(@Name as nvarchar(50) )
    + 'Gender from ' +cast(@GenderIDol as nvarchar(5)) +' to ' +cast(@GenderID as nvarchar(5))
    + 'Salary from ' +cast(@SalaryOl as nvarchar(5)) +' to ' +cast(@Salary as nvarchar(5))
    + 'City from ' +cast(@Cityol as nvarchar(50)) +' to ' +cast(@City as nvarchar(50))
    + 'Department from ' +cast(@DepartmentIDol as nvarchar(5)) +' to ' +cast(@DepartmentID as nvarchar(5))
    + 'ManagerID from ' +cast(@ManagerIDol as nvarchar(5)) + ' to ' +cast(@ManagerID as nvarchar(5))
    )

END;

First some comments.

Usage of Deprecated Features

Currently your trigger does a SELECT that returns a resultset from a trigger. That was at one time supported but has been since deprecated since at least 2012. I would remove them.

Audit requirement

I very much agree with @Austin Hasting that it's generally better to not transform the data into a concatenated string here. You lose the ability to query or filter. The user-friendly formatting should be left to the application or at least the stored procedures used by the application. It doesn't belong in the trigger.

Bad assumptions

Your trigger assumes that you will have only one row in inserted and deleted. That is not how T-SQL triggers will work. It works on the statement level, not row level. Therefore you should code your trigger as if it could contain 10 rows in both virtual tables. The way the code is, it may not necessarily error out but it may miss out on other rows because the assignments only operate on the last row being assigned. Please, don't do this row by agonizing row.

Lack of two-part naming

It's a very good habit to always reference to your objects with two-part names, <schema>.<object> and not just <object>, because an object can exist in several schema with same names, and everyone has their default schema which takes precedence over the schema you actually meant to. I'm assuming you are using the default dbo schema. At least qualify that.

Lack of statement terminator

Several features have been added to the T-SQL language to a point where the ; terminator are no longer totally optional. T-SQL has been an aberrant in the SQL standard in making it optional. Some hack their way by putting a ; in front of statement whenever it's required, which is very weird. The best reason to use one everywhere is because it makes for more readable code, and makes your intention explicit.

Lack of block

I really do not like triggers or stored procedure without an explicit BEGIN...END block. It is valid T-SQL to write without one but this has problems and can make for confusing scripting.

Usage of + operator

You are concatenating strings with the + operator. Without knowing the version of your SQL Server, it might be the only choice but I should point out that since 2012, you now have a CONCAT() function which is much better because it will handle the nulls whereas + will propagate nulls and thus leave you with.... a null.

Lack of explicit insert list

When doing an INSERT, and especially when you do have an explicit SELECT list, it's usually good to have an explicit list. Otherwise, schema change could break the query.

With the commentary out of the way, this is how I'd rewrite this.

ALTER TRIGGER tr_tblEmployee_ForUpdate
ON dbo.tblEmployee
FOR UPDATE AS
BEGIN
  WITH Updated AS (
    SELECT
      i.Name,
      i....
      d.Name AS OldName,
      d.... AS Old...
    FROM inserted AS i
    INNER JOIN deleted AS d
      ON i.<primary key> = d.<primary key>
  )
  INSERT INTO dbo.tblEmployeeAudit2 (<Name of column>)
  SELECT CONCAT(
    'Employee with ID = ',
    u.ID,
    ' changed Name from ', u.Name ' to ', u.OldName
    ...
  ) AS AuditDescription
  FROM Updated AS u;
END;


Airline Reservations I am looking for general feedback on this small, simple program I wrote.  It works perfectly, but I am striving for readable, clean code.

I also have specific questions:

Is the switch statement the most efficient/logical way to write this class?
Is my main method too large?  Should I break it into smaller methods?  How would you suggest splitting it up?

/**
* This AirlineReservation class assigns seats on an airplane and prints boarding passes.
* (1) A boolean array is used to store a seating chart and which seats are available
* (2) The user is asked if they want a first class reservation, second class reservation, or end
* (3) A switch statement case is selected based on the user's input
* (4) The requested class of flight is checked for available seats
*       (a) seats 1-5 are first class
*       (b) seats 6-10 are economy
* (5) if available, seat is booked and boarding pass is printed
* (6) if not available, user is notified and presented with the original 3 options.
*
* NOTE:  I have commented out a method I was using to check my array for accuracy.
*/

import java.util.Scanner;
import java.util.Arrays;

public class AirlineReservations
{

public static void main(String[] args)
{
    int totalSeats = 10;
    int firstClassSeats = 5;
    int economySeats = 5;
    int classChoice = 0;
    boolean continueInput = true;

    Scanner input = new Scanner(System.in);

    boolean[] seatingChart = new boolean[totalSeats];
    Arrays.fill(seatingChart, false);

    while (continueInput == true)
    {
        System.out.print("Please type 1 for First Class, 2 for Economy Class, or 3 to exit System: ");
        classChoice = input.nextInt();
        switch (classChoice)
        {
            case 1://first class requested
                if (firstClassSeats > 0)//seat available
                {
                    seatingChart[firstClassSeats-1]=true;
                    firstClassSeats--;
                    printBoardingPass((firstClassSeats+1), classChoice);
                    //printSeatArray(seatingChart);
                }
                else //seat not available
                    System.out.print("\nFirst class seats are now SOLD OUT!\n");
                break;

            case 2://economy class requested
                if (economySeats > 0)//seat available
                {
                    seatingChart[economySeats+4]=true;
                    economySeats--;
                    printBoardingPass((economySeats+6),classChoice);
                    //printSeatArray(seatingChart);
                }
                else//seat not available
                    System.out.print("\nEconomy seats are now SOLD OUT!\n");
                break;
            case 3://exit system
                continueInput = false;
                break;
            default://incorrect input
                System.out.print("\nIncorrect input.  Please enter only a 1, 2, or 3.");
                break;
        }//end switch classChoice
    }//end while continueInput
}//end main method

private static void printBoardingPass(int seat, int classChoice)
{
    String seatingClass = (classChoice == 1? "First" : "Economy");
    System.out.print("\nBoarding Pass:  " + seatingClass + " class, Seat # " + seat +"\n\n");
}//end printBoardingPass

//private static void printSeatArray(boolean[] seatingChart)
//{
    //for (boolean element : seatingChart)
        //System.out.print(element + "\n");
    //System.out.println();
//}
}//end class

Is my main method too large? Should I break it into smaller methods? How would you suggest splitting it up?

Your main method isn't too large; it is doing too many different things.

It is more typical in a java program to use the main method to set up an instance of a class that is going to do the work, and then hand off control of the program to that object.

In this case, main is initializing your seat map, running your input/output loop, providing your business behavior.

  Is the 'switch' statement the most efficient/logical way to write this class

Probably not -- there are two problems here.  First is that you are switching on an int, where the int is code for something else.  There's no particular reason that "1" should be first class and "2" should be economy -- that's just an arbitrary encoding required by this assignment.  A better choice would be to use an enum to represent the different seating classes.

public enum SeatingClass {
    FIRST_CLASS, ECONOMY
}

The second problem here is that you are using the switch to drive changes in behavior.  That usually means that there is a class hiding in the code, waiting for you to notice it.  In this case, there are two: first is the fact that what you are really doing is converting the inputs to Commands.

Also, notice that case 1 and case 2 are doing exactly the same behavior, but with different data.  That indicates that there should be a class that knows how to provide that behavior, and two different instances of it with different data values.  So here, you should have some sort of SeatSectionAssigner; each has a number of seats and an offset into the seat map that determines which seats get assigned.

  Any improvement/feedback is greatly appreciated, just keep in mind I am a little more than a month into learning java

Look for ways to decompose programs into classes that do one thing.

  I found the exact same assignment (Airline Reservations System) but it was really difficult for me to follow the program. Maybe that comes with programming experience? Reading other's code with ease, that is. But there isn't a "main" method there.

Yes, that code doesn't do anything on its own.  The implied assumption is that somewhere else is some code that looks like

Airline airline = new Airline();
airline.start();


ViewModel constructor with many parameters I have some ViewModels that have a lot of parameters like this one:

public class ProductsMainViewModel : NotificationObject, IActiveAware, ...
{
    public ProductsMainViewModel(IProductRepository productRepository, IWarehouseRepository warehouseRepository, IUnitOfMeasureRepository unitOfMeasureRepository,
            IProductCategoryRepository productCategoryRepository, IProductPriceRepository productPriceRepository, IPriceLevelRepository priceLevelRepository,
            ICodingRepository codingRepository, ICategoryRepository categoryRepository, IDialogService dialogService, Logging.ILoggerFacade logger, IRegionManager regionManager,
            IJsonSerializer jsonSerializer, ICodeService codeService, IEventAggregator eventAggregator)
    {
        // ...
    }
}

(All repositories have the same instance of IUnitOfWork)
Instantiating this is done by IUnityContainer, But there are some dialogs that get called in this ViewModel:

            var viewModel = new ProductViewModel(_warehouseRepository, _unitOfMeasureRepository,
                _productCategoryRepository, _priceLevelRepository, _productPriceRepository, _codingRepository, _dialogService, _codeService, _jsonSerializer);

            var result = _dialogService.ShowDialog("ProductWindow", viewModel);
            if (result == true)
            {
                 // ...
            }

that their repositories must have the same IUnitOfWork of the current ViewModel. So I decided to pass parameters manually. I found it a good idea to "not reference any IoC container" in my ViewModel in here.

  The benefit of this approach is that the ViewModel doesn't have any
  knowledge of the (Unity) container.  Also, in terms of understanding
  the application design the dependencies of the ViewModel are easy to
  see since they are in the constructor.

Well, any ideas on how to reduce the number of parameters? Any particular design pattern?

Is it a good idea to create a 'IFooRepositoriesContext' and put related repositories in it?

why don't you write an abstract factory containing all the references you need?
You can then implement a factory method for your ViewModel creating an instance based on some configuration parameters.
Your client code now doesn't need to know the constructor sintax but just the configuration needed for the right instance.


Calculate sum of digits from a given number using String's slice method This is the "classic" algorithm for calculating the sum of digits uses the modulo-operator together with the division-operator. I had the idea of using the slice-method with a negative index for accomplishing the task.

/**
 * Calculates sum of digits from a given number.
 * @param { number } num
 * @return { number }
 * @throws { exception } Throws exception in
 *   case given parameter is not a number.
 * Usage example:
 *   var CheckSum = calcCheckSum(328); // Returns 13
 */
function calcCheckSum(num) {
  var ret = 0;
  var i;

  if (typeof num != 'number' || isNaN(num)) {
    throw new Error('Number expected. { ' +
      typeof num + ' } ' +
      num + ' found.');
  }

  num = num.toString();

  for (i = num.length; i > 0; i--) {
    ret += parseInt(num.slice(i - 1, i));
  }

  return ret;
}

// -- TESTS -----------
for (var i = 0; i < 10; i++) {
  var randomNumber =
    Math.floor(
      Math.random() * (100000 - 100)
    ) + 100;

  var spacer = new Array(6);

  spacer = spacer.join(' ');

  console.log('%s : %s => %s',
               ('0' + i).slice(-2),
               (spacer + randomNumber).slice(-5),
               calcCheckSum(randomNumber)
  );
}

try {
  console.log(calcCheckSum('abcdef'));
} catch (e) {
  console.error(e);
}

try {
  console.log(calcCheckSum(NaN));
} catch (e) {
  console.error(e);
}
// ------------------------------

It seems to work as expected. Nevertheless I would appreciate your opinions: shall I stay with the well-known algorithm or I can use my self-figured out solution?

Moreover, is my parameter validation and my documentation done well? Or do I have to improve something?

Poor testing and vetting

There are a few problems with your approch.

Throwing an error seems to me to be the incorrect response. If the argument it not a number then the result should be NaN. Saves you having to wrap the function in a try catch which will basically stop the javascript engine from optimising the code.
Slice is a little over kill. You can use direct indexing str[index] or via str.charAt(index).
You had parseInt, which will remove any numbers after the decimal point. Use type coercion +num to convert from string to number and ""+num to convert to string.
You don't vet for exponent notation 123e-20
You don't vet - out of the number string and +,or  .
And your testing is very poor.

Rewrite

Below is a rewrite. It fails one test calcCheckSum("0006") should return NaN but it does not which means that isNaN("0006") is failing. This was a surprise to me and I can not make a decision on what to do untill I work out the extent of this bug.

 function calcCheckSum (num) {
    var ret, i;
    if (isNaN(num) || num === "") { // Could be a string that is a number. No need to check if its a type number
                                    // Why throw this will stop the whole program. Return a value that reflects the input
        return NaN;
    }
    // what about negatives,pluses, decimal points, exponent notation, fractions????
    num = (""+num).replace(/\+|\-|\./g,""); // remove junk if any
    if(num.indexOf("e") > -1){  // if exponent then remove it
        num = num.split("e")[0];
    }

    ret = 0;
    for (i = 0; i < num.length; i ++) {  // simpler as no need to -1 each iteration
        ret += +num[i];  // + does the type conversion. Split is expensive so just lookup char by index
    }
    return ret;
}

// -- TESTS -----------
var fails = [];
var valuesToReturnNAN = [NaN,"0006","a","0xff","","+",".","-","-0-","-.38.",true,false,Infinity,-Infinity];
var valuesToReturn6 = [123,6,1.23e20,1.23e-20,111111,"123","6","+6","-6","-.6","111111","111.111",".123",.123,0.123,123.,-123,-.123,+123.,+123.0,-123.0,0.123,"0.12300"];
valuesToReturnNAN.forEach(v=>{
    if( ! isNaN(calcCheckSum(v)) ){
        fails.push("failed : " +(typeof v) + " : (" + v + ") did not return NaN");
    }
});
valuesToReturn6.forEach(v=>{
    if( calcCheckSum(v) !== 6 ){
        fails.push("failed : " +(typeof v) + " : (" + v + ") did not return 6");
    }
});
console.log("Failed "+fails.length + " tests.");
fails.forEach(str=>console.log(str));


D3.js interpolating line on circumference of circle For now, I've tried to make a line rotate on the path of a circle, but used setInterval multiple times and there might be other ways of achieving the same.

I would like your thoughts before I add two more circles just like in this webpage.

var width = 300;
var height = 300;
var body = d3.select("body")
var svg = body.append("svg")
        .attr("width",width)
        .attr("height",height)
        .attr("fill","blue")

var rad = Math.PI;

var circlePath = svg.append("path")
                    .attr('d', "M70,100a30,30 0 1,0 60,0a30,30 0 1,0 -60,0")
                    .attr('fill', 'none')
                    .attr('stroke', 'steelblue' )

// var path  = <path d="M70,100a30,30 0 1,0 60,0a30,30 0 1,0 -60,0"/>

console.warn(circlePath.node());
var path1 = circlePath.node();

var myLine = svg.append('line')
                .attr('x1', 100)
                .attr('y1', 100)
                .attr('x2', function(){return path1.getPointAtLength(l).x})
                .attr('y2', function(){return path1.getPointAtLength(l).y}  )
                .attr('stroke', "red" )
                .attr('stroke-width',3)
var l = 1
setInterval(function(){
        myLine.transition()
                    .duration(20)
                    .attr('stroke', "blue")

                    .attr('x2', function(){return path1.getPointAtLength(l).x})
                .attr('y2', function(){return path1.getPointAtLength(l).y})

                .each("end", endAnimationfunc)

}, 5);
setInterval(function(){
    if(l<path1.getTotalLength()){
        l=l+1
    }
    else{
        l = 1
    }
},10)

var endAnimationfunc = function(){
    d3.select(this)
        .transition()
        .attr('x2', function(){return path1.getPointAtLength(l).x})
        .attr('y2', function(){return path1.getPointAtLength(l).y})

}

function translateAlong(path1){
    var l = path1.getTotalLength();
    // console.warn(l);
    return function(){
        // console.warn(d,i,a);

            var p = path1.getPointAtLength( l );
            console.log(p);

            return  "translate("+p.x + ","+p.y +")";

    }
}
<body></body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

I'd suggest using nested group elements (<g>s) with transform attributes.

I.e. draw the circle (just as a <circle> element) and the line inside a group, and then draw a nested group with a circle and line within that, and so on. When you rotate the outermost group, the nested ones will follow. Rotate each of them, and you'll get the effect from the demo.

This way, you only need to animate one thing: rotation. For instance:

var width = 200;
var height = 200;
var body = d3.select("body");
var svg = body.append("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("fill", "blue");

function addCircle(container, radius, x, y) {
    // Note the hardcoded rotation; it's just an example
    var group = container.append("g")
        .attr("class", "circle-container")
        .attr("transform", "translate(" + x + ", " + y + ")");

    function rotate() {
        group.transition()
        .duration(10000)
        .ease("linear")
        .attrTween("transform", function (d, i, a) {
            return function (t) {
                var rotation = t * 360;
                return "translate(" + x + ", " + y + ") rotate(" + String(rotation) + ")";
            };
        })
        .each("end", rotate);
    };
    rotate();

    group.append("circle")
        .attr("cx", 0)
        .attr("cy", 0)
        .attr("r", radius)
        .style("fill", "none")
        .style("stroke", "steelblue");

    group.append("line")
        .attr("x1", 0)
        .attr("y1", 0)
        .attr("x2", radius)
        .attr("y2", 0)
        .style("stroke", "steelblue");

    return group;
}

var c1 = addCircle(svg, 30, width/2, height/2); // centered
var c2 = addCircle(c1, 20, 30, 0); // offset by 1st circle's radius
var c3 = addCircle(c2, 15, 20, 0); // offset by 2nd circle's radius
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Heck, you can do this in pure SVG (added extra groups to isolate rotation):

<svg width="200" height="200">
  <!-- root transform to center everything -->
  <g transform="translate(100, 100)">

    <!-- draw the outermost group and animate it -->
    <g>
      <animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="10s" repeatCount="indefinite" />
      <circle cx="0" cy="0" r="40" fill="none" stroke="steelblue" />
      <line x1="0" y1="0" x2="0" y2="40" stroke="steelblue" />

      <!-- offset the children -->
      <g transform="translate(0, 40)">

        <!-- now repeat, only smaller -->
        <g>
          <animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="10s" repeatCount="indefinite" />
          <circle cx="0" cy="0" r="30" fill="none" stroke="steelblue" />
          <line x1="0" y1="0" x2="0" y2="30" stroke="steelblue" />

          <g transform="translate(0, 30)">

            <!-- and again -->
            <g>
              <animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="10s" repeatCount="indefinite" />
              <circle cx="0" cy="0" r="20" fill="none" stroke="steelblue" />
              <line x1="0" y1="0" x2="0" y2="20" stroke="steelblue" />
            </g>

          </g>
        </g>
      </g>
    </g>
  </g>
</svg>

At any rate, you can simply skip all the getPointAtLength calls. Your path is a circle, so a) you can use a <circle> element, and b) any point on its circumference can be described using some simple math:

var x = Math.cos(t) * radius + centerX;
var y = Math.sin(t) * radius + centerY;

where t is something between 0 and 2π (or beyond that; it'll just loop around). So your animation needs only change the value of t to find a point on the circle.


Code seems repeated, except for the callback function I've written some JavaScript code:

  app.get('/offers/', function(req, res){
    var funcGetOffers = utils.funcGetOffers;
    var options = {top_sort: true};
    funcGetOffers(function(offers){
      res.render('offers', { offers:offers });
    }, options);
  });

  app.get('/api/get_offers', function(req, res){
    var funcGetOffers = utils.funcGetOffers;
    var options = {top_sort: true};
    funcGetOffers(function(offers){
      res.json(offers);
    }, options);
  });

The code is almost the same, and only the callback function is different.  I want to get rid of the repeat code, but didn't find a good way.

funcGetOffers is a long function which gets a list of items from the database:

var funcGetOffers = function(callback, opt) {
  var order = [['updatedAt', 'DESC']];
  var where = {};
  if (opt && opt.top_sort) {
    order.unshift(['flag_top', 'DESC']);
  }
  var Offer = models.offer;
  Offer.findAll({order:order}).success(function(offers){
    // some calc with offers
    // callback
    callback(offers);
  });
}

Thank @Flambino make me more clear, I did some change to funcGetOffers to make it promisily, now the code:

var options = {top_sort: true};

utils.funcGetOffers(options).then(function(offers){
  res.render('offers', { offers:offers });
});

utils.funcGetOffers(options).then(function(offers){
  res.json(offers);
});

changed the funcGetOffers signature, use a bluebird to make it promisily.

utils.funcGetOffers(options).then(res.json) didn't work by the promise, but looks much better now!

You don't need the local funcGetOffers variable. Just call util.funcGetOffers directly.

You may extract the options to a var outside the request handlers, since it's the same in both places.

After that, there's not really any repetition left. Sure, the 2 request handlers each call utils.funcGetOffers, but the callbacks are so different that it'd be more complex to generalize them.

However, you can skip the callback function expression for the /api/get_offers handler, and simply use res.json directly.

var options = { top_sort: true }; // maybe call this offersOptions to make it clearer

app.get('/offers/', function(req, res){
  utils.funcGetOffers(function(offers){
    res.render('offers', { offers:offers });
  }, options);
});

app.get('/api/get_offers', function(req, res){
  utils.funcGetOffers(res.json, options);
});

I don't think it's necessary to do anything more elaborate than that.

And again, in utils.funcGetOffers you don't need all those local variables (you can access models.offer directly, and where isn't even used), and you can skip the success-callback, and just use the given one directly

var funcGetOffers = function(callback, opt) {
  var order = [['updatedAt', 'DESC']];
  if(opt && opt.top_sort) {
    order.unshift(['flag_top', 'DESC']);
  }
  models.offer.findAll({order:order}).success(callback);
}

In general, I'd recommend a bit more consistency. You obviously have a column named updatedAt (camelCase), but you apparently also have one called flag_top (underscored). Pick one way of naming things, and stick with it (for JavaScript, the convention is to use camelCase).

This extends to the options object (or opts, but there's no need to shorten it: Just call it options). There you have a key called top_sort, which should probably be camelCased - especially since you're not using it directly, but "translating" it to mean flag_top. In fact, it might be smarter to simply use the actual column name, rather than the - pretty ambuiguous - name top_sort.

And it'd be wise to handle errors too - not just success.

Lastly, there's really no need for the func prefix. If something's called getOffers it's implied that it's a function.