texts:
I made a class to perform tasks concurrently and have implemented it. From appearances and testing, everything seems to work. How can I improve this? I understand this is somewhat a broad question, so please let me know how I should narrow it down.

Here is the pseudocode:

The general idea is a single Starter spawns multiple TaskWorker to do the work. I want to start the loading process fairly early on and then block EDT until the completion of all TaskWorker.

class ImproveMe {
  private AtomicInteger incompleteTasksCount = new AtomicInteger( -1 );
  /* SwingWorker has a limitation of 10 */
  private static final int MAX_CONCURRENT_THREAD = 20;
  private static ExecutorService threadPool = Executors.newFixedThreadPool( MAX_CONCURRENT_THREAD );

  /* This just starts multiple TaskWorker */
  class Starter extends SwingWorker {
    Object doInBackground() {
      incompleteTasksCount.getAndSet( -1 );

      Tasks[] taskList = getTasks();
      for ( Task task : taskList ) {
        /* Track incomplete tasks */
        if ( incompleteTasksCount.compareAndSet( -1, 1 ) {
          incompleteTasksCount.incrementAndget();
        }
        threadPool.submit( new TaskWorker( task ) );
      }
      threadPool.shutdown();
    }
  }

  /* Performs the actual work -- I don't care about the results since it will be cached elsewhere */
  class TaskWorker implements Runnable {
    Task t;
    TaskWorker( Task t ) {
      this.t = t;
    }

    void run() {
      if ( t != null ) {
        do stuff with 't'
      }

      synchronized( incompleteTasksCount ) {
        if ( incompleteTasksCount.decrementAndGet() == 0 ) {
          /* everything is done! */
          incompleteTasksCount.notifyAll();
        }
      }
    }
  }

  /* User will call this to start the loading */
  public void startLoading() {
    if ( !threadPool.isShutdown() ) {
      Starter s = new Starter();
      s.execute();
    }
  }

  /* User will call this to ensure that everything has complete before continuing */
  public void blockUntilDone() {
    boolean cont = true;
    if ( incompleteTasksCount.get() == 0 || threadPool.isTerminated() ) {
      return;
    } else if ( incompleteTasksCount.get() == -1 ) {
      /* not loaded/started */
      return;
    }

    while ( cont ) {
      synchronized( incompleteTasksCount ) {
        try {
          incompleteTasksCount.wait();
        } catch ( InterruptedException e ) {
          e.printStackTrace();
          cont = false;
        } finally {
          if ( incompleteTasksCount.get() == 0 ) {
            cont = false;
          }
        }
      }
    }
  }
}

In reality, TaskWorker calls PrintService.getSupportedAttributeValues(..) because of the numerous printers and Java caches that so any future calls will return fairly quickly as compared to the first time (some of the network printers took 40+ seconds). I call ImproveMe.startLoading() somewhere fairly early in my program then before the actual program starts (e.g. GUI is shown), I use ImproveMe.blockUntilDone() to ensure everything is loaded.


texts:
I have this (working) code:

class CalendarDay

  attr_accessor :from_month, :to_month, :year

  def self.line_of_day_numbers(month,year,start,offset)
    @line=''
    @offset=offset
    finish = (start+6)-@offset
    self.first_line_padding(start)
    start-= @offset
    self.day_numbers(month,year,start,finish)
  end

  private

  def self.first_line_padding(start)
    if start < 7
      @line=' ' * (@offset * 3)
      @offset=0
    end
  end
  ...

But the methods are tangled and there's a mix of instance and local variables.

Tests include:

it "shows the day numbers" do
  expect(CalendarDay.line_of_day_numbers(2,2000,1,2)).to eq '       1  2  3  4  5'
end
it "shows the day numbers" do
  expect(CalendarDay.line_of_day_numbers(10,2000,1,0)).to eq ' 1  2  3  4  5  6  7'
end
it "shows the day numbers" do
  expect(CalendarDay.line_of_day_numbers(1,2000,8,6)).to eq ' 2  3  4  5  6  7  8'
end


texts:
def mergeCount(left,right,invCount):
  inversionCount = invCount
  # print(left,right)
  for right_item in right:
    offset = 0
    insertState = False
    for i in range(len(left)):
      if left[i] <= right_item:
        offset += 1
      elif left[i] > right_item:
        inversionCount += len(left) - offset
        left.insert(i,right_item)
        # print("inserted",right_item)
        insertState  = True
        break
    if not insertState:
      left.append(right_item)
  # print("new array is",left)
  return left,inversionCount

def mergeSortInversion(array):
  if len(array) <= 1:
    return array,0
  else:
    left_arr, left_count = mergeSortInversion(array[:len(array)//2])
    right_arr, right_count = mergeSortInversion(array[len(array)//2:])
    # print(left_arr,right_arr,left_count+right_count)
    return mergeCount(left_arr,right_arr,left_count + right_count)

My merge sort code is taking the same amount of time as the brute force method for some reason. How can I fix the implementation / make it better?


texts: Basic Subnet Mask Calculator + A Little Extra

texts:
For my Networking class, we learned about subnetting and subnet masks.

I decided to write a little "calculator" (a generous term) that when given n-many network bits, generates a 32-bit subnet mask, then displays it as octets, and as binary with the leading 0s removed. Example main:

int main() {
    int nNetworkBits = 26;
    BitField mask = generateSubnetMask(nNetworkBits);

    printf("%u\n", mask);  // Prints 4294967232
    printf("\n");

    printOctets(mask);  // Prints 255.255.255.192
    printf("\n");

    printBinary(mask);  // Prints 11111111111111111111111111000000
    printf("\n");
}

I'm pretty terrible at C, so I'd like comments on anything and everything that is worth mentioning. I figured out the math/bitshifting as I was writing the code, so if I'm doing anything "roundabout", I'd definitely like to know about it.

The only thing that I don't need advice on is my "abuse" of printf. I know I should be accumulating a string in a buffer then returning that buffer instead of printing directly from the functions. That's a pain in C though and detracted from the main problem that I was trying to solve, so I decided to go for the quick and dirty way.

#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>

#define TOTAL_BITS 32
#define N_OCTETS ((TOTAL_BITS / 8))

typedef uint32_t BitField;

BitField generateOctetMask(int octetI) {
    return (BitField)0xFF << (octetI * 8);
}

BitField generateSubnetMask(int nNetworkBits) {
    int nHostBits = TOTAL_BITS - nNetworkBits;
    return ~0 << nHostBits;  // TODO: Cast 0 to BitField?
}

void printOctets(BitField maskAddress) {
    for (int octetN = N_OCTETS - 1; octetN >= 0; octetN--) {
        BitField mask = generateOctetMask(octetN);
        printf("%d", (maskAddress & mask) >> (octetN * 8));

        if (octetN > 0) {
            printf(".");
        }
    }
}

void printBinary(BitField n) {
    bool areDropping = true;  // So we can drop leading 0s.

    for (BitField mask = 1u << 31; mask > 0; mask >>= 1) {
        bool isSet = n & mask;

        if (isSet) {
            areDropping = false;
            printf("1");

        } else if (!areDropping) {
            printf("0");
        }
    }
}

int main() {
    int nNetworkBits = 26;
    BitField mask = generateSubnetMask(nNetworkBits);

    printf("%u\n", mask);  // Prints 4294967232
    printf("\n");

    printOctets(mask);  // Prints 255.255.255.192
    printf("\n");

    printBinary(mask);  // Prints 11111111111111111111111111000000
    printf("\n");
}


texts:
I'm trying to improve my understanding of recursive and iterative
processes. I've started with SICP, but have branched off to try and
find a few exercises when I started having difficulty. Currently I've
been looking at a series of posts on the subject by Tom
Moertel.

Tom's code
defines a node object for binary search trees and a search function:

class BSTNode(object):
    """Binary search tree node."""
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

    def __repr__(self):
        return '(%s, %r, %r)' % (self.val, self.left, self.right)

def find_val_or_next_smallest(bst, x):
    """ Get the greatest value <= x in a binary search tree. Returns
    None if no such value can be found. """
    if bst is None:
        return None
    elif bst.val == x:
        return x
    elif bst.val > x:
        return find_val_or_next_smallest(bst.left, x)
    else:
        right_best = find_val_or_next_smallest(bst.right, x)
        if right_best is None:
            return bst.val
        return right_best

The exercise asks us to transform the search function into an
iterative process and gives a general
procedure
for doing so: refactor all recursive calls into tail calls using
accumulators and then create a loop structure.

I've refactored the else clause in the search function into:

    else:
        return work(find_val4(bst.right, x), bst)

def work(child_node, parent_node):
    if child_node is None:
        return parent_node.val
    return child_node

But I've been having trouble figuring out how to move the logic done
in the 'work' function into an accumulator. Any advice, hints, or ways
to think about this would be totally appreciated.


texts:
I solved the following problem:

Consider the range 0 to 10. The primes in this range are: 2, 3, 5, 7, and thus the prime pairs are: (2,2), (2,3), (2,5), (2,7), (3,3), (3,5), (3,7),(5,5), (5,7), (7,7).

Let's take one pair (2,7) as an example and get the product, then sum the digits of the result as follows: 2 * 7 = 14, and 1 + 4 = 5. We see that 5 is a prime number. Similarly, for the pair (7,7), we get: 7 * 7 = 49, and 4 + 9 = 13, which is a prime number.

You will be given a range and your task is to return the number of pairs that revert to prime as shown above. In the range (0,10), there are only 4 prime pairs that end up being primes in a similar way: (2,7), (3,7), (5,5), (7,7). Therefore, solve(0,10) = 4)

Note that the upperbound of the range will not exceed 10000. A range of (0,10) means that: 0 <= n < 10.

I was wondering if my solution could be improved or if I should use a completely different approach.

function isPrime(n) {
    if(n < 2){
        return false;
    }
    for (var i = 2; i <= parseInt(Math.sqrt(n)); i++) {
        if (n % i === 0) {
            return false;
        }
    }
    return true;
}

function getPrimes(s, e) {
    var primes = [];
    for (var p = s; p <= e; p++) {
        if(isPrime(p)){
            primes.push(p);
        }
    }
    return primes;
}

function generatePairs(primes){
    var pairs = [];
    for(var i = 0; i < primes.length; i++){
        for(var j = i; j < primes.length; j++){
            pairs.push([primes[i], primes[j]]);
        }
    }
    return pairs;
}

function sumDigits(n){
    var sum = 0;
    while(n > 0){
        sum += n % 10;
        n = parseInt(n/10);
    }
    return sum;
}

function solve(a, b) {
    var pairs = generatePairs(getPrimes(a, b - 1));
    var res = 0;
    for(pair of pairs){
        var tmp = sumDigits(pair[0] * pair[1]);
        if(isPrime(tmp)){
            res++;
        }

    }
    return res;
}


texts:
I am writing an advection-diffusion solver in Python. I am quite experienced in MATLAB and, therefore, the code implementation looks very close to possible implementation in MATLAB. I implemented the same code in MATLAB and execution time there is much faster. AS you may note, I am also (as in MATLAB) trying to use JIT in Python, however, it does not give me any improvements. Thus, I was wondering if you could review the code in terms of optimization for computational speed and give me some advices for future.

import numpy as np
import scipy as sp
from scipy.sparse import spdiags
from scipy import special
import numba as nb

@nb.jit
def adv_diff(D, w, years):
    BC1_top = 1
    F_bottom = 0
    L = 30
    tend = years
    C1_init = 0

    phi = 1
    dx = 0.1
    dt = 0.001
    x = np.linspace(0, L, L / dx + 1)
    N = x.size

    C1_init = C1_init * np.ones((N, 1))
    C1_init[0] = BC1_top

    [AL, AR] = AL_AR_dirichlet(D, w, phi, dt, dx, N)

    C1_old = C1_init

    time = np.linspace(0, tend, tend / dt + 1)

    C1_res = np.zeros((N, time.size))
    C1_res[:, 0] = C1_init[:, 0]

    for i in np.arange(1, len(time)):
        C1_old = update_bc_dirichlet(C1_old, BC1_top)
        B = AR.dot(C1_old)
        C1_new = linalg_solver(AL, B)
        C1_res[:, i] = C1_new[:, 0]
        C1_old = C1_new
        C1_old[1] = BC1_top

    return C1_res

@nb.jit
def linalg_solver(A, b):
    # linalg_solver: x = A \ b
    return np.linalg.solve(A, b)  #

@nb.jit
def update_bc_dirichlet(C, BC_top):
    # update_bc_dirichlet: function description
    C[0] = BC_top
    return C

@nb.jit
def AL_AR_dirichlet(D, w, phi, dt, dx, N):
    # AL_AR_dirichlet: creates AL and AR matrices with Dirichlet BC
    s = phi * D * dt / dx / dx  #
    q = phi * w * dt / dx  #
    e1 = np.ones((N, 1))  #
    AL = spdiags(np.concatenate((e1 * (-s / 2 - q / 4), e1 * (1 + s), e1 * (-s / 2 + q / 4)), axis=1).T, [-1, 0, 1], N, N).toarray()
    AR = spdiags(np.concatenate((e1 * (s / 2 + q / 4), e1 * (1 - s), e1 * (s / 2 - q / 4)), axis=1).T, [-1, 0, 1], N, N).toarray()
    AL[0, 0] = 1
    AL[0, 1] = 0
    AL[N - 1, N - 1] = 1 + s
    AL[N - 1, N - 1 - 1] = -s
    AR[0, 0] = 1
    AR[0, 1] = 0
    AR[N - 1, N - 1] = 1 - s
    AR[N - 1, N - 1 - 1] = s
    return AL, AR

if __name__ == '__main__':
    D = 0.5
    w = 3
    t = 10

    C = adv_diff(D, w, t)


texts: Convert python's strftime directives to user-friendly format examples

texts:
I'm converting python's very un user-friendly strftime date time directives to user-friendly formats so that users of an API will know how to format a date if they send an invalid format.

My thinking is that %Y-%m-%d is platform specific to Python where as even non-programmers would know what to send if we told them dates must be in the format YYYY-MM-DD. I guess my biggest issue with this code is I feel like this might already be inbuilt with strftime or python's datetime lib. If not, can this be improved or is this good enough?

import re

directives = {
    "%d": "DD",
    "%-d": "D",
    "%m": "MM",
    "%-m": "M",
    "%y": "YY",
    "%Y": "YYYY",
    "%H": "HH",
    "%-H": "H",
    "%I": "hh",
    "%-I": "h",
    "%p": "A",
    "%M": "mm",
    "%-M": "m",
    "%S": "ss",
    "%-S": "s"
}

format = "%Y-%m-%d"

pattern = re.compile('|'.join(directives.keys()))
nice_format = pattern.sub(lambda x: directives[x.group()], format)

print nice_format


texts:
Bell number \$B(n)\$ is defined as the number of ways of splitting \$n\$ into any number of parts, also defined as the sum of previous \$n\$ Stirling numbers of second kind.

Here is a snippet of Python code that Wikipedia provides (slightly modified) to print bell numbers:

def bell_numbers(start, stop):

   t = [[1]]                        ## Initialize the triangle as a two-dimensional array
   c = 1                            ## Bell numbers count
   while c <= stop:
       if c >= start:
           yield t[-1][0]           ## Yield the Bell number of the previous row
       row = [t[-1][-1]]            ## Initialize a new row
       for b in t[-1]:
        row.append(row[-1] + b)  ## Populate the new row
       c += 1                       ## We have found another Bell number
       t.append(row)                ## Append the row to the triangle
   for b in bell_numbers(1, 9):
       print b

But I have to print the \$n\$th bell number, so what I did was I changed the second last line of code as follows:

for b in bell_numbers(n,n)

This does the job, but I was wondering of an even better way to print the \$n\$th bell number.


texts: Configuring fields to be extracted by a data processor

texts:
I solved this problem using closures with Perl and I wonder if/how I could/should have done it differently?

Background:

User creates config file describing properties of some source data file that would be processed:

Type of file delimited (and the delim) or fixed width
How many fields to expect
Which fields are to be pulled out

Examples on the last (if delimited):

Fields: FIRST_NAME 2
Fields: LAST_NAME 3
Fields: ADDRESS 4

or (fixed width):

Fields: FIRST_NAME 58,30
Fields: LAST_NAME  88,30
Fields: ADDRESS    118,50

My Perl reads the config, and prepares ahead the action to take once I start reading the source data file.

Internally, I'm creating preparing my master hash (per the config), which I'll loop on for each record when reading the source.

Now to handle the said examples, I have this code, if the source file would be delimited:

sub ret_col_sub
{
    my ($col_name, $col_pos) = @_

    warn qq($col_name col_pos='$col_pos' is not a number) if $col_pos =~ /\D/;

    $col_pos--;

    # Return closure to caller, which will be called later when we're reading the source data file
    return sub
    {
        my $rec = shift;

        return $rec->[$col_pos];
    };
}

or fixed width:

sub ret_substr_sub
{
    my ($col_name, $substr_params) = @_;

    my ($offset, $len) = $substr_params =~ /(\d+)\s*,\s*(\d+)/;

    # The offset might be ZERO, check for length ... but $len must always be P O S I T I V E !
    warn qq($col_name substr_params='$substr_params' is missing the offset and length needed by substr) if not length $offset or not $len;

    $offset--;
    $len--;

    # Return closure to caller, which will be called later when we're reading the source data file
    return sub
    {
        my $rec = shift;

        return substr $rec, $offset, $len;
    };
}

Is there a better or another way of doing this, or any other suggestions?


texts:
I am working on a question in which I need to find a largest palindrome given a string. Here is the description.

public class LargestPalindrome {
  public static void main(String[] args) {
    System.out.println("Longest Palindrome 1: " +findLongestPalindrome("xyzracecar"));
    System.out.println("Longest Palindrome 2: " +findLongestPalindrome("abcexcbaddd"));
    System.out.println("Longest Palindrome 3: " +findLongestPalindrome("cacxx"));
  }

  public static String findLongestPalindrome(String str) {
    String palindrome = ""; // initializing empty string

    for(int i=0; i<str.length(); i++) {
      for(int j = str.length(); j>i; j--) {
       String data = str.substring(i, j);
        if(isPalindrome(data)) {
          if(data.length() > palindrome.length()) {
            palindrome = data;
          }
        }
      }
    }

    return palindrome;
  }

  /**
   * This method is used to check whether a given string is palindrome or not
   *
   */
  public static boolean isPalindrome(String s) {
    int last = s.length() - 1;

    for(int i=0; i<s.length()/2; i++) {
      if(s.charAt(i) != s.charAt(last)) {
        return false;
      }
      last--;
    }

    return true;
  }
}

The code is working fine. Can it be optimized anymore?


texts:
Looking for a critique of this simple logger class I'm working on in my transition to TypeScript.

The purpose of the logging class is to just print to a console either info, warn or error messages.

The main things I'm after feedback on are my usage of the TypeScript type system. I.e interfaces/types/whatever else could be done different or better.

interface LoggerConfig {
  prefix?: string;
  prefixColor?: TextColor.White;
  displayConsole?: boolean;
  outputExternal?: boolean;
}

type LogFn = (msg: string) => void;

interface Log {
  config: LoggerConfig;
  log: (msg: string, logColor: TextColor, override?: LoggerConfig) => void;
  info: LogFn;
  warn: LogFn;
  error: LogFn;
}

class Logger implements Log {
  config: LoggerConfig = {
    prefix: 'console :: ',
    prefixColor: TextColor.Green,
    displayConsole: false,
    outputExternal: false,
  };

  constructor(userConfig: LoggerConfig = {}) {
    this.config = {...this.config, ...userConfig};
  }

  log(msg: string, logColor: TextColor, override?: LoggerConfig) {
    const config = override ? {...this.config, ...override} : this.config;
    const {displayConsole, outputExternal, prefix, prefixColor} = config;

    if (displayConsole) {
      showConsole();
    }

    if (outputExternal) {
      external.printToConsole(`${prefix} ${msg}`);
    }

    print(prefixColor + prefix + logColor + ' ' + msg);
  }

  info(msg: string) {
    this.log(msg, TextColor.White);
  }

  warn(msg: string) {
    this.log(msg, TextColor.Yellow, {displayConsole: true});
  }

  error(msg: string) {
    this.log(msg, TextColor.Red, {displayConsole: true, outputExternal: true});
  }
}

const logger = new Logger({prefix: 'testLogger :: '})


texts: Closure, anonymous functions or binds on delayed functions

texts:
I'm calling an expensive function that dynamical changes as the end user types in a textbox. To reduce the amount of calls to the function I've used setTimeout to delay calling the function, and if the function is called again whilst waiting to run, it'll also remove the last function request via clearTimeout.

The function for this is:

// To not have different functions conflict
function makeDelay() {
    var timerID = false;
    return function (fn, timeout) {
        if (timerID !== false) {
            clearTimeout(timerID);
        }
        if (timeout == undefined) {
            timeout = 500;
        }
        timerID = setTimeout(function() {
            timerID = false;
            fn();
        }, timeout);
    }
}
var delay = makeDelay();
var $peoplePicker = $('.ms-peoplePicker');
var $results = $peoplePicker.find(".ms-PeoplePicker-results");

However I don't know what the most idiomatic way to use this function is. I know that I can use one of the following:

A closure

function get(input, html_output) {
    return function () {
        if (!input) {
            return;
        }
        $.ajax('/_api/pp_search/' + input).done(function (data) {
            html_output[0].innerHTML = data;
        })
    }
}

$peoplePicker.on('input', '.ms-PeoplePicker-searchField', function(event) {
    delay(get(event.currentTarget.value, $results));
});

bind

function get(input, html_output) {
    if (!input) {
        return;
    }
    $.ajax('/_api/pp_search/' + input).done(function (data) {
        html_output[0].innerHTML = data;
    })
}

$peoplePicker.on('input', '.ms-PeoplePicker-searchField', function(event) {
    delay(get.bind(undefined, event.currentTarget.value, $results));
});

Anonymous functions

function get(input, html_output) {
    if (!input) {
        return;
    }
    $.ajax('/_api/pp_search/' + input).done(function (data) {
        html_output[0].innerHTML = data;
    })
}

$peoplePicker.on('input', '.ms-PeoplePicker-searchField', function(event) {
    delay(function () {
        get(event.currentTarget.value, $results);
    });
});

Using a closure seems like the nicest, as you don't have to explicitly make a delayed function at usage via bind or an anonymous function. However, anonymous functions seem to be the de facto way to call functions like these.

Which, if any, way should I use this function?

Notes

I ask because I made a JavaScript program that heavily used closures for this style of function, but was really hard to read.


texts: DDD modeling for a User Voice-like system

texts:
I've taken on the challenge of modeling a simple User Voice-like system. High-level description:

It's a portal for some SaaS users;
They come and leave feature requests, suggestions, etc.;
They should be able to vote/unvote for any suggestions;
They can leave as many comments as they like on suggestions;
Comments may be removed by the owner, but may not be edited.

I've modeled the domain as follows, using a DDD approach. Please advise about mistakes, warnings, improvements, etc.

I've also applied the advices from these posts:

Don't create aggregate roots
Creating new aggregates in DDD
Link to an aggregate: reference or Id?

public abstract class Entity
{
    public Guid Id { get; protected set; } = Guid.NewGuid();
}

public class User : Entity // Aggregate Root
{
    public string Key => $"{Email}:{MarketplaceUrl}";

    public string Name { get; }

    public string Email { get; }

    public string MarketplaceName { get; }

    public Uri MarketplaceUrl { get; }

    internal User(string name, string email, string marketplaceName, Uri marketplaceUrl)
    {
        Name = name;
        Email = email;
        MarketplaceName = marketplaceName;
        MarketplaceUrl = marketplaceUrl;
    }

    public Suggestion MakeSuggestion(string text)
    {
        return new Suggestion(this, text);
    }
}

public class Suggestion : Entity // Aggregate Root
{
    public string Text { get; /* a suggestion cannot be altered */ }

    public User ByUser { get; }

    public DateTime SuggestedAt { get; }

    public ICollection<Comment> Comments { get; } = new List<Comment>();

    public ICollection<Vote> Votes { get; } = new List<Vote>();

    internal Suggestion(User byUser, string text)
    {
        ByUser = byUser;
        Text = text;
        SuggestedAt = DateTime.UtcNow;
    }

    public Comment AddComment(User byUser, string text)
    {
        var comment = new Comment(byUser, text);
        Comments.Add(comment);
        return comment;
    }

    public void RemoveComment(Comment comment, User userRemovingComment)
    {
        Comments.Remove(comment);
    }

    public void Unvote(User byUser)
    {
        var vote = Votes.SingleOrDefault(v => v.ByUser == byUser));

        if (vote != null)
            Votes.Remove(vote);
    }

    public Vote Vote(User byUser)
    {
        if (Votes.Any(v => v.ByUser == byUser))
            throw new CannotVoteTwiceOnSameSuggestionException();

        var vote = new Vote(byUser);
        Votes.Add(vote);
        return vote;
    }
}

public class Comment : Entity
{
    public string Text { get; /* a comment cannot be changed */ }

    public User ByUser { get; }

    public DateTime CommentedAt { get; }

    internal Comment(User byUser, string text)
    {
        ByUser = byUser;
        Text = text;
        CommentedAt = DateTime.UtcNow;
    }
}

public class Vote : Entity
{
    public User ByUser { get; }

    public DateTime VotedAt { get; }

    internal Vote(User byUser)
    {
        ByUser = byUser;
        VotedAt = DateTime.UtcNow;
    }
}

public interface IUserVoiceStore
{
    Task AddUserAsync(User user);

    Task AddSuggestionAsync(Suggestion suggestion);

    Task<Suggestion> GetSuggestionAsync(Guid id);

    Task<User> GetUserAsync(Guid id);

    // For when comments and votes are added/removed to/from a suggestion.
    Task UpdateSuggestionAsync(Suggestion suggestion);
}

public class UserVoiceService
{
    private readonly IUserVoiceStore store;

    public UserVoiceService(IUserVoiceStore store)
    {
        this.store = store;
    }

    public async Task<User> RegisterUserAsync(string name, string email, string marketplaceName, Uri marketplaceUrl)
    {
        var user = new User(name, email, marketplaceName, marketplaceUrl);
        await store.AddUserAsync(user);
        return user;
    }
}

public class CannotVoteTwiceOnSameSuggestionException : Exception { }

public class CannotRemoveCommentFromAnotherUserExcetion : Exception { }


texts:
I am using Google BigQuery API V2 for a custom Google Data Studio connector. The BigQuery.Jobs.query() calls take roughly 50 seconds which is too long, so I am looking for ways to speed things up:
function runQuery() {
  // Cloud Platform project.
  var projectId = 'XXXXXXXX';

  const sqlQuery = `SELECT orgId, status, DATETIME(createdAt,'Pacific/Auckland') as createdAt FROM publicdata:samples.shakespeare LIMIT 50000;`;

  var request = {
    query: sqlQuery,
    useLegacySql: false,
  };

  var queryResults = BigQuery.Jobs.query(request, projectId);
  var jobId = queryResults.jobReference.jobId;

  // Check on status of the Query Job.
  var sleepTimeMs = 500;
  while (!queryResults.jobComplete) {
    Utilities.sleep(sleepTimeMs);
    sleepTimeMs *= 2;
    queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
  }

  // Get all the rows of results.
  var rows = queryResults.rows;

  while (queryResults.pageToken) {
    queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
      pageToken: queryResults.pageToken
    });
    rows = rows.concat(queryResults.rows);
  }

  if (rows) {
    var headers = queryResults.schema.fields.map(function(field) {
      return field.name;
    });

    var data = [];
    for (var i = 0; i < rows.length; i++) {
      var obj = {};

      var cols = rows[i].f;
      for (var j = 0; j < headers.length; j++) {
        obj[headers[j]] = cols[j].v;
      }

      data.push(obj);
    }
    return data;
  } else {
    Logger.log('No rows returned.');
    return null;
  }
}


texts:
I've created an IValueConverter in order to Bind to the index value of a Collection.
However it seems to be rather slow/infefficient and I wonder if there is a better/different way to do this.
public class IndexValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            CollectionView collectionView = (CollectionView) parameter;
            IList collection = (IList) collectionView.ItemsSource;

            int convertedValue = collection.IndexOf(value) + 1;
            return convertedValue;
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
            return -1;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML
<CollectionView
    x:Name="JobPins"
    ItemsSource="{Binding ACollectionView}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="ADataModel">
            <Label
                BackgroundColor="Black"
                Style="{StaticResource ListLabels}"
                Text="{Binding .,
                Converter={StaticResource IndexConverter},
                ConverterParameter={x:Reference Name=JobPins}}"
                TextColor="WhiteSmoke" />
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>


texts:
I am creating a social network that let's users upload a profile picture. I just want to know if this is a secure way of doing it. Thanks.
<?php

include 'includes/header.php';
include 'includes/form_handlers/settings_handler.php';

//$userPic = '';
$date_time = date('Y-m-d_H-i-s');

if(!empty($userLoggedIn)) {

    if (isset($_FILES['fileToUpload'])) {
        $errors= array();
        $file_name = $_FILES['fileToUpload']['name'];
        $file_size = $_FILES['fileToUpload']['size'];
        $width = 1500;
        $height = 1500;
        $file_tmp = $_FILES['fileToUpload']['tmp_name'];
        $file_type = $_FILES['fileToUpload']['type'];
        $tmp = explode('.',$_FILES['fileToUpload']['name']);
        $file_ext=strtolower (end ($tmp));

        $extensions = array( "jpeg", "jpg", "png", "gif");

        if(in_array($file_ext,$extensions)=== false){

            $errors[]="extension not allowed, please choose a JPEG or PNG file.";
        }

        if ($file_size > 8097152) {

            $errors[] = 'File size must be 2 MB';
        }

        if ($width > 1500 || $height > 1500) {

            echo"File is to large";
        }

        if(!$errors) {

            $userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
            $profilePic = move_uploaded_file($file_tmp,"assets/images/profile_pics/" . $userPic);

            $file_path = "assets/images/profile_pics/" . $userPic;

            $stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
            $stmt->bind_param('ss', $file_path, $username);
            $stmt->execute();
            $stmt->close();

            header('Location: settings.php');
            exit();

        }
    }
} else {

    echo "Invalid Username";
}

?>


texts: How can I speed up my IDA* algorithm for N-puzzle?

texts:
I'm trying to solve the N-Puzzle problem using IDA* algorithm with a Manhattan heuristic. I already implemented the algorithm from the pseudocode in this Wikipedia page (link).
Here's my code so far :
class Node():
    def __init__(self, state, manhattan):
        self.state = state
        self.heuristic = manhattan

    def __str__(self):
        return f"state=\n{self.state}\nheuristic={int(self.heuristic)}"

    def __eq__(self, other):
        return np.array_equal(self.state, other.state)

def customSort(node):
    return node.heuristic

def nextnodes(node):
    zero = np.where(node.state == 0)

    y,x = zero
    y = int(y)
    x = int(x)

    directions = []
    if y > 0:
        directions.append((y - 1, x))
    if x > 0:
        directions.append((y, x - 1))
    if y < constant.SIZE2 - 1:
        directions.append((y + 1, x))
    if x < constant.SIZE2 - 1:
        directions.append((y, x + 1))

    arr = []
    for direction in directions:
        tmp = np.copy(node.state)
        goal = np.where(constant.GOAL_STATE == tmp[direction])

        tmp[direction], tmp[zero] = tmp[zero], tmp[direction]

        tile1_score = manhattan_distance(direction, goal)
        tile2_score = manhattan_distance(zero, goal)

        arr.append(Node(tmp, node.heuristic - tile1_score + tile2_score))

    arr.sort(key=customSort)

    return arr

def manhattan_distance(a, b):
    return abs(b[0] - a[0]) + abs(b[1] - a[1])

def count_distance(number, state1, state2):
    position1 = np.where(state1 == number)
    position2 = np.where(state2 == number)

    return manhattan_distance(position1, position2)

def manhattan_heuristic(state):
    distances = [count_distance(num, state, constant.GOAL_STATE) for num in constant.SIZE]
    return sum(distances)

def search(path, g, threshold):
    node = path[-1]
    f = g + node.heuristic

    if f > threshold:
        return f
    if np.array_equal(node.state, constant.GOAL_STATE):
        return True

    minimum = float('inf')
    for n in nextnodes(node):
        if n not in path:
            path.append(n)
            tmp = search(path, g + 1, threshold)
            if tmp == True:
                return True
            if tmp < minimum:
                minimum = tmp
            path.pop()

    return minimum

def solve(initial_state):path = solve(initial_state)
    initial_node = Node(initial_state, manhattan_heuristic(initial_state))
    threshold = initial_node.heuristic

    path = [initial_node]

    while 1:
        tmp = search(path, 0, threshold)
        if tmp == True:
            print(f"GOOD!")
            return path
        elif tmp == float('inf'):
            print(f"WRONG!")
            return False
        threshold = tmp

You can call the solve() function (and create some needed global variables) like this:
def define_goal_state(n):
    global GOAL_STATE
    global SIZE
    global SIZE2
    global ZERO

    m = [[0] * n for i in range(n)]
    dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
    x, y, c = 0, -1, 1
    for i in range(n + n - 2):
        for j in range((n + n - i) // 2):
            x += dx[i % 4]
            y += dy[i % 4]
            m[x][y] = c
            c += 1

    GOAL_STATE = np.array(m)
    SIZE = range(1, len(GOAL_STATE) ** 2)
    SIZE2 = len(GOAL_STATE)
    ZERO = np.where(GOAL_STATE == 0)

initial_state = np.array([8 7 3],[4 1 2],[0 5 6])
define_goal_state(len(initial_state))
path = solve(initial_state)

My implementation of the Wikipedia pseudocode is working and I get pretty fast results in a 8-Puzzle problem. But it gets really slow with a 15-Puzzle problem and above.
Regarding the solve() and the search() functions I think I respect almost identically the pseudocode. I also optimized my nextnodes() function to count only the tile that has been moved, not all tiles every time. Should be good here.
So where's the catch ? Why is my implementation taking so long ?
Does anyone have a clue ?


texts: Iterative procedure to get 3D coordinates from distance constraints

texts:
Imagine you have a series of n points randomly generated in a box in 3D space. You also have a list of distance bounds, e.g. points 5 and 3 should be between 1.0 and 2.0 Angstroms apart.

There are various methods to get from random coordinates to a solution that fills some or all distance bounds. Below is an implementation of Stochastic Proximity Embedding, one such method, in Julia. I am looking for input on improving the speed.

function run_spe(present_i, present_j, bounds_lower, bounds_upper, no_atoms)
    squares_lower = bounds_lower .* bounds_lower
    squares_upper = bounds_upper .* bounds_upper
    learning_rate = 1.0
    coord_new_i = zeros(3)
    coord_new_j = zeros(3)
    bound_near = 0.0
    no_cycles = 1500
    no_steps = 70000
    no_bounds = length(present_i)
    # Generate random starting coordinates
    coords = rand!(zeros(3, no_atoms)) * 100.0
    for cycle in 1:no_cycles
        for step in 1:no_steps
            # Pick a random bound from the list of bounds
            rand_ind = rand(1:no_bounds)
            i = present_i[rand_ind]
            j = present_j[rand_ind]
            # Compute square distance between atoms
            sq_dist = 0.0
            for m = 1:3
                sq_dist += abs2(coords[m, i] - coords[m, j])
            end
            # Check if square distance is within bounds
            # If it is, go to the next iteration
            # If it is not, find the nearest bound
            if sq_dist < squares_lower[rand_ind]
                bound_near = bounds_lower[rand_ind]
            elseif sq_dist > squares_upper[rand_ind]
                bound_near = bounds_upper[rand_ind]
            else
                continue
            end
            # Adjust coordinates to bring them closer to the nearest bound
            distance = sqrt(sq_dist)
            prefactor = learning_rate * 0.5 * (bound_near - distance) / distance
            for k in 1:3
                coord_new_i[k] = coords[k, i] + prefactor * (coords[k, i] - coords[k, j])
                coord_new_j[k] = coords[k, j] + prefactor * (coords[k, j] - coords[k, i])
            end
            for l in 1:3
                coords[l, i] = coord_new_i[l]
                coords[l, j] = coord_new_j[l]
            end
        end
        # Decrease learning rate after each cycle
        learning_rate -= 1 / no_cycles
    end
    return coords
end

present_i/present_j are lists of indices. bounds_lower/bounds_upper are lists of distances. For example, present_i[10] = 5, present_j[10] = 3, bounds_lower[10] = 1.0, bounds_upper[10] = 2.0 would mean the tenth bound corresponds to the example bound above.

I have done a bit of profiling and the major bottlenecks are the initial lines in the inner loop (from rand_ind up to continue). Ideally Julia tricks to speed individual steps up would be helpful, but if there is a better data structure than the lists I use that would also be good.

Sample data can be found here for testing and read in using something quick like:

# Set in_filepath as path to downloaded and uncompressed file
present_i = Int[]
present_j = Int[]
bounds_lower = Float64[]
bounds_upper = Float64[]
no_atoms = 2035
open(in_filepath, "r") do in_file
    for line in eachline(in_file)
        cols = split(strip(line), '\t')
        push!(present_i, int(cols[1]))
        push!(present_j, int(cols[2]))
        push!(bounds_lower, float(cols[3]))
        push!(bounds_upper, float(cols[4]))
    end
end


texts:
In order to solve this challenge:

  Challenge Description

  By starting at the top of the triangle and moving to adjacent numbers on the row below, the maximum total from top to bottom is 27.

   5

  9 6

 4 6 8

0 7 1 5

  5 + 9 + 6 + 7 = 27

  Input sample

  Your program should accept as its first argument a path to a filename. Input example is the following:

5
9 6
4 6 8
0 7 1 5

  You make also check full input file which will be used for your code evaluation.

  Output sample

  The correct output is the maximum sum for the triangle. So for the given example the correct answer would be

27

I came up with the following code:

static int GetMaxSum(int[][] numbers)
{
    int firstCandidate = 0;
    int secondCandidate = 0;
    int max = 0;

    for(int i = 1; i < numbers.Length; i++)
    {
        for(int j = 0; j < numbers[i].Length; j++)
        {
            firstCandidate = 0;
            secondCandidate = 0;

            if (j - 1 >= 0)
            {
                firstCandidate = numbers[i][j] + numbers[i - 1][j - 1];
            }

            if (j < numbers[i - 1].Length)
            {
                secondCandidate = numbers[i][j] + numbers[i - 1][j];
            }

            numbers[i][j] = firstCandidate > secondCandidate ? firstCandidate : secondCandidate;
        }
    }

    int lastIndex = numbers.Length - 1;
    var lastLine = numbers[lastIndex];
    for(int i = 0; i < lastLine.Length; i++)
    {
        if(lastLine[i] > max)
        {
            max = lastLine[i];
        }
    }

    return max;
}

static int[] ParseLine(string line)
{
    string[] numbers = line.Trim().Split(' ');
    int numbersLength = numbers.Length;
    var result = new int[numbersLength];

    for(int i = 0; i < numbersLength; i++)
    {
        result[i] = int.Parse(numbers[i]);
    }

    return result;
}

static void Main(string[] args)
{
    var list = new List<int[]>();
    int max = 0;

    using (StreamReader reader = File.OpenText(args[0]))
    {
        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();

            if (null == line)
            {
                continue;
            }

            list.Add(ParseLine(line));
        }
    }

    max = GetMaxSum(list.ToArray());

    Console.WriteLine(max);
}

and wanted some feedback on it.

The basic idea is:

Read all the file
Transform the content in a Lower Triangle Matrix structure
Calculate max sums directly in the matrix (being that it's used only internally and it can be thrown once it's been processed)

This was the most efficient - with regard to space and time - algorithm I could think of.

Everything you can find - readability problems, efficiency problems, design problems, etc... - is fine.


texts: Checking whether one string is a permutation of another

texts:
I solved the standard "write a method to determine if one string is a permutation of the other" question with the following code, using xor, map, and reduce:

from functools import reduce
from operator import xor

def checkPermutation(str1, str2):
    return not bool(reduce(xor, map(ord, str1 + str2)))

The idea is that if the two strings are permutations, the xor sum of the int value of every character of the concatenation of the two strings must be 0.

If I write the algorithm out by hand it seems come down to O(n) time and space:

def checkPermutation(str1, str2):
    # map every character in the strings to its integer value
    map = []
    str = str1 + str2
    for char in str:
        map.append(ord(char))

    # xor every number that was mapped into a sum
    sum = map[0]
    for i in range(1, len(map)):
        sum ^= map[i]

    return not bool(sum)

Essentially I think that's what reduce and map are doing but depending on how they're actually implemented in python, the time and space complexity of two solutions may differ.


texts: Encoding and decoding in Haskell -- 99 Problems exercise 13, 14

texts:
I've been working on these solutions to the Haskell 99 questions, encoding and decoding series for a while now, so I figured I ought to present them to see how I screwed up the implementation.

Problems:

  Encoding: Write a function which encodes a series of characters using
  run-length encoding and an algebraic data type such that the sequence
  "aaaabccaadeeee" outputs:

[Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']

  Decoding: Write a function which decodes a series of algebraic data types  representing run-length encoding as a series of characters such that the sequence

[Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']

  outputs "aaaabccaadeeee".

Here is the code I used for the problems:

import Data.List

main = do
    print $ decode (encode "Mississippi")

data Encoding = Multiple Int Char | Single Char deriving (Show)

encode :: [Char] -> [Encoding]

encode chars= map toEncoding ( (countChars . group) chars)

    where

    countChars :: [String] -> [(Int, Char)]
    countChars strings = map countCharsHelper strings

    countCharsHelper :: String -> (Int, Char)
    countCharsHelper chars = (length chars, head chars)

    toEncoding :: (Int, Char) -> Encoding
    toEncoding (1, a) = Single a
    toEncoding (num, a) = Multiple num a

decode :: [Encoding] -> [Char]

decode encodings = foldl (++) "" (map replicateChars (map fromEncoding encodings))
    where

    fromEncoding :: Encoding -> (Int, Char)
    fromEncoding (Multiple num char) = (num, char)
    fromEncoding (Single char) = (1, char)

    replicateChars :: (Int, Char) -> [Char]
    replicateChars (num, char) = replicate num char

And the output is the expected output "Mississippi", while decode and encode testing correctly via GHCi.


texts: Speed up query that handles auditing and versioning

texts:
I have the following tables:

tag_name_audit table

tag_name table

tag_adit table

tag table

The action that the query performs is auditing and version handling.
For example i can have one set of data that has a stable version and an edit version.
And you can release that last edit version and it becomes the last stable version.

I have the following query:

SELECT
            t.id as u_id,
            IF(tn.state = 'P',tna.name,tn.name) as name,
            t.version,
            tn.state
            FROM tag AS t
            INNER JOIN tag_name AS tn ON tn.tag_parent = t.id
            LEFT JOIN tag_name_audit AS tna ON tna.tag_name_parent = tn.id AND tn.state = 'P'
            AND  tna.id = (
                            SELECT MAX(id)
                            FROM tag_name_audit
                            WHERE tag_name_parent = tn.id
                        )
            WHERE tn.language = ?
            AND t.version IS NOT null
            AND tn.tag_parent IN (".$planIn.")

I'm curious if there are any better solutions writing it so that i can boost the performance of the query speed.

  Showing rows 0 - 8 (9 total, Query took 0.0009 seconds.)


texts:
The task

is taken from leetcode

  Given a string, find the first non-repeating character in it and
  return it's index. If it doesn't exist, return -1.

  Examples:

  s = "leetcode"

  return 0.

  s = "loveleetcode",

  return 2.

  Note: You may assume the string contain only lowercase letters.

My solution

/**
 * @param {string} s
 * @return {number}
 */
function firstUniqChar(s) {
  const arr = Array.from([...s]
                         .reduce((map, x, i) => map.set(x, !isNaN(map.get(x)) ? null : i) , new Map())
                         .values());
  for(let i = 0; i < arr.length; i++) {
    if (arr[i] !== null) { return arr[i]; }
  }
  return -1;
};


texts:
I recently coded the Dutch national flag problem in Java and wrote some tests.
The array in zero-indexed.
Please take a look at how I verify that elements of the output array are in the right order. It's the method verifyDutch

The Dutch national flag problem

public static void dutchFlag(int[] input, int mid) {
    if (input == null || input.length < 2) {
        return;
    }
    int i = 0; // the end of the red region
    int j = 0; // the element under consideration
    int k = input.length - 1; // the start of the blue region
    while (j <= k) {
        if (input[j] < mid) {
            swap(input, i, j);
            i++;
            j++;
        } else if (input[j] == mid) {
            j++;
        } else {
            swap(input, j, k);
            k--;
        }
    }
}

Testing

public class FlagSortsTests {

    @Test
    public void testDutchWithRandom() {
        int[] input = new int[10];
        Random random = new Random();
        for (int i = 0; i < input.length; i++) {
            input[i] = random.nextInt(100);
        }
        int mid = input[random.nextInt(input.length - 1)];
        FlagSorts.dutchFlag(input, mid);
        verifyDutch(input, mid);
    }

    @Test
    public void testDutchSmallestMid() {
        int[] input = { 12, 34, 781, -1 };
        int mid = -1;
        FlagSorts.dutchFlag(input, mid);
        verifyDutch(input, mid);
    }

    @Test
    public void testDutchLargestMid() {
        int[] input = { 12, 34, 781, -1 };
        int mid = 781;
        FlagSorts.dutchFlag(input, mid);
        verifyDutch(input, mid);
    }

    @Test
    public void testDutchWithoutMid() {
        int[] input = { 12, 34, 781, -1 };
        int mid = 90;
        FlagSorts.dutchFlag(input, mid);
        verifyDutch(input, mid);
    }

    private void verifyDutch(int[] input, int mid) {
        if (input == null || input.length < 2) {
            return;
        }
        for (int i = 1; i < input.length; i++) {
            if (input[i] < mid) {
                Assert.assertTrue(input[i - 1] < mid);
            } else if (input[i - 1] == mid) {
                Assert.assertTrue(input[i] >= mid);
            } else if (input[i - 1] > mid) {
                Assert.assertTrue(input[i] > mid);
            }
        }
    }

Update #1

The assert failure messages are wrong. Let me delete them until I write something more infomative


texts: Getting totals of each primary key by matching it with another worksheet with a many relationship

texts:
I have already resolved several others using Application.Index with Application.WorksheetFunction.Match and reduced time to perform from about 7-8 seconds to milliseconds. But I feel there is still room for improvement.

Should I use an array with Index and Match?

I was also told to use Scripting.Dictionary, but I am looking for someone who can demonstrate how to do it the right away in this scenario. Because in my head I have to populate the dictionary with a loop before I can even use that, so wont it be similar in terms of speed?

'Production Quantity for Dashboard
For i = 2 To Total_rows_Prod
    For j = 2 To Total_rows_Dash
        If ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 5) = ThisWorkbook.Worksheets("Dashboard").Cells(j, 1) Then
           ThisWorkbook.Worksheets("Dashboard").Cells(j, 4) = ThisWorkbook.Worksheets("Dashboard").Cells(j, 4) + ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 31) / ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 4)
        End If
    Next j
Next i

After doing some bottleneck testing as shown below (run time of code is shown at row 10):

However, when using Index and Match while only using 1 for-next loop as shown in the code below:

'Production Quantity for Dashboard
For i = 2 To Total_rows_Prod
    m = Application.Match(ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 5), ThisWorkbook.Worksheets("Dashboard").Range("A:A"), 0)
    If Not IsError(m) Then
        ThisWorkbook.Worksheets("Dashboard").Cells(Application.WorksheetFunction.Match(ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 5), ThisWorkbook.Worksheets("Dashboard").Range("A:A"), 0), 4) = ThisWorkbook.Worksheets("Dashboard").Cells(Application.WorksheetFunction.Match(ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 5), ThisWorkbook.Worksheets("Dashboard").Range("A:A"), 0), 4) + ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 31) / ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 4)
    End If
Next i

The run time would be negligible as shown below (still at row 10):

Any improvements that would make the time to perform optimally minimized would be great.

The final time I was able to make everything run with Index and Match replacements was 2 seconds:

But on a slower netbook running a Pentium Atom processor, it takes 26 seconds to perform the same code. So I am wondering if there is way to bring down that 26 seconds.


texts: Hibernate MassIndexer using chained invocation for building a batch job

texts:
I've a class called MassIndexer.java (on GitHub) and it uses chained invocation for building a batch job. Each method assigns a property of this job and finally the job will be started using method MassIndexer#start(). Here's an example for Java EE:

long executionId = new MassIndexer()
        .addRootEntities(Company.class, Employee.class)
        .start();

According to different environments, the requirement is different. Some methods are required in Java SE while all of them are optional in Java EE. If users use MassIndexer under Java SE and they forget to set the properties through those required methods, the job will fail. These required methods on Java SE are:

isJavaSE(boolean)
entityManagerFactory(EntityManagerFactory)
jobOperator(JobOperator)

Here's another example for Java SE:

long executionId = new MassIndexer()
        .addRootEntities(Company.class, Employee.class)
        .isJavaSE(true)
        .entityManagerFactory(emf)
        .jobOperator(jobOperator)
        .start();

However, the design of this class in not clear: people don't know which method is required and which isn't. The only way to know it is to read the documentation. And I'm wondering how can I improve the design of this class, so that people can easily understand what to do and how to do. For example, should this class be split into MassIndexerEE and MassIndexerSE? Should it be refactored into a builder class, e.g. BatchIndexingJobBuilder?

And there's no order or logic among these methods. You can call foo() then bar(), but bar() then foo() works too. Properties are used for configurations based on

selection of class types (about persistence)
database interaction (about persistence)
parallel processing (about job)
checkpoing algorithm (about job)

Someone must be confused when using this class, so I'm seeking advice.  Every review is welcomed.


texts: Finds customer who live within 100km and output them to a text file

texts:
I had an interview task where I had to output customers who live 100km within a particular latitude and longitude and then output them to a file with their username and ID. The customer file looks like the following:
{"latitude": "52.986375", "user_id": 12, "name": "Christina McArdle", "longitude": "-6.043701"}
{"latitude": "51.92893", "user_id": 1, "name": "Alice Cahill", "longitude": "-10.27699"}
{"latitude": "51.8856167", "user_id": 2, "name": "Ian McArdle", "longitude": "-10.4240951"}
{"latitude": "52.3191841", "user_id": 3, "name": "Jack Enright", "longitude": "-8.5072391"}

Here is the code to implement the calculation for the great-circle-distance
/**
 * solution accuired from
 * https://www.movable-type.co.uk/scripts/latlong.html
 */

const greatCircleDistanceCalc = (lat1, lon1, lat2, lon2) => {
  const R = 6371; // Radius of the earth in km
  const dLat = deg2rad(lat2 - lat1); // deg2rad below
  const dLon = deg2rad(lon2 - lon1);
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(deg2rad(lat1)) *
      Math.cos(deg2rad(lat2)) *
      Math.sin(dLon / 2) *
      Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const d = R * c; // Distance in km
  return d;
};

const deg2rad = (deg) => {
  return deg * (Math.PI / 180);
};

module.exports = {
    greatCircleDistanceCalc,
};

Here is the main app.js where the calculation is used and a customer file is read and a new file is outputted.
const fs = require("fs");
const { greatCircleDistanceCalc } = require("./greatCircleDistanceCalc.js");

const customerFile = fs.readFileSync("./customers.txt", "utf-8"); //Read in file
const customerArr = customerFile.split("\n").map((s) => JSON.parse(s)); //Convert file into array of objects

const dublinOffice = {
  latitude: "53.339428",
  longitude: "-6.257664",
};

const invitedArr = [];

//Sort data in ascending order
const sortedCustomers = customerArr.sort((a, b) => {
  return a.user_id - b.user_id;
});

const closestCustomers = (sortedCustomers, arr) => {
  for ({ latitude, longitude, user_id, name } of sortedCustomers) {
    if (
      greatCircleDistanceCalc(
        dublinOffice.latitude,
        dublinOffice.longitude,
        latitude,
        longitude
      ) <= 100
    ) {
      invitedArr.push(`${name}:${user_id}`);
    }
  }
  writeInvitedCustomer(arr);
};

const writeInvitedCustomer = (arr) => {
  const writeStream = fs.createWriteStream("Output.txt");
  const pathName = writeStream.path;

  arr.forEach((value) => writeStream.write(`${value}\n`));
  writeStream.on("finish", () => {
    console.log(`wrote all the array data to file ${pathName}`);
  });

  writeStream.on("error", (err) => {
    console.error(`There is an error writing the file ${pathName} => ${err}`);
  });

  writeStream.end();
};

closestCustomers(sortedCustomers, invitedArr);

Overall I am happy with the solution but I think the only thing is I am not sure how to write a test for this.
As always any feedback and suggestions are much welcome.


texts: Optimizing jQuery functions for mobile menu

texts:
I'm using Bootstrap 3 as the front-end framework for this. It is quite simple but I feel I'm doing it wrong. I'm sure this code can be optimized not to duplicate the $('a[href=""]') functions but I just can't wrap my head around it.

For now, this code is only for mobile. I'll have to figure out how to control the menu behavior for larger screens (not requested at this time).

jsFiddle (you need to resize your browser to see the effect)

$(document).ready(function () {

/*
 * Modification du boutton MENU pour CLOSE
 */

$('button').on('click', function(e){
    var str = $(this).text();
    if(str =="CLOSE"){
        $(this).html("MENU");
    }
    else{
        $(this).html("CLOSE");
    }

    if(str == "MAIN MENU"){
        e.stopPropagation();
        $('#menuContacts').css('display', 'none');
            $('#menuWines').css('display', 'none');
            $('#menuMain').css('display', 'block');

            $('button').html('CLOSE');
    }
});

/*
 * Modification du menuMain pour le menuContacts
 */

$('a[href="#contacts"]').on('click', function(e){
    e.preventDefault();
    $('#menuMain').css('display', 'none');
    $('#menuContacts').css('display', 'block');

    $('button').html('MAIN MENU');

});

/*
 * Modification du menuMain pour le menuWine
 */

$('a[href="#wines"]').on('click', function(e){
    e.preventDefault();
    $('#menuMain').css('display', 'none');
    $('#menuWines').css('display', 'block');

    $('button').html('MAIN MENU');

});
});


texts: Counting only weekend days between two timestamps

texts:
I am fairly new to the Groovy arena. I recently modified some code to add the following block. This code is added to remove dates we were supposed to remove from the total counts.  This data goes on reports that a bug was noticed, that we weren't removing the queue entry dates.

result.processed.each{
    def queueEntry = QueueEntry.findById(it.id)<<<START ADD>>>
    Set dates = new HashSet<Long>()

    def children = QueueEntry.findAllByParent(queueEntry)

    for(QueueEntry qe : children){
        def f = new GregorianCalendar()
        f.setTimeInMillis(DateUtils.getClearedTime(qe.entryTimestamp))
        def l = new GregorianCalendar()
        l.setTimeInMillis(DateUtils.getClearedTime(qe.exitTimestamp))
        while(f < l){
            if(f.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY && f.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY){//only add weekdays
                dates.add(f.time.time)
            }
            def xx = new GregorianCalendar()
            xx.setTimeInMillis(f.time.next().time)
            f = xx
        }
        dates.add(l.time.time)
    } <<<STOP ADD>>>
    Set outsideDays = it.numberOfDaysOutsideCVB
    Set days = DateUtils.businessDaysBetweenDates(it.entryTimestamp, it.exitTimestamp)
    days.removeAll(outsideDays)
    days.removeAll(dates)
    turnTimes << days.size()
}

The application is now crawling. I am obviously doing something wrong. When this is run for small data-sets it will complete slowly. On larger sets it doesn't finish. Prior to this change it was completing.


texts:
I wrote this prototype after reading the Wikipedia article on hooking.  I didn't bother to read any of the code examples listed there because, well, I just didn't.  I don't have a good excuse.

The documentation in this file should tell you enough about its purpose and intended usage.  I'm looking for a confirmation of whether I even understand what hooks are and how they should be used.  I'm also curious about any sort of preferred method of implementation or any way that I could improve these two objects (Hook and OnHook).

"""Implement hooks with a simple interface using decorators.

The Hook class creates a function that can be placed in code as an
anchoring point for as yet undetermined functionality, while the
OnHook function creates the interface to that functionality.

To create a hook, use the @Hook decorator on an empty function of
your chosen name.  The function's __call__ method will be generated
by the decorator.  Then, create a function that accepts a function
as an argument and adds it to the targets callback by using @OnHook.
OnHook expects the target hook as an argument.

Example:

    @Hook                           # decorator, no args
    def my_hook(): pass             # empty func, no params
    @OnHook(my_hook)                # decorator, hook as arg
    def on_my_hook(func): pass      # empty func, func as param

To add a callback to the new hook, use:

    on_my_hook(my_callback)

When the hook is executed, your callback will be executed along with
any other callbacks that have been registered.

Written 2014-02-02 by Jack Stout.

"""

class Hook:
    """Decorator to create a hook."""
    def __init__(self, func):
        self.callbacks = []

    def __call__(self):
        for callback in self.callbacks:
            callback()

def OnHook(target):
    """Decorator to create an interface to a hook.

    Requires a target hook as only argument.

    """
    def decorator(func):
        def add_callback(func):
            target.callbacks.append(func)
        return add_callback
    return decorator

# Here I've created two hooks with interfaces which would be used
# immediately before and after a hypothetical initiative() function.
@Hook
def pre_initiative(): pass
@OnHook(pre_initiative)
def on_pre_initiative(func): pass

@Hook
def post_initiative(): pass
@OnHook(post_initiative)
def on_post_initiative(func): pass

# Two dummy functions are created and are added to the hooks' callback lists.
def dummy_func_1():
    print("Inside pre_initiative!")
on_pre_initiative(dummy_func_1)

def dummy_func_2():
    print("Inside post_initiative!")
on_post_initiative(dummy_func_2)

# These print functions reveal what has been registered in the hook.
print(pre_initiative.callbacks)
# This function call is what we would see in production code.
pre_initiative()

print(post_initiative.callbacks)
post_initiative()

Less important but related:

This is a prototype but I'm working on a game project that could benefit from this method of quickly attaching function pointers to upcoming state changes.  While working on this file, I was imagining the first phase in a tabletop combat encounter where the players and game master roll initiatives and determine the combat order.  If a character were to gain a power that allowed them to adjust their initiative roll after everyone has rolled, it would require only a call to on_post_initiative(power_name).  When initiative() completes, post_initiative() would fire and execute power_name().

Before getting any feedback, if I were to revisit this code I would add the ability to include arguments to be used with the callback, i.e. on_post_initiative(power_name, character_name).


texts:
I built one JavaScript debounce function. I need a JavaScript expert's opinion if this is the correct way to do it, and if not, then what the flaw is in this current function.

var debounce = function(inpFun, wait) {
    var timeout;
    return function () {
        if(!timeout) {
            inpFun.apply(this, arguments);
            timeout = setTimeout(function() {
                timeout = undefined;
            }, wait);
        }
        else {
            console.log("Debouncing");
        }
    }
};

var buttonClickFunction = debounce(function (event) {
    console.log("Button Clicked");
    console.log(event.target.id);
}, 2000);

document.querySelector("#button1").addEventListener("click", buttonClickFunction);


texts: Elasticsearch update script using python bulk update

texts:
I'm using this script to bulk update docs in my index.
I need to update a field of a doc in Elasticsearch and add the count of that doc in a list inside python code. The weight field contains the count of the doc in a dataset. The dataset needs to be updated from time to time.So the count of each document must be updated too. hashed_ids is a list of document ids that are in the new batch of data. the weight of matched id must be increased by the count of that id in hashed_ids.
For example let say a doc with id=d1b145716ce1b04ea53d1ede9875e05a and weight=5 is already present in index. and also the string d1b145716ce1b04ea53d1ede9875e05a is repeated three times in the hashed_ids so the update_with_query query  will match the doc in database. I need to add 3 to 5 and have 8 as final weight.
The code below works for it but it is too slow and from time to time I get time out error.
hashed_ids = [hashlib.md5(doc.encode('utf-8')).hexdigest() for doc in shingles]
update_by_query_body =
{
  "query":{
    "terms": {
      "id":["id1","id2"]
    }
  },
  "script":{
    "source":"long weightToAdd = params.hashed_ids.stream().filter(idFromList -> ctx._source.id.equals(idFromList)).count(); ctx._source.weight += weightToAdd;",
    "params":{
      "hashed_ids":["id1","id1","id1","id2"]
    }
  }
}


texts: Insert rows in the datagridview with a dictionary

texts:
I would like to improve the function below without calling twice InserisciRigaNote.

Before I fill my dictionary. When I compare idNota with the current database id I check if it is equal or not, if different means that the dictionary is filled and I can proceed with the insertion of the row in DataGridView

I have a query that return this output:

I have to fill a DataGridView in that way

string query = ""; // Query MySQL
using (MySqlDataReader reader = db.ExecuteReader(query))
{
    if (reader.HasRows)
    {
        int idNota = 1;
        var note = new Dictionary<string, string>();
        while (reader.Read())
        {
            if (idNota != Convert.ToInt32(reader["id_nota_lavaggio"]))
            {
                InserisciRigaNote(note, idNota); // Function that insert row in the DataGridView

                idNota = Convert.ToInt32(reader["id_nota_lavaggio"]);
                note.Clear();
            }
            // Create a dictionary made by a language key and a description
            note[reader["id_lingua"].ToString()] = reader["descrizione_nota_lavaggio"].ToString();
        }
        if (note.Count > 0) // If there is something in the dictionary
        {
            InserisciRigaNote(note, idNota);
            note.Clear();
        }

    }
}

N.B.
I did not use Pivot to make the query because I need it's all completely dynamic


texts: Project Euler - Largest Product In A Grid


texts: (Y.E.S.E.J.) Yet Another Singleton with Enum in Java

texts:
I have a Java class which has to be generated only once for all the objects that I have - it is a small program. This singleton class holds a mapping of characters. I Googled stack overflow and found that using enum is the most safest way to create a singleton class as Josh Bloch explained in his Java book.

I also read some reviews that singletons are not good. But for my scope I think I need one. So my code is:

public enum  SingletonClassA {
    INSTANCE;
    private static Map<Character, Character> instance;
    static {
        Map<Character, Character> aCharMap = new HashMap();
        aCharMap.put('a', 'e');
        aCharMap.put('o', 'u');
        // in order to keep short I erased other puts.
        instance = Collections.unmodifiableMap(aCharMap);
    }

    public static Map<Character, Character> getInstance() {
        return instance;
    }
}

And in order to reach the elements of this HashMap I use

SingletonClassA.INSTANCE.getInstance().containsKey(aLetter);

Am I creating this singleton class correctly? Do I also need to create a private constructor?

If you have any suggestions about using another data structure for this case please recommend it, write the reasons also.


texts: Angular async pipe with loading spinner and manual refresh

texts:
I have an Angular 6 app with the following requirements:

Get data from a web service.
Load the data when the page is displayed.
Reload the data when the user requests a reload by through some UI, like a button.
Show a spinner while loading data in the header of the page. That is, not in the same place where the data is going to be displayed. Which means I cannot use ngIf with ; else #loading.

I have the following (simplified) code that is actually working. I also have a live code sample. However I wonder if this is the canonical way to do it. Especially as I a am new to RxJS. Other improvements or suggestions are also welcome.

Some things I am not sure of:

Using the refresh Subject to do load/reload.
Setting the loading member within RxJS operators (side effects).

The component:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  refresh: Subject<string>; // For load/reload
  items$: Observable<any>; // Some items

  loading: boolean = true; // Turn spinner on and off

  constructor (private http: HttpClient) { }

  ngOnInit() {
    this.refresh = new Subject();

    this.items$ = this.refresh.asObservable()
      .pipe(
        startWith('onInit'), // Emit value to force load on page load; actual value does not matter
        flatMap(_ => this.http.get<any>('https://swapi.co/api/people/')), // Get some items
        delay(1000), // Delay to let our spinner shine
        map(data => data.results), // Map data
        tap(_ => this.loading = false) // Turn off the spinner
      );
  }

  onRefresh() {
    this.loading = true; // Turn on the spinner.
    this.refresh.next('onRefresh'); // Emit value to force reload; actual value does not matter
  }
}

The template:

Items

        {{item.name}}


texts: How parse nicely a string into three (or more) pieces?

texts:
See, I have a file which consists of a bunch of lines like

NAME:0001;some text
ANOTHERNAME:000103;some more text
NEWNAME:42; blah blah

So what I need to do is to have a list of those names, list of numbers (IDs actually, so the order matters) and list of further comments. I wrote a code, which actually does work, but I'm afraid it's horrible and not pythonic at all.

reactions_file = open("reactions.txt","r")
lines = reactions_file.readlines()
reaction_names = []
reaction_other = []
reaction_IDs = []
reaction_notes = []
for line in lines:
    r_name = line.partition(":")[0]
    r_other = line.partition(":")[2]
    reaction_names.append(r_name)
    reaction_other.append(r_other)
for item in reaction_other:
    r_ID = item.partition(";")[0]
    r_note = item.partition(";")[2]
    reaction_IDs.append(r_ID)
    reaction_notes.append(r_note)
print(reaction_names)
print(reaction_IDs)
print(reaction_notes)
reactions_file.close()

How can it be changed to look less like written by newbie? :)


texts: Setting up radio button click ActionListeners

texts:
Instead of writing four almost identical setOnClickListener method calls, I opted to iterate over an array, but I'm wondering if this was the best way to do it. Do you have any suggestions for improving it?

/* Set up the radio button click listeners so two categories are not selected
   at the same time. When one of them is clicked it clears the others.
*/
final RadioButton[] buttons = {radio_books,radio_games,radio_dvds,radio_electronics};
for (int i = 0; i < 4; i++) {
    final int k = i;
    buttons[i].setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            for (int j = 0; j < 4; j++) {
                if (buttons[j] != buttons[k]) {
                    buttons[j].setChecked(false);
                }
            }
        }
    });
}


texts:
I have two fetch calls which updates the state. And I have two buttons. One makes a fetch call, another calls componentDidMount().

The first fetch call is in componentDidMount().

The second is On "All Time Sort" button click with handleSortRecent().

On "Recent Sort" button click, I want to show the previous informatin fetched in componentDidMount. To achieve this
I am calling the componentDidMount() method itself from handleSortRecent() method.

Is there a better way to do this without using Redux?

const API = "https://fcctop100.herokuapp.com/api/fccusers/top/";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dataRecent : [],
      dataAlltime : []
    }

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
    this.handleSortRecent = this.handleSortRecent.bind(this);
  }

  componentDidMount() {
    fetch(API+"recent")
      .then( response => response.json() )
      .then( data => this.setState( { dataRecent: data } ) );
  }

  handleClick () {
    fetch(API+"alltime")
    .then(response => response.json())
    .then(data => this.setState({dataRecent:data}))
  }

  handleSortRecent() {
    this.componentDidMount();
  }

  render() {
    const arrRecentList = this.state.dataRecent;

    return (

      <button onClick={this.handleClick}>All Time Sort</button>
      <button onClick={this.handleSortRecent}>Recent Sort</button>
      {
        arrRecentList.map(data =>

            {data.username}
             -
            {data.recent}
             -
            {data.alltime}

        )
      }

    );
  }
}


texts: Open/Closed Principle with calculating the total cost of items in a shopping cart

texts:
I came across the below example in a tutorial for the open-closed OOP principle. This example demonstrates function of calculating the total cost of items in a shopping cart. I have provided code for both before and after refactoring to comply with the open-closed principle. Both versions are from the tutorial I followed.

The drawback with the old code is that we need to add additional if/else to support new SKUs thus violating "closed for modifications" part in the open-closed principle. But even in the new design, we need to add additional IPriceRule to support new SKUs. So in what way is the new design better than old design? Is this because with the new design it is little more flexible to add complex calculation algorithm?

I have left comments in relevant sections of the code where it violates the principle.

Before:

class OrderItem {
    string sku;
    int quantity;
}

class Cart {
    List<OrderItem> items;

    public Cart() {
        items = new ArrayList<>();
    }

    public void addItem(OrderItem item) {
        items.add(item);
    }

    int totalPrice() {
        int price = 0;

        for(OrderItem item : items) {
            if( item.sku == "foo") {
                price += item.quantity * 10;
            }
            else if (item.sku == "bar") {
                price += item.quantity * 5;
            }
            // This is the problematic part. We need to add more if/else
            // conditions to support different SKUs. Hence this violates
            // closed for modifications part of open-closed.
        }

        return price;
    }
}

After refactoring to comply with the Open-Closed principle:

interface IPriceRule {
    boolean isMatch(OrderItem item);
    int calculatePrice(OrderItem item);
}

class FooPriceRule implements IPriceRule {
    @Override
    boolean isMatch(OrderItem item) {
        return item.sku.equals("foo");
    }

    @Override
    int calculatePrice(OrderItem item) {
        return item.quantity * 10;
    }
}

class BarPriceRule implements IPriceRule {
    @Override
    boolean isMatch(OrderItem item) {
        return item.sku.equals("bar");
    }

    @Override
    int calculatePrice(OrderItem item) {
        return item.quantity * 5;
    }
}

interface IPaymentCalculator {
    int calculatePrice(OrderItem item);
}

class PaymentCalculator implements IPaymentCalculator {
    List<IPriceRule> priceRules;

    public PaymentCalculator() {
        priceRules = new ArrayList<>();
        priceRules.add(new FooPriceRule());
        priceRules.add(new BarPriceRule());
        // Add new rules here to support new SKUs. But why is this better
        // than adding if/else in the old design? Because even this class
        // changes as we add more requirements right?
    }

    @Override
    int calculatePrice(OrderItem item) {
        for(IPriceRule priceRule : priceRules ) {
            if (priceRule.isMatch(item)) {
                return priceRule.calculatePrice(item);
            }
        }

        return 0;
    }
}

class Cart {
    List<OrderItem> items;
    IPaymentCalculator paymentCalculator;

    public Cart() {
        items = new ArrayList<>();
        paymentCalculator = new PaymentCalculator();
    }

    public void addItem(OrderItem item) {
        items.add(item);
    }

    int totalPrice() {
        int price = 0;

        for(OrderItem item : items) {
            price += paymentCalculator.calculatePrice(item);
        }

        return price;
    }
}


texts: Overloading both for (non) constant access

texts:
I'd offer a couple of iterator accesses to the class member, both constant and non-constant. I came to the following solution, but it seems to me far more verbose than needed. I'd like somehow to merge the two function members get_c, get_m in some fashion, but I'm not sure if possible.

#include <iostream>
#include <vector>
#include <cstdint>

using my_t = uint64_t;

// Own implementation of 3D-vector. size() == m_X * m_Y * m_Z
class Package
{
    // 3D-strides
    const size_t m_X = 10, m_Y = 2, m_Z = 4;

public:

    std::vector<my_t> m_v;

    template <class I>
    typename std::enable_if<std::is_same<I, typename std::vector<typename std::iterator_traits<I>::value_type>::iterator>::value, std::vector<my_t>::iterator>::type
    get_it(I i, size_t x, size_t y, size_t z)
    {
        return std::next(i, x * m_X * m_Y + y * m_Z + z);
    }

    template <class I>
    typename std::enable_if<std::is_same<I, typename std::vector<typename std::iterator_traits<I>::value_type>::const_iterator>::value, std::vector<my_t>::const_iterator>::type
    get_it(I i, size_t x, size_t y, size_t z) const
    {
        return std::next(i, x * m_X * m_Y + y * m_Z + z);
    }

    std::vector<my_t>::iterator
    get_m(size_t x, size_t y, size_t z)
    {
        return get_it(m_v.begin(), x, y, z);
    }

    std::vector<my_t>::const_iterator
    get_c(size_t x, size_t y, size_t z) const
    {
        return get_it(m_v.cbegin(), x, y, z);
    }

    Package() : m_v(m_X * m_Y * m_Z, 1)
    {}
};

void f_const(const Package & pkg)
{
    auto it = pkg.get_c(0, 1, 2);
    std::cout << "const: " << *it << "\n";
}

void f_modif(Package & pkg)
{
    auto it = pkg.get_m(0, 1, 2);
    *it += 10;
    std::cout << "modif: " << *it << "\n";
}

int main(int argc, char**argv)
{
    Package p;
    f_const(p);
    f_modif(p);
}

In other words, I'd like some context-aware single method for access. A two-methods functionally-equivalent solution could be

my_t & operator () (size_t x, size_t y, size_t z) {
  return *(m_v.begin() + x * m_X * m_Y + y * m_Z + z);
}

my_t operator () (size_t x, size_t y, size_t z) const {
  return *(m_v.cbegin() + x * m_X * m_Y + y * m_Z + z);
}

No surprise I'm still a novice in metaprogramming, but I'm wondering if this approach has some intrinstic fallacy.


texts: ML Pipeline with OneHotEncoder and model

texts:
can you please provide some advice on my codes below?
There is 7 categorical features and 1 categorical target. This is a classification problem and I'm using RandomForest to train the data.

I have used columnTransformer() to transform the categorical data through OneHotEncoder and put them in the pipeline. Then I will pickle the pipeline for API use through the def predict() that I build.

Would be good to have another pair of eyes to review my code. Thanks!

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)

numeric_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler())])

categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
    ('onehot', OneHotEncoder(handle_unknown='ignore'))])

numeric_features = df.select_dtypes(include=['int64', 'float64']).columns
categorical_features = df.select_dtypes(include=['object']).drop(['Severity_Level'], axis=1).columns

preprocessor = ColumnTransformer(
    transformers=[

        ('num', numeric_transformer, numeric_features),
        ('cat', categorical_transformer, categorical_features)])

rf = Pipeline(steps=[('preprocessor', preprocessor),
                      ('classifier', RandomForestClassifier())])

rf.fit(X_train, y_train)

pickle.dump(rf,open('model3.pkl','wb'))

Load model

model = pickle.load(open('model3.pkl','rb'))

Function for API use:

def predict(Project_Sector, IncidentType,
       Parent_Child_Type, Project_Lifecycle_Phase, LL_BU,
       Project_Size, HeadContractType):

    result = model.predict(x)

    # send back to browser
    output = {'results': (result[0])}
    print(output)


texts: Kindergarten Garden challenge: ugly zip-group-flatten?

texts:
I wrote up a solution for the "Kindergarten Garden" problem on exercism.io.

  My class will be handed a string that describes two rows of plants. Each student (either in a pre-set list or given as an argument) (sorted alphabetically) owns a 2x2 of plants. The method Garden.plants accepts a student name and returns a list of which plants they have, in the order:

12
34

My code just feels ugly and unreadable, though. I tried to refactor some of it out into a method, but it still didn't feel great to me, so I separated my ugly one-liner into a bunch of assignments to temporary variables, but it still feels like it could be better.

from functools import partial

def grouper(iterable, n):
    return zip(*[iter(iterable)] * n)
def flatten(seq):
    for item in seq:
        if hasattr(item, '__iter__') and not isinstance(item, str):
            yield from flatten(item)
        else:
            yield item

class Garden(object):
    plant_names = {"G":"Grass",
                   "C":"Clover",
                   "R":"Radishes",
                   "V":"Violets"}
    def __init__(self, rows, students=None):
        self.rows = rows.splitlines()
        if students is None:
            students = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred",
                        "Ginny", "Harriet", "Ileana", "Joseph",
                        "Kincaid", "Larry"]
        self.students = sorted(students)
        self.plant_assignments = {student: list(plant_group) for student,plant_group
                in zip(self.students, self.plant_groups(self.rows))}
    def get_plant_name(self,plant_letter):
        try:
            return self.plant_names[plant_letter]
        except KeyError:
            raise ValueError("Plant letter {} is not defined".format(plant_letter))
    def plants(self,name):
        return self.plant_assignments[name]
    def plant_groups(self,rows):
        """Group each row in twos, then zip, flatten,
        and map in the expected way so:

        "VVGGCC\nVVGGCC"

        becomes:

        [('Violet','Violet','Violet','Violet'),
         ('Grass','Grass','Grass','Grass'),
         ('Clover','Clover','Clover','Clover')]"""
        grouper_by_two = partial(grouper, n=2)
        grouped_by_two = map(grouper_by_two, rows)
        cubewise = zip(*grouped_by_two)
        flat_cube = flatten(cubewise)
        flat_cube_with_names = map(self.get_plant_name, flat_cube)
        yield from grouper(flat_cube_with_names, 4)

As an example in and out:

# sample input:
>>> g = Garden("GCRR\nVVRR", ["Alice","Bob"])
# sample output:
>>> g.plants("Alice")
["Grass","Clover","Violets","Violets"]
>>> g.plants("Bob")
["Radishes","Radishes","Radishes","Radishes"]


texts: dynarr - yet another simple C dynamic array library

texts:
I wrote my own dynamic array library for C as I was not happy with the others I found. It is very crude but the basic logic should be correct, it mainly revolves making realloc easier to use and avoiding repetitive code.
Please offer your suggestions and criticisms!
#include <stdlib.h>
#include <string.h>

#define DYNARRAY_H_INCREMENT 50

typedef struct dynarr dynarr;

struct dynarr {
    void *actual;
    size_t size;
    size_t e_size;
    size_t occupied;
    size_t increment;
    void (*mem_callback)(dynarr *);
};

void *dynarr_nomen(dynarr *array) {
    if (array->mem_callback) array->mem_callback(array);
    array->actual = NULL;
    array->occupied = 0;
    return NULL;
}

dynarr dynarr_init_full(size_t e_size, size_t increment, void (*mem_callback)(dynarr *)) {
    return (dynarr){
        .actual = NULL,
        .size = 0,
        .e_size = e_size,
        .occupied = 0,
        .increment = increment,
        .mem_callback = mem_callback,
    };
}

dynarr dynarr_init(size_t element_size) {
    return dynarr_init_full(element_size, DYNARRAY_H_INCREMENT, NULL);
}

void *dynarr_push(dynarr *array, void *data) {
    if (array->occupied == array->size) {
        // Array is full
        // Increase size
        size_t new_real_size = (array->size + array->increment) * array->e_size;
        array->actual = realloc(array->actual, new_real_size);
        if (!array->actual) return dynarr_nomen(array);
        array->size += array->increment;
    }

    // Copy data
    char *charr = (char *) array->actual;
    memcpy(charr + array->occupied++ * array->e_size, data, array->e_size);

    return array->actual;
}

void *dynarr_get(dynarr *array, size_t *size) {
    if (size) *size = array->occupied;
    return array->actual;
}

void *dynarr_compact(dynarr *array) {
    if (array->occupied == array->size) goto end;
    array->actual = realloc(array->actual, array->occupied * array->e_size);
    if (!array->actual) return dynarr_nomen(array);
    array->size = array->occupied;
    end: return array->actual;
}

void dynarr_free(dynarr *array) {
    free(array->actual);
    array->actual = NULL;
    array->occupied = 0;
}

I intend to split declarations into a separate header in the future, I have kept it as a simple single source file for now.
I also made a very crude example program which could definitely use some major improvements... or maybe it can even be replaced by something else.
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "dynarr.c"

volatile sig_atomic_t signaled = false;

void trap_interrupt(int sig) {
    signaled = true;
}

int main(void) {
    signal(SIGINT, trap_interrupt);

    int c;
    char data;
    dynarr input = dynarr_init(sizeof data);

    for (;;) {
        if (signaled) break;
        c = getc(stdin);
        if (c == EOF) break;
        data = c;
        if (!dynarr_push(&input, &data)) {
            puts("Ran out of memory!!!");
            break;
        };
    }

    size_t count;
    dynarr_get(&input, &count);
    printf("Stored %zu bytes in dynamic array\n", count);

    return EXIT_SUCCESS;
}


texts: User name and password validation in a MVP application

texts:
In a WinForms application I'm doing the password validation as follows:

When the user presses the OK button after entering username and password, an event will be fired and the listener in the presenter will then do the validation with the help of the Encryption class. It will basically compare the two hash values.

User Model

class User
{
    string UserID { get; set; }
    string Name { get; set; }
    string NIC {get;set;}
    string Designation { get; set; }
    string PassWord { get; set; }
    List<string> Permission = new List<string>();
    bool status { get; set; }
    DateTime EnteredDate { get; set; }

}

Login form

public partial class frmLogin : Form , IView
{
    public event EventHandler OnValidatePassword;

    public string UserName
    {
        get { return txtUser.Text; }
    }

    public string Password
    {
        get { return txtPassword.Text; }
    }

    public bool Valid { get; set; }

    private void btnOK_Click(object sender, EventArgs e)
    {

        OnValidatePassword(sender, e);
        if (Valid)
        {
            frmMain Main = new frmMain();
            Main.ShowDialog();
        }
    }
}

Presenter

class LoginPresenter
{
    IView _View;
    User _Model;
    DataService _DataService;

    public LoginPresenter( IView view, User model, DataService dataService )
    {
        _View = view;
        _Model = model;
        _DataService = dataService;
        SetModelPropertiesFromView();
        WireUpEvents();
    }

    private void SetModelPropertiesFromView()
    {
        _Model.UserName = _View.UserName;
        _Model.Password = _View.Password;
    }

    private void WireUpEvents()
    {
        _View.OnValidatePassword += new EventHandler(_View_OnValidatePassword);
    }

    void _View_OnValidatePassword(object sender, EventArgs e)
    {
        ValidatePassword();
    }

    private void ValidatePassword()
    {
        var hash = Encryption.GetHash(_Model.UserName, _Model.Password);
        var hashInDB = _DataService.GetUserCredentials( _Model.UserName); //returns a hash value

        if (hash != hashInDB)
        {
            MessageBox.Show("Invalid username or password");
            _View.Valid = false;
        }
        else
        {
            _View.Valid = true;
        }
    }
}

Encryption

class Encryption
{
    public static string GetHash(string salt, string password)
    {
        MD5CryptoServiceProvider hash = new MD5CryptoServiceProvider();
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(salt + password);
        byte[] hashBytes = hash.ComputeHash(plainTextBytes);

        string hashValue = Convert.ToBase64String(hashBytes);
        return hashValue;

    }
}

I'm unsure of the way I'm calling main form's ShowDialog() method in the login form.  In that case I'm not using a presenter for the main form as it is just a MDI form which is only holding links to other forms.

Would MD5 encryption would be enough in this level?

Could you please review this code and provide your feedback?


texts:
I would like to ask you for a code review of my c++11 Thread Pool implementation. Your constructive criticism is welcome! Could you give me some ideas how to extend it?

The main idea is to synchronise access to tasks with condition variable.

ThreadPoolExecutor.cpp

#include "ThreadPoolExecutor.h"
#include <algorithm>
#include <iostream>

namespace ThreadPool
{
    ThreadPoolExecutor::ThreadPoolExecutor(int maxWorkers)
    {
        this->maxWorkers = maxWorkers;
    }

    ThreadPoolExecutor::~ThreadPoolExecutor()
    {
        this->poolManager.join();
    }

    void ThreadPoolExecutor::ScheduleTask(std::function<void()> task)
    {
        std::unique_lock<std::mutex> lock(taskQueueMutex);
        bool wasEmpty = this->taskQueue.empty();
        this->taskQueue.push(task);
        if (wasEmpty)
        {
            this->notEmptyTaskQueue.notify_one();
        }

        lock.unlock();
    }

    void ThreadPoolExecutor::Run()
    {
        this->poolManager = std::thread(&ThreadPoolExecutor::ManagePool, this);
    }

    void ThreadPoolExecutor::ManagePool()
    {
        for (int i = 0; i < this->maxWorkers; i++)
        {
            this->workers.push_back(std::thread(&ThreadPoolExecutor::Worker, this));
        }

        for (auto &thread : this->workers)
        {
            thread.join();
        }
    }

    void ThreadPoolExecutor::Worker()
    {
#ifdef _DEBUG
        std::cout << "Hello from thread: " << std::this_thread::get_id() << std::endl;
#endif
        while (1)
        {
            std::unique_lock<std::mutex> lock(taskQueueMutex);
            if (this->taskQueue.empty())
            {
                this->notEmptyTaskQueue.wait(lock);
            }

            auto task = this->taskQueue.front();
            this->taskQueue.pop();
            lock.unlock();
            task();
        }
    }
}

ThreadPoolExecutor.h

#ifndef THREADPOOLEXECUTOR_H_
#define THREADPOOLEXECUTOR_H_

#include <functional>
#include <queue>
#include <thread>
#include <memory>
#include "Task.h"
#include <condition_variable>

namespace ThreadPool
{
    class ThreadPoolExecutor
    {
    public:
        ThreadPoolExecutor(int maxWorkers);
        ~ThreadPoolExecutor();
        void ScheduleTask(std::function<void()> task);
        void Run();

    private:
        int maxWorkers;
        std::vector<std::thread> workers;
        std::thread poolManager;
        std::queue<std::function<void()>> taskQueue;
        std::condition_variable notEmptyTaskQueue;
        void ManagePool();
        std::mutex taskQueueMutex;
        void Worker();
    };
}
#endif

And finally usage.

Program.cs

#include "ThreadPoolExecutor.h"
#include "ExampleTask.h"
#include <iostream>

using namespace ThreadPool;

int main()
{
    ThreadPoolExecutor executor = ThreadPoolExecutor(4);

    for (int i = 0; i < 10; i++)
    {
        int random = std::rand() % 6;
        std::chrono::seconds timeout(random);
        executor.ScheduleTask([i, timeout](){
            std::cout << "no " << i << std::endl;
            std::this_thread::sleep_for(timeout);
        });
    }

    executor.Run();

    ExampleTask task;
    executor.ScheduleTask(task);
    std::this_thread::sleep_for(std::chrono::seconds(15));

    for (int i = 0; i < 10; i++)
    {
        int random = std::rand() % 6;
        std::chrono::seconds timeout(random);
        executor.ScheduleTask([i, timeout](){
            std::cout << "no " << i << std::endl;
            std::this_thread::sleep_for(timeout);
        });
    }

    return 0;
}


texts: minmax evaluation with alpha beta pruning

texts:
I'm making some small board game and wanted to code a very simple greed AI with this algorithm. It turns out it doesn't play the most greedy moves, it is simply not working. I'd appreciate any comments around this code.
First, the position evaluation functions are:
uint8_t get_piece_value(PKind kind)
{
    switch (kind) {
    case PKind::FIRST:
        return 10;
    case PKind::SECOND:
        return 30;
    case PKind::THIRD:
        return 35;
    case PKind::FORTH:
        return 100;
}

int get_position_value(const Position& position)
{
    int value;

    for (auto var : position.pieces) {

        if (var.id.color == position.turnToPlay) {
            value += get_piece_value(var.id.kind);
            continue;
        }

        value -= get_piece_value(var.id.kind);

    }

    return value;
}

Now this is the function I use to get the valid moves:
std::vector<PMove> get_ALL_valid_moves(const Position& position)
{
    std::vector<PMove> allMoves;

    for (auto piece : position.pieces)
    {
        if (piece.id.color == position.turnToPlay) {
            auto validMoves = get_valid_moves(piece);

            if (validMoves.size() == 0) {
                continue;
            }
            for (auto var : validMoves) {
                allMoves.push_back(var);
            }
        } else {
            assert(("Wrong color passed to get ALL valid moves!!\n"));
        }
    }

    return allMoves;
}

Next, here are the minmax functions:
constexpr int MAX_EVAL = 9999;
constexpr int MIN_EVAL = -MAX_EVAL;

///Minmax evaluation with alpha beta pruning
int minmax_ab(const Position newposition, int depth, int alpha, int beta, bool isMaximizer)
{
    if (depth == 0) {
        return get_position_value(newposition);
    }

    std::vector<PMove> validMoves;

    validMoves = get_ALL_valid_moves(newposition);

    if (validMoves.size() == 0) {
        return get_position_value(newposition);
    }

    if (isMaximizer) {
        for (auto move : validMoves) {
            alpha  = std::max(alpha, minmax_ab(make_position(newposition, move), depth - 1, alpha, beta, false) );
            if (alpha >= beta) {
                return beta;
            }
        }
        return alpha;

    } else {
        for (auto move : validMoves) {
            beta = std::min(beta, minmax_ab(make_position(newposition, move), depth - 1, alpha, beta, true) );
            if (beta <= alpha) {
                return alpha;
            }
        }
        return beta;
    }

}

PMove minmax_root(const Position& position, const int depth)
{

    std::vector<PMove> validMoves = get_ALL_valid_moves(position);
    /// assume the starting value of the last valid move for best move
    PMove bestmove = validMoves.front();

    int besteval = get_position_value(make_position(position, bestmove));

    int eval = MIN_EVAL;

    for (auto move : validMoves) {
        eval = minmax_ab(make_position(position, move), depth - 1, MIN_EVAL, MAX_EVAL, false);

        if (eval > besteval) {
            besteval = eval;
            bestmove = move;
        }
    }

    return bestmove;
}
```


texts: Remove unwanted characters from a string

texts:
From what I've seen in other posts, if I actually know the unwanted characters, then I can do string.replace(). But in my case, any characters can appear in my input string, and I only want to keep the characters that I want (without messing up the order of course).

private string RemoveUnwantedChar(string input)
{
    string correctString = "";

    for (int i = 0; i < input.Length; i++)
    {
        if (char.IsDigit(input[i]) || input[i] == '.' || input[i] == '-' || input[i] == 'n'
                || input[i] == 'u' || input[i] == 'm' || input[i] == 'k' || input[i] == 'M'
                || input[i] == 'G' || input[i] == 'H' || input[i] == 'z' || input[i] == 'V'
                || input[i] == 's' || input[i] == '%')
            correctString += input[i];
    }
    return correctString;
}

Characters that I want:

0123456789
numkMGHzVs%-

How can I tidy this code to be neater and more readable?