texts: Editing system files in Linux (as root) with GUI and CLI text editors #2 (final)

texts:
This is the second iteration of this question

A note to start with: the first iteration of this question can be found here:
Editing system files in Linux (as root) with GUI and CLI text editors

As stated in there:

  My intention is to POSIX-ly write one generalized function for running various text editors I use for different purposes through sudoedit, i.e. editing files as root safely. Safely = for instance, if a power loss occurs during the file edit; another example could be lost SSH connection, etc.

I come to you now with a possible final solution:

sudoedit enhanced

# USAGE: Just source this file into your shell for instance if using Bash, then you can use these files: ~/.bashrc or ~/.bash_aliases

# Please, customize these lists to your preference before using this script!
sudoedit__cli_editor_list='nano vi'
sudoedit__gui_editor_list='gedit emacs xed subl' # VS Code has its own work-around

sudoedit_enhanced_run ()
# Generic function for text editing as root
# the proper, safe, way through `sudoedit`.
# Expected arguments:
# $1 = editor name; obviously mandatory
# $2 = wait option; to avoid this, pass an empty string ('')
# $3, ($4), ... = file(s); at least one file must be given
{
    # check the minimum number of arguments
    if [ $# -lt 3 ]; then
        printf '%b\n' "sudoedit_enhanced_run(): Low number of arguments.\\nExpected: \$1 = editor name; \$2 = wait option; \$3, (\$4), ... = file(s).\\nPassed $#: $*" >&2
        return 1
    fi

    # let's take a closer look at the first argument, the editor
    editor_name=$1

    # store an editor alias, if there is any
    editor_alias=$( alias "$editor_name" 2> /dev/null )

    # remove that alias for now
    if [ -n "$editor_alias" ]; then
        unalias "$editor_name"
    fi

    # find out if such editor exists on the system
    # and store the first two arguments to variables
    editor_path=$( command -v "$editor_name" 2> /dev/null )
    wait_option=$2

    # if that editor does not return valid path, print error and bail
    if ! [ -x "$editor_path" ]; then
        printf '%s\n' "sudoedit_enhanced_run(): This editor ('$editor_name') is not installed on this system." >&2
        return 1
    fi

    # if we got here, then both of the things are ok;
    # so let's move past the editor and its wait option to the actual files
    shift 2

    # check if all the files exist, it does not make sense to create a file this way
    for file in "$@"; do
        if ! [ -f "$file" ]; then
            printf '%s\n' "sudoedit_enhanced_run(): This file ('$file') does not exist or it is not a regular file." >&2
            return 1
        fi
    done

    # run the editor with one-time SUDO_EDITOR set-up
    SUDO_EDITOR="$editor_path $wait_option" sudoedit "$@"

    # re-define the editor alias, if there was any, afterward
    if [ -n "$editor_alias" ]; then
        eval "$editor_alias"
    fi
}

# Editor aliases generators / definitions

for cli_editor in $sudoedit__cli_editor_list; do
    alias su$cli_editor="sudoedit_enhanced_run $cli_editor ''"
done

for gui_editor in $sudoedit__gui_editor_list; do
    alias su$gui_editor="sudoedit_enhanced_run $gui_editor -w"
done

# VS Code specific workaround to work under root
alias sucode="sudo mkdir -p /root/.vscode && sudo code -w --user-data-dir=/root/.vscode"

I would like to get a second opinion before posting it to my GitHub.

Already posted on GitHub, whereas I also tried hard to describe the purpose and (in spite it shall be obvious) usage including some example images on the project GitHub page.


texts: Checking whether given array is sorted by divide-and-conquer

texts:
I've written a code that I try to use divide and conquer approach to determine if the given array is sorted. I wonder whether I apply the approach accurately.

public static boolean isSorted(List<Integer> arr, int start, int end) {
    if (end - start == 1) // base case to compare two elements
        return arr.get(end) > arr.get(start);

    int middle = (end + start) >>> 1; // division by two
    boolean leftPart = isSorted(arr, start, middle);
    boolean rightPart = isSorted(arr, middle, end);
    return leftPart && rightPart;
}

To use call,

isSorted(list, 0, list.size() - 1)


texts:
I've created a scraper using vba which is able to parse json response. When I was thinking of using scripting dictionary or json converter to scrape json data I could notice that applying split function on responsetext is fairly easy to get the expected outcome. It is working great now. I've written like this:

Sub Json_coder()
Dim http As New XMLHTTP60, itm As Variant
    With http
        .Open "GET", "http://jsonplaceholder.typicode.com/users", False
        .send
        itm = Split(.responseText, "id"":")
    End With
    x = UBound(itm)

    For y = 1 To x
        Cells(y, 1) = Split(Split(itm(y), "name"": """)(1), """")(0)
        Cells(y, 2) = Split(Split(itm(y), "username"": """)(1), """")(0)
        Cells(y, 3) = Split(Split(itm(y), "email"": """)(1), """")(0)
        Cells(y, 4) = Split(Split(itm(y), "street"": """)(1), """")(0)
        Cells(y, 5) = Split(Split(itm(y), "suite"": """)(1), """")(0)
        Cells(y, 6) = Split(Split(itm(y), "city"": """)(1), """")(0)
        Cells(y, 7) = Split(Split(itm(y), "zipcode"": """)(1), """")(0)
        Cells(y, 8) = Split(Split(itm(y), "phone"": """)(1), """")(0)
        Cells(y, 9) = Split(Split(itm(y), "website"": """)(1), """")(0)
        Cells(y, 10) = Split(Split(Split(itm(y), "company"": ")(1), "name"": """)(1), """")(0)
        Cells(y, 11) = Split(Split(itm(y), "catchPhrase"": """)(1), """")(0)
        Cells(y, 12) = Split(Split(itm(y), "bs"": """)(1), """")(0)
    Next y
End Sub


texts:
Pick peaks
Wrote my "hello world" on Thursday, so definitely a beginner. I know some Python, so not a novice to programming in general.
Question

For example, the array arr = [0, 1, 2, 5, 1, 0] has a peak at position 3 with a value of 5 (since arr[3] equals 5).
The output will be returned as an object with two properties: pos and peaks. Both of these properties should be arrays. If there is no peak in the given array, then the output should be {pos: [], peaks: []}.
Example: pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3]) should return {pos: [3, 7], peaks: [6, 3]} (or equivalent in other languages)
All input arrays will be valid integer arrays (although it could still be empty), so you won't need to validate the input.
The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don't know what is after and before and therefore, we don't know if it is a peak or not).
Also, beware of plateaus !!! [1, 2, 2, 2, 1] has a peak while [1, 2, 2, 2, 3] does not. In case of a plateau-peak, please only return the position and value of the beginning of the plateau. For example: pickPeaks([1, 2, 2, 2, 1]) returns {pos: [1], peaks: [2]} (or equivalent in other languages)
Have fun!

Solution
function pickPeaks(arr)
{
   const obj = {
      pos: [],
      peaks: []
   };
   let i = 1;
   while(i < arr.length-1)
   {
      let run = false;
      let peak = false
      if(new Set(arr.slice(i, i+2)).size === 1)  // There is a run of numbers.
      {
         previous = arr[i-1] < arr[i];
         var j = i;
         while(arr[j] === arr[i]) j++;  // Consume the run.
         next = arr[j] < arr[i]
         if(previous && next) peak = true;  // Was the run a plateau?
      }
      else if(arr[i] > arr[i-1] && arr[i] > arr[i+1]) peak = true;
      if(peak)
      {
         obj.pos.push(i);
         obj.peaks.push(arr[i]);
      }
      i = run ? j : i+1;
   }
   return obj
}


texts: Getting data from database through Ajax post request

texts:
Is the method used below to get data from a database efficient and optimal? The data is in a MySQL database, and in my server I have a PHP file with the following code to return some information:
if($_POST["method"] == "requestBusinessFood") {
    requestBusinessFood();
}

function requestBusinessFood() {
    $categoryID = $_POST["category"];

    $host = 'localhost';
    $user = 'root';
    $pass = '';
    $db = 'fooddatabase';

    $conn = mysqli_connect($host, $user, $pass, $db);
        $sql = "SELECT * FROM `foodtablebusiness` WHERE category = " . $categoryID;

        $result = mysqli_query($conn, $sql);
        $rows = array();
        while($r = mysqli_fetch_assoc($result)) {
         $rows[] = $r;
        }

        echo json_encode($rows);
}

On the webpage, I have a js file to retrieve the information in the following way:
  function createAJAXRequestToPopulateList(category) {
    return $.ajax({ url: '../server.php',
                    data: {method: 'requestBusinessFood',
                           category: category},
                    type: 'post'
    });
  }

function addActivityItem(){
    var selector = document.getElementById("categorySelector");
    ajaxRequest = createAJAXRequestToPopulateList(selector.options[selector.selectedIndex].value);
    ajaxRequest.done(populateList);
}

function populateList(responseData) {
    console.log(responseData);
}


texts: Find the next empty column on a chessboard

texts:
I was playing around with the "eight queens" problem, just to see how I could use C++ algorithms to write less code.

I figured out a way to find the next unused column using find_if_not.  I am showing both ways of writing it.  Assume we are looping over every valid "file" on a given "rank" ( in C++ terms, I am looping over rows and columns in an 8x8 matrix.)

used is simply a set of column indexes that are currently occupied by a queen.
col is the current index of the column where we will try to place the next queen.

Note for efficiency, the array of column indexes would not be created where it's shown in the code.

Method1:

set<unsigned>::iterator it;
for (; col < 8; ++col)
{
    it = used.find(col);
    if (it == used.end())
        break;
}
if (it != used.end())
    return false;

Method2:

array<unsigned, 8> colIdx{ 0, 1, 2, 3, 4, 5, 6, 7 };
auto it = find_if_not(colIdx.begin() + col, colIdx.end(),
    [&used](unsigned colIdx) { return used.find(colIdx) != used.end(); });
if (it == colIdx.end())
    return false;
else
    col = *it;


texts: Accurately measure ASP.NET Core 3.x actions execution times (Web API project)?

texts:
I want to be able to log the time spent by a certain Web API action in an ASP.NET Core 3.x application.

This is a very old question from ASP.NET which relies on global action filters, but in ASP.NET Core, I think middlewares are more appropriate.

From a client's perspective I want to measure as accurately as possible the following time:

Time to first byte - Time spent to send the request

So, using a slightly modified code from c-sharpcorner I have implemented the following:

/// <summary>
/// tries to measure request processing time
/// </summary>
public class ResponseTimeMiddleware
{
    // Name of the Response Header, Custom Headers starts with "X-"
    private const string ResponseHeaderResponseTime = "X-Response-Time-ms";

    // Handle to the next Middleware in the pipeline
    private readonly RequestDelegate _next;

    ///<inheritdoc/>
    public ResponseTimeMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    ///<inheritdoc/>
    public Task InvokeAsync(HttpContext context)
    {
        // skipping measurement of non-actual work like OPTIONS
        if (context.Request.Method == "OPTIONS")
            return _next(context);

        // Start the Timer using Stopwatch
        var watch = new Stopwatch();
        watch.Start();

        context.Response.OnStarting(() => {
            // Stop the timer information and calculate the time
            watch.Stop();
            var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;
            // Add the Response time information in the Response headers.
            context.Response.Headers[ResponseHeaderResponseTime] = responseTimeForCompleteRequest.ToString();

            var logger = context.RequestServices.GetService<ILoggingService>();
            string fullUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
            logger?.LogDebug($"[Performance] Request to {fullUrl} took {responseTimeForCompleteRequest} ms");

            return Task.CompletedTask;
        });

        // Call the next delegate/middleware in the pipeline
        return _next(context);
    }
}

Startup.cs (plugging the middleware)

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory,
    ILoggingService logger, IHostApplicationLifetime lifetime, IServiceProvider serviceProvider)
{
    app.UseResponseCaching();

    app.UseMiddleware<ResponseTimeMiddleware>();

    // ...
}

Is this a good approach? I am mostly interested in accuracy and not wasting server resources.


texts:
Goal:

Wrap a vector. The wrapper can create view on part of the vector.
Support const_view and view.
view allows modification of elements while const_view does not.
The views are ranges (has begin() and end() methods).

Problem:

Code duplication between the const_view and view.

The actual code implements a 2D sparse array that saves more memory than usual. So I want to learn how to solve this problem.

Simplified Code (implements a dense 2D array)

#include <vector>
class A_csub;
class A_sub;

typedef std::vector<int> V;
typedef typename V::iterator It;
typedef typename V::const_iterator Cit;

class A {
// 2D dense array with _r rows and _c columns.
public:
    A(const int r, const int c);
    A_csub cview(const int n) const;
    A_sub view(const int n); // view nth row
    It sub_begin(const int n); // iterator at begin of nth row
    Cit sub_cbegin(const int n) const;
    int _r;
    int _c;
private:
    V _v;
};

class A_csub {
public:
    A_csub(const A& a, const int n);
    Cit begin() const;
    Cit end() const;
    const int size() const;
private:
    const A& _a;
    const int _n;
};

class A_sub {
public:
    A_sub(A& a, const int n);
    It begin();
    It end();
    const int size() const;
private:
    A& _a;
    const int _n;
};

// -- A -- //
A::A(const int r, const int c) : _r(c), _c(c), _v(r*c) {}
A_csub A::cview(const int n) const { return A_csub(*this, n); }
A_sub A::view(const int n) { return A_sub(*this, n); }
It A::sub_begin(const int n) { return _v.begin() + n*_r; }
Cit A::sub_cbegin(const int n) const { return _v.cbegin() + n*_r; }

// -- A_csub -- //
A_csub::A_csub(const A& a, const int n) : _a(a), _n(n) {}
Cit A_csub::begin() const { return _a.sub_cbegin(_n); }
Cit A_csub::end() const { return begin() + _a._r; }
const int A_csub::size() const { return _a._r; }

// -- A_sub -- //
A_sub::A_sub(A& a, const int n) : _a(a), _n(n) {}
It A_sub::begin() { return _a.sub_begin(_n); }
It A_sub::end() { return begin() + _a._r; }
const int A_sub::size() const { return _a._r; }

int main() {
    A a(10,5);
    a.cview(4);
    A_sub b = a.view(4);
    for (auto && e:b) {e=1;}
}


texts:
I built an extension method to cycle through all items of an IEnumerable starting at some index:

public static IEnumerable<T> Circle<T>(this IEnumerable<T> list, int startIndex)
{
    if (list != null)
    {
        List<T> firstList = new List<T>();
        using (var enumerator = list.GetEnumerator())
        {
            int i = 0;
            while (enumerator.MoveNext())
            {
                if (i < startIndex)
                {
                    firstList.Add(enumerator.Current);
                    i++;
                }
                else
                {
                    yield return enumerator.Current;
                }
            }
        }
        foreach (var first in firstList)
        {
            yield return first;
        }
    }
    yield break;
}

So when you do

Enumerable.Range(1,10).Circle(5);

The result is 6,7,8,9,10,1,2,3,4,5.

What I don't like is the use of the firstList variable. Is there a way to do this with the enumerator only, without storing an intermediate result?

EDIT:
I use an enumerator to iterate the enumerable not more than once.


texts: Mouse control of a camera in an OpenGL program

texts:
Introduction

I'm doing an OpenGL program in C. As of now I'm working on the 3D camera system and got the control right. Now I'm working on the mouse control.
It works, but I have used two different ways to do it.

The problem

The two different ways are using a global variable and callback, and just using a local variable and function.

I don't know which one is better. One seems to loop over itself every time and the other only when the mouse moves, but uses a global variable.

For all the following code you will see that the Camera struct is defined as:

Camera camera = {
        .view = GLM_MAT4_IDENTITY_INIT,
        .pos = { 0.f,0.f,3.f },
        .target = { 0.f, 0.f, 0.f },
        .upAxe = { 0.0f, 1.0f, 0.0f },
        .front = { 0.0f, 0.0f, -1.0 },

        .yaw = -90.f,
        .pitch = 0.f,

        .lastX = SCR_HEIGHT / 2,
        .lastY = SCR_WIDTH / 2,

        .lastFrame = 0.0f,
        .deltaTime = 0.0f
};

The code

First the "global" way:

I have only shown the intended part of the code; other code is not pertinent.

main.c:

void mouseCallBack(GLFWwindow * window, double xpos, double ypos);

Camera camera = {
    .view = GLM_MAT4_IDENTITY_INIT,
    .pos = { 0.f,0.f,3.f },
    .target = { 0.f, 0.f, 0.f },
    .upAxe = { 0.0f, 1.0f, 0.0f },
    .front = { 0.0f, 0.0f, -1.0 },

    .yaw = -90.f,
    .pitch = 0.f,

    .lastX = SCR_HEIGHT / 2,
    .lastY = SCR_WIDTH / 2,

    .lastFrame = 0.0f,
    .deltaTime = 0.0f
};

int main()
{
    glfwSetCursorPosCallback(window, mouseCallBack);
    while (!glfwWindowShouldClose(window))
    {
    }
}

void mouseCallBack(GLFWwindow * window, double xpos, double ypos)
{

    float xoffset = xpos - camera.lastX;
    float yoffset = camera.lastY - ypos;

    camera.lastX = xpos;
    camera.lastY = ypos;

    float sensivity = 0.05f;
    xoffset *= sensivity;
    yoffset *= sensivity;

    camera.yaw += xoffset;
    camera.pitch += yoffset;

    if (camera.pitch > 89.f) camera.pitch = 89.f;
    if (camera.pitch < -89.f) camera.pitch = -89.f;

    vec3 front;
    front[0] = cos(glm_rad(camera.yaw)) * cos(glm_rad(camera.pitch));
    front[1] = sin(glm_rad(camera.pitch));
    front[2] = sin(glm_rad(camera.yaw)) * cos(glm_rad(camera.pitch));

    glm_normalize_to(front, camera.front);

}

The function and local way:

int main()
{
    Camera camera = {
            .view = GLM_MAT4_IDENTITY_INIT,
            .pos = { 0.f,0.f,3.f },
            .target = { 0.f, 0.f, 0.f },
            .upAxe = { 0.0f, 1.0f, 0.0f },
            .front = { 0.0f, 0.0f, -1.0 }
    };

    camera.yaw = 0.f;
    camera.pitch = 0.f;

    camera.lastX = SCR_HEIGHT / 2;
    camera.lastY = SCR_WIDTH / 2;

    camera.lastFrame = 0.0f;
    camera.deltaTime = 0.0f;

    while (!glfwWindowShouldClose(window))
    {
        //input
        processMouse(window, &camera);
    }
}

and in GLFWfunction.c:

void processMouse(GLFWwindow * window, Camera * camera)
{
    double xpos;
    double ypos;

    glfwGetCursorPos(window, &xpos, &ypos);

    if (xpos != camera->lastX || ypos != camera->lastY)
    {
        float xoffset = xpos - camera->lastX;
        float yoffset = camera->lastY - ypos;

        float sensivity = 0.1f;

        xoffset *= sensivity;
        yoffset *= sensivity;

        camera->yaw += xoffset;
        camera->pitch += yoffset;
        if (camera->pitch > 89.0f) camera->pitch = 89.f;
        if (camera->pitch < -89.0f) camera->pitch = -89.f;

        vec3 front;
        front[0] = cos(glm_rad(camera->pitch)) * cos(glm_rad(camera->yaw));
        front[1] = sin(glm_rad(camera->pitch));
        front[2] = sin(glm_rad(camera->yaw)) * cos(glm_rad(camera->pitch));
        glm_normalize_to(front, camera->front);

        camera->lastX = xpos;
        camera->lastY = ypos;
    }
}

What would you choose? My eyes tell me that the global alternative is good and clean, but contradict a bit of the C logic whereas the function one is good but is poorly written.


texts: Using 503 page when my site is in maintenance mode

texts:
This is my code for 503 page:

header.php

if(getOption('maintence_mode')==1)
{
header("location:503.php");
exit;
}

503.php

<?php
$protocol = "HTTP/1.0";
if ( "HTTP/1.1" == $_SERVER["SERVER_PROTOCOL"] )
$protocol = "HTTP/1.1";
header( "$protocol 503 Service Unavailable", true, 503 );
header( "Retry-After: 3600" );
?>

    <!DOCTYPE html>

    <meta http-equiv="Content-type" value="text/html; charset=UTF-8" />
    <title>Page Not Found </title>

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta http-equiv="refresh" content="6;url=index.php">

Site is currently in maintenance mode.

I want to know if my code is correct and how Google will handle SEO thing.  I don't have much knowledge about this, so it would be very helpful if someone could validate this code.


texts: Given N and M find all stepping numbers in range N to M

texts:
The stepping number:

  A number is called as a stepping number if the adjacent digits have a
  difference of 1. e.g 123 is stepping number, but 358 is not a stepping
  number.

  Example:

  N = 10, M = 20

  All stepping numbers are 10, 12

  Return the numbers in sorted order.

The code I wrote does accomplish what is asked, but the complexity is \$O(n^2)\$ I think, and I'm sure there is a better way of doing this.

class Solution {
public List<int> stepnum(int A, int B) {
    List<int> result = new List<int>();
    for (int i=A;i<=B;i++)
    {
        string num = i.ToString();
        int amount = num.Count();
        int less = 0;
        bool step=true, ascending=true;

        if(amount>=2)  //0 - 1
        {
            for(int j=0;j<amount;j++)
            {
                ascending=true;
                if(j<amount-1)
                {
                    if((int)Char.GetNumericValue(num[j])>(int)Char.GetNumericValue(num[j+1]))
                    {
                        ascending=false;
                    }
                    if(ascending)
                        less=(int)Char.GetNumericValue(num[j+1])-(int)Char.GetNumericValue(num[j]);
                    else
                        less=(int)Char.GetNumericValue(num[j])-(int)Char.GetNumericValue(num[j+1]);
                    if(less!=1)
                    {
                        step=false;
                        break;
                    }
                }
            }
            if(step)
            {
                result.Add(Convert.ToInt32(num));
            }
        }
        else
            result.Add(Convert.ToInt32(num));
    }
    return result;
}
}


texts:
I wonder if there is a better approach to validate the object fields. For specific types of objects some fields cannot be empty:
public class CredentialsValidator {

  public boolean validateCredentialsRequest(ValidationCredentialsRequest credentialsRequest) {
    switch (credentialsRequest.getCredentialType()) {
      case TYPEA:
        return validatetypeACredentials(credentialsRequest);
      case TYPEB:
        return validateTypeBCredentials(credentialsRequest);
      case TYPEC:
        return validateTypeCCredentials(credentialsRequest);
    }
    return true;
  }

  private boolean validateTypeCCredentials(ValidationCredentialsRequest credentials) {
    if (credentials.getIsNewCredential()) {
      return nonNull(credentials.getUsername())
          && !credentials.getUsername().isEmpty()
          && nonNull(credentials.getPassword())
          && !credentials.getPassword().isEmpty();
    }
    return nonNull(credentials.getCredentialsId());
  }

  private boolean validateTypeBCredentials(ValidationCredentialsRequest credentials) {
    if (credentials.getIsNewCredential()) {
      return nonNull(credentials.getHostname())
          && !credentials.getHostname().isEmpty()
          && nonNull(credentials.getPort())
          && !credentials.getPort().isEmpty()
          && nonNull(credentials.getUsername())
          && !credentials.getUsername().isEmpty()
          && nonNull(credentials.getPassword())
          && !credentials.getPassword().isEmpty();
    }
    return nonNull(credentials.getCredentialsId())
        && nonNull(credentials.getHostname())
        && !credentials.getHostname().isEmpty()
        && nonNull(credentials.getPort())
        && !credentials.getPort().isEmpty();
  }

  private boolean validatetypeACredentials(ValidationCredentialsRequest credentials) {
    if (credentials.getIsNewCredential()) {
      return (nonNull(credentials.getDomain())
              && !credentials.getDomain().isEmpty()
              && nonNull(credentials.getUsername())
              && !credentials.getUsername().isEmpty()
              && nonNull(credentials.getPassword())
              && !credentials.getPassword().isEmpty())
          || (nonNull(credentials.getSharePoint().getUsername())
              && !credentials.getSharePoint().getUsername().isEmpty()
              && nonNull(credentials.getSharePoint().getPassword())
              && !credentials.getSharePoint().getPassword().isEmpty());
    }
    return nonNull(credentials.getCredentialsId())
        && nonNull(credentials.getDomain())
        && !credentials.getDomain().isEmpty();
  }

My main class that invokes Validator:
public Mono<ValidationCredentialsResponse> validateCredentials(
      Mono<ValidationCredentialsRequest> validationCredentials) {
    return validationCredentials
        .filter(credentialsValidator::validateCredentialsRequest)
        .switchIfEmpty(Mono.error(new InvalidCredentialsException(MESSAGE)))
        .flatMap(
            validCredentials ->
                securityService

...
...
I use Spring Boot and Webflux for reactive programming


texts: Raising error if method not overridden by sub-class

texts:
Background

I have a base (only 2 classes inherit from it, and only from it) abstract (meaning I don't want it to be used directly) class that implements some common functionality.

Some of it depends on certain methods being defined, methods whose implementation differs per the exact sub-class; so I set-up a mechanism to raise an exception in case that kind of thing happened (better explicit fail than subtle debugging, right?).

Code

class Matrix:
    """Model an abstract base interface for 2-d matrices."""

    def __init__(self):
        """Raise error as class is abstract."""
        self.__eq__ = self._flip = self._rotate = self.__error
        raise NotImplementedError("{} should not be instantiated directly".format(type(self)))

    def __error(self):
        """Raise error as certain methods need to be over-rided."""
        raise NotImplementedError("method needs to be defined by sub-class")

Question

Is that an anti-pattern, like singletons or w/e? If so, what's a better way? Should I even check for this at all (i.e., maybe similar to excessive type-checking)?

  Disclaimer: Python was my first language, and I do NOT like Java (although I have some experience from Android development); so this is not me trying to port some ruddy static pattern from another language.


texts: Command-line program for applying several operations on a PDF file

texts:
I am building a command-line .exe that can apply several operations on a PDF file (add text, images, resize, crop, etc).

Currently, my Program.cs looks a bit like this (it uses CommandLineParser):

switch (invokedVerb)
{
    case "barcode":
        Operations.BarcodeOperations.AddBarCode(options.AddBarcodeVerb);
        break;

    case "addblankpage":
        Operations.PageOperations.AddBlankPage(options.AddBlankPageVerb);
        break;
}

As you can see, I have split the operations into several XXXOperations classes, each of them having very similar instructions:

public static void AddStuff(StuffOptions options)
{
    Logging.Log("here is a bunch of logging");

    // here sometimes there is some action-specific code but not often

    using (DocWrapper doc = new DocWrapper(options.File)) // this is in all actions
    {
        foreach (int page in doc.GetPagesToModify(options.Pages)) // this is in most actions
        {
            // call some stuff on the doc instance
        }

        doc.Save(options.OutputFile); // this is in all actions
    }
}

So, all actions create a new instance of DocWrapper, most of them loop on its pages (but I could modify the actions so that all of them do), and all of them save, but each of them do a different set of actions inside it.

How could I refactor this code so that the DocWrapper instantiation, the pages loop and the save are in a single place, but I can specify custom code inside the loop?

I'm thinking of using delegates to define my actions, but I have no idea where to start, since I'm not very familiar with them. I'm also considering inheriting from an abstract class that implements the loop and abstracts a DoWork method, called inside the loop and implemented in the XXXOperations class, but since I don't know delegates, I'm not sure which is more adapted to the situation.


texts:
I'm working on load/save application sessions functionality, and came up with this code:

public class SessionManager
{
    private static ISessionStorage storage = new DbTableSessionStorage();
    private static StudySession session;
    public static StudySession Current
    {
        get
        {
            if (session == null) {
                throw new Exception("Load or start new session before using SessionManager.Current");
            }

            return session;
        }
    }

    public static void LoadSession(int sessionId)
    {
        session = storage.LoadSession(sessionId);
    }

    public static void Save(StudySession session, int prefferedId = -1)
    {
        storage.SaveSession(session, prefferedId);
    }
}

public class DbTableSessionStorage : ISessionStorage
{
    public void SaveSession(StudySession studySession, int prefferedId = -1)
    {
        Session session = DSDatabase.Context["USER"].Read<Session>(prefferedId);
        if (session == null) {
            session = new Session();
        }

        if (prefferedId != -1) {
            session.Id = prefferedId;
        }

        session.Name = studySession.Name;
        session.Timestamp = studySession.Timestamp == DateTime.MinValue
                                ? DateTime.Now
                                : studySession.Timestamp;

        session.GroupId = studySession.GroupId;
        session.TestId = studySession.TestId;
        session.Position = studySession.Position;
        session.SoundOn = studySession.SoundOn;

        DSDatabase.Context["USER"].Save(session);
    }

    public StudySession LoadSession(int id)
    {
        StudySession result = new StudySession();

        Session session = DSDatabase.Context["USER"].Read<Session>(id);

        if (session != null) {
            result.Id = session.Id.Value;
            result.Name = session.Name;
            result.Timestamp = session.Timestamp;
            result.GroupId = session.GroupId;
            result.TestId = session.TestId;
            result.SoundOn = session.SoundOn;
        }

        return result;
    }
}

I am using it in this way:

public class Chapter {
//....

    public static Chapter[] GetChildren(int parentId)
    {
        string sqlQuery = baseSqlQuery + Environment.NewLine +
                 "WHERE CHAPTERS.GroupId=? AND CHAPTERS.ParentId=?";

        return DSDatabase.RunQuery<Chapter>(sqlQuery, SessionManager.Current.GroupId, parentId).ToArray();
    }

//....
}

It seems to me as not a very good solution, because my code becomes tightly coupled and hides the dependencies. I'm looking now for better solutions to this issue.


texts:
I've been reviewing my previous projects for the last few days. I've found that I never return an error from any of my methods. I always throw exceptions. I googled about exceptions vs errors and I feel like I should return an error if there's an error.

Please consider my service class from my previous project. We have online tutorials on our website and we send out a token (sort of a coupon) to users time to time. Users can redeem the token to get a full access to a certain tutorial on our website.

class TutorialTokenRedeemptionService {

    protected $memberRepository;
    protected $tutorialRepository;
    protected $tokenRepository;

    public function __construct(
        Repository\TutorialRepositoryInterface $tutorialRepository,
        Repository\TokenRepositoryInterface $tokenRepository,
        Repository\MemberRepositoryInterface $memberRepository
    )
    {

        $this->memberRepository   = $memberRepository;
        $this->tutorialRepository = $tutorialRepository;
        $this->tokenRepository = $tokenRepository;
    }

    public function redeem($tokenCode, Entity\MemberInterface $member)
    {

        // Let's see if we have the token in our system
        $token = $this->tokenRepository->findByCode($token);

        if( !$token ) {
            throw new Exception\TokenNotFound($token);
        }

        // Let's see if we have the associated tutorial
        $tutorial = $this->tutorialRepository->find($token->getBatch()->tutorial_id);

        //
        if( !$tutorial ) {
            throw new Exception\TutorialNotFound($token);
        }

        $member->addPurchasedTutorial($tutorial);
        $this->memberRepository->save($member);

        $token->setActivatedBy($member->id);
        $this->tokenRepository->save($token);

        return new TutorialTokenRedeemptionServiceResult(StatusCodes::OK, $member, $tutorial, $token);

    }

}

It might be considered an exception to users if the token he/she is trying to use is not in our system because users might have more than one token. Users can try other tokens. From the perspective of the TutorialTokenRedeeptionService and its client, it's an error because the service can't continue anymore. Am I going the right way?

What should be better? Throw exceptions all the time or throw exceptions and return errors depending on use cases?


texts: Project Euler problem 23 - non-abundant sums

texts:
I present my solution for Project Euler problem 23 written in Python (2.7).

The problem statement is:

  A perfect number is a number for which the sum of its proper divisors
  is exactly equal to the number. For example, the sum of the proper
  divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28
  is a perfect number.

  A number whose proper divisors are less than the number is called
  deficient and a number whose proper divisors exceed the number is
  called abundant.

  As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the
  smallest number that can be written as the sum of two abundant numbers
  is
  24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers.
  However, this upper limit cannot be reduced any further by analysis
  even though it is known that the greatest number that cannot be
  expressed as the sum of two abundant numbers is less than this limit.

  Find the sum of all the positive integers which cannot be written as
  the sum of two abundant numbers.

I have done everything to my knowledge to make the code run as fast as possible. It takes about 600 milliseconds on my machine.

It is one of the first times that I actually put the else part of the for statement to use. Using any alternatively turned out to be about 1.5× as slow.

SMALLEST_ABUNDANT = 12

# largest number for which we have to test if it can be expressed as the
# sum of two abundant numbers
MAX_TEST_SUM_OF_TWO_ABUNDANT = 28123

# largest number for which we have to know if it is abundant
MAX_TEST_ABUNDANT = MAX_TEST_SUM_OF_TWO_ABUNDANT - SMALLEST_ABUNDANT

# largest possible divisor that we have to consider
MAX_DIVISOR = MAX_TEST_ABUNDANT / 2

from collections import defaultdict

def solve_euler23():
    """Return the sum of all positive integers which cannot be written
    as the sum of two abundant numbers.
    """
    # mapping from a number to the set of its proper divisors (i.e.,
    # excluding the number itself)
    divisors = defaultdict(set)
    for divisor in range(1, MAX_DIVISOR+1):
        for number in range(2*divisor, MAX_TEST_ABUNDANT+1, divisor):
            divisors[number].add(divisor)

    def is_abundant(number):
        return sum(divisors[number]) > number

    abundant_numbers = sorted(filter(is_abundant, divisors))

    # make a set so that membership can be tested efficiently
    abundant_numbers_set = set(abundant_numbers)

    impossible_sum_of_two_abundant_numbers = []
    for number in range(1, MAX_TEST_SUM_OF_TWO_ABUNDANT+1):
        for abundant in abundant_numbers:
            if number - abundant in abundant_numbers_set:
                break # is the sum of two abundant numbers
        else:
            impossible_sum_of_two_abundant_numbers.append(number)

    return sum(impossible_sum_of_two_abundant_numbers)

if __name__=='__main__':
    print solve_euler23()

My questions are:

Is there a better algorithm?
Did I overlook something which would make the implementation of my chosen algorithm more efficient?
Can I make the code shorter or clearer?


texts: Extracting an arbitrary element from each row of a np.array

texts:
I have a large numpy array of shape (n,m). I need to extract one element from each row, and I have another array of shape (n,) that gives the column index of the element I need. The following code does this, but it requires an explicit loop (in the form of a list comprehension.):

import numpy as np

arr = np.array(range(12))
arr = arr.reshape((4,3))
keys = np.array([1,0,1,2])
#This is the line that I'd like to optimize
answers = np.array([arr[i,keys[i]] for i in range(len(keys))])
print(answers)
# [ 1  3  7 11]

Is there a built-in numpy (or pandas?) function that could do this more efficiently?


texts: How to increase scalability the method that output each file while switching multiple many conditions?

texts:
I have a common style (common.scss) and a text direction (RTL, LTR) option file (option-document-direction-rtl.scss, option-document-direction-ltr.scss). And by switching the reading of these files, the css file with RTL / LTR changed is output by method like gulp.js.

_common.scss

body {
  max-width: 1120px;
  background-color: black;
  color: white;
  text-align: $direction;
}

_option-document-direction-rtl.scss

$direction: right;

_option-document-direction-ltr.scss

$direction: left;

style.scss

@import "option-document-direction-rtl";
// switch to @import "option-document-direction-rtl";

@import "common.scss"

And I can get below two css files same time by some method (actually these scss files style be more complex):

rtl-style.css

body {
  max-width: 1120px;
  background-color: black;
  color: white;
  text-align: right;
}

ltr-style.css

body {
  max-width: 1120px;
  background-color: black;
  color: white;
  text-align: left;
}

Main subject

So, I have to switched these style condition different from text direction. For example, screen size without media queries. In this case, I think need a new options SCSS file, such as _computer.scss and _smartphone.scss. Here, I had a question.

The number of configuration files with new conditions may increase in the future. In the current method, in short, the css file to be output is changed depending on which of the "configuration files that describe the settings used in each condition" is read.

I'm afraid that my configuration files will grow and become more difficult to manage. What tools and mechanisms on SCSS can be used to increase the scalability of many configuration files?

I considered a method of dynamically changing the output file according to the argument at the time of build, but I have not been able to determine whether this is a way to improve scalability.


texts: Implementation of API to create a company account in a database

texts:
I'm working on an API that has a lot of controller functions like this:

def create = Action.async { implicit request =>

    if (request.body.asJson.isEmpty) {
        Future.successful(BadRequest("Missing body"))
    }
    else {
        val body = request.body.asJson.get.as[JsObject]
        val companyID = (body \ "company" \ "id").validate[String]
        val parsedAccount = (body \ "account").validate[Account]

        // Check that we have all of the fields we need
        if (parsedAccount.isError) {
            Future.successful(BadRequest("Missing account data"))
        } else if (companyID.isError) {
            Future.successful(BadRequest("Missing company data"))
        }
        else {

            // Insert the new account
            val account = parsedAccount.get
            (for {
                _ <- primaryDAO.insert(account, companyID.get)
                account <- primaryDAO.get(account.id)
            } yield account).map {
                case account => Created(account)
            }.recover {
                case e => BadRequest(e)
            }
        }
    }
}

I was hoping that I would be able to do something more like this (using early returns):

def create = Action.async { implicit request =>

    if (request.body.asJson.isEmpty) {
        return Future.successful(BadRequest("Missing body"))
    }

    val body = request.body.asJson.get.as[JsObject]
    val companyID = (body \ "company" \ "id").validate[String]
    val parsedAccount = (body \ "account").validate[Account]

    // Check that we have all of the fields we need
    if (parsedAccount.isError) {
        return Future.successful(BadRequest("Missing account data"))
    }
    if (companyID.isError) {
        return Future.successful(BadRequest("Missing company data"))
    }

    // Insert the new account
    val account = parsedAccount.get
    (for {
        _ <- primaryDAO.insert(account, companyID.get)
        account <- primaryDAO.get(account.id)
    } yield account).map {
        case account => Created(account)
    }.recover {
        case e => BadRequest(e)
    }
}

However this is not possible because the return statement only returns from my nested function (and back into the Action.async)

I am wondering what I can do in place of early returns (which I would use in imperative programming languages) to make my code cleaner.

The primary DAO implements a generic trait that I use for most of my DAOs and looks like this:

trait DAOGet[A <: BaseModel] {
    def get(pk: String): Future[Option[A]]
    def all: Future[Seq[A]]
    def all(page: Int, perPage: Int): Future[Seq[A]]
}

trait DAOInsert[A <: BaseModel] extends DAOGet[A] {
    def insert(model: A): Future[Any]
}

trait DAOUpdate[A <: BaseModel] extends DAOGet[A] {
    def update(model: A): Future[Int]
}

trait DAODelete[A <: BaseModel] {
    def delete(pk: String): Future[Int]
}

trait CRUDDAO[A <: BaseModel] extends DAOGet[A] with DAOInsert[A] with DAOUpdate[A] with DAODelete[A]


texts: Check if an element is present within a linked list

texts:
I am given a task to ask for a number and then check if it is present within a linked list or not.

class Node:
    def __init__(self,item):
        self.data = item
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self, newnext):
        self.next = newnext

class Linkedlist:
    def __init__(self):
        self.head = None

    def add_member(self,data):
        temp = Node(data)
        temp.setNext(self.head)
        self.head = temp

    def search_member(self,item):
        current = self.head
        while current != None:
            if current.getData() ==item:
                return True
            else:
                current =current.getNext()
        return False

llist = Linkedlist()
llist.add_member(23)
llist.add_member(98)
llist.add_member(415)
llist.add_member(123)
llist.add_member(981)
llist.add_member(454)
llist.add_member(213)
llist.add_member(198)
llist.add_member(455)
llist.add_member(253)
llist.add_member(978)
llist.add_member(45)
llist.add_member(203)
llist.add_member(918)
llist.add_member(45)
item = int(raw_input("Enter the number you want to search : "))
print llist.search_member(item)

How can I improve this code?


texts:
This method finds the maximum in a binary tree. I have used generics to make this code more usable. However, I am not sure if I have written efficient and good Java code.

This is a method inside a class using generics and implementing Comparable interface for the generic parameter E.

private E maximumElement(TreeNode<E> root, E parentValue) {
  E max;
  if(root==null)
        max=parentValue;
  else {
    max = root.element;
    E leftMax = maximumElement(root.left, max);
    E rightMax = maximumElement(root.right, max);
    if(rightMax.compareTo(max) > 0)
              max = rightMax;
    if(leftMax.compareTo(max) > 0)
              max = leftMax;
   }
   return max;
}


texts: Conditionally applying and removing css based on a table row clicked

texts:
I've a added a click event to each row on a table element. Which I then use the $this context from the event to add some css styling to that clicked row.

The behavior is as follows:

IF tr doesn't have kpi-selected css applied
WHEN tr is clicked on table
THEN remove css style from all other tr elements
THEN add css style to clicked row's label
AND search the datatable for the clicked label's KPI

What I've noticed during testing is that the gulf between clicking and the css style being added to the element is very slow.

Question:

How can I optimize this code to improve speed between clicking a tr and applying the required css?

JSFiddle:

http://jsfiddle.net/brianVarleyHPE/mtkndq3e/

Gist of code: In the real implementation there will be more than one section-list table, this is a gist showing only one.

HTML

    Availability By Asset Criticality

            Normal<input id="lblNormal" type="hidden" value="Normal">
            2

            Mission Critical<input id="lblMC" type="hidden" value="Mission Critical">
            0

            Entity Essential<input id="lblEE" type="hidden" value="Entity Essentiall">
            1

CSS:

.kpi-selected label {
    border:3px solid #0CA281;
    padding: 3px;
    border-radius:30px;
    -webkit-border-radius:30px;
    -moz-border-radius:30px;
}

JS

 $(".section-list").on('click', 'tr', function (e) {

        $('.section-list tr').removeClass("kpi-selected");

        if ($(this).attr('id') === "normalAvailability") {

            handleKPI_Selection($(this), 1, 'Normal');
        }
        else if ($(this).attr('id') === "mcAvailability") {

            handleKPI_Selection($(this), 1, 'Mission Critical');
        }
        else if ($(this).attr('id') === "eeAvailability") {

            handleKPI_Selection($(this), 1, 'Entity Essential');
        }

    });

    function handleKPI_Selection(td, index, searchFilter) {

        td.toggleClass("kpi-selected");
        if (td.hasClass("kpi-selected") && index !== 0) {

            historyTable.search('').columns().search('').draw();
            historyTable.columns(index).search(searchFilter);
            historyTable.draw();
        } else {
            historyTable.search('').columns().search('').draw();
        }

    }


texts:
Here we trying to fix logs that have overlaps with each other. Am I doing it right? Is there any way to improve/refactor it?

 DROP TYPE IF EXISTS logs_with_error;
  CREATE TYPE logs_with_error AS (
      model_id INT,
      model_type TEXT,
      initiator_id INT,
      initiator_type TEXT,
      error_type_id INT,
      state INT
  );

  CREATE OR REPLACE FUNCTION normalize_moderation_log_overflow() RETURNS INTEGER AS
      $BODY$
  DECLARE
      logs logs_with_error%rowtype;
      model moderation_logs%rowtype;
      initiator moderation_logs%rowtype;
  BEGIN
      FOR logs IN SELECT model_id, model_type, initiator_id, initiator_type, error_type_id, state
    FROM errors
    WHERE state = #{ Error.states[:initial] }
    AND error_type_id = (SELECT id FROM error_types WHERE normalizer_type = 'moderation_log_overflow')
      LOOP
        SELECT * INTO model FROM moderation_logs WHERE id = logs.model_id;
        SELECT * INTO initiator FROM moderation_logs WHERE id = logs.initiator_id;

        IF model.curr_state = initiator.curr_state AND model.next_state = initiator.next_state THEN
          IF model.ended_at < initiator.ended_at THEN
            UPDATE moderation_logs SET ended_at = initiator.ended_at WHERE id = model.id;
          END IF;
          DELETE FROM moderation_logs WHERE id = initiator.id;
        ELSE
          UPDATE moderation_logs SET started_at = model.ended_at WHERE id = initiator.id;
        END IF;

        UPDATE errors
        SET state = #{ Error.states[:resolved] };

        RAISE NOTICE '%', logs;
      END LOOP;
      RETURN 1;
  END
  $BODY$
  LANGUAGE 'plpgsql' ;


texts:
These are two of tasks, which I had to do for the recruitment process to be started in some company. Unfortunately they didn't like it so I've decided to share it here for discussion.

Add up all the even elements of the Fibonacci sequence below 1000. In my solution it is a method fibSumEven.
Write a recursive function that calculates the Fibonacci sequence up to 1000. In my solution it is a method fibR.

Fibonacci.h

#ifndef FIBONACCI_H_
#define FIBONACCI_H_

#include <iostream>
#include <string>
#include <sstream>

class CFibonacci
{

private:

    // Recursive function that calculates the Fibonacci sequence up to given LIMIT
    // limit - The limit, up to which sequence numbers will be calculated
    static int fibHelper(int limit, int x1, int x2)
    {
        int x = x1 + x2;
        if(x <= limit)
        {
            return fibHelper(limit, x2, x);
        }
        return x2;
    }

public:

    // A caller to recursive Fibonacci sequence up to given limit
    static int fibR(int limit = 1000)
    {
        if(limit <= 0)
        {
            return 0;
        }
        return fibHelper(limit, 0, 1);
    }

    //Adds up all the even elements of the Fibonacci sequence below limit
    static int fibSumEven(int limit=1000)
    {
        int x1 = 0, x2 = 1, x = 0, sum = 0;
        while(x <= limit)
        {
            x = x1 + x2;
            if(x % 2 == 0)
            {
                sum += x;
            }
            x1 = x2;
            x2 = x;
        }
        return sum;
    }
};

#endif /* FIBONACCI_H_ */

There was a disclaimer:

  Considering the ith element of the Fibonacci sequence Fib(i) = x, the element x is a natural number and is itself bounded by the value 1000 and not all the elements to Fib(1000).

Why could the solution have been disliked by the recruiters?


texts: Dynamically update attribute of a same name in different classes

texts:
I have this piece of code which I know can be improved greatly, but I simply don't know how. I've been googling for a little while, but truth to be told, I'm not really sure what I should be even looking for.

As you can see the code is very straight forward. Different classes have attributes of a same name, but I can't figure out how to dynamicaly swap between classes.

Please help me make it more dynamic, make it cleaner!!! Any help is much appreciated.

public void setHorsePurchaseInvoiceStatus(TransactionLine entity)
{
    if (entity.HorsePurchase != null)
    {
        switch (entity.Section)
        {
            case ("PI1"):
                entity.HorsePurchase.StatusPI1 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.PI1;
                break;
            case ("PI2"):
                entity.HorsePurchase.StatusPI2 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.PI2;
                break;
            case ("PI3"):
                entity.HorsePurchase.StatusPI3 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.PI3;
                break;
            case ("PI4"):
                entity.HorsePurchase.StatusPI4 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.PI4;
                break;
            case ("SI1"):
                entity.HorsePurchase.StatusSI1 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.SI1;
                break;
            case ("SI2"):
                entity.HorsePurchase.StatusSI2 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.SI2;
                break;
        }
    }
    else if (entity.HorseSale != null)
    {
        switch (entity.Section)
        {
            case ("PI1"):
                entity.HorseSale.StatusPI1 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusPI1;
                break;
            case ("PI2"):
                entity.HorseSale.StatusPI2 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusPI2;
                break;
            case ("PI3"):
                entity.HorseSale.StatusPI3 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusPI3;
                break;
            case ("PI4"):
                entity.HorseSale.StatusPI4 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusPI4;
                break;
            case ("SI1"):
                entity.HorseSale.StatusSI1 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusSI1;
                break;
            case ("SI2"):
                entity.HorseSale.StatusSI2 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusSI2;
                break;
            case ("SI3"):
                entity.HorseSale.StatusSI3 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusSI3;
                break;
        }
    }
    else if (entity.HorseDivideProfit != null)
    {
        switch (entity.Section)
            {
                case ("PI1"):
                    entity.HorseDivideProfit.StatusPI1 = getCurrentSectionStatus(entity) ?? entity.HorseDivideProfit.StatusPI1;
                    break;
                case ("SI1"):
                    entity.HorseDivideProfit.StatusSI1 = getCurrentSectionStatus(entity) ?? entity.HorseDivideProfit.StatusSI1;
                    break;
            }
    }
}


texts:
Minesweeper in Ruby (from exercism.io):

  Write a program that adds the numbers to a minesweeper board.

  Minesweeper is a popular game where the user has to find the mines
  using numeric hints that indicate how many mines are directly adjacent
  (horizontally, vertically, diagonally) to a square.

  In this exercise you have to create some code that counts the number
  of mines adjacent to a square.

  Transforms boards like this (where * indicates a mine):

+-----+
| * * |
|  *  |
|  *  |
|     |
+-----+

  into this:

+-----+
|1*3*1|
|13*31|
| 2*2 |
| 111 |
+-----+

As can be seen in the provided test suite, a method Board.transform is required whose input and output are arrays of strings, representing the rows of the board. A ValueError must be raised in case of an invalid character or a non-border cell at the edge of the board.

My solution:

class ValueError < RuntimeError
end

class Position
  attr_reader :y, :x

  def initialize(y, x)
    @y, @x = y, x
  end

  def neighbors
    Position.each(y-1 .. y+1, x-1 .. x+1)
  end

  def self.each(ys, xs)
    return enum_for(__method__, ys, xs) unless block_given?

    ys.each do |y|
      xs.each do |x|
        yield Position.new(y, x)
      end
    end
  end

  def ==(other)
    to_a == other.to_a
  end

  alias eql? ==

  def hash
    to_a.hash
  end

  def to_a
    [y, x]
  end
end

class Cell
  BLANK_CELL_CHAR = ' '
  MINE_CELL_CHAR = '*'
  BORDER_CELL_REGEX = /\A[-+|]\z/

  def self.from_char(char)
    case char
    when BLANK_CELL_CHAR
      BlankCell.new
    when MINE_CELL_CHAR
      MineCell.new
    when BORDER_CELL_REGEX
      BorderCell.new(char)
    else
      raise ValueError, "Illegal character"
    end
  end

  def blank?
    false
  end

  def mine?
    false
  end

  def border?
    false
  end
end

class BlankCell < Cell
  attr_accessor :num_adjacent_mines

  def initialize(num_adjacent_mines = nil) # nil means unknown
    @num_adjacent_mines = num_adjacent_mines
  end

  def blank?
    true
  end

  def to_s
    if @num_adjacent_mines.nil? || @num_adjacent_mines == 0
      BLANK_CELL_CHAR
    else
      @num_adjacent_mines.to_s
    end
  end
end

class BorderCell < Cell
  def initialize(char)
    @char = char
  end

  def border?
    true
  end

  def to_s
    @char
  end
end

class MineCell < Cell
  def mine?
    true
  end

  def to_s
    MINE_CELL_CHAR
  end
end

class Board
  def self.transform(input)
    board = Board.new(input)
    board.transform!
    board.to_a
  end

  def initialize(input)
    @height = input.length
    @width = input.first.length

    raise ValueError, "All lines must be of the same length" if input.any? { |line| line.length != @width }

    @cells = Position.each(0...@height, 0...@width).map do |position|
      char = input[position.y][position.x]
      cell = Cell.from_char(char)
      raise ValueError, "Expected a border cell" if should_be_border?(position) && !cell.border?
      [position, cell]
    end.to_h
  end

  def transform!
    Position.each(0...@height, 0...@width).each do |position|
      tranform_at!(position)
    end
  end

  def to_a
    (0...@height).map do |y|
      (0...@width).map do |x|
        at(Position.new(y, x)).to_s
      end.join
    end
  end

  private

    def tranform_at!(position)
      cell = at(position)
      if cell.blank?
        cell.num_adjacent_mines = position.neighbors.count do |position|
          at(position).mine?
        end
      end
    end

    def at(position)
      @cells.fetch(position)
    end

    def should_be_border?(position)
      position.y == 0 || position.y == @height - 1 ||
        position.x == 0 || position.x == @width - 1
    end
end

What do you think?


texts: Computational verification of Collatz conjecture using gmplib

texts:
Prerequisites

The unsigned long type has a size of 64 bits.

The following macros are defined.

/* all 3^n for n < 41 fits into 64-bit unsigned long */
#define LUT_SIZE 41
/* any reasonably high number */
#define LUT_SIZEMPZ 512

The following array is defined and properly initialized with corresponding values.

/* lut[n] contains 3^n */
mpz_t lut[LUT_SIZEMPZ];

Additionally, the following auxiliary function is defined.

/* count trailing zeros */
mp_bitcnt_t mpz_ctz(const mpz_t n)
{
    return mpz_scan1(n, 0);
}

Problem

This code review request follows my previous request Computational verification of Collatz conjecture. The implementation in this request should handle the numbers which cannot be handled with the code in previous post.

In short: My program verifies the convergence of the Collatz problem, using this algorithm. The convergence for all values n ≤ 87 × 260 has already been proven.

The following function is called for n of the form \$4n+3\$, in order from the smallest one to the largest one, only if all preceding calls returned zero.

This function should either

return 0 if the problem for the n is convergent, or
loop infinitely if the trajectory for the n is cyclic.

Code

The 128-bit input n is split into two 64-bit parts nh and nl such that n = nh * 2^64 + nl.

int check_convergence(unsigned long nh, unsigned long nl)
{
    mpz_t n;
    mpz_t n0;
    mpz_t n_max;
    mp_bitcnt_t e;

    mpz_init_set_ui(n, nh);
    mpz_mul_2exp(n, n, (mp_bitcnt_t)64);
    mpz_add_ui(n, n, nl);

    mpz_init_set_ui(n_max, 87UL);
    mpz_mul_2exp(n_max, n_max, (mp_bitcnt_t)60);

    mpz_init_set(n0, n);

    do {
        if (mpz_cmp(n, n_max) <= 0) {
            mpz_clear(n);
            mpz_clear(n0);
            mpz_clear(n_max);
            return 0;
        }

        mpz_add_ui(n, n, 1UL);

        e = mpz_ctz(n);

        mpz_fdiv_q_2exp(n, n, e);

        assert( e < LUT_SIZEMPZ );

        mpz_mul(n, n, lut[e]);

        mpz_sub_ui(n, n, 1UL);

        mpz_fdiv_q_2exp(n, n, mpz_ctz(n));

        if (mpz_cmp(n, n0) < 0) {
            mpz_clear(n);
            mpz_clear(n0);
            mpz_clear(n_max);
            return 0;
        }
    } while (1);
}


texts:
I am trying to insert into a database using JDBC and each thread will be inserting into the database. I need to insert around 30-35 columns. I wrote a stored procedure that will UPSERT into those columns.

The problem I am facing is that in the run() method, I have around 30 columns written over there for insertion. Is there any way I can simplify my run method so that it doesn't looks so messy which is looking right now for me? And I have a few more columns as well. So if I keep on adding new columns there, it will be looking so messy at one point in my run method.

Is there any way to clean this, keeping in mind the thread safety issues?

class Task implements Runnable {

    private Connection dbConnection = null;
    private CallableStatement callableStatement = null;

    public Task() {

    }

    @Override
    public void run() {

    dbConnection = getDbConnection();
    callableStatement = dbConnection.prepareCall(Constants.UPSERT_SQL);

    callableStatement.setString(1, String.valueOf(userId));
    callableStatement.setString(2, Constants.getaAccount(userId));
    callableStatement.setString(3, Constants.getaAdvertising(userId));
    callableStatement.setString(4, Constants.getaAvgSellingPriceMainCats(userId));
    callableStatement.setString(5, Constants.getaCatAndKeywordRules(userId));
    callableStatement.setString(6, Constants.getaClvBehavior(userId));
    callableStatement.setString(7, Constants.getaClvChurn(userId));
    callableStatement.setString(8, Constants.getaClvInfo(userId));
    callableStatement.setString(9, Constants.getaClvSegmentation(userId));
    callableStatement.setString(10, Constants.getaCsaCategoriesPurchased(userId));
    callableStatement.setString(11, Constants.getaCustomerService(userId));
    callableStatement.setString(12, Constants.getaDemographic(userId));
    callableStatement.setString(13, Constants.getaFinancial(userId));
    callableStatement.setString(14, Constants.getaGeolocation(userId));
    callableStatement.setString(15, Constants.getaInterests(userId));
    callableStatement.setString(16, Constants.getaLastContributorsPurchased(userId));
    callableStatement.setString(17, Constants.getaLastItemsLost(userId));
    callableStatement.setString(18, Constants.getaLastItemsPurchased(userId));
    callableStatement.setString(19, Constants.getaLastProductsPurchased(userId));
    callableStatement.setString(20, Constants.getaLastSellersPurchasedFrom(userId));
    callableStatement.setString(21, Constants.getaMainCategories(userId));
    callableStatement.setString(22, Constants.getaMessaging(userId));
    callableStatement.setString(23, Constants.getaPositiveSellers(userId));
    callableStatement.setString(24, Constants.getaPromo(userId));
    callableStatement.setString(25, Constants.getaScores(userId));
    callableStatement.setString(26, Constants.getaSegmentation(userId));
    callableStatement.setString(27, Constants.getaSellers(userId));
    callableStatement.setString(28, Constants.getaSrpBuyerUpiCount(userId));
    }
  }

    private Connection getDBConnection() {

    Connection dbConnection = null;

          Class.forName(Constants.DRIVER_NAME);
      dbConnection = DriverManager.getConnection(url,user,password);

      return dbConnection;
    }


texts: URL pattern matching for request blocking

texts:
I'm trying to write a URL pattern matching utility that, given a pattern and a URL it'll tell whether the URL matches the pattern or not. I want to use this for users to provide a list of URL patterns that will be use to block requests to URLs that match the given pattern. I don't want to use straight Regex because it'd be painful for the user to write, especially since all dots would need to be escaped.

I found this set of pattern matching rules which seem simple yet powerful enough for what I need. So I want to write a class that matches the specs given on that page. In the class below I attempt to do this, although I leave the "file" scheme out since I won't be needing it. Also, I'm letting the user provide no path, in which case I'll consider it equivalent to providing an empty path. Finally, I'm letting the user use extra asterisks on the host, which would be treated as literal asterisks, which I don't think should be much of a problem. I've tested it with the cases listed on the page and a few others and worked fine, but I wonder if there's some edge cases I'm not considering that break Google specifications.

public class UrlPattern
{
    public readonly Regex SchemeMatch;
    public readonly Regex HostMatch;
    public readonly Regex PathMatch;

    public UrlPattern(string pattern)
    {
        if (string.IsNullOrWhiteSpace(pattern))
            throw new ArgumentException("Pattern cannot be null or whitespace.");

        pattern = pattern.Trim();

        var index = pattern.IndexOf("://");

        if (index < 0)
            throw new ArgumentException("Pattern must have a scheme-host separator.");

        var scheme = pattern.Substring(0, index);
        var hostAndPath = pattern.Substring(index + 3);

        index = hostAndPath.IndexOf("/");

        if (index < 0)
        {
            hostAndPath = $"{hostAndPath}/";
            index = hostAndPath.IndexOf("/");
        }

        var host = hostAndPath.Substring(0, index);
        var path = hostAndPath.Substring(index);

        var schemePattern = MakeSchemePattern(scheme);
        var hostPattern = MakeHostPattern(host);
        var pathPattern = MakePathPattern(path);

        SchemeMatch = new Regex(schemePattern, RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
        HostMatch = new Regex(hostPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
        PathMatch = new Regex(pathPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
    }

    private static string MakePathPattern(string path)
    {
        return $"^{Regex.Escape(path).Replace("\\*", ".*")}$";
    }

    private static string MakeHostPattern(string host)
    {
        if (host == "*")
            return ".+";

        if (host.StartsWith("*."))
            return $"^(.+\\.)?{Regex.Escape(host.Substring(2))}$";

        return $"^{Regex.Escape(host)}$";
    }

    private static string MakeSchemePattern(string scheme)
    {
        switch (scheme)
        {
            case "*":
                return "^https?$";
            case "http":
                return "^http$";
            case "https":
                return "^https$";
            case "ftp":
                return "^ftp$";
            default:
                throw new ArgumentException("Invalid scheme pattern.");
        }
    }

    public bool IsMatch(Uri uri)
    {
        if (!SchemeMatch.IsMatch(uri.Scheme))
            return false;

        if (!HostMatch.IsMatch(uri.Host))
            return false;

        if (!PathMatch.IsMatch(uri.PathAndQuery))
            return false;

        return true;
    }

    public bool IsMatch(string url)
    {
        return IsMatch(new Uri(url));
    }
}


texts: Optimisation XML handling within vb.net application

texts:
I need to optimize this snippet to be faster:

Dim lst = (From t In DocElet.ChildNodes Select ID = t.item("ID").outerxml).Distinct().ToList()
       Parallel.For(0, lst.Count, Sub(i)
         Dim P As XmlElement = GetElement(lst(i))
       Dim ls = (From t In DocElet.ChildNodes Where t.item("ID").innerText = P.InnerText Select t)
         Parallel.ForEach(ls, Sub(D)
         Dim verif_date As String = D.Item("DAD").InnerText
        Sej.ID = D.Item("ID").InnerText
         End Sub)
            End Sub)

This is the XML structure:

<?xml version="1.0" encoding="utf-8"?>
<PatientData>
<Sejour><ID></ID><DAD></DAD></Sejour>
  </PatientData>

I'm asking how I can optimize my code because it takes a lot of time (50 sec) in the case where the list contains 20000 elements.


texts: Decode string with hex character codes to UTF-8 characters

texts:
From a system we receive messages that contain codes that represent UTF-8 characters.

For example :

var str="Test =64 =C2=AE =E1=A6=92 test";

To decode these codes to utf-8 I've added a simple function that does 3 regex replacements:

protected static string ReplaceHexCodesInString(string input)
{

    var output = input;
    var encoding = Encoding.UTF8;

    var regTripleHex = new Regex("=(E[0-9A-F])=([0-9A-F]{2})=([0-9A-F]{2})");
    output = regTripleHex.Replace(output, m => encoding.GetString(new[]{
            byte.Parse(m.Groups[1].Value, System.Globalization.NumberStyles.HexNumber),
            byte.Parse(m.Groups[2].Value, System.Globalization.NumberStyles.HexNumber),
            byte.Parse(m.Groups[3].Value, System.Globalization.NumberStyles.HexNumber)
        }));

    var regDoubleHex = new Regex("=([C-D][0-9A-F])=([0-9A-F]{2})");

    output = regDoubleHex.Replace(output, m => encoding.GetString(new[]{
            byte.Parse(m.Groups[1].Value, System.Globalization.NumberStyles.HexNumber),
            byte.Parse(m.Groups[2].Value, System.Globalization.NumberStyles.HexNumber)
        }));

    var regRemainingHex = new Regex("=([0-9A-F]{2})");

    output = regRemainingHex.Replace(output, m => encoding.GetString(new[]{
            byte.Parse(m.Groups[1].Value, System.Globalization.NumberStyles.HexNumber)
        }));

    return output;
}

This seems to work as expected for what's currently in those messages.
Note that messages don't contain 4-bit utf-8 characters
(f.e. 0xf0 0x90 0x8c 0xb8 = 𐌸)

But can this be simplified?
Perhaps there's already a standard function?

I searched, but haven't found a good standard build-in C# function that already does this type of conversion.

Well, except for an example that uses a function from System.Net.Mail.
But it seems very error-prone and requires a very specific format.

var input = "bl=61=C2=B0";
var output = System.Net.Mail.Attachment.CreateAttachmentFromString("", "=?utf-8?Q?" + input.Trim() +"?=").Name;


texts:
I have a package directory pkg with several classes that I would like to build into a convenient dict property.

The structure of pkg/ looks like:

pkg/base.py:

class _MyBase(object):
    pass

pkg/foo.py:

from .base import _MyBase

class Foo(_MyBase):
     pass

And in pkg/__init__.py, it is a bit clunky, but once pkg is imported, a all_my_base_classes dict is built with a key of the class name, and value of the class object. The classes are all subclasses of pkg.base._MyBase.

import os
import sys
import pkgutil

import base
# I don't want to import foo, bar, or whatever other file is in pkg/

all_my_base_classes = {}
pkg_dir = os.path.dirname(__file__)
for (module_loader, name, ispkg) in pkgutil.iter_modules([pkg_dir]):
    exec('import ' + name)
    pkg_name = __name__ + '.' + name
    obj = sys.modules[pkg_name]
    for dir_name in dir(obj):
        if dir_name.startswith('_'):
            continue
        dir_obj = getattr(obj, dir_name)
        if issubclass(dir_obj, base._MyBase):
            all_my_base_classes[dir_name] = dir_obj

Running it from an interactive Python shell, one directory below pkg/:

>>> import pkg
>>> pkg.all_my_base_classes
{'Foo': <class 'pkg.foo.Foo'>}

So it works as expected, but pkg/__init__.py is pretty terrible looking. How can it be better?


texts:
I have a worksheet that lists a person's name (column A; many duplicate names are in this column) with associated data (columns B through G). I have code below that takes this list of a ~ 1000 rows and then:

Copies and pastes each row three times (to create four identical rows for each entry).
Loops through the now ~4000 rows and creates a new worksheet for each person.  As there are many duplicate names in column A this only creates a handful of new worksheets.

The thing is, it runs but runs quite slowly (and I receive the Excel not responding warning at times). Is there anything to clean this up to make it more efficient? And after this I run another macro to save the new worksheets to a new workbook. Would it be faster to do that with code here?

Sub Split_Data()

    Const NameCol = "A"
    Const HeaderRow = 1
    Const FirstRow = 2
    Dim SrcSheet As Worksheet
    Dim TrgSheet As Worksheet
    Dim SrcRow As Long
    Dim LastRow As Long
    Dim TrgRow As Long
    Dim person As String
    Dim lRow As Long
    Dim RepeatFactor As Variant

'Optimize Macro Speed
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

'Copy each row and paste three times
    lRow = 2
    Do While (Cells(lRow, "B") <> "")
        RepeatFactor = 4

        Range(Cells(lRow, "A"), Cells(lRow, "G")).Copy
        Range(Cells(lRow + 1, "A"), Cells(lRow + RepeatFactor - 1, "G")).Select

        Selection.Insert Shift:=xlDown
        lRow = lRow + RepeatFactor - 1
        lRow = lRow + 1
    Loop

    Set SrcSheet = ActiveSheet
    LastRow = SrcSheet.Cells(SrcSheet.Rows.Count, NameCol).End(xlUp).Row
    For SrcRow = FirstRow To LastRow
        person = SrcSheet.Cells(SrcRow, NameCol).Value
        Set TrgSheet = Nothing
        On Error Resume Next
        Set TrgSheet = Worksheets(person)
        On Error GoTo 0
        If TrgSheet Is Nothing Then
            Set TrgSheet = Worksheets.Add(After:=Worksheets(Worksheets.Count))
            TrgSheet.Name = person
            SrcSheet.Rows(HeaderRow).Copy Destination:=TrgSheet.Rows(HeaderRow)
        End If
        TrgRow = TrgSheet.Cells(TrgSheet.Rows.Count, NameCol).End(xlUp).Row + 1
        SrcSheet.Rows(SrcRow).Copy Destination:=TrgSheet.Rows(TrgRow)
    Next SrcRow

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub


texts: Serving a webpage that displays the HTTP request information sent by the client

texts:
In order to learn web server programming in Node and JavaScript, I decided to implement a simple web server that only does one thing:

Display data of the HTTP request as an HTML table.

The actual data to display is arbitrary. In this example I'm displaying the contents of the header, along with the method, url, and http versions.
Here is the working solution:
const http = require('http');

const port = 3344;

const htmlCSS = `

`;

const server = http.createServer((req, res) => {
  const {
    headers,
    method,
    url
  } = req;

  console.log(`\n${headers['user-agent']}\n${method}\n${url}`);
  console.log(new Date());
  console.log();

  writeResponse(req, res);
});

server.listen(port);

function writeResponse(req, res) {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  writeBody(req, res);
  res.end();
}

function writeBody(req, res) {
  const htmlTitle = '<title>Your Request Is</title>';
  const htmlEncode = '<meta charset="UTF-8">';
  const htmlHead = `<head>${htmlTitle}${htmlCSS}${htmlEncode}</head>`;
  const htmlTop = `<html lang="en">${htmlHead}<body>`;
  const htmlBot = '';

  res.write(htmlTop);
  writeTable(req, res);
  res.write(htmlBot);
}

function writeTable(req, res) {
  const htmlTableTop = '

';
  const htmlTableBot = '

';

  res.write(htmlTableTop);
  writeAllRows(req, res);
  res.write(htmlTableBot);
}

function writeAllRows(req, res) {
    const {
    httpVersion,
    httpVersionMinor,
    httpVersionMajor,
    headers,
    method,
    url
  } = req;

  for (const key in headers) {
    writeRow(res, key, headers[key]);
  }
  writeRow(res, 'method', method);
  writeRow(res, 'url', url);
  writeRow(res, 'httpVersion', httpVersion);
  writeRow(res, 'httpVersionMinor', httpVersionMinor);
  writeRow(res, 'httpVersionMajor', httpVersionMajor);
}

function writeRow(res, key, val) {
  const entry = `<tr><td>${key}</td><td>${val}</td></tr>`;
  res.write(entry);
}

While I have some particular questions, I'm looking forward for all kinds of feedback! So if you see anything at all that can be improved, any comment is much appreciated!

Can I use other modules to make this job easier?
For a job this simple, is it worth to work with HTML and CSS as separate files?
How are HTML and CSS normally handled inside JS files (edits, appends, etc)?
How well am I handling the construction of HTML and CSS?
Can this be done more concisely?
What would you do differently to improve this in any way?


texts: Timestamp function with millisecond precision

texts:
I want to be able to print timestamps with milliseconds precision and time_t doesn't provide this.  I also want the code to be portable, so operating specific functions are out.  ftime seems to be deprecated but there doesn't seem to be a general-purpose alternative to using ftime.

How could this be improved?

#include <stdio.h>
#include <string.h>
#include <sys\timeb.h>
#include <time.h>

static char* get_timestamp(char* buf) {
    struct timeb start;
    char append[100];
    if (buf) {
        ftime(&start);
        strftime(buf, 100, "%H:%M:%S", localtime(&start.time));

        /* append milliseconds */
        sprintf(append, ":%03u", start.millitm);
        strcat(buf, append);
    }
    return buf;
}

int main()
{
    char tmp[100];
    int countdown = 0;
    for (int i = 0; i < 10; i++, countdown = 0) {
        printf("%s\n", get_timestamp(tmp));
        while (countdown++ < 1000000)
            ;
    }
}


texts: Creating an array of random numbers with no duplicates

texts:
I only need three random numbers within the range of 1-54 (deck of cards) and none of the three numbers can be a duplicate. I cannot use an ArrayList; I must use a standard array. Is the method I chose to check for duplicates good enough?

public class Test {

public static int genRandom() {
    // generate random int value between 1 and 54
    int random = 1 + (int) (Math.random() * ((54 - 1) + 1));
    return random;
}

public static boolean containsDuplicates(int[] arr) {
    // check to see if positions have matching values
    if (arr[0] == arr[1] || arr[0] == arr[2] || arr[1] == arr[2]) {
        System.out.println("Duplicates Exist");
        // if matching value is found, randomize the array again
        shuffle(arr);
        return true;
    }
    System.out.println("No duplicates");
    return false;
}

public static void shuffle(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        arr[i] = genRandom();
        System.out.println(arr[i]);
    }
    containsDuplicates(arr);
}

public static void main(String[] args) {

    int[] cards = new int[3];
    shuffle(cards);
}
}


texts: Typescript design pattern for rendering different objects with similarities

texts:
It's a web project. The code is working. The question is a design pattern question to write code that's more elegant, you know.
I've created a Codepen of this question.
I created a css grid WITHOUT using 'grid' but using float and clear.
I know such project works better written in React but it's just a try.
The grid I'm creating is entirely recreated when calling the render(world) method.
I'm not using any HTML outside of javascript (typescript).
I'm only using 4 CSS classes:
.block-first, .block-lasts {
  width: 20px;
  height: 20px;
  border-radius: 20px;
  float: left;
}

.block-first {
  clear: both;
}

.image-in-block {
  width: 20px;
  height: 20px;
}

.container {

}

In the grid are square blocks of equal size being 1- a uniformly colored block or 2- a block containing an image.
So I first fill up a matrix 20x20 of instances of classes that implements a IBlock interface containing a getProperty() method. Those classes are 1- ColorBlock or 2- ImageBlock. Below are these classes and the interface:
interface IBlock {
  getProperty() : string;
}
class ImageBlock implements IBlock{
  url: string;
  constructor(url: string) {
    this.url = url;
  }
  getProperty() : string {
    return this.url;
  }
}
class ColorBlock implements IBlock{
  color: string;
  constructor(hexColor: string) {
    this.color = hexColor;
  }
  getProperty() : string {
    return this.color;
  }
}

My problem is that I need to use different code to render each. For the ColorBlock I'm going with a colored div with background: '#ff00ff'; But for the ImageBlock I'm going with a nested img tag instead of a background-image: url('https://...');.
For distinguishing between the different classes, I'm using object_instance.constructor.name, I think that's the whole problem.
Now the rest of my code:
Matrix prepping:
const world = new Array(20);
for(let i=0; i<20; i++) {
  world[i] = new Array(20);
  world[i].fill(new ColorBlock('#ff00ff'));
}

The function rendering each block as ColorBlock or ImageBlock:
function html_process_image_or_color_block(dom, block_instance) {
  const html_block = dom;
  const block = block_instance;
  const block_property = block.getProperty();
  switch (block.constructor.name) {
    case 'ImageBlock':
      const image_tag = document.createElement('img');
      image_tag.src = block_property;
      image_tag.classList.add('image-in-block');
      html_block.appendChild(image_tag);
      break;
    case 'ColorBlock':
      html_block.setAttribute('style', `background: ${block_property};`)
      break;
    default: break;
  }
  // return html_block;
}

And finally the render(world) function that uses the 20x20 Matrix and the above function:
function render(world) {
  const html_container = document.createElement('div');
  html_container.classList.add('container');
  for(let i=0; i<20; i++) {

    //code for rendering first left most block
    const html_first_block = document.createElement('div');
    html_first_block.classList.add('block-first');
    const first_block = world[i][0];
    html_process_image_or_color_block(html_first_block, first_block);
    html_container.appendChild(html_first_block);

    //code for rendering all other blocks on its right
    for(let j=1; j<20; j++) {
      const html_block = document.createElement('div');
      html_block.classList.add('block-lasts');
      const block = world[i][j];
      html_process_image_or_color_block(html_block, block);
      html_container.appendChild(html_block);
    }
  }
  document.body.innerHTML = '';
  document.body.appendChild(html_container);
}

render(world);

In my opinion the code is terrible :) and I appreciate all your time and effort!
Codepen


texts: Calculating the factorial of a number efficiently

texts:
I was trying to calculate the factorial of a large number in a short time:

class TestClass {
    public static void main(String args[] ) throws Exception {
        BufferedReader keyboard=new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(keyboard.readLine());
        while(n!=0){
            int uptoValue=Integer.parseInt(keyboard.readLine());
            calculateFactorial(uptoValue);
            n--;
        }
    }
    private static void calculateFactorial(int uptoValue) {
        // TODO Auto-generated method stub
        BigInteger answer=new BigInteger("1");
        for(int i=1;i<=uptoValue;i++){
            answer=answer.multiply(new BigInteger(String.valueOf(i)));
        }
        System.out.println(answer);
    }
}

Which gave me total sum of  running  time of 1.7618 against various inputs.

Now I tried to solve it using pattern decomposition to avoid the number of loops, and wrote the following code:

class TestClass {
    public static void main(String args[] ) throws Exception {
        BufferedReader keyboard=new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(keyboard.readLine());
        while(n!=0){
            int uptoValue=Integer.parseInt(keyboard.readLine());
            calculateFactorial(uptoValue);
            n--;
        }
    }
    private static void calculateFactorial(int uptoValue) {
        // TODO Auto-generated method stub
        BigInteger answer=new BigInteger("1");
        boolean oddUptoValue=false;
        int tempUptoValue=0;
        if(uptoValue%2!=0){
            tempUptoValue=uptoValue-1;
            oddUptoValue=true;
        }else{
            tempUptoValue=uptoValue;
        }
        for(int i=1;i<=tempUptoValue/2;i++){
            int temp=(tempUptoValue-i+1)*i;
            answer=answer.multiply(new BigInteger(String.valueOf(temp)));
        }
        if(oddUptoValue){
            answer=answer.multiply(new BigInteger(String.valueOf(uptoValue)));
        }
        System.out.println(answer);
    }
}

Which gave me a total sum of running time of 1.6362 sec against various inputs.

How can I improve the runtime? What are more efficient algorithms to calculate the factorials of a large number?


texts: ASP.NET MVC Html.XXFor OK to discard lambda argument and just use Model directly?

texts:
I find it a bit odd in ASP.NET MVC that the Html helper extensions, like Html.EditorFor, take a Func<T1, TResult> where the T1 argument is just the already in scope Model variable, e.g.:

@Html.EditorFor(x => x.Name)

If I really wanted Model renamed, I would just assign it once to a variable in the top of the razor view. So, I feel compelled to do the following:

@Html.EditorFor(_ => Model.Name)

Does this seem reasonable?


texts: Validate parentheses "()" and "[]" are balanced

texts:
Firstly I was using regex to get if the number of parentheses in a string is balanced or not, but the performance was quite slow when any large string was passed to the regex. So I created this custom method, which returns whether a string contains balanced parentheses or not. Please review this code and point out any mistakes and improvements.

checkBalancedBrackets(str) {
    var b1 = [];
    var b2 = [];
    for ( var i=0; i < str.length; i++ ) {
        var ch = str.charAt(i);
        if (ch == "(" ) b1.push(ch);
        else if ( ch == "[" ) b2.push(ch);
        else if ( ch == ")" ) {
            if (b1.length < 1) {
                return false;
            } else {
                b1.pop();
            }
        }
        else if ( ch == "]" ) {
            if (b2.length < 1) {
                return false;
            } else {
                b2.pop();
            }
        }
    }
    return b1.length == 0 && b2.length == 0;
}


texts:
I would really like some advice from any DB gurus who have a few minutes free. After doing some reading and playing with sqlfiddle over the weekend I have constructed this PostgreSQL schema and it is the first proper one I've ever done, so I am sure I've made some poor choices.

This is what I've got for a "job" and "advert" site:

--
-- Application Database Structure
--

-- Company Table
CREATE TABLE company (
    id SERIAL PRIMARY KEY,
    name varchar(60) NOT NULL
);

-- Country Table
CREATE TABLE country (
    id SERIAL PRIMARY KEY,
    name varchar(255) NOT NULL
);

-- Location Table
CREATE TABLE location (
    id SERIAL PRIMARY KEY,
    name varchar(255) NOT NULL,
    country_id integer NOT NULL REFERENCES country (id),
    coordinate varchar(255) NOT NULL
);

-- Source Table
CREATE TABLE source (
    id SERIAL PRIMARY KEY,
    name varchar(60) NOT NULL
);

-- Payment Method Table
CREATE TABLE payment_method (
    id SERIAL PRIMARY KEY,
    name varchar(60) NOT NULL
);

-- Payment Table
CREATE TABLE payment (
    -- Generic
    id SERIAL PRIMARY KEY,
    ip varchar(255),
    email varchar(255) NOT NULL,
    amount varchar(255),
    payment_method_id integer NOT NULL REFERENCES payment_method (id),
    -- Credit Card
    card_name varchar(255),
    card_expiration varchar(255),
    -- Paypal
    paypal_email varchar(255),
    paypal_transactionid varchar(255)
);

-- Job Table
CREATE TABLE job (
    -- Identification
    id SERIAL PRIMARY KEY,
    solrid varchar (10),
    -- Job Information
    title varchar(60) NOT NULL,
    description varchar(255) NOT NULL,
    truncated_description varchar(255) NOT NULL,
    keyword_description varchar(255) NOT NULL,
    how_to_apply varchar(255) NOT NULL,
    website_url varchar(255) NOT NULL,
    logo_url varchar(255),
    page_url varchar(255) NOT NULL,
    -- Dates
    date timestamp NOT NULL,
    expires timestamp NOT NULL,
    -- Linked Tables
    company_id integer NOT NULL REFERENCES company (id),
    source_id integer NOT NULL REFERENCES source (id),
    location_id integer NOT NULL REFERENCES location (id),
    payment_id integer NOT NULL REFERENCES payment (id),
    -- Status Flags
    active boolean DEFAULT FALSE,
    premium boolean DEFAULT FALSE,
    indexed boolean DEFAULT FALSE,
    error boolean DEFAULT FALSE,
      -- Email Flags
    email_reminder boolean DEFAULT FALSE,
    email_confirmation boolean DEFAULT FALSE
);

-- Advert Table
CREATE TABLE advert (
    -- Identification
    id SERIAL PRIMARY KEY,
    -- Content
    title varchar(60) NOT NULL,
    description varchar(255) NOT NULL,
    page_url varchar(255) NOT NULL,
    -- Dates
    date timestamp NOT NULL,
    expires timestamp NOT NULL,
    -- Email Flags
    email_reminder boolean DEFAULT FALSE,
    email_confirmation boolean DEFAULT FALSE
    -- Linked Tables
    source_id integer NOT NULL REFERENCES source (id),
    payment_id integer NOT NULL REFERENCES payment (id),
    -- Status Flag
    active boolean DEFAULT FALSE,
    error boolean DEFAULT FALSE
);

Could anyone give me some guidance / possible improvements before I start building my site about this DB?


texts:
I'm developing a class to compare prices. For example, give me products which price are above 50 or under 50. Here's my API:

var indicator = new PriceIndicator(PriceComparison.Above, 50);
var actual = indicator.Apply(listOfProductPrices);

I managed to design my code for the operator Above and Under comparison:

public abstract class PriceComparison
{
    public static readonly UnderPriceComparison Under = new UnderPriceComparison();

    public static readonly AbovePriceComparison Above = new AbovePriceComparison();

    public abstract bool Evaluate(double price, double valueToCompare);
}

public class AbovePriceComparison : PriceComparison
{
    public override bool Evaluate(double price, double valueToCompare)
    {
        return price > valueToCompare;
    }
}

public class UnderPriceComparison : PriceComparison
{
    public override bool Evaluate(double price, double valueToCompare)
    {
        return price < valueToCompare;
    }
}

public class PriceIndicator : IBuyIndicator
{
    private readonly PriceComparison _comparison;
    private readonly int _value;

    public PriceIndicator(PriceComparison comparison, int value)
    {
        _comparison = comparison;
        _value = value;
    }

    public IList<BuyOrder> Apply(IList<int> productPrices)
    {
        return productPrices.Where(price => _comparison.Evaluate(price, _value))
                            .Select(b => new BuyOrder(b))
                            .ToList();
    }
}

Now, I want to manage Range price. I want my API to look as simple as the one above. Ideally, it would be

var indicator = new PriceIndicator(PriceComparison.Range, 50, 100); // Here's the change
var actual = indicator.Apply(listOfProductPrices);

I don't know how I can design this. What I tried to do so far is to add another Evaluate method in PriceComparison, which takes three parameters: double price, double left, double right.  But then, my previous two methods have to implement it and will have to throw IncorrectComparisonException because they can only compare with one value. So I'm not really fan of this design.


texts:
My job for now is to teach a trainee how to program. I told him to solve the following task, given by a book (I try to translate it):

  Write a program for compound interest calculation. The user has to
  enter the amount of money, the years, and the interest rate. The
  program should look like this:

Money in Euro: 100
Annual percentage rate: 6
Term in years: 4
Money after 1 years: 106.0
Money after 2 years: 112.36
Money after 3 years: 119.1016
Money after 4 years: 126.247696

Important Note

He hasn't learned anything about OOP, exception handling or using objects and methods yet. He now learns how to design simple algorithms. But he has gotten a hint how to use the scanner class to get the user input.

I want to show him my own example solution, so that he can learn. I want to ask you, if my example solution is okay for showing it to a beginner. Is it well written or have I ignored any good practices?

// use "int variable = scanner.nextInt()" for getting int values
// use "double variable = scanner.nextDouble()" for getting double values

import java.util.Scanner;

public class Main {
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String args[]) {
        // write your solution here:
        double money;
        int years;
        double rate;

        System.out.print("Money in Euro: ");
        money = scanner.nextDouble();
        System.out.print("Annual percentage rate: ");
        rate = scanner.nextDouble();
        System.out.print("Term in years: ");
        years = scanner.nextInt();

        for (int i = 1; i <= years; i++) {
            money += money * (rate / 100);
            System.out.println("Money after " + i + ". years: " + money);
        }
    }
}


texts: Algorithm that combines same objects to single common key

texts:
I wrote this algorithm but i was wondering if there was any way i can make it less 'expensive'. The algorithm needs to transform this data structure:

const deliveryHours = {
  monday: [
    {
      start: {
        hour: 3,
        minute: 0,
      },
      end: {
        hour: 6,
        minute: 0,
      },
    },
  ],
  tuesday: [
    {
      start: {
        hour: 3,
        minute: 0,
      },
      end: {
        hour: 6,
        minute: 0,
      },
    },
    {
      start: {
        hour: 5,
        minute: 0,
      },
      end: {
        hour: 3,
        minute: 0,
      },
    },
  ],
  wednesday: [
    {
      start: {
        hour: 3,
        minute: 0,
      },
      end: {
        hour: 4,
        minute: 0,
      },
    },
    {
      start: {
        hour: 5,
        minute: 0,
      },
      end: {
        hour: 1,
        minute: 0,
      },
    },
  ],
}

to:

[ { hours: { from: 3, to: 4 }, wednesday: true },
  { hours: { from: 3, to: 6 }, tuesday: true, monday: true },
  { hours: { from: 5, to: 1 }, wednesday: true },
  { hours: { from: 5, to: 3 }, tuesday: true } ]

This is my attempt, it is clearly not the best way to go about it but im having a hard time finding another way:

const deliveryHours = {
  monday: [
    {
      start: {
        hour: 3,
        minute: 0,
      },
      end: {
        hour: 6,
        minute: 0,
      },
    },
  ],
  tuesday: [
    {
      start: {
        hour: 3,
        minute: 0,
      },
      end: {
        hour: 6,
        minute: 0,
      },
    },
    {
      start: {
        hour: 5,
        minute: 0,
      },
      end: {
        hour: 3,
        minute: 0,
      },
    },
  ],
  wednesday: [
    {
      start: {
        hour: 3,
        minute: 0,
      },
      end: {
        hour: 4,
        minute: 0,
      },
    },
    {
      start: {
        hour: 5,
        minute: 0,
      },
      end: {
        hour: 1,
        minute: 0,
      },
    },
  ],
}

const mapDeliveryHours = (deliveryHours) => {
  const result = {};
  for (let i = 0; i < Object.keys(deliveryHours).length; i += 1) {
    const day = Object.keys(deliveryHours)[i];

    const ranges = deliveryHours[day];

    for (let j = 0; j < ranges.length; j++) {
      const range = ranges[j];

      result[range.start.hour.toString() + range.end.hour.toString()] = {
        hours: {
          from: range.start.hour,
          to: range.end.hour,
        },
        [day]: true,
      };

      for (let k = 0; k < Object.keys(deliveryHours).length; k++) {
        const innerDay = Object.keys(deliveryHours)[k];
        const innerRanges = deliveryHours[innerDay];

        for (let l = 0; l < innerRanges.length; l++) {
          const innerRange = innerRanges[l];
          if (day !== innerDay
            && innerRange.start.hour === range.start.hour
            && innerRange.end.hour === range.end.hour
          ) {
            result[range.start.hour.toString() + range.end.hour.toString()] = {
              ...result[range.start.hour.toString() + range.end.hour.toString()],
              [innerDay]: true,
            };
          }
        }
      }
    }
  }
  return Object.values(result);
};

console.log(mapDeliveryHours(deliveryHours))


texts: Converting data when output std container via ostream_iterator

texts:
I have a strongly typed enum and std::vector of this type.

enum class Colors { red, green, blue };
std::vector v = { Colors::blue, Colors::red };

I trying to output v to standard output via std::copy.

std::copy(v.begin(), v.end(), std::ostream_iterator<Colors>(std::cout, " ");

Compilation failed because compiler do not know how to print Colors. I can define operator << for colors, but it looks too excessive for me. Then try print int values of v elements.

std::copy(v.begin(), v.end()
  , std::ostream_iterator<std::underlying_type<Colors>::type>>(std::cout, " ");

Compilation failed because it is prohibited to print Colors to std::ostream_iterator<int>. Ok. Then std::transform can help.

std::transform(v.begin(), v.end()
,   std::ostream_iterator<std::underlying_type<Colors>::type>(std::cout, " ")
,   [&](Colors &c) -> std::underlying_type<Colors>::type
    {
        return std::underlying_type<Colors>::type(c);
    }
);

However, this lambda looks ugly. Is there neater way to copy or transform vector of Colors? Maybe boost has some way?

Of course, a loop can print, but I'd prefer to avoid explicit loop.

for(auto c : v)
{
    std::cout << std::underlying_type<Colors>::type(c) << std::endl;
}

I have a lot of different enum classes in my project. All of them I need to print out. I don't like idea to create operator << for each one individually. However, if I try to  make templated operator << then I've got a global redefinition of this operator. And this is not what I actually want.

template <typename T>
std::ostream &operator << (std::ostream &_os, const T &_t) {
    _os << typename std::underlying_type<T>::type(_t);
    return _os;
}