Efficiently shift elements right by one in an __mm256 vector The code below correctly shifts v256f_stats by one and puts the results into v256f_x3. This is then used to get the delta between n[1..7] and n[0..6]. The undefined element in the output is not an issue.

Is there a more efficient way of doing this?

// create a shift-by-1 copy
v256f_x1 = _mm256_permute2f128_ps(v256f_stats, v256f_stats, 0);
v256f_x2 = _mm256_permute2f128_ps(v256f_stats, v256f_stats, 0x11);
v256f_x1 = _mm256_permute_ps(v256f_x1, 0b10010011);
v256f_x2 = _mm256_permute_ps(v256f_x2, 0b10010011);
v256f_x3 = _mm256_blend_ps(v256f_x1, v256f_x2, 0b11100000);

With AVX2, it could be done with one vpermps aka _mm256_permutevar8x32_ps:

auto shifted = _mm256_permutevar8x32_ps(v256f_stats, _mm256_set_epi32(6, 5, 4, 3, 2, 1, 0, 0));

Clang rewrites the original shuffle into the same assembly.

Here is an alternative with just AVX1:

auto stats00 = _mm256_permute2f128_ps(v256f_stats, v256f_stats, 0);
stats00 = _mm256_blend_ps(stats00, v256f_stats, 0b01111111);
auto shifted = _mm256_permute_ps(stats00, _MM_SHUFFLE(2, 1, 0, 3));

Roughly the same idea as the original, but reworked so that the _mm256_permute_ps comes after the blend so it only needs to be done once.

This time Clang is too clever for its own good, it replaces the blend/shuffle with two shuffles, which is worse because the blend was cheaper (p015, while the shuffles are p5).


Program to print the multiple occurrence of numbers in a list I wrote this program to print how many times each number occurs in a list:

class deleteduplicate:

    def __init__(self):
        a=[]
        num=int(input("Enter the number of elements"))
        for i in range(0,num):
            try:
                a.append(int(input("Enter the number {}".format(i))))
            except ValueError:
                print ("Wrong Input")
                i=i-1

        flagarray=[]
        countarray=[]
        j=0;
        for c in a:
            flagarray.append(False)
            countarray.append(1)

        for c in a:
            count=1
            flag=False
            ca=[]
            for i in range(j,len(a)):

                if a[i] == c and flagarray[i]==False:

                    flag=True
                    count=count+1
                    flagarray[i]=True
                    ca.append(i)
            if  len(ca)>0:
                print(str(c)+"ocuurs"+str(len(ca))+"times")

            j=j+1

deleteduplicate()

Welcome to code review.
Style
Check PEP0008 the official Python style guide for maintaining code within Python acceptable standards.

Class names: Apart from the fact that this is a bad use of classes, class names should be UpperCaseCamelCase which implies that since this
delete_duplicates is a class, then the name should be DeleteDuplicates.
Method/function/variable names: should be lowercase and words separated by underscores ex: flagarray=[] is flag_array = []
Space around operators: a space should be left on both sides of a binary operator: a=[] is a = [] and flagarray=[] is flag_array = []
Descriptive variable names: names should reflect the objects they represent and not names like j, c, i which are confusing because j could be a variable, a string, a number ...
f-strings: (Python 3.6 +) are better used for combining strings and variables in a single statement. ex: print(str(c)+"ocuurs"+str(len(ca))+"times") can be print(f'{c!s} occurs {len(ca)} times')

Code

Functions: A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. Since this a bad use of classes because a class is usually used for an object with multi-attributes and multi-methods and this is not the case here, you might use a regular function.
Augmented assignment: Python supports augmented assignments ex: i=i-1 is i -= 1, count=count+1 is count += 1 ...
Semicolons: are for combining multiple short statements on the same line, this j=0; (line 15) is an invalid use of semicolons.
Comparison to True and False: is usually done using if something: and if not something_else: ex: flagarray[i]==False: is if not flag_array[i]:. Non-empty sequences and non-zero variables evaluate to True ex: if  len(ca)>0: is if ca:
Inefficiency: If you need to print duplicates of a list you shouldn't be entering each of the list members manually (what if you have a list of size 10,000,000 items? will you be manually entering one by one?)
Counter() You could use counter dict from the collections library for counting list members

An improved version:
If you want to get duplicates and print them:
from collections import Counter

def get_duplicates(numbers: list):
    """Return list duplicates."""
    num_duplicates = Counter(numbers)
    return {item for item in num_duplicates if num_duplicates[item] > 1}

if __name__ == '__main__':
    list_of_duplicates = [1, 2, 2, 3, 4, 3, 5, 2, 7, 1, ]
    print(get_duplicates(list_of_duplicates))

If you want to delete duplicates then use a set
print(set(list_of_duplicates))

output: {1, 2, 3, 4, 5, 7}


JavaScript HTTP regular expression I am currently using the following to convert [url=][/url] to an HTML link:

s = message.replace(/\[url=([^\]]+)\]\s*(.*?)\s*\[\/url\]/gi, "$2")

That work's fine.

I then added on another replace function using a regular expression to replace www with http://www like so:

s = message.replace(/\[url=([^\]]+)\]\s*(.*?)\s*\[\/url\]/gi, "$2")
.replace(/www/g, "http://www");

This is probably not the best/efficient method and also does not support https:// which is not a priority at the moment, but it is something I would like to include at some point. What could I do to improve the regular expression?

I asked this on Stack Overflow. However, I was informed that the type of question was not really fit for there, which I understand.

Like ojdo has pointed out, using plain regexes to parse something like BBCode is too complicated of a route to take.

It would be too long of a task to educate you on building proper parsers, but here's a short simplified example, of how one would go on parsing something like BBCode.

First tokenize

First off, we transform the input text into some higher level data structure which we can then work on more easily. For the BBCode, let's tokenize the input into begin tags, end tags, and text in between:

function tokenize(input) {
  var m;
  var tokens = [];
  while (input.length > 0) {
    if ((m = input.match(/^\[([a-z]+)(=([^\]]+))?\]/i))) {
      // start tag [foo=*]
      tokens.push({type: m[1].toLowerCase() + "_start", argument: m[3], raw: m[0]});
    }
    else if ((m = input.match(/^\[\/([a-z]+)\]/i))) {
      // end tag [/foo]
      tokens.push({type: m[1].toLowerCase() + "_end", raw: m[0]});
    }
    else {
      // text between tags (this regex always matches)
      m = input.match(/^\[?[^\[]*/);
      tokens.push({type: "text", raw: m[0]});
    }
    // skip forward
    input = input.slice(m[0].length);
  }
  return tokens;
}

Given an input like "[URL=google.com]click here[/URL]", the tokenize function produces an array of tokens like this:

[
  { type: 'url_start', argument: 'google.com', raw: '[URL=google.com]' },
  { type: 'text', raw: 'click here' },
  { type: 'url_end', raw: '[/URL]' }
]

Then produce HTML

Normally one would now transform this list of tokens into a tree structure, but as the BBCode-to-HTML conversion is very one-to-one, we don't really need to, and can pass the list of tokens directly to another function that converts it to HTML:

function tokensToHtml(tokens) {
  var output = "";
  for (var i=0; i<tokens.length; i++) {
    var tok = tokens[i];

    if (tok.type === "url_start") {
      var url = tok.argument;
      // prepend URL-s with http:// if needed
      if (!/^https?:\/\//.test(url)) {
        url = "http://" + url;
      }
      output += "";
    }
    else if (tok.type === "url_end") {
      output += "";
    }
    else {
      // anything else is a text token or an unknown tag
      // which we also treat just as text
      output += escapeHtml(tok.raw);
    }
  }
  return output;
}

function escapeHtml(str) {
  return str.replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

As can be see, we simply replace each token with corresponding HTML. When writing out the <a href=... we also take care of prepending the http:// as needed. Additionally we escape all HTML special chars in URL and within rest of the text - using a little escapeHtml utility function.

To tie it all together:

function bbCodeToHtml(input) {
  return tokensToHtml(tokenize(input));
}

It should be fairly obvious how to extend the tokensToHtml to support additional BBCode tags.

One missing feature is to automatically append close tags if one would input something like "[URL=google.com]bla bla". This is left as an exercise for the reader :)


Convert Ternary Expression to a Binary Tree This is programming question I came across (geeksforgeeks) :
Given a string that contains ternary expressions. The expressions may be nested, task is convert the given ternary expression to a binary Tree.Any feedback appreciated.

All the required classes are added as members.
I am using a simple recursive approach to build the tree.
Each time  a '?' expression is encountered then the next element is added as the left node.Similarly, each time a ':' expression is encountered then the next element is added as the right node.

 Input :  string expression =   a?b:c
    Output :        a
                  /  \
                 b    c

    Input : expression =  a?b?c:d:e
    Output :     a
               /  \
              b    e
            /  \
           c    d

The Code:

public class TernaryExpressionToBinaryTree {

    public class Node {
        private Character data;
        private Node left;
        private Node right;

        public Node(Character data) {
            this.data = data;
        }
    }

    public class BST {
        public Node getRoot() {
            return root;
        }

        public void setRoot(Node root) {
            this.root = root;
        }

        public Node root;

        public void addNode(Character data) {
            root = addNode(root, data);
        }

        private Node addNode(Node node, Character data) {
            if (node == null) {
                return new Node(data);
            }
            if (data < node.data) {
                node.left = addNode(node.left, data);
            } else {
                node.right = addNode(node.right, data);
            }
            return node;
        }
    }

    /*
    Preorder traversal
     */
    public void displayTree(Node node) {
        if (node != null) {
            System.out.print(node.data + " | ");
            displayTree(node.left);
            displayTree(node.right);
        }
    }
    public Node buildTreeFromTernaryExpression(Node node, String expression, int index) {

        // check corner cases
        if (expression == null || expression.trim().isEmpty() || index < 0 || index > expression.length()) {
            return null;
        }
       // if its is a valid character
        if (node == null || index == 0 || expression.charAt(index) != '?' || expression.charAt(index) != ':') {
            node = new Node(expression.charAt(index));
        }
      //if it is a valid expression ? or :
        if ((index + 1) < expression.length()-1 && expression.charAt(index + 1) == '?') {
            node.left = buildTreeFromTernaryExpression(node.left, expression, index + 2);
        }

        if ((index + 1) < expression.length()-1 && expression.charAt(index + 1) == ':') {
            node.right = buildTreeFromTernaryExpression(node.right, expression, index + 2);
        }
        return node;
    }

    public static void main(String args[]) {
        TernaryExpressionToBinaryTree ternaryExpressionToBinaryTree = new TernaryExpressionToBinaryTree();
        Node root = ternaryExpressionToBinaryTree.buildTreeFromTernaryExpression(null, "a?b?c:d:e", 0);
        ternaryExpressionToBinaryTree.displayTree(root);
    }
}

You can delete the BST class. You don't use it anywhere.
Error handling looks weird to me. I suggest throwing an exception if the input is invalid. You also don't check all possible cases. For instance, you code prints a tree ? | a | b | for the input ??a:b, which is clearly invalid. I'd recommend either adding proper error handling or just dropping it altogether (the problem statement says that the string is a ternary expression, anyway).
Comments should not repeat the code. If you have something like // if it is a valid character, it's a good indicator that the following check should be moved to a separate method with a proper name (something like private boolean isValidCharacter(Node node, String expression, int index).


Project Euler #48 in C++ This question is similar to Project Euler #48 but constraints are different:

$$N < 2000000$$

Just in case the link is unavailable, here is the problem statement:

We've to print

$$\left( \sum_{i=1}^N i^i \right) \mod 10^{10}$$

I've tried the following, but I need something faster than that, because the execution time limit is 2s, and this program can only compute values until \$ N=30000\$ (approx) in the given time limit.

#include <iostream>
using namespace std;

#define Mod 10000000000

int main()
{
    int N;
    cin>>N;
    long long Temp,Sum=0;
    for( int ii=1 ; ii<=N ; ii++ )
    {
        if(ii%10==0)
        {
            continue;
        }
        Temp=1;
        for( int jj=1 ; jj<=ii ; jj++ )
        {
            Temp*=ii;
            Temp=Temp%Mod;
        }
        Sum+=Temp;
        Sum=Sum%Mod;
    }
    cout<<Sum;
    return 0;
}

I've added

if(N%10==0)
{
    continue;
}

because numbers of form $$ (k*10)^{k*10}=k^{k*10}*10^{k*10}=k^{k*10}*10^{k}*10^{10} $$ are not at all going to contribute to the answer.

Note: code is compiled using g++ 4.8.2, C++11 mode

Time complexity

Let's have a look at the time complexity of your algorithm.

The bound is: \$N<2\cdot 10^6\$ and we want to compute: \$\left(\sum_{i=1}^N i^i\right)\mod(10^{10})\$.

Naively computing \$i^i\$ like you are doing will require \$\mathcal{O}(i)\$ operations. Computing the sum \$\sum_{i=1}^N i^i\$ will cost you \$\sum_{i=1}^N \mathcal{O}(i) = \mathcal{O}(N^2)\$ operations. Or in other words you're looking at the order of \$N^2 = 10^{12}\$ iterations of your inner loop. Or if every iteration of your inner loop take 10 ns (i.e. about 10 clock cycles on a 1GHz CPU), you're looking at \$10\cdot 10^{-9}\cdot 10^{12}=10^4\$ (\$10\$ cycles, \$10^{-9}\$ seconds per cycle) seconds which is about 3 hours.

However by using Exponentiation by Squaring you can reduce the time to calculate \$i^i\$ from \$\mathcal{O}(i)\$ to roughly \$\mathcal{O}(\log_2(i))\$ meaning that your expected complexity to calculate the sum: \$\sum_{i=1}^N i^i\$ is \$\mathcal{O}(N\log_2(N))\$. For \$N=10^6\$ you're looking at about \$2\cdot 10^7\$ iterations (\$\log_2(10^6)\approx 20\$) which should take our hypothetical computer about \$2\cdot 10^7\cdot 10\cdot 10^{-9}=0.2\$ seconds to compute.

So to fix your performance you need to use a better exponential computation, there are plenty of examples on the web.

Your code

Now to look at your loop:

    if(ii%10==0)
    {
        continue;
    }
    Temp=1;
    for( int jj=1 ; jj<=ii ; jj++ )
    {
        Temp*=ii;
        Temp=Temp%Mod;
    }
    Sum+=Temp;
    Sum=Sum%Mod;

The ii%10 == 0 optimization gives you maybe 10% speed gain which isn't much. And I say maybe, it depends on if your CPU correctly predicts the branch so it's probably a bit less than 10%. These kind of problems very rarely depend on how you optimize your code, but rather that you have the correct time complexity, see the above.


Paginate a long unordered list I'm working in an application where there's a long unordered list of items that have to be paginated. New items are added to the list regularly, and the items come from a database.

The only control I have is via the front end. I cannot control how they are all loaded in the DOM before page load.

I was able to work this out using Ben Everard's jqPagination plugin.

All list items are hidden with display:none. Then, when the next/previous buttons are clicked, a group of items are given the 'active' class - which sets them to display:block.

  //get the total number
      var maxItems = $('li').length,
          numPages = maxItems / 5,
          oldSet,
          pageSet = 5;

      function showPages(s,c) {
        $('li').slice(s, c).addClass('active');
        pageSet = c;
      }

    $(document).ready(function() {

      //Show first set of items
      showPages(0, pageSet);

      $('.pagination').jqPagination({
        max_page  : Math.ceil(numPages),
        paged     : function(page) {

          //Remove the active class from previously active items
          $('.active').removeClass('active');

          //Reset the pageSet number
          pageSet = 5 * page;
          oldSet = pageSet - 5;

          showPages(oldSet, pageSet);

        }
      });

    });

This works pretty fast as is, but I'm concerned about whether it will run slow once the list grows (say to 1200 items).

How could I prevent any performance issues? Is it unavoidable?

You can't totally guarantee performance here, since so much is up to how the browser handles DOM manipulation and reflowing content when it's shown/hidden. But there are some things you can improve. Most notably: Don't find and re-find all the elements every time the page changes.

But first, in terms of structure, there's something weird going on. Only the jqPagination stuff is inside a $(document).ready() callback. Yet you're also trying to access page elements before that. The whole point of the ready event is that it fires when you can start using the DOM; if you try before that, the page might not have finished loading. So the browser might literally only have half the page, with the rest still on its way across the interwebs.

So when you do this:

var maxItems = $('li').length

you risk finding zero li elements, because the page isn't ready yet.

Secondly, I worry about the way you're selecting elements. $('li') will select all list item elements anywhere on the page. Doesn't matter if they're part of the list you want to paginate or not. In other words, you're selector casts its net much too wide.

Similarly with the $('active').removeClass('active'); call. Again, that's selecting any element with the active class, regardless of where it is on the page. Using a class named active is a pretty common thing for highlighting links, buttons, and tons of other things. So that line could easily wreak havoc on other parts of the page. Again, too greedy a selector.

Incidentally, I'd also use an ID of the list-pagination buttons, if there's only that one list. Having multiple elements with the class pagination is perhaps less common, but your code certainly doesn't expect more than one, so better to use an ID, which is what you'd use for unique, non-repeated elements.

Back to structure: Your code is split in two. You have the showPage function, which does indeed show pages. But the code to hide the previous page (the removeClass call), is somewhere else. Why? If I call showPage I'd expect it to show a page. Not just show the requested page, and leave previous stuff around. You're also calculating some stuff before calling showPage, despite it being able to do so itself.

In other words, you've added a function, but not given it all the functionality it should probably have.

Finally, you have 5 as a magic number repeated in multiple places. Stick it in a variable and reference that variable instead. That way we a) know what the number is (it's got a name now), and b) you only have to change it in one spot to change the behavior. When it's spread out, maintenance becomes much harder.

I'd do this:

$(function () { // equivalent to $(document).ready(...)
  var perPage = 5,
      allItems = $('#theBigList').children('li'), // change to fit your list's selector
      previousItems = null; // stores the last set of elements

  // a simpler implementation
  function goToPage(page) {
    var offset = (page - 1) * perPage;

    // hide previous items, if any
    if(previousItems) {
      previousItems.removeClass('active');
    }

    // show new items, and store the set
    previousItems = allItems.slice(offset, perPage).addClass('active');
  }

  $('#paginationControls').jqPagination({
    maxPage: Math.ceil(allItems.length / perPage),
    paged: goToPage
  });

  goToPage(1); // might not be necessary if jqPagination automatically invokes its "paged" callback with the argument 1 upon initialization
});

Again, though, if things slow down for very long lists, it's probably because they're very, very long lists. It's not really the javascript that's at fault; it's how fast the browser is.


Mac Bash: how to combine the open and str subtract to one line code? new to bash , I use the following code to open the super folder with a file path.

function openUp(){
  cd $(echo $1 | sed 's@\(.*\)/.*@\1@' );
  open ..
}

like drag a file to terminal, then open the super folder conveniently.

  openup /Users/de/Downloads/32/S01E32-array-arrayslice-collection-collections-1-master.zip

How to combine the two line code to one line?

I originally think open directly without changing directory.

You can use open with an absolute path, it doesn't have to be a relative path.

That is, you could write the same in one line, with some basic improvements:

openUp() {
  open "$(sed 's@\(.*\)/.*@\1@' <<< "$1")/.."
}

The basic improvements:

Instead of echo "..." | cmd, use here strings: cmd <<< "..."
Double-quote variables used as command line arguments (in your example, of cd, and echo
It's not recommended to use the function keyword, write without

A more important improvement would be to stop using sed to get the name of the base directory. Using a regex is error-prone and not as intuitive as the dirname command:

openUp() {
  open "$(dirname "$1")/.."
}

Notice that the arguments of dirname and open are both double-quoted,
as mentioned earlier.
This is necessary, to protect from word-splitting and globbing.


Reading databases of sports data I need to read databases which contain 44-50 tables, with around 5 million entries in total (~ 100k entries per table).

The data consists of positional tracking data in sports (players, refs and the ball) and match-events (shots, plays, tackles, ...):

Match-events are negligible regarding performance.

Table: PlayerXYZ or Ball
-------------------------------------------
|id (int Primary Key)| x | y | z | timekey |
--------------------------------------------

Right now, it takes 86 seconds to read the database and assign the content to a DataTable dictionary. That's a "speed" of 57000 entries per second.

private async void ProcessLoadMatch()
{
    var window = Application.Current.MainWindow as MetroWindow;
    var controller = await window.ShowProgressAsync("Please wait...", "Process message", false, new MetroDialogSettings());

    controller.SetTitle("Loading Match-Data...");
    await Task.Run(() => HandleLoadMatch(controller));
    await controller.CloseAsync();

}

static bool HandleLoadMatch(ProgressDialogController ProgCtrl)
{
    string DataBasePath = @"W:\data\sqlite";
    string DataBaseName = "db";
    string dbpath = @DataBasePath + @"\" + @DataBaseName + ".sqlite";

    SQLiteConnection con = new SQLiteConnection("Data Source=" + dbpath + ";Version=3;");
    con.Open();

    DataTable tables = con.GetSchema("Tables");
    double currentTable = 0;
    double Percentage = 0;
    foreach (DataRow row in tables.Rows)
    {
        currentTable++;
        Percentage = (100 / tables.Rows.Count) * currentTable;
        string tablename = (string)row[2];
        ProgCtrl.SetMessage("Loading Data\nCurrent Table ("+currentTable+" of "+tables.Rows.Count+"): " + tablename + " ...");
        ProgCtrl.SetProgress(Percentage / 100);

        string CmdString = "SELECT * FROM " + tablename;
        SQLiteCommand cmd = new SQLiteCommand(CmdString, con);
        SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);
        DataTable MatchDt = new DataTable();
        sda.Fill(MatchDt);

        CurrentDataSet.CurrentMatch.Data.Add(tablename, MatchDt);
    }
    con.Close();
    return true;

}

CurrentDataSet.CurrentMatch.Data:

class CurrentMatch
{
    public static Dictionary<string, DataTable> Data = new Dictionary<string, DataTable>();
}

My system:

Mac Mini (late 2012)
i5-3210m clone
16GB RAM
256GB SSD

Is there any performance potential left in my code? I load different databases on a regular basis, so any significant performance gains would be appreciated.

Just a few thoughts...

Instead of using data tables and data sets I would try to go with POCO and a data reader. This is definitely more linq friendly. Perhaps even faster to load.
You could try to load the tables in parallel - I doubt a single table brings the SSD to its limits.
All SQLite objects need to be disposed.
Your naming conventions is in great need of improvement - lots of abbreviations and mixed case.
The return true isn't necessary. The method never returns a false anyway. It might as well be just void.


Array Stutter Implementation I was assigned this homework assignment to complete. The question originates from CodeStepByStep. Below is the prompt for the question:

  Write a function stutter that takes an array of Strings as a parameter
  and that replaces every String with two of that String. For example,
  if an array stores the values ["how", "are", "you?"] before the
  function is called, it should store the values ["how", "how", "are",
  "are", "you?", "you?"] after the function finishes executing.

Below is my implementation:

function stutter(arr) {
    if(arr.length == 0) { return []; }
    if(arr.length == 1) {
        arr.push(arr[0]);
        return arr;
    }
    let size = arr.length;
    for(let i = 0; i < size + 2; i += 2) {
        arr.splice(i + 1, 0, arr[i]);
    }
    //If last two elements are not the same
    if(arr[arr.length - 2] != arr[arr.length - 1] && arr.length != 1) {
        arr.push(arr[arr.length - 1]);
    }
    return arr;
}

It would be really helpful if I could get some feedback on how my code is written. I am fairly new to JavaScript, and I don't know some of the functions that could have made this a lot easier. Feedback on code efficiency and the implementation itself is warmly invited!

By reviewing your code, the first thing that comes to my mind is a lot of if statements. You should try and keep those minimal by writing solutions to be as general as they can be.

Another thing that I don't like in your code is that you are doing manipulation of array passed to the function, instead of going out with a fresh one. It looks like this manipulation is what leads to a lot of ifs in the first place.

So main point on how you can refactor your code is that you initialize an empty array which will act as a result and then manipulate that code:

function stutter(arr) {
    const result = []

    for (let word of arr) { // for..of loop is a bit clearer to read
        result.push(word, word) // push can accept N arguments
    }

    return result
}

So by initalizing resulting array with an empty one, you cleared of a case that the argument array passed in is empty, because for..of loop won't do the looping at all.
I've used for..of loop here since it's less code, but you could also use the C-like for like you've written in your question. Note that that loop also wouldn't loop if the argument array was empty, therefor no need for the if(arr.length == 0).

By the way, I'm a bit puzzled with what exactly is the point of the last if you have in the code, but I think that with the refactoring I've provided, then there is no need for it at all.

Since you've asked for more JS way of doing this, here are two ways:

Using map and flat (this one won't run in Edge):

function stutter(arr) {
    return arr.map(x => [x, x]).flat()
}

Using just reduce:

function stutter(arr) {
    return arr.reduce((result, current) => [...result, current, current], [])
}

EDIT

As @AndrewSavinykh pointed out, the assignment is worded in such way that the original array should be mutated. If that truly is the case, and both Andrew and me are not misreading it, then the solution would be to  just reassign the result to arr and return arr (@JollyJoker pointed that previous answer was not correct) use splice (the code is updated for the first example, but same thing can be done for the other two):

function stutter(arr) {
    const result = []

    for (let word of arr) { // for..of loop is a bit clearer to read
        result.push(word, word) // push can accept N arguments
    }

    arr.splice(0, arr.length, result)
    return arr
}

On the other hand, I'd advise against input arguments mutation, because you can easily forget which function mutates the arguments and which not, so it can create some additional cognitive load while reading the code. Also, it goes against the principles of functional programming where you want your functions to be as pure as they can.


Ensure that all `h2` tags have a `span` inserted I'm running these on page load to ensure that all h2 tags have a span inserted (it's a large WordPress site that needs to have this done to get the right styles)

$('.bottomLine').each(function() {
    $(this).insertAfter($(this).parent().find('.price'));
});
$('.prod-desc > h2').each(function() {
    $(this).wrapInner('');
})
$('h2.review_text').each(function() {
    $(this).wrapInner('');
})
$('.related > h2').each(function() {
    $(this).wrapInner('');
})
$('.up-sells > h2').each(function() {
    $(this).wrapInner('');
})

EDIT

I'm kinda getting the message that this is a bad idea so I will expand upon why I think I need to.

I need to create this out of h2 tags.

Which I currently make using:

  Join us on instgram

and SCSS

.seporator {
  text-align: center;
  text-transform: uppercase;
  padding: 40px 40px 46px;
  width: 100%;

  span {
    padding-bottom: 10px;
    border-bottom: 1px solid $red;
    line-height: 48px;
    margin-bottom: 10px;
  }
}

Throughout the WordPress site I see that the previous theme has been using a CSS hook to style h2 elements within the page as breaks. Therefore when I perform the insertion of a  and add h2 to my scss I get the design.

  h2 {
    @extend .seporator;
    font-size: 1.5rem;
  }

If this underlined, correctly spaced design can be achieved using purely h2 tags then I would love to hear about it.

I would agree with discussion in comments that this should be looked at as a stop-gap solution only, as the real answer here is to change the HTML source, or better yet, the CSS styling for the desired h2's such that you don't need these span's at all.

If you truly want to wrap every h2 like this, why is this not just:

$('h2').wrapInner('<span />');

Note here that I also skip the unnecessary call to each(), as wrapInner() will already be applied against every element in the jQuery collection.

Your other function against .bottomLine also seems odd in that you are just moving one set of items in DOM to different positions, something that would unnecessarily cause document reflow. Again, this is something that should probably be fixed in source.


Single Validation function, called once per Animation function Just looking for a way to include a single validation function inside of another function, that will stop any other lines from executing if it fails.

NOT an if statement... I'm trying to avoid nesting, because.. idk, I want to try to avoid it as much as possible.

So.... Is it bad to throw an Error to do this? I can't use return because it only ends the checkAnimationState(); but it doesn't also break out of the moveBlock() function...

JS FIDDLE

$(function(){
    // cache dom
    var $button = $('#button');
    var $block = $('#block');

    // event handlers
    $button.on('click', moveBlock);

    // functions
    function checkAnimationState(){
      if(!$block.hasClass('animating')){
        $block.addClass('animating');
      } else {
        throw Error('Block is already animating... BE PATIENT.');
      }
    }

  function moveBlock(){
    checkAnimationState(); // prevent animation if already animating.. validation..
    $block.animate(
        {marginLeft:'400px'},
      {
        duration: 3000,
        easing: "linear",
        complete: function(){
            $block.removeAttr('style').removeClass('animating');
        }
      }
    ); // end .animate();
  }
});

You have some possibilities:

1. If you wanna throw and error it's advised to use try...catch to handle the error, also this way the action the user's done will be executed when the condition is matched (when the block is finished animating) if you use finally. try...catch...finally DEMO

$(function(){
  // cache dom
    var $button = $('#button');
  var $block = $('#block');

  // event handlers
    $button.on('click', moveBlock);

  // functions
    function checkAnimationState(){
    if(!$block.hasClass('animating')){
        $block.addClass('animating');
    } else {
        throw Error('Block is already animating... BE PATIENT.');
    }
  }

  function moveBlock(){
    try{
        checkAnimationState(); // check for animation - essentially validation
    }
    catch(e){
        console.log(e);
        return false;
    }
    finally{
      $block.animate(
        {marginLeft:'400px'},
        {
          duration: 3000,
          easing: "linear",
          complete: function(){
            $block.removeAttr('style').removeClass('animating');
          }
        }
      )
    }
  }
});

2. You can use callback inside your checkAnimationState() function to execute or pass the animation command: callback DEMO

$(function(){
  // cache dom
    var $button = $('#button');
  var $block = $('#block');

  // event handlers
    $button.on('click', moveBlock);

  // functions
    function checkAnimationState(callback){
    if(!$block.hasClass('animating')){
        $block.addClass('animating');
      callback();
    }
  }

  function moveBlock(){
    checkAnimationState(function(){
      $block.animate(
        {marginLeft:'400px'},
        {
          duration: 3000,
          easing: "linear",
          complete: function(){
            $block.removeAttr('style').removeClass('animating');
          }
        }
      )
    }); // check for animation - essentially validation
  }
});

3. You can have your checkAnimationState() function return a value wether the condition is matched or not and use an if(...) statement. (I know this one is probably not what the OP wants, but I just wanted to mention it for other people who may stumble upon this question) if (...) DEMO

$(function(){
  // cache dom
    var $button = $('#button');
  var $block = $('#block');

  // event handlers
    $button.on('click', moveBlock);

  // functions
    function checkAnimationState(){
      var isAnimating = !$block.hasClass('animating');
    $block.addClass('animating'); //since jQuery wont add an existing class, no need to check for it's existance before adding
    return isAnimating;
  }

  function moveBlock(){
    if(checkAnimationState()){ // check for animation - essentially validation
      $block.animate(
        {marginLeft:'400px'},
        {
          duration: 3000,
          easing: "linear",
          complete: function(){
            $block.removeAttr('style').removeClass('animating');
          }
        }
      )
    }
  }
});


Is it a good practice to have static final field DUMMY in interfaces used as listeners? Often I have to write classes implementing listener interfaces with empty methods bodies.

For example:

MyOnClickListener .java

public interface MyOnClickListener {
    void onClick();
}

and

MyDummyOnClickListener .java

public class MyDummyOnClickListener implements MyOnClickListener {
    public void onClick() {
        // skip
    }
}

Maybe it would be better to have a static final field DUMMY in each such an interface?

MyOnClickListener .java

public interface MyOnClickListener {
    void onClick();

    public static final MyOnClickListener DUMMY = new MyOnClickListener() {
        public void onClick() {
            // skip
        }
    }
}

So I need only 1 .java class, and each time when I change interface I don't have to find and open another .java class with "dummy" implementation.

What do you think? What are the disadvantages of such a solution?

A common pattern to avoid these instances is to create a 'default' abstract class for the interface. One that comes to mind is the SAX parser's DefaultHandler

Consider an abstract class (marked abstract even though it implements the method):

public abstract class DefaultOnClickListener implements MyOnClickListener {
    public void onClick() {
        // override to implement
    }
}

Now, you can extend the class, and chose to change the behaviour, by overriding the method, or leaving the default behaviour, by not overriding the method.

This solution means that the dummy implementations are only in one place.


TabController for handling opening and closing of tabs I created a class TabController to handle opening and closing of tabs. It needs some data from my viewModel, so should I pass in the viewmodel via the constructor or is that overkill? It really only needs the parameters browserCollection and activeWindow, so I could just pass those two in if that's better. I'm just starting learning about design patterns so I can code well but am having trouble wiring everything up.

public abstract class TabController
{
    ViewModel vm;

    #region constructor
    public TabController(ViewModel vm)
    {
        this.vm = vm;
    }
    #endregion

    public abstract void go(Uri address);
    public abstract void newTabGo(Uri address);
    public abstract void newEmptyTab();

    public void newTab(Uri address, int insertionIndex)
    {
        vm.browserCollection.Insert(insertionIndex, new MyBrowserControl(address));
    }
}

//first class, starts out this way when the program starts -- no tabs are open
public class NoTabsOpen : TabController
{
    ViewModel vm;

    #region constructor
    public NoTabsOpen(ViewModel vm)
        : base(vm)
    {
        this.vm = vm;
    }
    #endregion

    public override void go(Uri address)
    {
        if (address != null)
            vm.browserCollection.Add(new MyBrowserControl(address));
    }

    public override void newTabGo(Uri address)
    {
        if (address != null)
            base.newTab(address, 0);
    }

    public override void newEmptyTab()
    {
        base.newTab(null, 0);
    }

}

//second class - active when at least one tab is open
public class TabsOpen : TabController
{
    ViewModel vm;

    #region constructor
    public TabsOpen(ViewModel vm)
        : base(vm)
    {
        this.vm = vm;
    }
    #endregion

    public override void go(Uri address)
    {
        if (address != null)
        {
            MyBrowserControl mbc = vm.browserCollection[vm.activeWindow];
            mbc.mySource = address;
        }
    }

    public override void newTabGo(Uri address)
    {
        if (address != null)
        base.newTab(address, vm.activeWindow + 1);
    }

    public override void newEmptyTab()
    {
        base.newTab(null, vm.activeWindow + 1);
    }
}

public TabsOpen(ViewModel vm)
    : base(vm)
{
    this.vm = vm;
}

There's no reason to set this.vm = vm here. You're already doing that by passing the argument to your base class' constructor. Both of your subclass ctors could look like this.

public TabsOpen(ViewModel viewModel)
  : base (viewModel) { }

I changed the parameter name to make it a bit clearer. Speaking of naming, it's a convention in C# to PascalCase method names. You've camel cased yours. It's consistent though, so I can't gripe too much about it.

To address your actual question though, typically yes, you will pass your view model to the controller as you've done here. However, that's because the controller is typically updating the view. That doesn't seem to be the case here, so the thought comes to mind that it is better to only inject what you actually need.

I like that you've used polymorphism to simulate the state of an object, but it makes me wonder if what you have here is really a view model and not some other concept.


Dynamic IP Notification Using Google App Engine This script is very basic: it does one thing. Connect to it's root and it will log your IP if it has never seen it before. Connect to /logs, and it will show a list of unique IPs within the server storage. I can't take 100 percent credit for it. I grabbed it off of Stack Overflow, modified it to actually run on App Engine, and changed the save mechanism to prevent duplicate entries. This thing is so simple it's shocking; considering how many different super-elaborate ways I can waste money and time doing the same thing. I use it to keep track of my ssh IP. I run wget on my App Engine address every ten minutes. Can this be improved? Are there any flaws which may compromise its efficiency?

helloworld.py

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class Log(db.Model):
    access_time = db.DateTimeProperty(auto_now_add=True)
    ip_address = db.StringProperty()
class MainPage(webapp.RequestHandler):
    def get(self):
        ip = self.request.remote_addr
        log = Log()
        logs = Log.all()
        is_new = True
        for log in logs:
                if ip == log: is_new = False
        if is_new:
                log.ip_address = ip
                log.put()
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Logged your visit from ip address %s' % ip)
class LogPage(webapp.RequestHandler):
    def get(self):
        logs = Log.all()

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Ip addresses: ')
        for log in logs:
            self.response.out.write(log.ip_address + ',')
app = webapp.WSGIApplication([('/', MainPage), ('/logs', LogPage)],
                                     debug=True)

app.yaml

runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: helloworld.app

P.S. I'm pretty sure this isn't violating any contracts or agreements. Tell me if I'm wrong about that.

Credit: Get IP address in Google App Engine + Python

Lint

PEP 8 recommends two blank lines around class definitions.  Indentation should be consistently 4 spaces — an important convention in Python, where indentation matters a lot.

log = Log() is pointless.

Database

A more Pythonic way to write this…

logs = Log.all()
is_new = True
for log in logs:
        if ip == log: is_new = False

… would be is_new = ip not in Log.all().

But your code wouldn't even work, since an IP address would never be equal to a db.Model object!

It also doesn't scale well, since it doesn't take advantage of the datastore's capabilities.  You should be using a query like this:

Logs.all().filter('ip_address =', ip).run(limit=1)


C++ Super Simple HTML Tag Generating Code v0.1 I made this simple code which makes easy HTML tag generation. It is open-source and right now only makes tag names and replaces tags... :/

#include <iostream>
#include <fstream>

std::string makeHtmlTags(std::string tagname, std::string tagcontent) {
    return "<" + tagname + ">" + tagcontent + "</" + tagname + ">";
}

void changeHtmlTag(std::string * tag, std::string newtagname)
{
    if(tag->at(2) != '/')
        *tag = "<" + newtagname + ">";
    else
        *tag = "</" + newtagname + ">";
}

int main()
{
    std::string html = makeHtmlTags("hello", "world");
    std::string tag1 = html.substr(2, 5);
    changeHtmlTag(&tag1, "goodbye");
    changeHtmlTag(&tag1, "/goodbye");
    std::cout << tag1;
}

What can I do to make it more useful?

At least in my opinion, there's quite a bit of room for improvement here. As far as usability goes, probably the most obvious change would be to directly support nesting. HTML and XML are frequently nested fairly deeply, but this doesn't really do anything to support nesting at all.

Looking at the code itself, I'd consider at least a couple of points:

1) You typically want to pass strings by const reference rather than value to avoid copying the string (unless you really need a copy, but you don't here). So:

std::string makeHtmlTags(std::string tagname, std::string tagcontent)

would change to:

std::string makeHtmlTags(std::string const &tagname, std::string const &tagcontent)

I would probably write ChangeHtmlTag to return the new string instead of modifying the existing one:

std::string changeHtmlTag(std::string const &tag, std::string const &newtagname)
{
    if(tag.at(2) != '/')
        return "<" + newtagname + ">";
    return "</" + newtagname + ">";
}

Rather than using .at, I'd also consider just returning the input intact if the input is too short to be a tag, then do the modification if it's long enough to be a tag.

The biggest problem I see, however, is that the code just doesn't seem like it does enough/has enough intelligence to make it obvious that using it gains much over playing with the strings directly.


Number of way to render an amount of money I made an algorithm to train my skill in dynamic programming and I would like to have feed back on it. This algorithm takes a money system (int) and have a certain amount of money to render.

Do you see any problems in this code?

public static int wayToRenderMemo(int[] array, int i, double cost, HashMap memo) {
    if(i>=array.length) {
        return 0;
    }
    else if(cost < 0) {
        return 0;
    }
    else if(cost == 0) {
        return 1;
    }
    else if(memo.containsKey(String.valueOf(i)+":"+String.valueOf(cost))) {
        return (int) memo.get(String.valueOf(i)+":"+String.valueOf(cost));
    }
    else {
        int res = 0;
        for(int j = 0; j < array.length; j++) {
            res += wayToRenderMemo(array, i+j, cost-array[j], memo);
        }
        memo.put(String.valueOf(i)+":"+String.valueOf(cost), res);
        return res;
    }
}

public static void main(String []args) {
    int[] array = {1, 2, 5, 10, 20, 50, 100};

    double amountOfMoneyToRender = 20;
    System.out.println("Number of way to render "+amountOfMoneyToRender+"€ with the following system : "+Arrays.toString(array));
    HashMap memo = new HashMap();
    long t3 = System.currentTimeMillis();
    System.out.println(wayToRenderMemo(array, 0, amountOfMoneyToRender, memo));
    long t4 = System.currentTimeMillis();
    double time2 = (t4-t3)/1000.0;
    System.out.println("Result found in : "+time2+"seconds");
}

Java 1.5 was released in 2004, use generics for collections.
Consider making  array (terrible variable name BTW) and memo fields of object that does the computation instead of passing them as arguments every time
Why is amountOfMoneyToRender a double instead of int or long?
String.valueOf is unnecessary for i + "some literal"
Instead of using containsKey + get just do get and check for null.
It might be good idea to change loop into for(int j = i; j < array.length; j++), it will make easier to spot bug in your code (with amountOfMoneyToRender=10, the result should be 11, not 100)


Advanced multi-conditonal split with an regex in Perl I would like to split a string on multiple conditions such as:

After each /;/
After each /{/ or /}/
After each /\w+:/ but not after /\w+:\s+\{/
After each /#\w.*$/

I've found that I can keep a pattern and split before it with

/(?=pattern)/

or split after it (if the pattern has a fixed width)

/(?<=pattern)/

or split after it (if the pattern has a variable width)

/pattern\K/

or even remove the pattern during the operation

/pattern/

With all this knowledge I wrote this:

#!/usr/bin/perl
$_ = do { local $/; <DATA> };
s/\#\w.+\n\K|\n//g;

my @content = split /(?:(?<=[;{}])|(?<=:)(?!\s*\{)|#\w.*\$\K)/, $_;

print join "\n", @content;

__DATA__
carrot;
#orange
apple: {pear; { cabbage; } }
#passion
sprout: celeri;
tomato;

Where the output should be this (after manually reindenting it):

carrot;
#orange
apple: {
  pear;
  {
    cabbage;
  }
}
#passion
sprout:
celeri;
tomato;

I am not really happy with this method for multiple reasons:

I cannot use a x regex in split like split m/re/x to make the regex more readable
I need to treat the exception for the special case /^\s*#.*$/ where I cannot remove CR otherwise I will get for instance #passionsprout:

Can I do a better job?

Think the other way around: try to add a newline to all characters that need one. That way your regex is a bit simpler.

#!/usr/bin/perl -w

use strict;

my $content = do { local $/; <DATA> };

my $regex = qr{
  (?m)
    (^
     |
     :\s*
    )
    \{                  # open curly brace preceded by
                        # beginning of line
                        # OR
                        # colon

  |                     # OR
    [:;\}]              # any of these characters
    (?!\s*\n)           # NOT followed by newline
}x;

$content =~ s/($regex)/$1\n/g;
print $content, "\n";


Countdown module that hides an element when a specified date is reached I have the following piece of code which hides an element when a specified date was reached. I would like to get some tips about do's and don'ts.

Specifically, I'm interested in:

improvements brought to this code
avoid bad practices

And whatever you guys consider I should be careful about.

var Timer = (function(){
    var $el = $('#element');

    function count() {
        setInterval(function() {
            check();
        }, 1000);
    }

    function hide() {
        $el.hide();
    }

    function check() {
        var currentDate = new Date();
        var endingDate = new Date("July 25, 2016 11:06:00");

        if (currentDate.getTime() >= endingDate.getTime()) {
            hide();
        }
    }

    return {
        count: count
    };
})();

Timer.count();

My notes:

There is no need to create a function that calls check, you can just pass check
There is no need for function hide, you only call it once, and it only has 1 line of code, I would inline that function
Very minor, but there is no need to declare endingDate inside check, I would declare it once outside of the function
You are using a revealing pattern, I would use a simple self executing pattern. On the whole if you expose 1 function that you will run only once, use a self executing function.
Once the date is passed you will be hiding that element non-stop every second, that sounds like overkill
I abhor anonymous functions, choose a meaningful name, and you can spare a line of comment ;)

My approach with these notes would be

    (function HideElementWhenTimeComes (){
      var $el = $('#element'),
          endingDate = new Date("July 25, 2016 11:06:00"),
          intervalID;

      function check() {
        var currentDate = new Date();
            if (currentDate.getTime() >= endingDate.getTime()) {
              $el.hide();
              clearInterval(intervalID);
            }
      }

      intervalID = setInterval(check , 1000 );

    })();


Windows DLL Module Class I am doing a project where I use DLL's as run-time modules or plugins. To do this, I use the Windows LoadLibrary() and FreeLibrary() API calls to call two functions exported by the DLL. I decided to make a class so dealing with the DLL's would be easier. Is there anything I can add to my class to make it better, is there anything I'm doing wrong? Feel free to criticize anything you want.

SaModule.h

#ifndef SAMODULE_H__
#define SAMODULE_H__

#include <Windows.h>
#include <string>
#include <exception>
#include "WinException.h"

class SaModule
{
private:

    typedef const char* (*LPFNGETNAME)();
    typedef bool (*LPFNDOSCAN)(std::string&, std::string&);
    HINSTANCE hInstance;
    std::string path;

public:

    SaModule();
    SaModule(const std::string& path);
    ~SaModule();

    void Load(const std::string& path);
    void Unload();

    LPFNDOSCAN DoScan;
    LPFNGETNAME GetName;

    HINSTANCE GetHandle() const;
    operator HINSTANCE() const;

};

#endif//SAMODULE_H__

SaModule.cpp

#include "SaModule.h"
#include "WinException.h"
#include <sstream>
#include <iomanip>

SaModule::SaModule(): path(), hInstance(NULL)
{
    //Nothing...
}

SaModule::SaModule(const std::string& path): path(path), hInstance(NULL)
{
    Load(path);
}

SaModule::~SaModule()
{
    Unload();
}

void SaModule::Load(const std::string& path)
{

    this->path = path;

    if( NULL == (hInstance=LoadLibrary(path.c_str())) )
        throw WinException();

    if( NULL == (GetName=reinterpret_cast<LPFNGETNAME>(GetProcAddress(hInstance,"GetName"))) )
        throw WinException();

    if( NULL == (DoScan=reinterpret_cast<LPFNDOSCAN>(GetProcAddress(hInstance, "DoScan"))) )
        throw WinException();

}

void SaModule::Unload()
{
    FreeLibrary(hInstance);
}

HINSTANCE SaModule::GetHandle() const
{
    return hInstance;
}

SaModule::operator HINSTANCE() const
{
    return hInstance;
}

WinException.h

#ifndef WINEXCEPTION_H__
#define WINEXCEPTION_H__

#include <Windows.h>
#include <exception>
#include <string>

class WinException: public std::exception
{
private:

    DWORD dwError;
    std::string errMsg;

public:

    WinException();
    const char* what() const;

};

#endif//WINEXCEPTION_H__

WinException.cpp

#include "WinException.h"
#include <sstream>
#include <iomanip>

WinException::WinException()
{

    std::ostringstream ss;
    dwError = GetLastError();
    LPVOID lpMsgBuf = NULL;

    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, dwError, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), reinterpret_cast<LPTSTR>(&lpMsgBuf), 0, NULL);

    ss << "Error: 0x" << std::hex << std::setfill('0') << std::setw(8) << dwError << std::endl
        << reinterpret_cast<LPTSTR>(lpMsgBuf);

    errMsg = ss.str();

    LocalFree(lpMsgBuf);

}

const char* WinException::what() const
{
    return errMsg.c_str();
}

Example Usage

#include <iostream>
#include "SaModule.h"

int main(int argc, char* argv[])
{

    try
    {
        SaModule mod("some.sa.dll");
        std::cout << "Loaded Module: " << mod.GetName() << std::endl;
    }
    catch( WinException& ex )
    {
        std::cout << ex.what() << std::endl;
    }

    return 0;

}

Just a couple of quick thoughts.

DoScan and GetName probably should be initialised to NULL as well.
Load doesn't call Unload for any previous loaded dlls. If Load should be called once only per SaModule, that should be detected.
A more informative exception could be thrown. "...during attempted insertion of plugin xyz", for example.
Beware of function name decoration, if that could be an issue.


Map coloring with MRV and Degree heuristics in Python I am relatively new to Python. I wrote this solution to the well known map coloring problem and also implemented the MRV and Degree heuristics. Here, I am considering the map of Australia - ['WA', 'NT', 'SA', 'Q', 'NSW', 'V', 'T'] and 3 given colors - ['R','G', 'B']

# choosing first node with degree heruistics
# applying MRV with backtracking

from enum import Enum
import pdb

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

class Graph:
    def __init__(self, totalNodes, adjacencyList, color):
        self.totalNodes = totalNodes
        self.adjacencyList = adjacencyList
        self.color = color
        self.nodeSequence = [""]*totalNodes

    def isSafe(self, node, c):
        for i in range(len(self.adjacencyList[node])):
            if(self.color[self.adjacencyList[node][i]] == c):
                return False
        return True

    def graphColorUtil(self, node, colorLimit):
        if node == '':
            # check and color any uncolored node
            for key, value in self.color.items():
                if value == 0:
                    self.graphColorUtil(key, colorLimit)
            return True

        # pdb.set_trace()
        for c in range(1, colorLimit+1):
            if(self.isSafe(node, c) == True):
                self.color[node] = c
                nextNode = self.getNodeWithMRV(node, colorLimit)
                if(self.graphColorUtil(nextNode, colorLimit) == True):
                    return True
                else:
                    self.color[node] = 0

        return False

    def graphColoring(self, colorLimit):
        # pdb.set_trace()
        startNode = self.pickNode('')
        if(self.graphColorUtil(startNode, colorLimit) == True):
            return True
        else:
            print("Solution does not exists")
            return False

    # pick node using MRV
    def pickNode(self, initialNode):
        maxCount = 0
        selectedNode = ''
        # the very first node
        if (initialNode == ''):
            for node, neighbourList in self.adjacencyList.items():
                if (len(neighbourList) > maxCount and self.color[node] == 0):
                    maxCount = len(neighbourList)
                    selectedNode = node
        # the other nodes
        else:
            for i in range(len(self.adjacencyList[initialNode])):
                childNode = self.adjacencyList[initialNode][i]
                if (self.color[childNode] == 0 and len(self.adjacencyList[childNode]) > maxCount):
                    maxCount = len(self.adjacencyList[childNode])
                    selectedNode = childNode

        return selectedNode

    def getNodeWithMRV(self, parentNode, colorLimit):
        selectedNode = ''

        for i in range(len(self.adjacencyList[parentNode])):
            childNode = self.adjacencyList[parentNode][i]
            countColor = 0
            for c in range(1, colorLimit+1):
                if(self.isSafe(childNode, c) == True):
                    countColor += 1
            if (countColor < minCount):
                selectedNode = childNode

        return selectedNode

# driver code
def main():
    adjacencyList = {
        'WA': ['NT', 'SA'],
        'NT': ['WA', 'SA', 'Q'],
        'SA': ['WA', 'NT', 'Q', 'NSW', 'V'],
        'Q': ['NT', 'SA', 'NSW'],
        'NSW': ['SA', 'Q', 'V'],
        'V': ['SA', 'T', 'NSW'],
        'T': ['V']
    };

    color = {
        'WA': 0,
        'NT': 0,
        'SA': 0,
        'Q': 0,
        'NSW': 0,
        'V': 0,
        'T': 0
    };

    g = Graph(7, adjacencyList, color)
    colorLimit = 3
    g.graphColoring(colorLimit)

    for node, color in g.color.items():
        print(node, Color(color).name)
main()

What could be the possible ways to refactor this code? I am also interested for feedback on Python code style in general.

Although not familiar with MRV and degree heuristics, i can make some remarks about the Python code style:

Loops can be made more Pythonic

for i in range(len(self.adjacencyList[initialNode])):
    childNode = self.adjacencyList[initialNode][i]

should be written as:

for childNode in self.adjacencyList[initialNode]:

Conditionals

if(self.isSafe(childNode, c) == True):

should be

if self.isSafe(childNode, c):

method isSafe

def isSafe(self, node, c):
    for i in range(len(self.adjacencyList[node])):
        if(self.color[self.adjacencyList[node][i]] == c):
            return False
    return True

could be:

def isSafe(self, node, c):
    for adjacency in self.adjacencyList[node]:
        if self.color[adjacency] == c:
            return False
    return True

or even, more Pythonic, but a bit cryptic:

def isSafe(self, node, c):
    # return True if all node neighbours colors differ from c
    return all([self.color[adj] != c for adj in self.adjacencyList[node]])

Data structure

The repetition of the keys in the adjacencyList and color
suggest a data structure like the following, although this requires a
lot changes in the existing code:

nodes = {
    'WA' : {'color' : 0, 'neighbours' : ['NT', 'SA']},
    'NT' : {'color' : 0, 'neighbours' : ['WA', 'SA', 'Q']},
    'SA' : {'color' : 0, 'neighbours' : ['WA', 'NT', 'Q', 'NSW', 'V']},
    'Q'  : {'color' : 0, 'neighbours' : ['NT', 'SA', 'NSW']},
    'NSW': {'color' : 0, 'neighbours' : ['SA', 'Q', 'V']},
    'V'  : {'color' : 0, 'neighbours' : ['SA', 'T', 'NSW']},
    'T'  : {'color' : 0, 'neighbours' : ['V']},
}

Others:

self.nodeSequence is not used
self.totalNodes is not used
minCount = 0 was edited out in getNodeWithMRV but should be there, or if (countColor < minCount) should be if (countColor < 0)
pickNode is called only once with a constant argument '', and can therefor be made simpler
getNodeWithMRV will always return '' because countColor will never be smaller than 0.
the ; at the end of adjacencyList = ... and color = ... an origin in another language :-)


Alternating chars N times Write a function that returns a string length N of alternating strings: "A" and "B", starting with the 1st string. How could this be improved for be more performance or efficiency?

Eg: num = 5, should return "ABABA" & given num = 2, should return "AB".

function solution(num) {
 const str1 = 'A', str2 = 'B';
 let res = [];

 for(let i = 1; res.length < num; i++ ) {
  res.push(i % 2 ? str1 : str2);
 }

  console.log(res.join(''))
}

solution(5) // return "ABABA"

A short code review;

Your code does not work, it should return something instead it calls console.log
Your for loop is icky, either update i and check i

for(let i = 0; i < num; i++ ))

or check res.length

while(res.length < num)
solution is too generic for this function name
console.log() is missing a semi-colon
Performance;

Checking whether i is odd every time seems like much, you can avoid that
RememberString.repeat(), you could repeat by calling "AB".repeat(num/2) and add an "A" if num is odd.

Obligatory rewrite

    //repeatAB(5) => "ABABA"
    function repeatAB(n) {
        return "AB".repeat(n/2) + (n%2 ? "A" : "");
    }

    console.log(repeatAB(5)) // returns "ABABA"

I ran this approach against the other approaches for the heck of it, this approach destroys the other approaches (at least visually):

http://jsbench.github.io/#11a2b8507a7f9290c6ef6cda596f8179


Print a right-justified list of a list I'm working through Chapter 6 in "Automate the Boring Stuff, 2nd Edition." Here is the chapter project at the end.
Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

Your printTable() function would print the following:

   apples Alice  dogs
  oranges   Bob  cats
 cherries Carol moose
   banana David goose

The first time I tackled this project, here was what I came up with:
#! python3
# Displays a table with each column right-justified.

table_data = [["apples", "oranges", "cherries", "bananas"],
    ["Alice", "Bob", "Carol", "David"],
    ["dogs", "cats", "moose", "goose"]]

def print_table(table_data):
    # Create a new list of 3 "0" values: one for each list in table_data
    col_widths = [0] * len(table_data)
    # Search for the longest string in each list of table_data
    # and put the numbers of characters in the new list
    for y in range(len(table_data)):
        for x in table_data[y]:
            if col_widths[y] < len(x):
                col_widths[y] = len(x)

    # Rotate and print the list of lists
    for x in range(len(table_data[0])):
        for y in range(len(table_data)):
            print(table_data[y][x].rjust(col_widths[y]), end=" ")
        print()

print_table(table_data)

The second time, I found out about the MAX method after several searches on Google. Here is what I came up with using the MAX method.
#! python3
# Displays a table with each column right-justified

table_data = [["apples", "oranges", "cherries", "bananas"],
            ["Alice", "Bob", "Carol", "David"],
            ["dogs", "cats", "moose", "goose"]]

def print_table(table_data):
    # Create a new list of 3 "0" values: one for each list in table_data
    col_widths = [0] * len(table_data)
    # Search for longest string in each list of table_data
    # and put the numbers of characters in new list
    for y in range(len(table_data)):
        x = max(table_data[y], key=len)
        if col_widths[y] < len(x):
            col_widths[y] = len(x)

    # Rotate and print the lists of lists
    for x in range(len(table_data[0])):
        for y in range(len(table_data)):
            print(table_data[y][x].rjust(col_widths[y]), end=" ")
        print()

print_table(table_data)

Any feedback would be greatly appreciated. Thanks!

You can transpose the given list of lists using a single line:
zip(*table_data)

That's it. Now, to find the longest word in each column, it would be another 1-liner:
map(len, [max(_, key=len) for _ in table_data])

You are calculating len(table_data) a lot of times. Better to store it as a variable? Although, another comprehension could be:
for row in zip(*table_data):
    for index, cell in enumerate(row):
        print(cell.rjust(col_width[index]), end=" ")

You whole function now becomes:
from typing import List
def print_table(table_data: List):
    col_width = list(map(len, [max(_, key=len) for _ in table_data]))
    for row in zip(*table_data):
        for index, cell in enumerate(row):
            print(cell.rjust(col_width[index]), end=" ")
        print()


Preorder traversal of a tree I am practising my coding skills on interviewbit. I got one question about preorder (for a tree). This is what I did first:

public class Solution {
   private ArrayList<Integer> result = new ArrayList<Integer>();
   public ArrayList<Integer> preorderTraversal(TreeNode a) {
       if(a == null){
          return result;
       }
       result.add(a.val);
       preorderTraversal(a.left);
       preorderTraversal(a.right);
       return result;
    }
}

Then I googled solutions for the same problem and this is what I found.

public class PreOrder{
    public ArrayList<Integer> preorderTraversal(TreeNode a) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if(a == null)
            return result;
        stack.push(a);
        while(!stack.isEmpty()){
            TreeNode popped = stack.pop();
            result.add(popped.val);
            if(popped.right != null)
                stack.push(popped.right);
            if(popped.left != null)
                stack.push(popped.left);
        }
        return result;
    }
}

I understood the second method too. What am I asking is the other method better than mine? If yes then how?

NOTE: I am not allowed to change function arguments and return types.

It depends. (As usual.)

The recursive version is easier to read an maintain, and does the job fine for relatively small data sets.

However, when the data set grows large, you create a new stack frame for each recursive call, which may lead to great stack memory usage up to stack overflow. Furthermore, this is comparatively slow.

The second version uses constant stack size and puts all the real memory usage in the heap where it should be. Not using recursion, it is also bound to be faster (on a micro-level only).

Thus, know the problem you solve: for small sets, write nice code and use your version, for big data sets, optimize by unrolling and use the second version.

(BTW: in my university courses, it was generally recommended to use the second version for NP problems due to raw speed - albeit in C at that time.)


iframe play & thumbnail function This is quite a simple function, but I just wanted some opinions on it, like is this the correct way to run a function and check if an element exists or not?

const button = document.querySelector('.js-brand-video--thumbnail')
const iframe = document.querySelector('.js-brand-video--iframe')

function playVideo () {
  if (button) {
    button.classList.add('video-poster--hidden')
    iframe.src = iframe.getAttribute('data-src')
  }
}

if (button)
  button.addEventListener('click', playVideo, false)

querySelector can return null. So while you are checking button, you aren't checking for iframe. You will possibly get Assigning property src to undefined or something like that.

classList is one of the newer properties. If you see your code being used in older browsers, you should watch out. Check the compatibility table for support.

A practice used by jQuery and other libraries is to use sets. It's where you put results in an array and for each item, operate on it. If no items are on the set, no code executes.

// Use querySelectorAll to get elements. querySelectorAll returns a
// NodeList. To use array methods, we convert it to an array with
// slice.
const buttons = Array.prototype.slice.call(document.querySelectorAll('.js-brand-video--thumbnail'));
const iframes = Array.prototype.slice.call(document.querySelectorAll('.js-brand-video--iframe'));

// forEach runs the callback for each item in the array. If no items
// reside, no loop runs, therefore no code executes.
button.forEach(function(button){
  button.addEventListener('click', function(){
    button.classList.add('video-poster--hidden')
    iframe.forEach(function(iframe){
      iframe.getAttribute('data-src');
    });
  }, false)
});


Filtering (search) a model with multiple params in hash This function in my Profile model receive a hash from a search form and should filter the table depending on those values. I guess there is something like a pattern for such a standard behavior, right now I ended up with this (unfortunately I had to reproduce the code here, so it might not work for some reasons, but you get the idea).

Just a note: we're storing in the model some strings containing multiple data, each of these fields should be a one-to-many relationship (db normality violation). I give an example: country_preferences is a string filled up by an html select :multiple => true. In the string I then find values like: ["Australia", "China", "United Kingdom"].

  def search opts # This default doesn't work the way I would like = {:user_type => :family}

    #TODO: default opts value in method sign if possible
    opts[:user_type] ||= :family

    # initial criteria
    fields= "user_type= ?"
    values= [opts[:user_type]]

    # each field filters the list in one of these three ways
    staight_fields = [ :country, :first_name, :last_name, :nationality ]
    like_fields = [:country_preferences, :keyword, :languages ]
    bool_fields = [:driver, :housework, :children ]

    # cicle the options and build the query
    opts.each do |k, v|
      if straight_fields.include? k
        fields += " AND #{k} = ?"
        values += v
      elsif like_fields.include? k
        fields += " AND #{k} like %?%"
        values += v
      elsif bool_fields.include? k
        fields += " AND #{k} = ?"
        values += v == 'true'
      else
        logger.warn "opts #{k} with value #{v} ignored from search"
      end
    end

    # execute the query and return the result
    self.registered.actives.where([fields] + values)
  end

I think I can use more scope but how can I combine them together? In general, how can I make this code much better?

The boss, when introducing the project, said one-to-many relationships for that kind of fields would be a pain in the back. What do you think about this pragmatic solution?

Have you looked into using a pre existing gem for this? I found one called has_scope that seems like it might do exactly what you're trying to refactor. You would need to add a scope for each of your filters and then add some has_scope calls in your controller.

Here's a few examples. I'm not as familiar with Rails 3 scopes as I am with 2, so the code likely won't work as is.

Model:

class Profile < ActiveRecord::Base
  scope :country, lambda {|country| where(:country => country) }
  scope :keyword, lambda {|keyword| where(["keyword LIKE :term", {:term => "%#{keyword}%"}]) }
  scope :driver, where{:driver => true)
end

Controller:

class ProfileController < ApplicationController
  has_scope :country
  has_scope :keyword
  has_scope :driver, :type => :boolean
end


Calculating difference statistics over a moving window I'd like to calculate some statistics of given data (frequencies of difference among elements on various distances in percent multiplied by 10) using moving window within that data. Is it possible to speed up the code below? I noticed that some calculations are repeating. But I was not able to exclude them without additional slowness.

def get_dist_stat(pdata, pwin_length):
    ''' pdata - given data array
        pwin_length - the lenght of window
        the function returns stat table where
            row represents the distance between elements
            col represents the difference for that distance in percent multiplied by 10 (assume that maximum difference can be 20 percent)

    '''

    l_data = len(pdata)
    l_win = pwin_length
    print("l_data=", l_data)
    print("l_win=", l_win)

    # stat table
    stat_table = np.zeros((l_win-1, 20*10), dtype = int)

        # loop over all data
    for k in range(l_data - l_win + 1):

        win = pdata[k : k + l_win]
        print('-' * 10)
        print("k=", k, " kend=", k + l_win )

        print("win=", win)

        # loop over window
        for i  in range(1 , l_win):
            b=win[i:]
            a=win[:-i]
            diff=(abs((b-a)/a*100 ) * 10).astype(int)
            print("i=",i)
            print("b=", b)
            print("a=", a)
            print("diff=",diff)

            # storing found differences into stat table
            apercents, acount = np.unique(diff, return_counts = True)
            l_apercents = len(apercents)
            for j in range(l_apercents):
                stat_table[i-1, apercents[j]] += acount[j]
    return stat_table

adata=np.array([1.1,1.2,1.3,1.4,1.5])
print("adata=", adata)

astat_table=get_dist_stat(adata,3)
print(astat_table)

And that is its output

adata= [1.1 1.2 1.3 1.4 1.5]
l_data= 5
l_win= 3
----------
k= 0  kend= 3
win= [1.1 1.2 1.3]
i= 1
b= [1.2 1.3]
a= [1.1 1.2]
diff= [90 83]
i= 2
b= [1.3]
a= [1.1]
diff= [181]
----------
k= 1  kend= 4
win= [1.2 1.3 1.4]
i= 1
b= [1.3 1.4]
a= [1.2 1.3]
diff= [83 76]
i= 2
b= [1.4]
a= [1.2]
diff= [166]
----------
k= 2  kend= 5
win= [1.3 1.4 1.5]
i= 1
b= [1.4 1.5]
a= [1.3 1.4]
diff= [76 71]
i= 2
b= [1.5]
a= [1.3]
diff= [153]
[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
  0 0 0 0 2 0 0 0 0 0 0 2 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]

You've already made the key observation here, which is that most of the work is redone. Each time you pick a window, most of the calculations are the same as the previous window.

In fact it's much faster to do all the calculations ahead of time into one big ndarray, and then for each window, pick out the calculations that are relevant. So we don't need the temporary a and b lists.

How many dimensions do we need? Just starting point and length. It's going to be a triangular array, so we'll waste some space.

precomputed_results = np.zeros(l_win+1, l_data), dtype = int)
# First pass
for interval in range(1, l_win):
    for first_point_index in range(l_data-interval):
        # compute diff relative to elements [first_point_index] and [first_point_index+interval]
        # line will be similar to precomputed_results[...] = ...

# Second pass
for interval in range(1, l_win):
    for first_point_index in range(l_data-interval):
        # use slicing on precomputed_results


Find the first unique character in a string Implementation for a relatively basic programming challenge:

  Find the first unique character in a string

So evaluating the string ABCA would return B.

My implementation does the following:

Initialize a boolean array that is the size of the input string - note that the default initialization value is false
The boolean array's values correspond to whether or not the input string character that shares the same index value is unique or not.
Compare each character in the input string against all the characters to the right of it
If there is a match, set the values in the boolean array to true for each character index value.
Iterate through the boolean array and return the first value that is false.
If iteration completes, throw a NoUniqueCharacters Exception

Is there a better approach?

I briefly considered using some sort of Ordered Map (if such a thing exists) that maps characters to their counts where the character key values are ordered by their index in the string

public Character identifyFirstUniqueCharacterInString(final String string) throws NoUniqueCharactersException {
        final char[] chars = string.toCharArray();
        final boolean[] repeatedCharacterIndices = new boolean[chars.length];
        for (int candidateCharacterIndex = 0; candidateCharacterIndex < chars.length; candidateCharacterIndex++) {
            for (int comparisonCharacterIndex = candidateCharacterIndex + 1; comparisonCharacterIndex < chars.length; comparisonCharacterIndex++) {
                if (chars[candidateCharacterIndex] == chars[comparisonCharacterIndex]) {
                    repeatedCharacterIndices[candidateCharacterIndex] = true;
                    repeatedCharacterIndices[comparisonCharacterIndex] = true;
                }
            }
        }
        for (int repeatedCharacterIndex = 0; repeatedCharacterIndex < repeatedCharacterIndices.length; repeatedCharacterIndex++) {
            if (!repeatedCharacterIndices[repeatedCharacterIndex]) {
                return chars[repeatedCharacterIndex];
            }
        }

        throw new NoUniqueCharactersException();
    }

One alternative is to let String.indexOf(int, int) do the iteration for you:

return IntStream.range(0, input.length())
                .filter(i -> input.indexOf(input.charAt(i), i + 1) == -1)
                .mapToObj(i -> Character.valueOf(input.charAt(i)))
                .findFirst().orElseThrow(NoUniqueCharactersException::new);

Loop with IntStream from 0 (inclusive) to the length of input (exclusive).
Filter for indices i where input.indexOf(input.charAt(i), i + 1) gives -1, i.e. there is no occurrence of the character at index i past that position.
For any matches, convert to our desired Character wrapper class using mapToObj().
In order to return the first character, we findFirst() from the IntStream, orElseThrow() our custom NoUniqueCharactersException.

A second alternative is to use String.lastIndexOf(int):

// instead of this
// .filter(i -> input.indexOf(input.charAt(i), i + 1) == -1)
// use this
.filter(i -> i == input.lastIndexOf(input.charAt(i)))

In this case, if the last index of the character at position i is indeed i, that means we have found our unique character.


Serving a webpage that displays the HTTP request information sent by the client In order to learn web server programming in Node and JavaScript, I decided to implement a simple web server that only does one thing:

Display data of the HTTP request as an HTML table.

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

const port = 3344;

const htmlCSS = `

`;

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

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

  writeResponse(req, res);
});

server.listen(port);

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

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

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

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

';
  const htmlTableBot = '

';

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

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

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

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

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

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

Can I use other modules to make this job easier?

You can use some web framework like fastify or express.
This would ease the code a lot

For a job this simple, is it worth to work with HTML and CSS as separate files?

Assumig your project will grown, it is a good approach to move some "static text" in a separated file.

How are HTML and CSS normally handled inside JS files (edits, appends, etc)?

You have made a server side rendering (SSR) by your hand.
Since it would be hard to manage manually all those piece of strings and would be also dandgerous to
some script injection, you could use some fremework as vue
or other templating systems like handlebarsjs or others - here a list

How well am I handling the construction of HTML and CSS?

There could be some security issue for links like that if you start to process those values:
http://localhost:3000/?user=%3Cimg%20src=%27aaa%27%20onerror=alert(1)%3E
the framework protect you from these cases usually.
This code:
  const htmlTitle = '<title>Your Request Is</title>'
  const htmlEncode = '<meta charset="UTF-8">'
  const htmlHead = `<head>${htmlTitle}${htmlCSS}${htmlEncode}</head>`
  const htmlTop = `<html lang="en">${htmlHead}<body>`

produce every time the same output string, so you could do it once instead of every request:
this will stress less the nodejs garbage collector for high throughput site.

Can this be done more concisely?

You could write less code using some Object and Array functions:
function stringTemplates (request) {
  return `

<title>Your Request Is</title>

${Object.entries(request.headers).map(processLine).join('')}
${['httpVersion', 'httpVersionMinor', 'httpVersionMajor', 'method', 'url'].map(prop => processLine([prop, request[prop]])).join('')}

`
}

function processLine ([header, value]) {
  return `<tr><td>${header}</td><td>${value}</td></tr>`
}

What would you do differently to improve this in any way?

This shows only GET, but in order to learn the HTTP standard it would useful to show in:

query parameters
form parameter (with different encoding)


Secure Functions in a Database Class I am trying to solve as many issues as possible with my Database Class and bind statements as far as possible without actually doing it in the front-end. The goal is to do all of the heaving lifting for PHP Developers and Web Designers as possible to make their job even more easier than other PHP frameworks.

The Database class is my main worry to make sure that I keep security with simplexity.

class Database {
// Instance of the Database and Error
private $db;
private $error;
private $stmt;

    public  function  __construct ()  {
    //  Init the database connection
    //  Sets the connection type
    $host = 'mysql:host' . $this->_hostname ';dbname' . $this->_database;

    //  Sets the connection options
    $options = array(
                     PDO :: ATTR_PERSISTENT  =>  TRUE ,
                     PDO::ATTR_ERRMODE    => PDO:ERRMODE_EXCEPTION
                    );

    try {
        //  Generates the Database connection of our class
        this->db = new PDO($host, $this->_username, $this->_password, $options);
    }
    catch(PDOException $exception) {
        //  Catches all errors from the Database connection
        $this->error = $exception->getMessage();
    }
}

The instance of the Database is defined and called in __construct() to allow it to be called globally in other classes.

For queries to be done, I managed a small (secure?) work around in the form of functions

public function execute() {
    //  Executes our SQL query
    return $this->stmt->execute();
}

public function results() {
    //  Returns all of the results from the table
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

public  function  result ()  {
    //  Returns one of the results from the table
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

With my knowledge, this is the most secure route of handling PDO and information unless I am wrong?

The other way, which seems to be more dangorious and common is to do $db->prepapre() and also db->execute() directly.

Am I handling the database class more securely than directly allowing the PDO built-in functions to do it directly in my class's code and pages?

This may sound harsh, I meant to be friendly though :)

It's bad/unsafe/vulnerable. This type of situation comes around a lot, which is sort of understandable. However, what is your class really doing? It's essentially pointless to make this class. You've basically just put a class in a class without doing anything different! So actually what you've done is make things less secure.

You mentioned a "more dangerous" option of preparing the query. That would be a false assumption. Preparing queries are one of the largest features of the PDO and MySQLi interfaces. They're far from dangerous if used correctly.

It's hard to tell if what you're really doing is "secure" because the actual SQL handling functions you've left out.

Now that that's out of the way...

To improve your coding, you can:

Fix indentation
Pick a coding style and apply it. You want clean code, not messy. Here's Zend's styles, which is one I like to offer because it's easy to follow and apply.

Then you're code will be nice and tidy!

Hows 'bout that PHP now!

Starting from the top:

$host = 'mysql:host' . $this->_hostname ';dbname' . $this->_database;

Where are you getting $_hostname and $_database? Same with $_username and $_password. It's okay to add those in your question next time (just without the actual values!) :)

In you first try...catch you have a typo. The assignment to this->db should really be $this->db. I'm not sure why you didn't receive an error for that.

This

public function execute() {
    return $this->stmt->execute();
}

is a nice try, but what's it's point? It's really not useful at all. That's be another reason home-made DB access classes aren't so great. If you do keep it, is it being called by the caller? If not, then you could make it private at least.

In both results() and result(), you return the associative array (PDO::FETCH_ASSOC) which may not be the best idea. What if you want to change the format of return down the line? There's not one easy way to do this.

Speaking of those two functions, I suggest you changes their names. I almost started to write how you had to of the same function. It's hard to tell them apart is what I'm saying.

So overall, there are many database access classes that come with frameworks that actually do improve the safety and handling of databases, unfortunately it's difficult to replicate your own. Don't be discouraged though! It's not a simple task, Laravel has about 50 different classes + interfaces just to make sure connecting to the database is perfect!


Searching a nested data structure for 2 attributes So I have the following data structures

export class BudgetGroupInfo {
    name: string;
    bcInfo: BudgetCatInfo[] = [];
}

export class BudgetCatInfo {
    name: string;
    description: string;
    bcAccounts: BCAccountInfo[] = [];
}

export class BCAccountInfo {
  name: string;
  description: string;
}

What I need to be able to do is find which BudgetGroupInfo contains both BudgetCatInfo.name and BCAccountInfo.name

This is what I have so far and it works, but I feel like this isn't the most efficient want to do this.

getGroupInfo(budCat: string, account: string, budgetGroupInfo: BudgetGroupInfo[]): BudgetGroupInfo {
    let groupInfo = null;

    budgetGroupInfo.forEach(infoGroup => {
      infoGroup.bcInfo.filter(bcInfo => bcInfo.name == budCat)
      .map(bcInfo => bcInfo.bcAccounts)
        .forEach(accounts => {
            const acctInfo: BCAccountInfo = accounts.find(acct => acct.name == account);
            if(acctInfo) {
              groupInfo = infoGroup;
            }
          });
      })

    return groupInfo;
  }

First I go through the groups and find which ones have the specific budCat
I take the valid BudgetCatInfo and map the bcAccount array
I search that array and look for the specified account
If I find it then I set it for return.

Just a note that there won't always be a result and there will never be multiple matches.

You are correct, this is an inefficient way to do this search. Even if the groupInfo is found in the first iteration of each loop, you still go through (almost) every single element.

First a couple comments on your code:

The return type is lying to me. The function doesn't return BudgetGroupInfo. It returns BudgetGroupInfo | null. The fact that this doesn't complain means that you don't have strictNullChecks on. In my experience, this is the single most helpful feature available. It will let TypeScript tell you about a whole class of errors that it otherwise ignores.
filter.map.forEach is fine if you know only a few elements will be looped over, but if you end up having a lot of data, this will end up taking 3x the time. I don't find it that helpful for readability here, so I'd just pull the checks into the loop function.
TypeScript is generally pretty good about figuring out what variable types are. You don't need to manually type the result of Array#find.

The main trick for optimizing this is to make use of Array#some and change the outer forEach into a find. Here's how I'd write your function:

function getGroupInfo(budCat: string, account: string, budgetGroupInfo: BudgetGroupInfo[]) {
    return budgetGroupInfo.find(group => {
        return group.bcInfo.some(info => {
            if (info.name !== budCat) return false;
            return info.bcAccounts.some(acct => acct.name === account);
        });
    });
}

There are a few subtle differences:

This returns undefined instead of null if there is no result. If this is a problem, it's a straightforward fix.
I removed the return type of the function. TypeScript can infer it easily in this case, and it will still be correctly inferred if you turn on strictNullChecks
If there is multiple matches (I know you said there wouldn't be but...) my version will return the first match, while yours returns the last match.


Add/remove class to label tags I came up with this jQuery snippet to add/remove a class on <label> tags that contain either checkboxes or radio buttons, in order to improve usability so users can see what item(s) they have selected.

But I would like to know if there's a way to optimize the code (or not if that's the case).

$('label input[type=radio], label input[type=checkbox]').click(function() {
  $('label:has(input:checked)').addClass('active');
  $('label:has(input:not(:checked))').removeClass('active');
});

You're adding a click handler to all your inputs, and then implementing the click handler such that each click processes all the labels.  This is probably not what you want.

I'd suggest the following:

$('label input[type=checkbox]').click(function() {
    $(this.parentNode).toggleClass('active', this.checked);
});

$('label input[type=radio]').click(function() {
    $('input[name="' + this.name + '"]').each(function(){
        $(this.parentNode).toggleClass('active', this.checked);
    });
});

Happily enough, that approach is also more efficient, as it's processing 1 element per click for checkboxes instead of n elements per click.  For radio buttons it still has to process multiple elements, but the number processed is still less than the total number of elements on the page (assuming the page contains more than a single group of radio buttons).

Here's a live example:  http://jsfiddle.net/DfU3R/3/

As nickles80 rightly notes, however, the performance difference between the two approaches will likely be negligible, and premature optimization is the root of all evil.


Dictionary foreach loop with multiple occurences A little look on what are Dictionaries:

dictWordCounter<string, int>
dictWordPercent<string, double>
topTwentySeven<string, double>

WordCounter is the number of words. For example, if the word frog is 10 times it will be {frog, 10}.
WordPercent is the percent after some math in the program. For example, frog could be {frog, 0,55}.
topTwentySeven is the top 27 values from the WordPercent dictionary that I want to operate on.

So, I need to count something like this:

If a word is just one, count it normally
If a word is twice or more, count it x2
Total number of words (after x2) must be still 27, not more

For example if it was "topThree" and words:

{Frog, 2}, {Monkey, 1}, {Giraffee, 1}, and their values from Percent Dictionary would be {Frog, 0,1}, {Giraffee, 0,2}, {Monkey, 0,45}, I want to count: 0,1*0,1*0,2 and (1-0,1) * (1-0,1)*(1-0,2).

Could someone look on this and check if it can be improved?

   var topTwentySeven = dictWordPercent.OrderByDescending(kvp => Math.Abs(kvp.Value - 0.5))
        .Take(27)
        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

    int compare = 0;
    double temp2 = 1.0, A = 1.0, B = 1.0;
    for (int counter = 0; counter < 27; )
    {

        foreach (var word in topTwentySeven)
        {
        dictWordCounter.TryGetValue(word.Key, out compare);
            if (compare >= 2 && counter < 26)
            {
                temp = word.Value;
                temp2 = temp * temp;
                A *= temp2;
                B *= (1 - temp2);
                counter = counter + 2;

            }
            else if (compare == 1 && counter < 27)
            {
                temp = word.Value;
                A *= temp;
                B *= (1 - temp);
                counter = counter + 1;
            }
            else if (counter >= 27)
            {
                //Do nothing
            }
        }
    }

int top27C = topTwentySeven.Count();

double aN = 0.0, bN = 0.0;
aN = Math.Pow(A, (1 / top27C));
bN = Math.Pow(B, (1 / top27C));

I need both A and B.

totalSum = Math.Round(((aN / (aN + bN)) * 100), 2);

Don't write dead code - it rots like a corpse and makes it hard to maintain your code:

else if (counter >= 27)
{
    //Do nothing
}

Just delete this.

You can use the ++ increment operator here:

counter = counter + 1;

Like this:

++counter;

There is a += operator you can use here:

counter = counter + 2;

Like this:

counter += 2;

There is a Math.Pow() method you can use:

temp2 = temp * temp;

Like this:

temp2 = Math.Pow(temp, 2);


Interfacing with RESTful web services The following working function seems a bit hacky to me as it has been pieced together from a handful of (probably poorly written) online tutorials, and I want to know if there is a better (or more standard) way to approach this.

/***
 * GET HTTP Operation
 *
 * @param   request Request URI
 * @return  Element Root Element of XML Response
 */
protected Element get(String request) {

    HttpURLConnection connection = null;

    Element rootElement;

    try {

        URL url = new URL(this.baseUrl + request);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        BASE64Encoder enc = new sun.misc.BASE64Encoder();
        String userpassword = this.username + ":" + this.password;
        String encodedAuthorization = enc.encode( userpassword.getBytes() );
        connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);
        connection.setRequestProperty("Content-type", "application/xml");
        connection.setRequestProperty("Accept", "application/xml");

        InputStream responseStream = connection.getInputStream();

        //--- Parse XML response InputStream into DOM

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse(responseStream);

        rootElement = doc.getDocumentElement();

    } catch(Exception e) {

        System.out.print(e.toString());
        rootElement = null;

    } finally {

        if(connection != null) {
            connection.disconnect();
        }

    }

    return rootElement;
}

I am a Java novice and am especially unclear on proper try/catch usage.

I am creating a Java Wrapper for an REST API and this is a small piece of that puzzle.  You can click here to see a bigger picture of the project as a whole.

Adding another answer since I'm actually looking at the code now...

You are swallowing every exception that gets thrown.  The calling code has no idea whether it tried to hit a page that didn't exist, its request was malformed, etc.  If you don't want to expose the exceptions (probably a good idea so your client code doesn't have to worry), then you might want to set some sort of error flag as part of your class that can be probed for the cause of not getting back the XML, or throw your own custom exceptions.

I'm assuming in your other methods you do similar sorts of set up for the connection (the accepts, etc)...I'd recommend moving that out into its own setup method.  If you need to specialize based on the type of request, then pass in the type and you can at least consolidate all of that into one place.