texts:
I made a tool set to facilitate bit manipulation as follows. Any comments are welcome, be it about the interface design, the implementation, or even the naming. Also, I want to make sure that the tool set is not lacking something for use-cases I failed to catch :-) Original code and unit tests can be found here and here.

/// The index is zero-based, starting from the least significant bit.
/// The most significant bit or sign bit is the head bit.

template <typename T>
constexpr unsigned num_bits(T = 0) {
  return sizeof(T) << 3;
}

template <typename T>
constexpr unsigned head_bit_idx(T = 0) {
  return num_bits<T>() - 1;
}

template <typename T>
T bit_flag(unsigned idx) {
  // since C++14, `1 << (num_bits<int> - 1)` is well-defined and makes `INT_MIN`
  return static_cast<T>(1) << idx;
}

template <typename T>
constexpr T head_bit_flag() {
  return static_cast<T>(1) << head_bit_idx<T>();
}

template <typename T>
bool test_bit(T x, unsigned idx) {
  return x & bit_flag<T>(idx);
}

template <typename T>
bool test_head_bit(T x) {
  return test_bit(x, head_bit_idx(x));
}

template <typename T>
T set_bit(T x, unsigned idx) {
  return x | bit_flag<T>(idx);
}

template <typename T>
T set_head_bit(T x) {
  return set_bit(x, head_bit_idx<T>());
}

template <typename T>
T clear_bit(T x, unsigned idx) {
  return x & ~bit_flag<T>(idx);
}

template <typename T>
T clear_head_bit(T x) {
  return clear_bit(x, head_bit_idx<T>());
}

template <typename T>
T flip_bit(T x, unsigned idx) {
  return x ^ bit_flag<T>(idx);
}

template <typename T>
T flip_head_bit(T x) {
  return flip_bit(x, head_bit_idx<T>());
}

template <typename T>
unsigned num_bits_set(T x) {
  unsigned cnt = 0;
  // behavior of signed type underflow is unspecified
  std::make_unsigned_t<T> v = x;
  while (v) {
    ++cnt;
    v &= v - 1;
  }
  return cnt;
}


texts: What are the top voted comments on closed questions, and who made the comments?

texts:
Following this linked question and the feedback it generated, I put together a new query which utilizes a JOIN.

WITH UpvotedComments AS (
  SELECT
    PostId,
    Score,
    Text,
    --Comments.UserDisplayName doesn't return users' current display names
    Commenter = (
      SELECT DisplayName
      FROM Users
      WHERE Id = UserId
    )
  FROM Comments
  WHERE Score > 0
), ClosedPosts AS (
  SELECT Id, ClosedDate
  FROM Posts
  WHERE ClosedDate IS NOT NULL
)

SELECT Score, Text, Commenter

FROM UpvotedComments

INNER JOIN ClosedPosts ON UpvotedComments.PostId = ClosedPosts.Id

ORDER BY Score DESC, ClosedDate DESC

It can get a bit slow on sites like Stack Overflow, where the returns are greater than 50 000.


texts: Enhanced Hashmap - Add a number to all keys/values

texts:
I had the below problem in a coding test and I got 28/30 tests passes and 2 failed due to a time-out.

Problem You have created a programming language and now you have decided to add hashmap support to it. It was found that in
common programming languages, it is impossible to add a number to all
hashmap keys/values. So, you have decided to implement your own
hashmap in your new language with following operations.

insert x y - insert and object with key x and value y
get x - return the value of an object with key x
addToKey x - add x to all keys in map
addToValue y - add y to all values in map

Your task is to implement this hashmap, apply the given queries, and
to find the sum of all the results for get operations

For Example

For queryType=["insert","insert","addToValue","addToKey","get"] and query=[[1,2],[2,3],[2],[1],[3]], the output should be hashMap(queryType,query)=5.

Explanation

insert 1 2 - hashmap will be {1:2}
insert 2 3 - hashmap will be {1:2,2:3}
addToValue 2 - hashmap will be {1:4,2:5}
addToKey 1 - hashmap will be {2:4,3:5}
get 3 - value is 5

Input/Output

[execution time limit] 3 seconds (Java)
[input] array.string queryType
Array of query types. its is guaranteed that each queryType[i] any one of the above mentioned operation
1<=queryType.length<=10^5
[input] array.array.integer query
Array of queries, where each query is mentioned by 2 numbers for insert and one number for others
Key values are in range [-10^9,10^9]

Below is my solution in Java
long hashMap(String[] queryType, int[][] query) {
        long sum = 0;
        Integer currKey = 0;
        Integer currValue = 0;
        Map<Integer, Integer> values = new HashMap<>();
        for (int i = 0; i < queryType.length; i++) {
            String currQuery = queryType[i];
            switch (currQuery) {
            case "insert":
                HashMap<Integer, Integer> copiedValues = new HashMap<>();
                if (currKey != 0 || currValue != 0) {
                    Set<Integer> keys = values.keySet();
                    for (Integer key : keys) {
                        copiedValues.put(key + currKey, values.get(key) + currValue);
                    }
                    values.clear();
                    values.putAll(copiedValues);
                    currValue = 0;
                    currKey = 0;
                }
                values.put(query[i][0], query[i][1]);
                break;
            case "addToValue":
                currValue += values.isEmpty() ? 0 : query[i][0];
                break;
            case "addToKey":
                currKey += values.isEmpty() ? 0 : query[i][0];
                break;
            case "get":
                copiedValues = new HashMap<>();
                if (currKey != 0 || currValue != 0) {
                    Set<Integer> keys = values.keySet();
                    for (Integer key : keys) {
                        copiedValues.put(key + currKey, values.get(key) + currValue);
                    }
                    values.clear();
                    values.putAll(copiedValues);
                    currValue = 0;
                    currKey = 0;
                }
                sum += values.get(query[i][0]);
            }
        }
        return sum;
    }

Is there any other data structure I can use instead of hashmap or Can I improve my code to be more linear?


texts: Bash script to validate a MySQL database

texts:
I am fairly new to bash script programming so I would love some feedback.
I am trying to write a series of migration scripts for our DBs (please don't direct me to other tools; I spent a lot of time evaluating them and am forced to write custom code) and this is script that contains validation logic.

Basic requirements:

Validate file format.
Make sure the script exists in at least 1 descriptor. A descriptor dictates the scripts to execute and in which order. If a release file isn't in a descriptor it's inert so validate it's present
ensure a corresponding rollback exists
ensure a validation script exists
execute the validation script and verify results.

how I intend it (for now) to be used is

source ./validation.sh
validateFormat scripts/release/DBA-1234 || echo "fail"

as an example. Or this, which would apply all:

validate

ideally, I would love to be able to chain them together functionally but when I try the below, it doesn't seem to know my symbols:

  xargs: validateFormat: No such file or directory

find scripts/releases -name '*.sql' | xargs validateFormat | validateDescriptor | cat | mysql

or just

find scripts/releases -name '*.sql' | xargs validate | cat | mysql

release-format (DBA-1234_some_message.sql)

([A-Z]{2,5}[_-][0-9]{1,5})[_-]?(.*)

validation.sh

#!/usr/bin/env bash

user=root
password=my-secret-pw
port=3306
host=127.0.0.1
release_format=$(cat .utils/release-format)
releases=${scripts}/releases/
validators=${scripts}/validators/
descriptors=${scripts}/descriptors/
rollbacks=${scripts}/rollbacks/

validateDescriptor() {
  [[ -z $1 ]] && return -1
  local script=$(basename $1)
  grep -rq ${script} ${descriptors};
  return $?
}

ensureRollback() {
  [[ -z $1 ]] && return -1
  ls ${rollbacks}/$(toTicket ${1})* 2>&1 >/dev/null
  return $?
}

ensureValidator() {
  [[ -z $1 ]] && return -1
  ls ${validators}/$(toTicket ${1})* 2>&1 >/dev/null
  return $?
}

validateFormat() {
  [[ -z $1 ]] && return -1
  [[ $(basename -s .sql $1) =~ ${release_format} ]] && return 0 || return -1
}

toTicket() {
  [[ -n $1 ]] && basename -s .sql ${1} | sed -E "s/$release_format/\1/"
}

toValidator() {
  [[ -z $1 ]] && return -1
  local ticket=$(toTicket ${1})
  local validator=$(ls ${validators}/${ticket}* | head -1)
  [[ $? != 0 ]] && return $? || echo ${validator}
}

applyValidationScripts() {
  [[ -z $1 ]] && return -1
  local validator=$(toValidator ${1})

  if [[ ! -e ${validator} ]]; then
    return -1
  fi

  result=$(mysql -sN -h ${host} -u ${user} -p${password} -P ${port} <${validator})
  if [[ $? != 0 ]]; then
    return $?
  fi

  if [[ $(echo ${result} | wc -l | tr -d ' ') != 1 ]]; then
    echo "validation result count was more than 1 row. Invalid results"
    return -1
  else
    return $((result - 1))
  fi
}

validate() {
  for release in $(find ${releases} -type f -exec basename -s .sql {} \;); do
    #  applyValidationScripts ${release}
    validateFormat ${release}  && ensureRollback ${release} && ensureValidator ${release} && validateDescriptor ${release}
    [[ $? != 0 ]] && echo "${release} failed validation"
  done;
}


texts:
I was solving Project Euler #7 on Hackerrank
 but for two cases, execution time is more than 2 sec.
Can you help with optimizing? I'm new to programming.

#include <stdio.h>
#include <stdbool.h>
/*INPUT EXAMPLE
2 -> no of test cases
3 -> 1st test case
5 -> 2nd test case
*/
bool IsPrime(unsigned long);

int main(){
  int n;
  scanf("%d", &n);

  while (n != 0) {
    n--;
    unsigned long m, l = 2, k = 1;
    scanf("%lu", &m);
    if (m == 1) {
      printf("%d\n", 2);
    } else if(m == 2){
      printf("%d\n", 3);
    }else{
    while(1){
      if(IsPrime(6*k-1) == true){
        l++;
        if(l == m){
          printf("%lu\n", 6*k-1);
          break;
        }
      }
      if(IsPrime(6*k+1) == true){
        l++;
        if(l == m){
          printf("%lu\n", 6*k+1);
          break;
        }
      }
      k++;
    }
  }
  }
}
bool IsPrime(unsigned long n){
    unsigned long k;
    for(k = 2; k*k <= n; k++){
        if(n % k == 0){
            return false;
        }
    }
    return true;
}


texts: Passing multiple parameters from the command line in Java

texts:
I am working on a project in which I need to pass multiple arguments from the command line-

Below is the use case I have-

From the command line, I will be passing atleast four paramaters- noOfThreads, noOfTasks, startRange and tableName1, so if I am passing these four thing, then I need to store them in a variable and for any table names- I need to add it into the string list so that I can use them in my other code.
Secondly, I can pass five parameters instead of four just like above- So five parameters can be- noOfThreads, noOfTasks, startRange , tableName1 and tableName2. So here tableName2 is extra. so if I am passing these five thing, then I need to store them in a variable and here I am passing tableName1 and tableName2 as two tables so I will be storing these two tables in a string list.
Thirdly, I can pass six parameters instead of five just like above- So sixparameters can be- noOfThreads, noOfTasks, startRange , tableName1, tableName2 and tableName3. So here tableName3 is extra. so if I am passing these six thing, then I need to store them in a variable and here I am passing tableName1 , tableName2 and tableName3 as three tables so I will be storing these three tables in a string list again.

So for above scenario, I have the below code with me. It is looking very ugly currently as I have lot of repetition in my code as mentioned below. Is there any way I can make it more cleaner?

Below is my code-

private static List<String> databaseNames = new ArrayList<String>();
private static int noOfThreads;
private static int noOfTasks;
private static int startRange;
private static String tableName1;
private static String tableName2;
private static String tableName3;

public static void main(String[] args) {

if (args.length > 0 && args.length < 5) {

    noOfThreads = Integer.parseInt(args[0]);
    noOfTasks = Integer.parseInt(args[1]);
    startRange = Integer.parseInt(args[2]);
    tableName1 = args[3];
    databaseNames.add(tableName1);
} else if (args.length > 0 && args.length < 6) {
    noOfThreads = Integer.parseInt(args[0]);
    noOfTasks = Integer.parseInt(args[1]);
    startRange = Integer.parseInt(args[2]);
    tableName1 = args[3];
    tableName2 = args[4];
    databaseNames.add(tableName1);
    databaseNames.add(tableName2);
} else {
    noOfThreads = Integer.parseInt(args[0]);
    noOfTasks = Integer.parseInt(args[1]);
    startRange = Integer.parseInt(args[2]);
    tableName1 = args[3];
    tableName2 = args[4];
    tableName3 = args[5];
    databaseNames.add(tableName1);
    databaseNames.add(tableName2);
    databaseNames.add(tableName3);
}
}


texts:
I am solving interview questions from here.

  Problem : Given a N cross M matrix in which each row is sorted, find the overall median of the matrix. Assume N*M is odd.

  Note: No extra memory is allowed.
  For example:

 Matrix=     [1, 3, 5]
             [2, 6, 9]
             [3, 6, 9]

  A = [1, 2, 3, 3, 5, 6, 6, 9, 9]
  Median is 5. So, output is 5.

This is my approach:

def find_median( A):
    """Returns the median value from given list"""
    for i in range(1,len(A)):
        A[0].extend(A[i])

    return (sorted(A[0])).pop(len(A[0])/2)

Test Cases:

assert find_median([[1,3,5],[2,5,9],[3,6,11]]) == 5
assert find_median([[0,1,1],[2,6,10],[3,5,9]]) == 3
assert find_median([[1,3,4,12,14],[1,6,9,10,15],[0,1,3,3,4]]) == 4

I am able to solve the problem but I wanted to know is there a better approach to solve this problem?


texts:
I have looked around for an already existing script for this, but couldn't find one, so i decided to make my own.

The point of this is to make it easy to reload an element, whether its a form or a link.

To use the script, you add a class to the link/form called "js_container-reloader".
What the script does is it simply gets the content of the action url or href, creates a wrapper around the element you are reloading, takes the ajax response and puts it in to the wrapper, then removes the wrapper.

Its working as it should at the moment, but i wonder if there is a better way of doing this.

//Form element reloader
$(document).on("submit", ".js_container-reloader", function(e){
    e.preventDefault();

    //Call the reloader function
    elementReloader(e.currentTarget);
});

//Link element reloader
$(document).on("click", ".js_container-reloader", function(e){
    e.preventDefault();

    //Call the reloader function
    elementReloader(e.currentTarget);
});

/*  Element reloader function
*   Takes an element and the type of request this is */
function elementReloader(element){

    //Set variables
    var element = $(element),
        requestUrl,
        requestType,
        data,
        reloadContainer;

    //Wrap the element in a reloader div and save the div to a variable
    element.wrap("

");
    reloadContainer = element.closest('.js_reload-container');

    //If the element is a form
    if(element.is("form")){

        //Save the forms action
        requestUrl = element.attr('action');

        //Save the request type
        requestType = element.attr('method');

        //Save the forms data
        data = element.serialize();

    //If the request should be done by GET
    }else{

        //Get the forms action
        requestUrl = element.attr('href');

        //Save the request type
        requestType = "GET";
    }

    //Run the ajax script
    $.ajax({
        type: requestType,
        url: requestUrl,
        data: data,
        success: function(result){

            //If the result returned false, reload the alert container
            if(!result){
                reloadAlertContainer();

            //If its not false then load the container with the result
            }else{

                //Add the result to the wrapper
                reloadContainer.html(result);

                //Remvoe the wrapper
                reloadContainer.find(".js_container-reloader").unwrap();
            }
        },
        error: function(xhr) {

            /*  Reload the alerts container
            *   An alert is saved to the session if there was an error
            *   with any script that was loaded.
            *   This function reloads the container which shows the session alert. */
            reloadAlertContainer();
        },
    });
}

I don't assume my code is expert level as i am not an expert, but the goal is to make it as easy and dynamic as possible for future implementations.
I tried looking in to combining the code, especially the first 2 functions for the event listeners, together in to one function, but couldn't find a way that seemed like a proper solution.

Just to clarify about the form posting - i do the form validation and checking in php, in the actual file that is being loaded, and not in JavaScript/jQuery. This script is just for reloading elements.


texts:
I would like to know if this is the correct way to use try/catch when dealing with multiple MySQL queries and PDO:

try {
    $create = $con[$_POST['user-selected-connection']]->query("...");
    KD::notice('success','table successfully created');
    try {
        $insert = $con[$_POST['user-selected-connection']]->query("...");
        KD::notice('success','table was populated successfully');
    } catch(PDOException $e) {
        KD::notice('error','was unabled to insert records'.$e->getMessage());
    }
} catch(PDOException $e) {
    KD::notice('error','The table was not created.'.$e->getMessage());
}

This is part of a get started wizard in my application, and this is the part where the user needs to create tables in order to proceed.  That can be done in two ways; either copy/paste the provided SQL query manually into their MySQL handler (e.g. phpMyAdmin), or by just clicking a button if they have created a user with CREATE privileges in the previous step. (The previous step, which is "set up database, and add users into the application", tells them the benefits of having a super user for future tasks).

Anyway, I need to use try/catch since the user has the ability to chose which user they want to use when creating the tables. And if the selects user doesn't have the required privileges, a fatal error message is returned. That's how I figured I needed to use try/catch to handle the fatal error, and notify that the user didn't have access.

I do this task in two stages to make sure that the required records actually gets inserted after the table is created. (had a few test runs where the table was created, and the records wasn't inserted when in the same query).

Is this an appropriate way to do this?

If the create part fails, will it jump to catch right away, or will it still try to execute the insert query before throwing the error?


texts: Acquiring and formatting data from a JSON file

texts:
I have a JavaScript function that is getting data out of a JSON file and then doing some formatting to it.  The code works but I feel like it just an awful way of doing it.  All criticism and help appreciated.

function MCScrap(ZWA, ZWB, ZWC, ZWD, Number) {

$(document).ready(
        function() {
            setInterval(function() {

                $.getJSON("mccount.json", function(machines) {
                    console.log(machines);
                    var Tcount = machines.Machines[Number].Tcount;
                    var Ycount = machines.Machines[Number].Ycount;
                    var TScount = machines.Machines[Number].TScount;
                    var YScount = machines.Machines[Number].YScount;
                    document.getElementById(ZWA).innerHTML = Ycount;
                    document.getElementById(ZWB).innerHTML = Tcount;
                    document.getElementById(ZWD).innerHTML = TScount + "%";
                    document.getElementById(ZWC).innerHTML = YScount + "%";
                    if (TScount < 3) {
                        document.getElementById(ZWB).style.backgroundColor = 'lime';
                    } else if (TScount < 5) {
                        document.getElementById(ZWB).style.backgroundColor = 'orange';
                    } else {
                        document.getElementById(ZWB).style.backgroundColor = 'red';
                    }

                    if (YScount < 3) {
                        document.getElementById(ZWA).style.backgroundColor = 'lime';
                    } else if (YScount < 5) {
                        document.getElementById(ZWA).style.backgroundColor = 'orange';
                    } else {
                        document.getElementById(ZWA).style.backgroundColor = 'red';
                    }
                }
                );

            }, 3000);
        });
}


texts:
Similar to this question here, I am trying to implement sort algorithms in Julia, as part of a package.

The code for the implementation is as follows:

"""
The swapping function implementation
"""
function swap!{T}(x::AbstractArray{T}, a::T, b::T)

  tmp = x[a]
  x[a] = x[b]
  x[b] = tmp
  return x

end

"""
`insertsort!{T}(x::AbstractArray{T}) ↦ x::AbstractArray`
Sorts an array using the **Insertion Sort** approach.
"""
function insertsort!{T}(x::AbstractArray{T})

  for index = 2:length(x)

    current  = x[index]
    position = index

    # For sublist sorting
    while position > 1 && x[position - 1] > current
      x[position] = x[position - 1]
      position -= 1
    end

    x[position] = current

  end

  return x
end

"""
`bubblesort!{T}(x::AbstractArray{T}) ↦ x::AbstractArray`
Sorts an array using the **Bubble Sort** approach.
"""
function bubblesort!{T}(x::AbstractArray{T})

  for i in 2:length(x)
    for j in 1:length(x)-1
      if x[j] > x[j+1]
        swap!(x, j, j+1)
      end
    end
  end

  return x
end

"""
`selectsort!{T}(x::AbstractArray{T}) ↦ x::AbstractArray`
Sorts an array using the **Selection Sort** approach.
"""
function selectsort!{T}(x::AbstractArray{T})

  for i in 1:length(x)-1
    iMin = i
    for j in i+1:length(x)
      if x[j] < x[iMin]
        iMin = j
      end
    end

    swap!(x, i, iMin)
  end

  return x
end

"""
`quicksort!{T}(x::AbstractArray{T}) ↦ x::AbstractArray`
Sorts an array using the **Quick Sort** approach.
"""
function quicksort!{T}(x::AbstractArray{T}, first::T = 1, last::T = length(x))

  if last > first

    pivot       = x[first]
    left, right = first, last

    while left <= right
      while x[left] < pivot
        left += 1
      end
      while x[right] > pivot
        right -= 1
      end
      if left <= right
        swap!(x, left, right)
        left += 1
        right -= 1
      end
    end

    quicksort!(x, first, right)
    quicksort!(x, left, last)
  end

  return x
end

"""
`mergesort!{T}(x::AbstractArray{T}) ↦ x::AbstractArray`
Sorts an array using the **Merge Sort** approach.
"""
function mergesort!{T}(x::AbstractArray{T})

  if length(x) > 1
    mid    = div(length(x), 2)
    left   = mergesort!(x[1:mid])
    right  = mergesort!(x[mid+1:length(x)])
    result = Array(eltype(left), length(left) + length(right))

    k = 1

    while length(left) != 0 && length(right) != 0
      if left[1] <= right[1]
        result[k] = left[1]
        left      = left[2:end]
      else
        result[k] = right[1]
        right = right[2:end]
      end
      k += 1
    end

    while length(left) != 0
      result[k] = left[1]
      left = left[2:end]
      k += 1
    end

    while length(right) != 0
      result[k] = right[1]
      right = right[2:end]
      k += 1
    end

  for i = 1:length(x)
    x[i] = result[i]
  end

  end

  return x
end

All the sort algorithms are in-place. Are there any ways I can make speed up the implementations along with optimizing code for performance and quality?

(The reason I created a separate swap function, rather than doing x[a], x[b] = x[b], x[a] is that I felt it'd look more neat. Need your views on that too,)


texts:
I have written a function that is designed to convert an object into an array of key/pair values ("flattening it") like so:

Input

{
  "a": true,
  "b": {
    "c": 500
  }
}

Output

[
  ["a", true],
  ["b", [
    ["c", 500]
  ]
]

Here is the code I have written to do it:

function isCyclicObject(object, seenObjects) {
  seenObjects = (seenObjects instanceof Array) ? seenObjects : [];

  if (object instanceof Object) {
    if (seenObjects.indexOf(object) !== -1) {
      return true;
    }

    seenObjects.push(object);

    for (var key in object) {
      if (object.hasOwnProperty(key) && isCyclicObject(object[key], seenObjects)) {
        return true;
      }
    }

    return false;
  }

  return false;
}

function flattenObject(object) {
  if (!(object instanceof Object) || isCyclicObject(object)) {
    return null;
  }

  var flattened = [];

  for (var key in object) {
    var value = object[key];

    if (value instanceof Object) {
      value = flattenObject(value);

      if (value === null) {
        return null;
      }
    }

    flattened.push([key, value]);
  }

  return flattened;
}

I don't really have any major concerns over my code, however I would really appreciate having someone review it and point out any mistakes or flaws in my code that I haven't noticed. I'm also not all too familiar with how to lay out my JS code, so I believe that could possibly be improved too.

And here is the code I wrote to test its functionality:

function compareArrays(first, second) {
  if (!(first instanceof Array) || !(second instanceof Array)) {
    return false;
  }

  if (first.length != second.length) {
    return false;
  }

  for (var i = 0; i < first.length; i++) {
    var firstValue = first[i],
        secondValue = second[i];

    if (firstValue instanceof Array && secondValue instanceof Array) {
      if (!compareArrays(firstValue, secondValue)) {
        return false;
      }
    } else if (firstValue != secondValue) {
      return false;
    }
  }

  return true;
}

function testFlattenObject(object, expected) {
  var flattened = flattenObject(object);

  var objectString = JSON.stringify(object),
      expectedString = JSON.stringify(expected),
      flattenedString = JSON.stringify(flattened);

  var failed = false;

  if (object instanceof Object) {
    failed = !compareArrays(flattened, expected);
  } else {
    failed = flattened !== null;
  }

  if (failed) {
    console.error("Test failed for " + objectString + ": expected " + expectedString + " but got " + flattenedString);
  } else {
    console.log("Test passed");
  }
}

testFlattenObject({}, []);

testFlattenObject({
  a: true
}, [
  ["a", true]
]);

testFlattenObject({
  a: true,
  b: {
    c: 500
  }
}, [
  ["a", true],
  ["b", [
    ["c", 500]
  ]]
]);


texts: Rust/WebAssembly VS pure JavaScript benchmark in Node.js

texts:
I've wanted to try Rust and WebAssembly for a while. I recently realized that I could try both at the same time by compiling Rust to WebAssembly.

I wanted to know what the performances of something like that would be so I came up with a simple test :

Make a few mathematical operations in pure js a few times in a loop and measure execution time
Do the same thing in a Rust function, compiled to WebAssembly and imported into Node.js
Compare results

Does this approach make any sense to you?

Does my implementation below make any sense to you?

Am I benchmarking what I think I am benchmarking?

index.js

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const fs = require('fs');
var source = fs.readFileSync('./compute.wasm');

const server = http.createServer(async (req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  const start = process.hrtime.bigint();

  let n = 1000000;

  let js_result = 0;
  for (let i = 0; i < n; i++) {
    js_result += Math.sqrt(i) / Math.exp(i);
  }

  const js = process.hrtime.bigint();

  const env = {
    memoryBase: 0,
    tableBase: 0,
    memory: new WebAssembly.Memory({
      initial: 256
    }),
    table: new WebAssembly.Table({
      initial: 0,
      element: 'anyfunc'
    })
  }

  var typedArray = new Uint8Array(source);

  WebAssembly.instantiate(typedArray, {
    env: env
  }).then(result => {
    const wasm_result = result.instance.exports.compute(n);
    const wasm = process.hrtime.bigint();
    const js_time = js - start;
    const wasm_time = wasm - js;
    const winner = js_time > wasm_time ? "wasm" : "js";
    const str = `+==========+================================+================================+
|          | time (ns)                      | result                         |
+----------+--------------------------------+--------------------------------+
| js       | ${js_time}${" ".repeat(31 - js_time.toString().length)}| ${js_result}${" ".repeat(31 - js_result.toString().length)}|
+----------+--------------------------------+--------------------------------+
| wasm     | ${wasm_time}${" ".repeat(31 - wasm_time.toString().length)}| ${wasm_result}${" ".repeat(31 - wasm_result.toString().length)}|
+==========+================================+================================+
${winner} wins!`;
    res.end(str);

  }).catch(e => {
    // error caught
    console.log(e);
    res.end("err");
  });

});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

compute.rs

#[no_mangle]
pub extern fn compute(idx: i32) -> f64 {
    let mut sum = 0.0;
    for i in 0..idx {
        sum += (i as f64).sqrt() / (i as f64).exp();
    }
    return sum;
}

Compile this code as follows

rustup update
rustup target add wasm32-unknown-unknown
rustc --target wasm32-unknown-unknown -O --crate-type=cdylib compute.rs -o compute.big.wasm

Reduce the size by removing unused stuff from the module:

cargo install --git https://github.com/alexcrichton/wasm-gc
wasm-gc compute.big.wasm compute.wasm

Run the app node index.js and go to http://127.0.0.1:3000/ to output the result, for example

+==========+================================+================================+
|          | time (ns)                      | result                         |
+----------+--------------------------------+--------------------------------+
| js       | 35706500                       | 0.7072407184868039             |
+----------+--------------------------------+--------------------------------+
| wasm     | 6141100                        | 0.7072407184868039             |
+==========+================================+================================+
wasm wins!


texts: Checking if two floating point numbers are equal

texts:
Is this the best way to check if two floating point numbers are equal, or close to being equal?

template <class T>
bool IsEqual(T rhs, T lhs)
{
    T diff = std::abs(lhs - rhs);

    T epsilon = std::numeric_limits<T>::epsilon( ) * std::max(std::abs(rhs), std::abs(lhs));

    return diff <= epsilon ;
}


texts: Sorting an object by value w/ `sort` and `reduce`

texts:
Given an object with unsorted numeric values, such as:
const unsorted = {
  green: 80,
  blue: 90,
  red: 30,
  yellow: 100,
}

We want a data structure with the same key/value pairs sorted in descending order of the values, e.g.:
const sorted = {
  yellow: 100,
  blue: 90,
  green: 80,
  red: 30,
}

My solution:
function sortObjectByValue (obj) {
  const sorted = Object.keys(obj)
    .sort((a, b) => obj[b] - obj[a])
    .reduce((acc, cur) => {
      acc[cur] = obj[cur]
      return acc
    }, {})

  return new Map(Object.entries(sorted))
}

What I hope could be improved:

Two iterations, first sort then reduce; this seems inefficient.
Using Map. I wish we could just use objects, it would make using this elsewhere much easier. I doubt this can be avoided though, as we need to ensure that the order is preserved.


texts:
I created a PHP program to generate random phone numbers. A valid phone number:

must be exactly 11 digits in length, and
must start with any of the values mentioned in the $a array, and

How can I improve it? Specifically, how can I improve

its readability, and
its performance, assuming I want to generate millions of results.

<?php
      function rand_(){
    $digits_needed=7;

    $random_number=''; // set up a blank string

    $count=0;

    while ( $count < $digits_needed ) {
        $random_digit = mt_rand(0, 8);
        $random_number .= $random_digit;
        $count++;
    }

    return $random_number;

    }

    $a=array('0812', '0813'  ,'0814' ,'0815' ,'0816' ,'0817' ,'0818','0819','0909','0908');
        $i=0;
        while($i<21){
            $website = $a[mt_rand(0, count($a) - 1)];
           print $website . rand_().'<br>';
           $i++;
        }


texts: Outputting a logo from the Wordpress Customiser

texts:
I managed to solve a little problem I had myself by reading and modifying.
My code works, but as a novice I would like to ask if you could advise me of a cleaner way to achieve the same thing.

Things look a bit messy to me, so I'm sure there is probably a better way to do this.

This code simply outputs a logo from the Wordpress Customiser.

Any advice or direction will be greatly appreciated.

<?php
             $custom_logo_id = get_theme_mod('custom_logo');
             $logo = wp_get_attachment_image_src($custom_logo_id, 'full');
             if (has_custom_logo()) {
                 echo '';
             } else { ?>
                 <img src='<?php echo get_template_directory_uri(); ?>/img/logo.png'>
<?php }
 ?>


texts: BBCode to HTML converter using functional programming

texts:
I was inspired to write a BBCode to HTML converter as I'm currently learning functional programming. I wanted achieve functional cohesion. jsFiddle

I'd like feedback on:

structuring of the code. Should the functions getHtmlTag and getHtml be contained within bbTagToHtmlTag since they are coupled through the rules variable?
any regex expressions that can reduce the code base
any changes to the data model to reduce complexity

Below is the newer version of the code. This version is slightly less coupled compared to the original version and the functions are separated to allow for more reuse. This new version doesn't involve any recursion, so it may be more efficient.

I suspect the cost of reuse is an increase in code base. Although, I'm sure there's more regex magic that can be used to slim down the code base.

/* Escapes a string for use with regular expressions */
function escapeString(input) {
    return input.replace(/([\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,
                         function(c){return "\\" + c;});
}

/* replaces all */
function replaceAll(search, input, replacement, ignore) {
   return input.replace(
       new RegExp(escapeString(search), "g"+(ignore?"i":"")),
       replacement);
};

/* Check if an index is event */
function isIndexEven(val, index, context) {
    return (index % 2 === 0);
};

/* Sets the attributes on an HTML string given a set of attributes */
function setHtmlAttrs(htmlCode, attrs) {
    return attrs.reduce(function(htmlCode, attr, index) {
        var re = new RegExp('\\$' + (index + 1), 'g');
        return htmlCode.replace(re, attr);
    }, htmlCode);
};

/* Gets the html tag(s) for a bbCode tag */
function eleFragsToHtml(isClosing, elementFragments) {
    return '<' + elementFragments.map(function(frag) {
        return (isClosing ? '/' + frag.join(' ') : frag.join(' '));
    }).join('><') + '>';
};

/* Converts a single bbCode Tag to Html */
function bbTagToHtmlTag(rules, tag) {
    var attrs = tag.replace(/\[\w+|\]/g, '').trim().split(' ');
    var key = tag.replace(/\[\/?| .+|\]/g, '');
    var isClosing = /\//.test(tag);
    var htmlTemplate = (isClosing ? rules[key].map(function(rule) {
                                        return rule.filter(isIndexEven)
                                }).reverse()
                        : rules[key]);
    var output = eleFragsToHtml(isClosing, htmlTemplate);
    return setHtmlAttrs(output, attrs);
};

/* Converts bbCode to HTML */
function bbCodeToHtml(rules, bbCode) {
    /* Creates the Regular Expression Search */
    var regex = new RegExp( ['\\[.?[',
                             Object.keys(rules).join('|'),
                             '].*?\\]'].join(''), 'g' );
    return bbCode.match(regex)
                 .reduce(function(htmlCode, tag) {
                     return replaceAll(tag,
                                      htmlCode,
                                      bbTagToHtmlTag(rules, tag));
                 }, bbCode);
};

Below is the test setup using the same rule set as the linked post.

var rules = {
    'b': [ ['strong'] ],
    'bg': [ ['span', 'style\"background-color:$1\"'] ],
    'big': [ ['span', 'style=\"font-size: larger;\"'] ],
    'c': [ ['span', 'style=\"color:$1\"'] ],
    'f': [ ['span', 'style=\"font-family:$1\"'] ],
    'i': [ ['em'] ],
    'img': [ ['a', 'href=\"$1\"'],
             ['img', 'src=\"$1\" style=\"max-height: 200px; max-width: 200px;\"'] ],
    'p': [ ['pre'] ],
    'small': [ ['small'] ],
    's': [ ['span', 'style=\"text-decoration: line-through;\"'] ]
};
var sample = '[big][big][c red]WARNING[/c][/big][/big][s]test[/s][img test.jpg][/img]';
$('#console').text(bbCodeToHtml(rules, sample));


texts:
This is a battleship console game I wrote in C++.

#include <string>
#include <iostream>
#include <process.h>
#include <cstdlib>
#include <time.h>
using namespace std;

int const ROW = 3;
int const COL = 3;

int subX, subY;

int guesses = 5;

int board[ROW][COL];

bool hasWon = false;

void winScreen()
{
    cout << "You won with " << guesses << " guesses left! :) " << endl;
}

void generateGrid()
{
    for (int x = 0; x < ROW; x++)
    {
        for (int y = 0; y < COL; y++)
        {
            //0 = empty
            //1 = has guessed
            //2 = sub

            //empty board
            board[x][y] = 0;
            cout << "-" << x << "," << y << "- ";
        }
        cout << endl;
    }
}

void generateSubCoords()
{
    subX = 0 + (rand() % ROW);
    subY = 0 + (rand() % COL);
    //2 = sub
    board[subX][subY] = 2;
}

void displayGrid(int changeX, int changeY)
{

    cout << "_______________________________________" << endl;
    for (int x = 0; x < ROW; x++)
    {
        for (int y = 0; y < COL; y++)
        {
            if (x == changeX && y == changeY)
            {
                if (board[x][y] != 2)
                {
                    board[x][y] = 1;
                }
            }

            if (board[x][y] == 0)
            {
                cout << "-" << x << "," << y << "- ";
            }
            else if (board[x][y] == 1)
            {
                cout << "-X,X- ";
            }

            if (board[x][y] == 2 )
            {
                if (x == changeX && y == changeY)
                {
                    cout << "-HIT- ";
                }
                else
                {
                    cout << "-" << x << "," << y << "- ";
                }
            }

        }
        cout << endl;
    }
}

void playerGuess()
{

    int guessX, guessY;

    bool goodInput = false;

    cout << endl;
    do {
        cout << guesses << " guesses left. " << endl;

        //get X pick
        cout << "X: ";
        cin >> guessX;
        if (guessX < 0 || guessX>2)
        {
            goodInput = false;
            cin.clear();
            cin.ignore(256, '\n');
            cout << "Out of Range!" << endl;
            //display grid again with X's on board where guessed
            break;
        }
        else
        {
            goodInput = true;
        }

        //get Y pick
        cout << "Y: ";
        cin >> guessY;
        if (guessY < 0 || guessY>2)
        {
            goodInput = false;
            cin.clear();
            cin.ignore(256, '\n');
            cout << "Out of Range!" << endl;
            //display grid again with X's on board where guessed
            break;
        }
        else
        {
            goodInput = true;
        }

        displayGrid(guessX, guessY);
        cout << endl;
        guesses--;

    } while (!goodInput);

    //if guessed right
    if (guessX == subX && guessY == subY)
    {
        hasWon = true;
        winScreen();
    }
}

void main()
{
    srand(time(NULL));
    cout << "BATTLE-SHIP 2000" << endl << endl;
    int board[ROW][COL];

    generateGrid();
    generateSubCoords();

    do
    {
        if (hasWon)
        {
            break;
        }

        playerGuess();
    } while (guesses > 0);

    //if lost
    if (!hasWon)
        cout << "Sorry, you lost. :(" << endl;

    cout << "The sub was located at -" << subX << "," << subY << "-." << endl;
}

I really feel like I'm overcomplicating things. I feel like I overuse do whiles and I should try to use a catch and throw option or something a little more creative. Any suggestions would be appreciated.


texts:
Any suggestions or comments? Is my style any good?

Initially I struggled with this problem as I found that using the "+=" operator gave the wrong results. I also tried a while loop the first time which was a baaaad idea. But what actually worked was using a static accumulator variable.

#include <stdio.h>

static unsigned long total;

int main(void)
{

  total = 0;

  for(unsigned int i = 1; i < 334; i++){

     total  = total + (3*i);

  }

  for(unsigned int j = 1; j < 1000; j++){

    if(j%5==0 && j%3!=0){

      total  = total + j;

    }else{

      total = total + 0;

    }

  }

  printf("Project Euler problem 1 solution = ");
  printf("%lu \n", total);

  return 0;
}

Ref: Euler 1: Multiples of 3 and 5


texts: Handling a WordPress form with multiple checkboxes

texts:
if (isset($_POST["save-options"])) {

    foreach ($names_of_array as $type => $value) {

        update_option('updated_img', $_POST['show_img_url']);

        if (isset($_POST["post0"])) {

            update_option($names_of_array[0], true);
        } else {

            update_option($names_of_array[0], false);
        }

        if (isset($_POST["post1"])) {

            update_option($names_of_array[1], true);
        } else {

            update_option($names_of_array[1], false);
        }

        if (isset($_POST["post2"])) {

            update_option($names_of_array[2], true);
        } else {

            update_option($names_of_array[2], false);
        }

        if (isset($_POST["post3"])) {

            update_option($names_of_array[3], true);
        } else {

            update_option($names_of_array[3], false);
        }
        if (isset($_POST["post4"])) {

            update_option($names_of_array[4], true);
        } else {

            update_option($names_of_array[4], false);
        }
    }
}

HTML table is in form>>>>

                <input name="post0"  value="<?php echo $names_of_array; ?>"  type="checkbox" <?php echo (get_option("show_price") == true ? 'checked' : ''); ?>   >
                <input name="post1" value="<?php echo $names_of_array; ?>"  type="checkbox" <?php echo (get_option("show_width") == true ? 'checked' : ''); ?> >
                <input name="post2" value="<?php echo $names_of_array; ?>"  type="checkbox" <?php echo (get_option("show_height") == true ? 'checked' : ''); ?> >
                <input name="post3" value="<?php echo $names_of_array; ?>"  type="checkbox" <?php echo (get_option("show_weight") == true ? 'checked' : ''); ?> >
                <input name="post4" value="<?php echo $names_of_array; ?>"  type="checkbox" <?php echo (get_option("show_color") == true ? 'checked' : ''); ?> >
                <input name="updated_img"  type="button" id="insert-my-media" class="media-button button"  value="Add my media">
                <input name="show_img_url" type="text" class="next-button" id="set_imaged_id" value="<?php echo $_POST['show_img_url']; ?>" >


texts: How can I simplify this JQuery validation process?

texts:
How can I simplify this functioning JQuery validation process:
class UserEdit {
  addUser(uobj) {
    if(uobj.adduser == "" && uobj.addfullname == "" && uobj.addemail == "" && uobj.addlevel == "")
    {
        $('#adduserError').show();
        $('#addfullnameError').show();
        $('#addemailError').show();
        $('#adduserlevelError').show();
        return false;
    }
    if(uobj.adduser == "")
    {
        $('#adduserError').show();
        return false;
    }
    if(uobj.addfullname == "")
    {
        $('#addfullnameError').show();
        return false;
    }
    if(uobj.addemail == "" || (uobj.addemail.indexOf("@",0)) == -1 || (uobj.addemail.indexOf(".",0)) == -1 ||  uobj.addemail.length < 6)
    {
        $('#addemailError').show();
        return false;
    }
    else
    {
      $('#loadingDiv').show();
      $.post('process/editUser.php', {uobj:uobj}, function(data)
      {
        var modal = "#addUserModal";
        $('#loadingDiv').hide();
        dataCheck(data, modal);
      });
    }
  }
}

All of the above works as it should.  I just know there must be a way to simplify it.
Note (because I believe someone will ask):  I use the dataCheck function to check the data returned from the PHP process, and then close the modal if the process was successful.  There are a couple of other modules within the class that use the same dataCheck function.  That was my initial attempt to at least simplify how to handle the return data in each module.
Now I want to try to simply the code above.  Any help is appreciated.


texts:
I need to get a table from an Excel worksheet.  Sometimes I know the worksheet that contains the table, other times I might know it's going to be in one of a handful of worksheets, and still other times I might not even know what workbook it's in.

To me, this seemed like a good place to use an overloads function. What I did was create the following overloaded function which recursively calls itself to dig down into each "level" of the input object's hierarchy so that it allows me to look for the table using a variety of input objects.

I'd like to get some feedback on this solution; is it acceptable practice? Is this a good use of overloading?  Is there a better (more practical, more efficient, etc.) way to do it?

Note 1: I've omitted class members not related to this question.

Note 2:  I haven't gotten deep enough into debugging to add any specific error handling to the try/catch structure, but I do plan to add more specific "catches" eventually.

Imports Microsoft.Office
Imports Microsoft.Office.Interop.Excel
Imports System.Windows.Forms
Imports System.Runtime.InteropServices

Public Class MyExcel
    Public Overloads Function GetTable(ByVal SearchName As String, ByVal SearchSheets() As Worksheet, Optional ByVal ExactMatch As Boolean = False) As ListObject
        If Not ExactMatch Then SearchName = "*" & SearchName & "*"
        Try
            For Each ws As Worksheet In SearchSheets
                For Each lo As ListObject In ws.ListObjects
                    If lo.Name Like SearchName Then Return lo
                Next
            Next
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return Nothing
    End Function
    Public Overloads Function GetTable(ByVal SearchName As String, ByVal SearchBooks() As Workbook, Optional ByVal ExactMatch As Boolean = False) As ListObject
        Dim loFound As ListObject
        Dim wsList As New List(Of Worksheet)
        Try
            For Each wb In SearchBooks
                For Each ws In wb.Worksheets
                    wsList.Add(ws)
                Next
                loFound = Me.GetTable(SearchName:=SearchName, SearchSheets:=wsList.ToArray, ExactMatch:=ExactMatch)
                If Not loFound Is Nothing Then Return loFound
            Next
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return Nothing
    End Function
    Public Overloads Function GetTable(ByVal SearchName As String, ByVal SearchApps() As Microsoft.Office.Interop.Excel.Application, Optional ByVal ExactMatch As Boolean = False) As ListObject
        Dim loFound As ListObject
        Dim wbList As New List(Of Workbook)
        Try
            For Each app In SearchApps
                For Each wb In app.Workbooks
                    wbList.Add(wb)
                Next
                loFound = Me.GetTable(SearchName:=SearchName, SearchBooks:=wbList.ToArray, ExactMatch:=ExactMatch)
                If Not loFound Is Nothing Then Return loFound
            Next
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return Nothing
    End Function
End Class


texts: Setting the path to toolbarAssociatedXibName, with fallback

texts:
I have some code that I've included in a project I want to release.  Here is one such block:

NSString *path = nil;
if (delegate && [delegate respondsToSelector:@selector(toolbarAssociatedXibName:)]) {
    path = [delegate toolbarAssociatedXibName:_toolbar];
    if (![[NSBundle mainBundle] pathForResource:path ofType:@"nib"]) {
        IFLog(@"Delegate responded with an invalid value (%@) for `toolbarAssociatedXibName:`. Attempting default value (%@).", path, _identifier);
        path = _identifier;
    }
} else {
    path = _identifier;
}

The equivalent pseudocode:

Variable declaration (set to null value)
If there is an option to set the variable to a custom value
    Set it to that custom value
    If the value is not valid
        Log the error
        Set the value to a specified default
Otherwise
    Set the value to a specified default

Is it possible to shorten/compact this block of code?  I have also tried combining this block into a single line of code, ending up with this:

(delegate && [delegate respondsToSelector:@selector(toolbarAssociatedXibName:)] ? !![[NSBundle mainBundle] pathForResource:[delegate toolbarAssociatedXibName:_toolbar] ofType:@"nib"] ? path = [delegate toolbarAssociatedXibName:_toolbar] : IFLog(@"Delegate responded with an invalid value (%@) for `toolbarAssociatedXibName:`. Attempting default value (%@).", [delegate toolbarAssociatedXibName:_toolbar], _identifier), path = _identifier : path = _identifier);

That does absolutely nothing for readability.  Any suggestions?


texts:
The following code is my solution for the following Daily Coding Challenge

  Given an array of numbers, find the maximum sum of any contiguous
  subarray of the array.

  For example, given the array [34, -50, 42, 14, -5, 86], the maximum
  sum would be 137, since we would take elements 42, 14, -5, and 86.

  Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we
  would not take any elements.

  Do this in O(N) time.

I think this is done in O(N) time and is the best solution. If someone can think of a better way, I would be interested.

array = [4, -2, 7, -9]
running_sum = 0
for i in range(1,len(array)):
    if array[i-1] > 0:
        array[i] = array[i] + array[i-1]
    else:
        array[i-1] = 0
print(max(array))


texts: Improving PHP MVC code for personal website

texts:
Github for project: https://github.com/wrpd/portfolio

I have a very general understanding of MVC but haven't ever implemented it. In an effort to improve my understanding and get back into a little bit of web development I started watching and reading some tutorials and started to implement a basic MVC to redesign my personal website on.

I'm looking for critique on my current code. How can I make it more elegant?
What am I misunderstanding about MVC basics? Can I make things functionally more concise (In the code itself. For variable names and such I'm keeping it purposely verbose to aid in understanding for myself)?

Specifically, I'm wondering if my project structure is okay and how to better handle routing and initializing? My routes are currently set with a routing class like so:

<?php

router::set_route('/', function(){

    index_controller::create_view('index');

});

router::set_route('/about', function(){

    about_controller::create_view('about');

});

router::set_route('/projects', function(){

    projects_controller::create_view('projects');

});

router::set_route('/contact', function(){

    contact_controller::create_view('contact');

});

?>

Is this an optimal way of routing to my pages?

My init is currently autoloading my classes and requiring my routes. Like so:

<?php

function autoload($class_name){

    if (file_exists('./app/core/classes/'. $class_name . '.php')){

        include './app/core/classes/'. $class_name . '.php';

    } else if (file_exists('./app/controllers/' . $class_name . '.php')){

        include './app/controllers/' . $class_name . '.php';

    } else if (file_exists('./app/models/' . $class_name . '.php')){

        include './app/models/' . $class_name . '.php';

    }
}

spl_autoload_register(autoload);

require_once './app/core/routes/routes.php';
?>

Should it be a class that I instantiate in index.php or is that sufficient? I like that index.php can just contain

require_once '/path/to/init.php'

but I don't know if that's the best practice.

Essentially, I'd like to make the foundation for my personal site as solid as I can while following best practice. I've seen a lot of code examples and samples but some are quite dated and my depth of knowledge isn't deep enough to know if I'm doing things the best way that I can.


texts:
I solved this question in Swift, but was wondering if there is a better way or if my code can be improved:

  Given a 6x6 2D Array:

1 1 1 0 0 0

0 1 0 0 0 0

1 1 1 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

  We define an hourglass in to be a subset of values with indices
  falling in this pattern in's graphical representation:

a b c

   d

e f g

  There are hourglasses in, and an hourglass sum is the sum of an hourglass' values.

import Foundation

var inputAsArray = [Int]()
for _ in 0...5 {
    inputAsArray += readLine()!.componentsSeparatedByString(" ").map{ Int($0)! }
}
//var inputAsArray = [
//    1, 1, 1, 0, 0, 0,
//    0, 1, 0, 0, 0, 0,
//    1, 1, 1, 0, 0, 0,
//    0, 9, 2, -4, -4, 0,
//    0, 0, 0, -2, 0, 0,
//    0, 0, -1, -2, -4, 0
//]

// method creates all possible "hourglasses" and returns a nested array of hourglasses
typealias hourglass = [Int]
private func hourGlasses(input: [Int]) -> [hourglass] {
    var hourglasses = [hourglass]() // initializes hourglass to hold array of hourglass
    for index in 0..<22 { // there are 36 indexes (6x6) but we +14 in the loop below when creating the hourglass so we only need to go up to 24. We can't make hourglass with 23 and 24, so we go up to 22
        guard [4,5,10,11,16,17].indexOf(index) == nil else {continue} // continue to next iteration because we can't create hourglass with the last 2 indexes from the right wall
        hourglasses.append([ // creates the hourglass array
                input[index], input[index+1], input[index+2],
                                        input[index+7],
            input[index+12], input[index+13], input[index+14],
            ])
    }
    return hourglasses
}

// method takes in array of input and sends it to hourGlasses to make a nested array. Then it finds the largest sum by using reduce over the nested array
private func maxHourglassSum(input: [Int]) -> Int {
    let hourglasses: [hourglass] = hourGlasses(input)
    // reduce the nested arrays to get sum in each. then compare that sum to maxSum
    var maxSum = Int?() // set to optional instead of 0 because all numbers in input can be negative
    for singleHourglass in hourglasses {
        let singleHourglassSum = singleHourglass.reduce(0, combine: +) // reduce adds up sum for a single hourglass
        if maxSum == nil || singleHourglassSum > maxSum {
            maxSum = singleHourglassSum
        }
    }
    return maxSum!
}

print(maxHourglassSum(inputAsArray))


texts: Building a Map of Set using Java Streams

texts:
I wrote a collector that would take a stream of Map.Entry<Integer, MyObject> which I want to make into Map<Integer, Set<MyObject>>

import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
class MyObject {

}
class Main {
  public static void main(String[] args) {
    Map<Integer, Set<MyObject>> collected = Stream.of(
       Map.entry(123, new MyObject()),
       Map.entry(123, new MyObject()),
       Map.entry(234, new MyObject()),
       Map.entry(345, new MyObject())
    )
    .collect(
      ConcurrentHashMap<Integer, Set<MyObject>>::new,
      (map, entry) -> {
        map.computeIfAbsent(
          entry.getKey(),
          k -> new HashSet<MyObject>()
        )
        .add(entry.getValue());
      },
      (map1, map2) -> {
        map2.forEach((map2Key, map2Object) -> {
          final Set<MyObject> objects =
            map1.computeIfAbsent(map2Key, k -> new HashSet<MyObject>());
          objects.addAll(map2Object);
        });
      }
    );
    System.out.println(collected);
  }
}

I was wondering if there's a built in way of doing this, as it seems to be a common thing to do.

One way I can refactor this is to move the collector out to a different class like so:

class EntryToMapCollector<K, V> implements Collector<Map.Entry<K, V>, Map<K, Collection<V>>, Map<K, Collection<V>>> {
    @Override
    public Supplier<Map<K, Collection<V>>> supplier() {
        return ConcurrentHashMap<K, Collection<V>>::new;
    }

    @Override
    public BiConsumer<Map<K, Collection<V>>, Map.Entry<K, V>> accumulator() {
        return (map, entry) -> {
            map.computeIfAbsent(entry.getKey(), k -> new HashSet<V>())
                .add(entry.getValue());
        };
    }

    @Override
    public BinaryOperator<Map<K, Collection<V>>> combiner() {
        return (map1, map2) -> {
            final Map<K, Collection<V>> combined = new ConcurrentHashMap<>(map1);
            map2.forEach((map2Key, map2Observations) -> {
                combined.computeIfAbsent(map2Key, k -> new HashSet<V>())
                    .addAll(map2Observations);
            });
            return combined;
        };
    }

    @Override
    public Function<Map<K, Collection<V>>, Map<K, Collection<V>>> finisher() {
        return m -> m;
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Set.of(Characteristics.CONCURRENT, Characteristics.UNORDERED);
    }
}

and replace the call with .collect(new EntryToMapCollector<Integer, MyObject>());

https://repl.it/@trajano/ForkedSpryRobot


texts:
In the following answer, @Incomputable basically dared me to implement a generalization of std::minmax_element.

  Have you thought about creating a search function that finds N elements based on N predicates, and return an std::array with the iterators to found elements? I just believe that std::minmax_element can be generalized.

I'm happy to oblige:

#include <array>

template<typename IteT, typename... PredsT>
auto multi_search_elements(IteT begin, IteT end, PredsT const&... preds) {
    const std::size_t count = sizeof...(PredsT);
    std::array<IteT, count> selected;

    selected.fill(begin);
    if(begin != end) {
      for(++begin; begin != end; ++begin) {
        std::size_t i = 0;
        ( (selected[i] = preds(*selected[i], *begin) ? selected[i] : begin,
           ++i), ...);
      }
    }

  return selected;
}

Usage:

#include <iostream>
#include <vector>
#include <functional>

int main() {
  std::vector<int> vals = {1,2,3,4,5};

  auto found = multi_search_elements(vals.begin(), vals.end(), std::less<int>(), std::greater<int>());

  for(auto i : found) {
    std::cout << *i << std::endl;
  }
  return 0;
}

Edit: I understand this fold expression might look like voodoo to people who are not used to that type of code, so I'll elaborate on what's going on here for those of you who are curious:

The fold expression looks like this: (EXPR, ...), which will expand to EXPR, EXPR, EXPR, etc..., where the "binary" operator used is actually the comma operator, which effectively just sequences the expressions while leaving them unrelated.

After that, all I do is make EXPR be SUB_EXPR, ++i, so the whole thing expands as:

(SUB_EXPR, ++i), (SUB_EXPR, ++i), (SUB_EXPR, ++i), (SUB_EXPR, ++i), ...

Which is essentially:

selected[i] = preds_0(*selected[i], *begin) ? selected[i] : begin,
++i,
selected[i] = preds_1(*selected[i], *begin) ? selected[i] : begin,
++i,
selected[i] = preds_2(*selected[i], *begin) ? selected[i] : begin,
++i,
selected[i] = preds_3(*selected[i], *begin) ? selected[i] : begin,
++i


texts:
I am writing a simple wrapper around fetch.
async function apiCall(
  endpoint: string,
  {
    data,
    headers: customHeaders,
    ...customConfig
  }: { data?: Object; headers?: Object } = {}
) {
  const config = {
    method: data ? 'POST' : 'GET',
    body: data ? JSON.stringify(data) : undefined,
    headers: {
      'content-type': data ? 'application/json' : undefined,
      ...customHeaders,
    },
    ...customConfig,
  }

  return fetch(endpoint, config as any).then(async (response) => {
    if (response.ok) {
      const json = await response.json() //
      return json
    } else {
    //   what if `response` contains error messages in json format?
      return Promise.reject(new Error('Unknown Error'))
    }
  })
}

It works fine. The problem is with this snippet:
 return fetch(endpoint, config as any).then(async (response) => {
    if (response.ok) {
      const json = await response.json()
      return json
    } else {
    //   what if `response` contains error messages in json format?
      return Promise.reject(new Error('Unknown Error'))
    }
  })

If response is not ok, it rejects with a generic Error. This is because by default, window.fetch will only reject a promise if the actual network request failed. But the issue is that, even if response is not ok, it might still be able to have error messages in json format. This depends on the backend implementation details but sometimes you are able to get the error messages in the response body by response.json(). Now this use case is not covered in the wrapper I built.
So I wonder how I am going to be able to account for that? I guess you can do something like
fetch(endpoint, config as any).then(async (response) => {
      if (response.ok) {
        const json = await response.json()
        return json
      } else {
          try {
            const json = await response.json()
            return Promise.reject(json)
          } catch {
            return Promise.reject(new Error('Unknown Error'))
          }
      }
    })

I wonder if there is some more elegant way to do that?
Lastly, I am very aware of libraries like Axios. I built this partly to satisfy my intellectual curiosity.
By the way, a lightly unrelated question but I wonder if the following snippets are equivalent?
 if (response.ok) {
        const json = await response.json()
        return json
      }

 if (response.ok) {
        return response.json()
      }


texts:
Recently, I worked on one of the Codility Training - Genomic Range Query (please refer to one of the evaluation report for the detail of the task.

The solution in Python is based on prefix sum, and was adjust in accordance to this article.

import copy

def solution(S, P, Q):
    length_s = len(S)
    length_q = len(Q)

    char2digit_dict = {'A':1, 'C':2, 'G':3, 'T':4}
    str2num = [0]*length_s

    count_appearances = [[0, 0, 0, 0]]*(length_s+1)
    cur_count = [0, 0, 0, 0]

    for i in range(0, length_s):
        str2num[i] = char2digit_dict[S[i]]

        cur_count[str2num[i]-1] += 1
        count_appearances[i+1] = copy.deepcopy(cur_count)

    results = []
    for i in range(0, length_q):
        if Q[i] == P[i]:
            results.append(str2num[Q[i]])

        elif count_appearances[Q[i]+1][0] > count_appearances[P[i]][0]:
            results.append(1)
        elif count_appearances[Q[i]+1][1] > count_appearances[P[i]][1]:
            results.append(2)
        elif count_appearances[Q[i]+1][2] > count_appearances[P[i]][2]:
            results.append(3)
        elif count_appearances[Q[i]+1][3] > count_appearances[P[i]][3]:
            results.append(4)

    return results

However, the evaluation report said that it exceeds the time limit for large-scale testing case (the report link is above).

The detected time complexity is \$O(M * N)\$ instead of \$O(M + N)\$. But in my view, it should be \$O(M + N)\$ since I ran a loop for \$N\$ and \$M\$ independently (\$N\$ for calculating the prefix sum and \$M\$ for getting the answer).

Could anyone help me to figure out what the problem is for my solution? I get stuck for a long time. Any performance improvement trick or advice will be appreciated.


texts: Client-server application for logging running processes

texts:
My first client-server application. It's a simple Python script that gets a list of running processes from Server_1 and writes it to a datetime-named file on Server_2, every 5 seconds.
I am planning on refactoring this code into one or two functions, maybe one for securing the connection and one for implementing the logic.
I also know nothing about security best-practices, and I'm looking for some pointers. Any feedback on any aspect of the code is welcome.

import os
import paramiko
from time import sleep
from datetime import datetime

SERVER_1 = os.getenv('HOST_1') or ""
SERVER_1_PASS = os.getenv('PASS_1') or ""
SERVER_2 = os.getenv('HOST_2') or ""
SERVER_2_PASS = os.getenv('PASS_2') or ""

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(SERVER_1, username='root', password=SERVER_1_PASS)

ssh2 = paramiko.SSHClient()
ssh2.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh2.connect(SERVER_2, username='root', password=SERVER_2_PASS)

while True:

    now = datetime.now()
    dt_string = now.strftime("%d-%m-%YT%H:%M:%S")

    stdin, stdout, stderr = ssh.exec_command("ps -aux")

    processes = stdout.readlines()
    output = [line.strip() for line in processes]

    ftp = ssh2.open_sftp()
    try:
        file = ftp.file(dt_string, "a", -1)
        file.write('\n'.join(output))
        file.flush()
        ftp.close()
    except IOError as e:
        print("Could not write to file")
        print(e)

    sleep(5)
```


texts:
DIVSUM - Divisor Summation
  #number-theory
  Given a natural number n (1 <= n <= 500000), please output the summation of all its proper divisors.

  Definition: A proper divisor of a natural number is the divisor that is strictly less than the number.

  e.g. number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22.

  Input

  An integer stating the number of test cases (equal to about 200000), and that many lines follow, each containing one integer between 1 and 500000 inclusive.

  Output

  One integer each line: the divisor summation of the integer given respectively.

Example

Sample Input:

  3
  2
  10
  20

Sample Output:

  1
  8
  22

code:-

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        BufferedReader BR=new BufferedReader(new    InputStreamReader(System.in));
    int t,i,j;
    t=Integer.parseInt(BR.readLine());
    int a[]=new int [t];
    int sum[]=new int [t];
    for(i=0;i<t;i++)
    {
        a[i]=Integer.parseInt(BR.readLine());
        sum[i]=0;
        for(j=1;j<a[i];j++)
        {
            if(a[i]%j==0)
            sum[i]+=a[j];
        }

   }

    for(i=0;i<t;i++)
    {
        System.out.println(sum[i]);
    }
    }
}

I am getting time limit exceeded error for this program from SPOJ.  How do I avoid it?


texts:
I am working on a Java textbook chapter on recursion, and I am to implement an Eight Queens solution using recursion.  Though I know that I am to post working code in Code Review, I do believe this code would work if I didn't run out of memory.  I have walked through the debugger, and the queens seem to adjust position exactly like they should until there is a Stack Overflow.

My question really is this:  After running into this Stack Overflow issue, my instincts are to either find a way to increase Stack memory (I have not found a way to do this) or reduce Stack memory usage.  To reduce Stack memory usage, I do wonder if there might be a way to put some of the weight of the recursion on the heap instead.  The most likely way to reduce Stack memory usage would likely be some clever refactoring, which is why I am posting in Code Review.  What I feel the best answer for this is, is just to ditch as much recursion as I can, but if I am to follow the exercise instructions, I don't have that option.

This is what I have:

Queen.java

class Queen {
    private int row;
    private int col;
    private int qNum;

    Queen(){
        row = 0;
        col = 0;
    }

    int getRow() {
        return row;
    }

    int getCol() {
        return col;
    }

    void setQNum(int qNum){
        this.qNum = qNum;
    }

    // requires canAdvance check first
    void advance(){
        if (col == 7){
            ++row;
            col = 0;
        }
        else{
            ++col;
        }
    }
    void matchPosition(Queen previousQueen){
        if (previousQueen.getCol() == 7){
            row = previousQueen.getRow() + 1;
            col = 0;
        }
        else{
            row = previousQueen.getRow();
            col = previousQueen.getCol() + 1;
        }
    }

    boolean canAdvance(){
        return !(row == 7 && col == 7);
    }

    private boolean isAttacked(Queen attacker){
        return getRow() == attacker.getRow() ||
                getCol() == attacker.getCol() ||
                Math.abs(getRow() - attacker.getRow()) ==
                        Math.abs(getCol() - attacker.getCol());
    }

    boolean isSafe(Queen[] queens){
        for(int attIndex = 0; attIndex < qNum; ++attIndex){
            if(this.isAttacked(queens[attIndex])){
                return false;
            }
        }
        return true;
    }
}

Main.java

class Main{
    public static void main(String[] args){
        Queen[] queenArr = {
                new Queen(),
                new Queen(),
                new Queen(),
                new Queen(),
                new Queen(),
                new Queen(),
                new Queen(),
                new Queen()
        };

        // Storing array index numbers allow the code to be more readable.
        for(int i = 0; i < 8; ++i){
            queenArr[i].setQNum(i);
        }

        placeQueen(queenArr, 1);
        for(Queen queen : queenArr){
            System.out.printf("row = %d  col = %d%n", queen.getRow(), queen.getCol());
        }
    }

    private static void placeQueen(Queen[] queens, int index){
        if (queens[index].canAdvance()){
            queens[index].advance();
        }
        else{
            while(index > 0 && !queens[index].canAdvance()){
                --index;
            }
            placeQueen(queens, index);
        }

        if (queens[index].isSafe(queens)){
            if (index == 7){
                return;
            }
            else{
                // next queen is set to position of current queen
                queens[index + 1].matchPosition(queens[index]);
                ++index;
            }
        }
        placeQueen(queens, index);
    }
}


texts: Should I use unnamed or named functions?

texts:
I am using jQuery 1.7.2

I have two ways of writing the same code. One way seems more verbose and the other seems more flexible. Is this the only difference? Is there any performance difference? Is there a better way of writing these?

Code sample #1 uses two named functions so they are reusable. It's a bit more code.

Code sample #2 uses two unnamed functions that work only on the hover method. It's less code but not reusable.

Any thoughts or comments?

//  CODE SAMPLE #1

// IPP FUNCTIONS
var openIPP = function openIPP() {
    $IPPNonDefault.stop().animate({"height": OpenHeight}, DownRate);
}
var closeIPP = function closeIPP() {
    $IPPNonDefault.stop().animate({"height": "0px"}, UpRate);
}

// IPP ACTIONS
$IPPWrapper.mouseover(openIPP).mouseout(closeIPP);

//  CODE SAMPLE #2

$IPPWrapper.hover(
    function() {
        $IPPNonDefault.stop().animate({"height": OpenHeight}, DownRate);
    },
    function() {
        $IPPNonDefault.stop().animate({"height": "0px"}, UpRate);
    }
);


texts: Getting rid of extra test during initialization of loop/recursion

texts:
I'm reluctant to ask this question.  My code below works, it's intelligible, and it seems reasonably efficient.  It's just that there's a trivial, nitpicky issue that's driving me crazy.  The function maxes below collects all elements of a sequence that are "maximum" according to some criterion.

;; Example of use of maxes
;; Collect all maps with the maximum value for `:a`:
(maxes :a [{:a 1 :b 2} {:a 4 :b 5} {:a 5 :b 5} {:b 3 :a 5}])
;;=> [{:b 5, :a 5} {:b 3, :a 5}]

(defn- maxes-helper
  "Helper function for maxes."
  [f s best-val collected]
  (if (empty? s)
    collected
    (let [new-elt (first s)
          new-val (f new-elt)]
      (cond (== new-val best-val) (recur f (rest s) best-val (conj collected new-elt))
            (>  new-val best-val) (recur f (rest s) new-val  [new-elt])
            :else                 (recur f (rest s) best-val collected)))))

(defn maxes
  "Returns a sequence of elements from s, each with the maximum value of (f element)."
  [f s]
  (if (empty? s)
    nil
    (let [new-elt (first s)
          new-val (f new-elt)]
      (maxes-helper f (rest s) new-val [new-elt]))))

What's really bugging me that I have to test for emptiness of the input collection s both in the top-level function and in the tail-recursive helper function.  I also want to add a custom exception when (f new-elt) is non-numeric, and so I need to test that twice, both for new-val and for first call to (f new-elt) that becomes the first best. So I've got a trivial amount of duplication of code, and I keep thinking that there must be a way to get rid of the duplication.  But I can't see how to do this (without testing that best is numeric on every iteration).  Am I missing something obvious (or non-obvious)?

(BTW I wrote another version using reduce, but it's about twice as slow, according to Criterium.)


texts: Calculating the total sum of inversion count for all subarrays

texts:
My approach was to visit all inversion count pair and count how many subarrays these pair contribute. Visiting every pair requires \$\mathcal{O}(n^2)\$ time, but I want an optimized version of this, something like \$\mathcal{O}(n \log n)\$.

Can I do something with the Fenwick tree?
Inversion in an array
Fenwick tree

e.g.  if arr = [1,3,4,2] , then total inversion count for all subarrays = 5.

number = int(input("Input number := "))
main_list = list(map(int,input().split()))
answer = 0
for i in range(number):
    for j in range(number):
        if i<j and main_list[i]>main_list[j]:
            k = (i+1) * (number-j)
            answer += k
print(answer)


texts:
I'm implementing a login script and I want it to be more secure:

function sec_session_start() {
        $session_name = 'sec_session_id';   // Set a custom session name
        $secure = SECURE;
        // This stops JavaScript being able to access the session id.
        $httponly = true;
        // Forces sessions to only use cookies.
        if (ini_set('session.use_only_cookies', 1) === FALSE) {
            //header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
            exit();
        }
        // Gets current cookies params.
        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
        // Sets the session name to the one set above.
        session_name($session_name);
        session_start();            // Start the PHP session
        session_regenerate_id();    // regenerated the session, delete the old one.
    }

    function  checkIp($mysqli) {
        if(isset($_SESSION['user_id'])){
            $user_id = $_SESSION['user_id'];
            $user_ip = $_SERVER['REMOTE_ADDR'];
            $user_browser = $_SERVER['HTTP_USER_AGENT'];

            if($stmt === $mysqli->prepare("SELECT UserIP, BrowserInfo FROM users WHERE UserID = ? LIMIT 1")){
                $stmt->bind_param('i', $user_id);
                $stmt->execute();
                $stmt->store_result();

                if($stmt->num_rows == 1){
                    $stmt->bind_result($db_ip,$db_browser);
                    $stmt->fetch();

                    if($user_ip == $db_ip && $user_browser == $db_browser){
                        return true;
                    }else{
                        return false;
                    }
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

Are these functions secure enough to prevent session hijacking? If they are not, what can I do to make them secure enough?


texts:
I have the solution for the problem, but it is taking me 7 seconds to run on a large dataset. I am trying figure out a better way of doing this. It has to run in under 3 seconds.

Problem Statement:

There are N plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any plant has more pesticide than the plant at its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each plant. Print the number of days after which no plant dies, i.e. the time after which there are no plants with more pesticide content than the plant to their left.

Explanation:

Initially all plants are alive.

Plants = \$\{(6,1), (5,2), (8,3), (4,4), (7,5), (10,6), (9,7)\}\$
Plant = \$(i,j)\$ \$\Rightarrow\$ \$j\$th plant has pesticide amount \$i\$.
After the 1st day, 4 plants remain as plants 3, 5, and 6 die.
Plants = \$\{(6,1), (5,2), (4,4), (9,7)\}\$
After the 2nd day, 3 plants survive as plant 7 dies.
Plants = \$\{(6,1), (5,2), (4,4)\}\$
After the 3rd day, 3 plants survive and no more plants die.
Plants = \$\{(6,1), (5,2), (4,4)\}\$

I added the test case to this Pastebin.

static void Main(string[] args)
{
    Stopwatch timer = new Stopwatch();
    timer.Start();
    string data = "";// Console.ReadLine(); //"6 5 8 4 7 10 9";

    foreach (var line in File.ReadLines(@"FilePath"))
    {
        data = line;
    }

    bool happyState = false;
    bool plantDied = false;
    int numberOfDays = 0;

    LinkedList<int> lstPlants = new LinkedList<int>(data.Split(new char[] { ' ', '\t' }).Select(s => int.Parse(s)).ToList());

    LinkedListNode<int> lastNode = lstPlants.Last;
    LinkedListNode<int> currentNode = lstPlants.First;
    int cValue = currentNode.Value;

    while (!happyState)
    {
        numberOfDays++;
        plantDied = false;
        happyState = false;
        lastNode = lstPlants.Last;
        currentNode = lstPlants.First;
        cValue = currentNode.Value; //bug fix
        while (currentNode != lstPlants.Last)
        {
            if (currentNode.Next.Value > cValue)
            {
                plantDied = true;

                cValue = currentNode.Next.Value;
                lstPlants.Remove(currentNode.Next);
                //currentNode = currentNode.Next;
            }
            else
            {
                currentNode = currentNode.Next;
                cValue = currentNode.Value;
            }
        }

        if (!plantDied)
        {
            numberOfDays--;
            happyState = true;
        }

    }
    timer.Stop();
    Console.WriteLine("Time taken to calculate is {0} seconds and the answer is {1}.", timer.Elapsed.TotalSeconds, numberOfDays);
    Console.ReadLine();
}


texts:
In my program below I am getting the parent node game 1 and then removing one of the two child nodes, depending on which one is clicked. I currently have two event listeners, with two separate functions for removing one child vs the other. It doesn't feel very dry to me, and I think I could benefit from having someone skilled in JS take a look at this and show me how this could be more easily accomplished.

var firstWinner = document.getElementById('game1');

function removefirst() {
    firstWinner.removeChild(firstWinner.childNodes[0]);
}

function removeSecond() {
    firstWinner.removeChild(firstWinner.childNodes[1]);
}

var gameOneNodes = document.getElementById('game1').childNodes;
gameOneNodes[1].addEventListener('click', removefirst, false)
gameOneNodes[0].addEventListener('click', removeSecond, false)


texts: Node.js HTTP server with request logging

texts:
Here is the code:

var http = require("http");
var fs = require("fs");
var path = require("path");
var ip = require("request-ip");

var hostname = "localhost";
var port = 3001;

const logs = {};

http.createServer ( function(req, res) {

    addLog(req);

    console.clear();
    console.log(logsToString());

    if (req.method.toLowerCase() === "get"){
        if (req.url === "/"){
            pipeToRes(res,200,  "text/html", "./public/index.html", "utf-8");
        } else if (req.url.match(/.css$/)){
            pipeToRes(res, 200, "text/css", path.join(__dirname, "public", req.url), "utf-8");
        } else if (req.url.match(/.js$/)){
            pipeToRes(res, 200, "application/javascript", path.join(__dirname, "public", req.url), "utf-8");
        } else if (req.url.match(/.ttf$/)){
            pipeToRes(res, 200, "application/octet-stream", path.join(__dirname, "public", req.url), "");
        } else if (req.url.match(/.ico$/)){
            pipeToRes(res, 200, "image/ico", path.join(__dirname, "public", req.url), "");
        } else {
            fillRes(res, 404, "text/plain", "404: File Not Found");
        }
    } else{
        let body = [];

        req.on("data", function(chunk){
            body.push(chunk);
        });
        req.on("end", function(){
            body = Buffer.concat(body).toString();
            fillRes(res, 405, "text/plain", `Request Body: ${body}\n\n `+"405: Method Not Allowed: This server \
            does not require any information from you, but only responds to GET requests by serving back to \
            the client the web files (HTML, CSS, JS, Image Files, icons, Videos, e.t.c..) to view them on the \
            browser.");
        });

    }

}).listen(port);

console.log(`Server ${hostname} is listening on port ${port}`);

function addLog(req){
    var thisIP = ip.getClientIp(req)
    if (logs[thisIP] != undefined){
        logs[thisIP].push({"method": req.method, "url": req.url});
    } else {
        logs[thisIP] = [{"method": req.method, "url": req.url}];
    }
}

function logsToString(){
    var formatted = "----------------\nCURRENT LOGS\n----------------\n\n";

    for (var clientIp in logs){
        formatted += "\nFROM IP ("+clientIp+"):"
        var clientLogs = logs[clientIp];

        for (var i = 0; i < clientLogs.length; i++){
            var thisLog = clientLogs[i];
            formatted += "\n\t- Recieved "+thisLog["method"]+" request for "+thisLog["url"]
        }
    }

    return formatted;
}

function fillRes(res, responseCode, mimeType, data){
    res.writeHead(responseCode, {"Content-Type": mimeType});

    res.end(data);
}

function  pipeToRes(res, responseCode, mimeType, pathParam, readAs){
    res.writeHead(responseCode, {"Content-Type": mimeType});

    fs.createReadStream(pathParam, readAs).pipe(res);
}

Points I am interested in:

Is using the functions fillRes and pipeToRes a good choice rather than repeating res.writeHead ... res.end()
What about their names? The semantics of fillRes is that basically you are manipulating the response object passed to you by http.createServer, as in you are "filling" the response write stream. is something like writeResponse or writeRes better?
What do you think about the technique used to log the requests? Each time a request is received, the server checks if this specific IP has requested before and then groups all his request in a list. A dictionary called logs stores all these requests, where the IP is the key, and the value is a list of all the requests from that IP.
Anything else? What should I improve? Please remember that I am a total newbie, and all help is really honestly greatly appreciated.


texts:
Is this an acceptable use of typedef in the class, Inventory?

Inventory.h

#ifndef INVENTORY_H
#define INVENTORY_H

#include "Item.h"
#include <unordered_map>

class Inventory
{
public:
    typedef std::unordered_map<Item, int> ItemTable; ///< Items and their quantities

    const ItemTable& items() const;
    void add_item(Item item, int quantity);
    int quantity(Item item);
    bool remove_item(Item item, int quantity);

private:
    ItemTable items_;
};

#endif

Inventory.cpp

#include "Inventory.h"
#include "Item.h"
#include <cstddef>

const Inventory::ItemTable& Inventory::items() const
{
    return items_;
}

void Inventory::add_item(Item item, int quantity)
{
    int total_of_item = items_[item];
    items_[item] = total_of_item + quantity;
}

int Inventory::quantity(Item item)
{
    return items_[item];
}

bool Inventory::remove_item(Item item, int quantity)
{
    int total_of_item = items_[item];

    if (quantity > total_of_item) {
        return false;
    }

    items_[item] = total_of_item - quantity;
    return true;
}


texts: All roads lead to - project using directions in Google Maps API

texts:
I made simple javascript project that uses Google Maps API. The project is live here: https://krzysztofzuraw.github.io/all-roads-lead-to/. Source code here: https://github.com/krzysztofzuraw/all-roads-lead-to.

Flow is as follows: user enter address -> address is geocoded -> main waypoint is created -> user select start & point -> directions are displayed on map.

What I found out while developing that code starts to become a little bit messy - instead of callbacks I use promises but I started to chain them as callbacks. Is there a better way to design it? I was thinking about using RxJS here so I can hook into streams.

Code below:

const searchForm = document.querySelector('.place-search');
let map;

function initMap() {  // eslint-disable-line no-unused-vars
  map = new google.maps.Map(
    document.getElementById('map'),
    {
      zoom: 4,
      center: { lat: 52.00, lng: 21.00 },
    });

  const directionsService = new (google.maps.DirectionsService)();
  const directionsDisplay = new (google.maps.DirectionsRenderer)();
  directionsDisplay.setMap(map);

  searchForm.addEventListener('submit', (event) => {
    event.preventDefault();
    const placeValue = event.target.querySelector('[name=place]').value;
    geocodeAddress(placeValue).then((geocodedCoords) => {
      const mainWayPoint = createMainWaypoint(geocodedCoords);

      searchForm.parentElement.style.display = 'none';
      const titleText = `All roads lead to ${placeValue}`;
      document.title = titleText;

      createPoint(map).then((startingCoords) => {
        createPoint(map).then((endCoords) => {
          calculateAndDisplayRoute(
            directionsService,
            directionsDisplay,
            mainWayPoint,
            startingCoords,
            endCoords,
          );
        });
      });
    });
  });
}

function geocodeAddress(address) {
  return new Promise((resolve, reject) => {
    const geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      address,
    }, (results, status) => {
      if (status === 'OK') {
        resolve({
          lat: results[0].geometry.location.lat(),
          lng: results[0].geometry.location.lng(),
        });
      } else {
        reject('Cannot find address');
      }
    });
  });
}

function createMainWaypoint(coords) {
  map.setCenter(coords);
  return new google.maps.Marker({
    position: coords,
    map,
    title: 'Place where all roads lead',
    icon: 'compass.png',
  });
}

function createPoint(map) {
  return new Promise((resolve, reject) => {
    google.maps.event.addListenerOnce(map, 'click', (event) => {
      resolve(
        new google.maps.Marker({
          position: {
            lat: event.latLng.lat(),
            lng: event.latLng.lng(),
          },
          map,
        }),
      );
      reject(
        'Error creating point',
      );
    });
  });
}

function calculateAndDisplayRoute(service, display, wayPoint, startingPoint,     endPoint) {
  service.route({
    origin: { lat: startingPoint.position.lat(), lng:     startingPoint.position.lng() },
    destination: { lat: endPoint.position.lat(), lng: endPoint.position.lng() },
    waypoints: [{ location: wayPoint.position }],
    travelMode: 'DRIVING',
  }, (response, status) => {
    if (status === 'OK') {
      display.setDirections(response);
    } else {
      alert('Route not found!');
    }
  });
}


texts:
In my initial problem posted on SO, whenever anyone accessed the Mail.php on the server, it used to send an empty email to the $to. To avoid this I came up with a solution.
require 'PHPMailer/PHPMailerAutoload.php';

    $yourName = $_POST['yourName'];
    $sender  = $_POST['emailID'];
    $subject  = $_POST['subject'];
    $message  = $_POST['message'];
    $to = 'email@email.com';

        if(empty($yourName) || empty($sender) || empty($subject) || empty($message) || empty($message))
        {
            echo "Fields are empty";
        }
        else
        {
                $mail = new PHPMailer;
                //$mail->SMTPDebug = 2;
                $mail->isSMTP();
                $mail->Host = 'smtp.gmail.com';
                $mail->SMTPAuth = true;
                $mail->Username = 'gmailUser';
                $mail->Password = 'gmailPassword';
                $mail->SMTPSecure = 'tls';
                $mail->Port = 587;

                $mail->setFrom($sender,$yourName);
                $mail->addAddress($to);
                $mail->addReplyTo($sender);

                $mail->isHTML(true);

                $mail->Subject = $subject;
                $mail->Body    = "From: ". $sender. "
" ." Name: ". $yourName. "
". " Message Body " .$message;
                $mail->AltBody = "From: ". $sender. "
" ." Name: ". $yourName. "
". " Message Body " .$message;

                if(!$mail->send())
                {
                    echo 'Message could not be sent.';
                    echo 'Mailer Error: ' . $mail->ErrorInfo;
                }
                else
                {
                    echo "Message has been sent....You're being redirected.....";
                }
        }

This fix, basically allows the user to interact with Mail.php, but Mail.php doesn't sends a null email to $to
Now hours later, I find out that this is a very bad approach.

I would like to know how a professional would solve this problem?
Any good approach which I could use to efficiently optimize the code?


texts: Enumerate multi-subsets for a multiset in Python

texts:
Given a multiset (i.e., allow repeated elements), enumerate all distinct multi-subsets without using itertools(order is not important).

Example: Let s = 'a,a,b' then print to the console,

a
a,a
b
a,b
a,a,b

I am wondering if my approach (presented below) is efficient, and would appreciate stylistic advice. For example, I am not used to using *args, and in places my approach feels kludgey.

My attempt:

Count items in s:

A = s.split(',')
A_counts = defaultdict(int)
for i in A:
    A_counts[i] += 1

In our example we have {'a':2, 'b':1}. Use this to enumerate all tuples of points in the product of sets range(3)xrange(2), i.e., [[0,0],[0,1],[1,0],[1,1],[2,0],[2,1]]. Each tuple corresponds to a unique multi-subset. For example, the tuple [2,1] corresponds to a,a,b and the tuple [2,0] corresponds to a,a.

Enumerate all tuples:

def enumerate_tuples(*args):
    res = [[i] for i in range(args[0])]
    for arg in args[1:]:
        tmp = [j + [i] for i in range(arg) for j in res]
        res = tmp
    return res

Now print the corresponding multi-subset to console:

ordered_alphabet = list(A_counts)
args = (A_counts[i] + 1 for i in ordered_alphabet)
tuples = enumerate_tuples(*args)

# cycle through tuples printing corresponding string
for tup in tuples:
    if sum(tup) == 0: continue
    group = [ordered_alphabet[i] for i in range(len(tup)) for _ in range(tup[i])]
    out = ','.join(group)
    print(out)


texts: A recursive_transform for std::vector with various return type

texts:
This is the follow-up question for A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++ and A get_from_variant function in C++. Thanks to G. Sliepen and Quuxplusone provide detailed review suggestions. However, the existed version of recursive_transform function assumes the return type is always the same as the input type. In other words, it works well with the lambda function like [](double x)->double { return x + 1; } (the type of both input and output are double) or [](int x)->int { return x + 1; } (the type of both input and output are int). In the next step, I want to focus on the case which the return type is different from the input type. For example, [](int x)->std::string { return std::to_string(x); }. Because the origin return type of recursive_transform is specified in T, it can not handle the case which the type of the processed output from the lambda function f is different from T. Let's change type T into auto as below. This auto syntax used here makes type deriving adaptive.
template<class T, class F>
auto recursive_transform(const T& input, const F& f) {
    return f(input);
}

The another part of this recursive_transform is the recursive structure and it is more complex than above. The container has been specified in std::vector here first.
template<class T, class F> requires is_iterable<T>
auto recursive_transform(const T& input, const F& f) {
    typedef typename std::iterator_traits<typename T::iterator>::value_type
        value_type;

    std::vector<decltype(recursive_transform(std::declval<value_type&&>(), f))> output(input.size());
    std::transform(input.begin(), input.end(), output.begin(),
        [f](auto& element)
        {
            return recursive_transform(element, f);
        }
    );
    return output;
}

The test of the above template function recursive_transform.
std::vector<int> test_vector = {
    1, 2, 3
};
auto recursive_transform_result = recursive_transform(
    test_vector,
    [](int x)->std::string { return std::to_string(x); });                          //  For testing

std::cout << "string: " + recursive_transform_result.at(0) << std::endl;            //  recursive_transform_result.at(0) is a std::string

std::vector<decltype(test_vector)> test_vector2 = {
    test_vector, test_vector, test_vector
};

auto recursive_transform_result2 = recursive_transform(
    test_vector2,
    [](int x)->std::string { return std::to_string(x); });                          //  For testing

std::cout << "string: " + recursive_transform_result2.at(0).at(0) << std::endl;     // recursive_transform_result.at(0).at(0) is also a std::string

A Godbolt link is here.
All suggestions are welcome.

Which question it is a follow-up to?
A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++ and
A get_from_variant function in C++

What changes has been made in the code since last question?
In the previous version of recursive_transform function, it works well when the return type is as same as the input type. The main idea in this question is trying to implement a extended version which the return type is different from the input type.

Why a new review is being asked for?
The previous version recursive_transform function assumes the return type is always the same as the input type. I am trying to focus on the case which the return type is different from the input type to make the function more generic. However, I know that I make my algorithms more specialized in std::vector again in this version of code. I have no idea how to implement a more generic recursive_transform function in both various output type and various container type in a simple and smart way. If there is any suggestion or possible idea about this, please let me know.


texts: A directive allowing to make a whole DOM subtree readonly

texts:
What do you think about this directive? For each input, it traverses the DOM towards the root and if it finds an element with the class readonly, it makes the input readonly.
An ng-readonly directive on the input itself get honored: The input becomes readonly whenever ng-readonly evaluates to true or any enclosing element has the class readonly.
.directive("input", function($parse) {
    return {
        restrict: "E",
        link: function($scope, element, attr) {
            if (attr.type === "radio" || attr.type === "checkbox") {
              return; // for simplicity, let's ignore them
            }

            var org = attr.ngReadonly;
            if (!org && attr.readonly) {
              return; // readonly seems to be set manually, so let's not touch it
            }

            $scope.$watch(function() {
                var readonly = $parse(org)($scope);
                for (var e = element; e.length && !readonly; e=e.parent()) {
                    readonly = e.hasClass("readonly");
                }
                console.log(element.attr("ng-model"), readonly)
                attr.$set("readonly", !!readonly);
            });
        },
    };
})

The purpose is to allow to make a whole subtree readonly, no matter what's inside. It works, but I can imagine there can be performance problems and/or interferences with ng-readonly setting the value independently of this directive.
An explanation why I'm not simply binding to a scope variable
While I really appreciate Thomas' answer, I disagree with this part:

Again, I highly recommend that you simply bind to a scope variable instead of checking for the presence of a class further up the tree.

I really find it both complicated and error-prone: I'm having a big form in which many fields already have their readonly logic (e.g., bank name is read only when a known BIC is entered). Now, I'd have to add is_readonly to all existing ng-readonly directives and add the directive to every input field missing it.
Moreover, the form includes some partials, which have no idea about the outer scope. Again, I'd have to add change the partial as above and make it to get is_readonly from the outer scope.


texts:
I'm taking user input from a file in form (1, 2, 3) to create a color, and I just wanted to know if I was taking most cases into account, and if there is any way I could improve this method in terms of being robust and readable.

private Color getColorFromString(String rgb) throws MalformedColorException{
    rgb = rgb.replaceAll("[()\\s]", "");
    String[] colors = rgb.split(",");
    if(colors.length > 3){
        throw new MalformedColorException("Too many arguments");
    }else if (colors.length < 3){
        throw new MalformedColorException("Too little arguments");
    }
    try{
        int red = Integer.parseInt(colors[0]);
        int green = Integer.parseInt(colors[1]);
        int blue = Integer.parseInt(colors[2]);

        return new Color(red, green, blue);
    }catch(NumberFormatException e){
        throw new MalformedColorException("Malformed number", e);
    }
}