Temperature and currency converters in OOP JS

0. Little Typo

thermometer instead of termometer.

1. Global Variables

  let cel = "";
let fah = "";

Variables inside a global scope can be changed from everywhere.

1.1 Example

Imagine temperature.js is your script with the global variables inside. Now someone adds a table.js to display tables on the html page.

<script src="temperature.js"></script>
<script src="table.js"></script>

One line in table.js is cel = "<td>...</td>". The author of the code has accidentally a spelling mistake and writes cel instead of cell to indicate a table cell and breaks with this line your code in temperature.js.

1.2 Quick fix

function Termometer(kelven) {
    this.kelven = kelven;
    this.cel;
    this.fah;

    /* ... */
}

With this fix we binde the variables to Thermometer. To access them you need to create an instance of Thermometer.

const thermometer = new Thermometer(0)
console.log(thermometer.cel)

This means that inside table.js the author needs to write explicite thermometer.cel = ... to break your code.

2. Intuitive API

  const thermometer= new Thermometer(0)

thermometer.init()

console.log(thermometer.getCelsius())
console.log(thermometer.getFahrenheit())

To call thermometer.init() feels so wrong and it is not intuitive.

2.1 Quick fix

When new Thermometer(0) gets called, in the background a new instance gets build by the javascript runtime and it initializes all variables inside the instance.

To avoid the init method we can store the calculation in variables:

function Thermometer(kelven) {
    this.kelven = kelven;
    this.celsius = this.kelven - 273
    this.fahrenheit = Math.floor(this.celsius * (9 / 5) + 32)

    this.getCelsius = function() { return this.celsius }
    this.getFahrenheit = function() { return this.fahrenheit }
}

The code snipped above looks more intuitive with ES6-Classes:

class Thermometer {
    constructor(kelven) {
        this.kelven = kelven
        this.celsius = this.kelven - 273
        this.fahrenheit = Math.floor(this.celsius * (9 / 5) + 32)
    }

    getCelsius() { return this.celsius }
    getFahrenheit() { return this.fahrenheit }
}

Now, we can can interact with it like:

const thermometer = new Thermometer(0)

console.log(thermometer.getCelsius())
console.log(thermometer.getFahrenheit())

3. Unflexible

  function Thermometer(kel) {
   this.kel = kel

   this.getCelsius = function () {
       cel = this.kel - 273;
       return cel;
   }

   /* ... */
}

Currently the Thermometer only works for kelvin..

It would be great to archive that we can pass in celcius and it still works!

3.1 Common Interface

That this works all Units needs to share a common api that gets called by Thermometer. The Thermometer could call methods or properties like inCelcius, inFahrenheit and inKelvin.

function Thermometer(temperature) {
    this.getCelsius = function () { return temperature.inCelsius }
    this.getFahrenheit = function () { return temperature.inFahrenheit }
    this.getKelvin = function () { return temperature.inKelvin }
}

Based on that we can create our units:

function Kelvin(value) {
    this.inKelvin = value
    this.inCelsius = value - 273
    this.inFahrenheit = Math.floor(this.inCelsius * (9 / 5) + 32)
}

function Fahrenheit(value) {
    this.inKelvin = Math.floor((value + 459) * (9 / 5))
    this.inCelsius = Math.floor((value - 32) / (9 / 5))
    this.inFahrenheit = value
}

function Celsius(value) {
    this.inKelvin = value + 273
    this.inCelsius = value
    this.inFahrenheit = Math.floor(value * (9 / 5) + 32)
}

Now the Thermometer works for all units:

const kelvinMeter = new Thermometer(new Kelvin(0))
const fahrenMeter = new Thermometer(new Fahrenheit(0))
const celsiMeter = new Thermometer(new Celsius(0))

4. Unexpected Behavior

  this.getEur = function() {
   eur = Math.floor(this.sum1 / 4.72);
}

When I would call valuta.getEur() I would expect that the method getEur returns a value. Instead it returns undefined and changes a global variable.

const valuta = new Valuta(1, 2, 3)
const euro = valuta.getEur() // undefined


public boolean hasNext() {
    if(itr.hasNext())
    if (next != null) {
        return true;
    }
    return false;
}

First, there's inconsistent usage of braces for your block if statements. Second, if you are already keeping track of what is the next element to be returned by your de-dup iterator, wouldn't it be enough to just check against that?

public boolean hasNext() {
    return next != null;
}

A suggestion regarding the remove() implementation: the Javadoc API suggests that it can be called only once per call to next(). Since your implementation of next() is already quite different, you may want to re-consider whether your implementation can be as simple as calling remove() on the underlying iterator. In your example, is it expected to be removing only one 'C' or all 'C's when remove() is called?


Factory to augment JS classes with validation methods

Your solution works, and is perfectly functional, but it's bad practice.

What you're describing is the service locator anti-pattern, it means that instead of passing what you need to a function, you pass a magic box that holds what you need and many other things, and it's the responsibility of your consuming class to know this magic box (called a service locator), and be tightly coupled with it, to get the object it really needs. It's a redundant layer of abstraction that only makes things harder instead of easier.

Do you have a Matrix class? Pass it a MatrixValidator with a .validate() method. Have a Checkbox class? Pass it a CheckboxValidator with a .validate() method.

This way, your actual classes don't need to know anything about their validators, they only see an object with a .validate() method, and the .validate() method gets implemented differently for each validator. That's called polymorphism, and it's a powerful tool in your OO arsenal.

Additionally, dynamically adding methods to constructors (a.k.a. classes) is frowned upon, because it makes it hard to read. With the polymorphism method, all of your methods are known at write time, and nothing is added in runtime, which is good for both readability and performance.

Now, you might ask, "who will determine which Validator instance to inject to each of my classes", that would be "the entity that creates your instances", normally, that would be a factory of some sort, otherwise, look up Dependency Injection for a good pattern to follow.


I'm not sure what you want to achieve with the constructor.

public function __construct($var1,$var2, $var3)
    {
        $this->_var1= $this->$var1;
        $this->_var2= $this->var2;
        $this->_var3= 8;  // i need this 8 if no value is passed

    }

If you want to set the properties to the given parameters, you should do

 $this->_var1= $var1;

And with

$this->_var3= 8;  // i need this 8 if no value is passed

you always set property $_var3 to 8, nonetheless if $var3 is being passed.

For setting a default value to a paramter you can write it like this

public function __construct($var1, $var2, $var3 = 8)
        {
            $this->_var1 = $var1;
            $this->_var2 = $var2;
            $this->_var3 = $var3;

        }

so if you call

$r = new testClass($var1, $var2, 10);

$this->_var3 would be set to 10, and if you call

$r = new testClass($var1, $var2);

$this->_var3 would be set to the default 8.

In your testMethod you're using $this->var2 & $this->var3, without the underline. These properties are not defined.

return $runQuery($query);

remove the $ in the function's name, or it would be taken as variable.

In your SQL-Query there's a column named "name". In all cases where the column types are strings, you have to write the value in single quotes.

$query = "SELECT * from table where id = ".this->_var1." AND name= '".$this->_var2."' AND x= ".$this->_var3;

For debugging purposes, set

ini_set('display_errors', 1);
error_reporting(E_ALL);

to the starting script.


There is a structural issue with your code: the recursive function works at two levels. 1) It constructs a dict representing a node, and 2) it does some work in constructing the representation for the children. This makes it unnecessarily complicated. Instead, the function should focus on handling one node, and delegate the creation of child nodes to itself via recursion.

You seem to have requirements such as:

A node that has no children nor attributes converts to an empty string. My implementation: return output_dict or ""
Multiple children with same nodeName convert to a list of dicts, while a single one converts to just a dict. My implementation makes this explicit by constructing lists first, then applying this conversion: v if len(v) > 1 else v[0]
A node with children but no attributes raises a TypeError. I suspect this is an oversight and did not reproduce the behavior.

Note that (2) means that a consumer of your JSON that expects a variable number of nodes must handle one node as a special case. I don't think that is good design.

def get_attributes_from_node(self, node):
    attributes = {}
    if node.attributes:
        for attrName, attrValue in node.attributes.items():
            attributes["@" + attrName] = attrValue
    return attributes

def recursing_xml_to_json(self, node):
    d = collections.defaultdict(list)
    for child in node.childNodes:
        if child.nodeType == Node.ELEMENT_NODE:
            d[child.nodeName].append(self.recursing_xml_to_json(child))

    output_dict = self.get_attributes_from_node(node)
    output_dict.update((k, v if len(v) > 1 else v[0])
                       for k, v in d.iteritems())

    return output_dict or ""


Search a directory structure for tar files and report on their size

The biggest complaint I would have with this code is that you're essentially defining your size map twice.  Imagine if you decide you don't want to report on files between 50 and 75MB - you remove the "75" entry from the dictionary, but forget to remove it from the MakeDictionaryKey method, and your program will occasionally fail at runtime.

First, I'd consider modifying your dictionary so instead of using "999" as a synonym for "really big file", you use int.MaxValue:

        , {100, 0}
        , {int.MaxValue, 0}

In your MakeDictionaryKey method, you're then looking for the smallest key value where the key value is greater than the file size you've provided to it.  With a bit of LINQ, that simply becomes:

private static int MakeDictionaryKey(int n)
{
   return sizeMap.Keys.Where(x => x <= n).Min();
}


CodeEval Challenge: Remove specified characters from a string

You can extract out the requirement into its own method:

private static String removeCharacters(String input, String excludedLetters) {
    // ...
}

And since you have to split from a single String first, you can use a wrapper method in addition to the one above:

private static String removeCharacters(String line) {
    String[] parts = // ...
    return removeCharacters(parts[0], parts[1]);
}

If you are on Java 8, you can use a combination of try-with-resources and Files.lines() to Streamline the processing (pun intended):

try (Stream<String> lines = Files.lines(Paths.get(/* ... */))) {
    lines.map(Main::removeCharacters).forEach(System.out::println);
}


The things to consider when it comes to async event handlers are:

Exceptions thrown for the handler might be rethrown on the UI SynchronizationContext, which usually crashes the application.
After you raise the event, the handlers won't be completed yet. The execution of a handler might be interleaved with the execution of the code after the raising and execution of multiple handlers can also be interleaved with each other.

Assuming those caveats are acceptable for you, code like this should be fine.

Also:

view.OnRefreshObjectExplorerClicked += new EventHandler(async (s, e) => await RefreshObjectExplorerAsync());

You should be able to simplify this to just:

view.OnRefreshObjectExplorerClicked += async (s, e) => await RefreshObjectExplorerAsync();

It seems you never unsubscribe the event handlers, are you sure that's okay?


Digital root computation with benchmarking

I think your algorithmic part is exceedingly verbose.  One of the nicenesses of Python is how it can lead to code that reads almost like English.  And for this particular problem, even leaving performance considerations aside, I think iteration is clearer than recursion.  So I would rewrite things as:

def digits_of(number):
    """Yields the digits of an integer."""
    while number > 0:
        yield number % 10
        number //= 10

def digital_root(number):
    """Computes the digital root of an integer."""
    while number > 9:
        number = sum(digits_of(number))
    return number

I'm pretty sure my 6 year old daughter could make sense of that last function with very little help.


I'm not really familiar with mocha. If I understand correctly, the true and false values here closely releated, in the sense that they should be opposites:

var stub = sinon.stub(Backbone, "sync", function(method, model) {
    expect(model.get("completed")).to.equal(true);
});

var todo = new app.Todo({completed: false});

In that case, to avoid mistakes, it would be better to include that logic in the code, for example:

var initial_state = false;
var stub = sinon.stub(Backbone, "sync", function(method, model) {
    expect(model.get("completed")).to.equal(initial_state);
});

var todo = new app.Todo({completed: !initial_state});

And maybe add another test for the inverse, for initial_state = true.

Instead of this:

var todo = new app.Todo({completed: false});
todo.toggle();

Since you only use the todo instance once, I would combine the two lines to shorten the code:

new app.Todo({completed: false}).toggle();

Instead of this .to.equal(true):

expect(stub.calledOnce).to.equal(true);

I think it would be more natural (and shorter) with .to.be.ok():

expect(stub.calledOnce).to.be.ok();


Implementing simple and fast inheritance in JavaScript

(1) Any opinion about this?

Emulating language features/idioms which are not supported by the language itself (e.g. classes in JavaScript) does not seem to be a very good idea to me.
JavaScript is not an classical OOP-Language (yet), but there are Prototypes:

(function(){

    var Person = Object.create(null);
    Person.name = "";
    Person.say = function Person_say () {

        console.log("Person: " + this.name);

    };

    var Student = Object.create(Person);
    Student.say = function Student_say () {

        Person.say.call(this);
        console.log("Student: " + this.name);

    };

    var PsychicStudent = Object.create(Student);
    PsychicStudent.say = function PsychicStudent_say () {

        Student.say.call(this);
        console.log("PsychicStudent: " + this.name);

    };

    var ParanormalStudent = Object.create(PsychicStudent);
    ParanormalStudent.say = function ParanormalStudent_say () {

        PsychicStudent.say.call(this);
        console.log("ParanormalStudent: " + this.name);

    };

    var p = Object.create(Person);
    p.name = "A";
    p.say();

    var s = Object.create(Student);
    s.name = "B";
    s.say();

    var s1 = Object.create(PsychicStudent);
    s1.name = "C";
    s1.say();

    var s2 = Object.create(ParanormalStudent);
    s2.name = "D";
    s2.say();

}());

For insights i recommend:

http://javascript.crockford.com/prototypal.html
http://www.crockford.com/javascript/inheritance.html especially the conclusion at the end

(2) Is this fast?

Emulation is probably slower than using native methods - i suppose.
However, it depends on the underlying engine. V8 is faster than Gecko.

(3) What about correctness?

Depends on how you understand correctness. JavaScript is powerful enough to emulate classical inheritance to some extend.

(4) FYI

If you want a more Java-like access to the parent-prototype with "super"-sugar, you can do something like this:

(function(){

    Object.extend = function Object_extend (parent) {

       var child = Object.create(parent);

       child.super = function (name,ctx) {

            if (typeof parent[name] === "function") {

                parent[name].call(ctx);

            }

            return parent;

        };

        return child

    };

    var Person = Object.create(null);
    Person.name = "";
    Person.say = function Person_say () {

        console.log("Person: " + this.name);

    };

    var Student = Object.extend(Person);
    Student.say = function Student_say () {

        Student.super("say", this)
        console.log("Student: " + this.name);

    };

    var PsychicStudent = Object.extend(Student);
    PsychicStudent.say = function PsychicStudent_say () {

        PsychicStudent.super("say", this);
        console.log("PsychicStudent: " + this.name);

    };

    var ParanormalStudent = Object.extend(PsychicStudent);
    ParanormalStudent.say = function ParanormalStudent_say () {

        ParanormalStudent.super("say", this);
        console.log("ParanormalStudent: " + this.name);

    };

    var p = Object.create(Person);
    p.name = "A";
    p.say();

    var s = Object.create(Student);
    s.name = "B";
    s.say();

    var s1 = Object.create(PsychicStudent);
    s1.name = "C";
    s1.say();

    var s2 = Object.create(ParanormalStudent);
    s2.name = "D";
    s2.say();

}());

However, bear in mind, that "super" is also a foreign concept to JavaScript.
You cannot type foreign syntax and expect it to behave identically with comparable performance.
Additionally, you may emulate "super" as shown above, but you will have to use with great care, meaning 'ParanormalStudent.super' and 'this.super' may point to the same function, however, the latter will result in exceeding the call stack. This seems to me like a bad practice, since as a programmer you will have a tool which may either work or produce chaos.


PHP spell checker with suggestions for misspelled words

Here are a couple of tweaks that could help performance:

Rather than storing the dictionary in-memory, offload that to a database (potentially even caching commonly misspelled words as an optimization)
Ignore words under a certain length
(for example, MySQL's fulltext searching ignores words with fewer than 4 characters by default)

The thing that concerns me most with your algorithm is how much time it would take to compare every single word in the dictionary.  This problem compounds with more words in the search query.

There has to be a way to quickly filter the dictionary to a smaller list of higher probability similarities (i.e. by word length, first letter, etc. ?)


Removing key/value pairs in list of dicts

Any solution will have to read the values associated to each key of each dictionary; so you won't be able to drop under \$\mathcal{O}(n\times{}m)\$ where \$m\$ is the length of each dictionary. This is pretty much what you are doing, but the if k not in keep_keys call slows things a bit as it is \$\mathcal{O}(m)\$ when it could be \$\mathcal{O}(1)\$ by using a set or a dictionary.

If you change the keep_keys list into a set you simplify the logic a bit: as soon as you find a key whose value is not None you can add it into the set.

dicts = [{'a': 1, 'b': None, 'c': 4}, {'a': 2, 'b': None, 'c': 3}, {'a': None, 'b': None, 'c': 3}]
expected = [{'a': 1, 'c': 4}, {'a': 2, 'c': 3}, {'a': None, 'c': 3}]

keep_keys = set()

for d in dicts:
    for key, value in d.items():
        if value is not None:
            keep_keys.add(key)

remove_keys = set(d) - keep_keys

for d in dicts:
    for k in remove_keys:
        del d[k]

print dicts == expected

This code, as your original one, assume that there is at least one item in dicts; otherwise set(d) will generate an exception as the variable d is not defined yet.

But this code mixes the actual logic with some tests. You should wrap it in a function to ease reusability and put the testing code under an if __name__ == '__main__': clause:

def filter_nones(dictionaries):
    if not dictionaries:
        return

    keep_keys = set()

    for dict_ in dictionaries:
        for key, value in dict_.iteritems():
            if value is not None:
                keep_keys.add(key)

    remove_keys = set(dict_) - keep_keys

    for dict_ in dictionaries:
        for key in remove_keys:
            del dict_[key]

if __name__ == '__main__':
    dicts = [
            {'a': 1, 'b': None, 'c': 4},
            {'a': 2, 'b': None, 'c': 3},
            {'a': None, 'b': None, 'c': 3},
    ]
    expected = [
            {'a': 1, 'c': 4},
            {'a': 2, 'c': 3},
            {'a': None, 'c': 3},
    ]

    filter_nones(dicts)
    print dicts == expected


const stack = new Array()

Use the literal notation ([]) instead. Here's an answer on Stack Overflow that elaborates why you should do that instead of new Array().

const duplicate = () => {
    try {
        const dup = pop();
        push(dup);
        push(dup);
    } catch(e) {
        throw new Error(e);
    }
};

The rule of thumb when it comes to using exceptions is to never use them where you can use an if. That is, don't use exceptions as a flow control mechanism. You should only use it if you want to bail out and do no further.

Also, e is already an instance of Error. You only need to do throw e, not throw new Error(e).

Now if you look closely, all the operations are distinct to each other. They also only operate on the stack only. You can easily implement them as pure functions, taking in the current stack, and returning a new representation of the stack.

For example, duplicate can be implemented as a function that takes an array, and returns a new array, with the last item repeated once more:

const duplicate = stack =>
  stack.length < 1 ? -1
  : [...stack, stack[stack.length - 1]]

add can be implemented as a function that takes an array, and return an new array which replaces the last two items with their sum:

const add = stack =>
  stack.length < 2 ? -1
  : [...stack.slice(0, -2), stack[stack.length - 1] + stack[stack.length - 2]]

Doing it this way makes it easier to implement each operation without having them becoming dependent on some common state object, or each other.

Here's how I would implement it:

// Implement each operation as distinct, pure functions.
const push = (stack, v) => [...stack, v]

const pop = stack =>
  stack.length < 1 ? -1
  : stack.slice(0, -1)

const duplicate = stack =>
  stack.length < 1 ? -1
  : [...stack, stack[stack.length - 1]]

const add = stack =>
  stack.length < 2 ? -1
  : [...stack.slice(0, -2), stack[stack.length - 1] + stack[stack.length - 2]]

const subtract = stack =>
  stack.length < 2 ? -1
  : [...stack.slice(0, -2), stack[stack.length - 1] - stack[stack.length - 2]]

// Map operation tokens to their implementation.
// Should we add more operations, we simply add the implementation and reference
// its token in this map
const operations = {
  'DUP': duplicate,
  'POP': pop,
  '+': add,
  '-': subtract
}

const solution = s => {

  // For each token, parse and process.
  // You can implement this piece using iteration functions, loops, or even recursion.
  // I'm just more accustomed to reduce because it can carry a value across iterations
  // which, in this case, holds the stack for me.
  const result = s.split(' ').reduce((stack, token) => {

    // If any operation returned -1, we return -1 all the way.
    return stack === -1 ? -1
      // If token is a number, push it to the stack.
      : !isNaN(parseFloat(token)) && isFinite(token) ? push(stack, Number(token))
      // If token is an operation, apply operation.
      : operations[token.toUpperCase()] ? operations[token.toUpperCase()](stack)
      // Unknown token.
      : -1

  // Our stack as initial reduce value, an empty array.
  }, [])

  // If the result is -1, then so be it. Otherwise, return the top of the stack.
  return result === -1 ? -1 : result[result.length - 1]
}

console.log(solution("3 DUP 5 - -"));
console.log(solution("13 DUP 4 POP 5 DUP + DUP + -"));
console.log(solution("5 6 + -"));


You have probably an error in your first for loop:

    weights[i] = start+weights[i]
    start += weights[i]

as the resulting value of start (BTW not very descriptive name) will be increased twice by weights[i], so the fix may be

    start += weights[i]
    weights[i] = start

But anyway, why you accumulate weights of individual words and moreover you assign the final result (which will be always 1, of course) in the start variable, if you never use it? IMHO your program perform something other than you want.

As your two input lists correspond one to other, why not use the zip() function to make pairs of corresponding values:

word_weights = zip(words, weights)

and use it in your for loops?

Why don't utilize the enumerate() function for obtaining indices without any effort?


A bag of numbers in C++ for constant time statistics queries

Since the code is not doing a rocket science, I'll only mention subtle things that slipped through.

Non-associative math:

Floating point math is very dangerous to deal with. This is especially true when optimizations are all high (I actually had to observe it myself). So, the expression:

m_sum * m_sum / m_size;

has chances to produce different results on different optimization levels. It is better to put parentheses:

(m_sum * m_sum) / m_size;

Calling non explicit constructor:

    m_size = 0;
    m_sum = 0;
    m_square_sum = 0;

Those statements might not compile if the constructor of Num is explicit. I think sometimes it is reasonable to make it explicit. Instead, directly call the constructor with the 0 in it:

    m_size = Num(0);
    //ditto

Non-portable code:

return sqrt(var());

Unqualified call assumes that sqrt() is present in the current namespace. It is not always so, since cmath guarantees only functions being available in std namespace.

Unnecessary include:

<cstdlib> looks useless here. <cstddef> should be used instead for std::size_t.

cosmetics:

Num is too generic. FloatingPoint would do better, though the class can use fixed point as well. If I would know word for combination of both, I would put it instead of Num. It will tell more about the type.

Indentations inside of namespaces is weird for me.

Design:

May be it would be possible to write something like in a python:

bag - num(12);

so it would remove the number from bag. The current design seems slightly verbose.

ADL:

As mentioned in the comment, it is good to put the operator inside of the namespace in which the class appears, and in namespaces that inlined into namespace that declares the class. It will trigger argument dependent lookup, the reason why using std::swap; swap(a, b); works.


Looking for all numbers where each digit is bigger than the previous digit

Instead of searching all numbers and checking them one by one, why not construct the numbers from the rule. In other words, start with the smallest digit being 1, then the next digit being 2 and so on. The digits can then be increased right to left as long as the rule holds.

For example, finding all 8 digit numbers:

Start with each digit increasing by 1 left to right:

12345678

Add one to the final digit:

12345679

Run out of digits so increase the digit to the left:

12345689
12345789
12346789
...
23456789

EDIT for further explanation:

For smaller numbers, you then need to repeat this process recursively. For example:

123 -> 124 -> 125 ... 129

You would now need to "reset" the second digit and any following it to one above what it was:

129 -> 134 -> 135 -> 136 ... 139
139 -> 145 -> 146 -> 147 ... 149
149 -> 156 -> 157 -> 158 -> 159

And so on.

You are still effectively working backwards through the digits, recursively increasing them right to left.

Hope that helps.


The obvious downside of your current approach is that you do a lot potentially unnecessary copying. One common solution is to return (const) iterators to the entries, i.e.,:

class Record
{
    public:
        // ...

       auto cbegin() const { return entries.cbegin(); }
       auto cend() const { return entries.cend(); }

       // Perhaps similar methods for getting non-const iterators ...
};

This solution allows you to use e.g., standard algorithms on the entries, but you can't manipulate the underlying range from the outside (due to const-ness).

To support your earlier use case, you can still do std::vector<std::string> res(r.cbegin(), r.cend()); if you wish, where r is an object of type Record.


Yes, you seem to have it correct.

openssl_random_pseudo_bytes(16) is good because it is generating a 64 bit token value for the token, which is more than strong enough.

The

    //ensure request is ajax
    if(!$app->slim->request->isXhr()){
        $app->halt(403,'Access Denied to Ajax Resource');
    }

check is great because this inherently protects against CSRF. This would be checking a header such as X-Requested-With which cannot be sent cross domain without CORS. Therefore it makes it impossible for an attacker to send such a request cross domain for their malicious site.

Remember there is no need to refresh the CSRF token, apart from once per session. It can sometimes hurt usability if you do because it can stop your application working if there are multiple tabs open.

  I assume it is safe to return the CSRF token to the user in the JSON response here?

Yes, because an attacker will not be able to read the response. Of course implementing SSL/TLS so your URLs are encrypted over HTTPS is highly recommended to prevent any Man-In-The-Middle or eavesdropping attacks.


Just like many CSS frameworks, bootstrap is meant to reduce (or even eliminate) the need to write CSS. Instead, it offers predefined classes to be used with divs to give the page a shape.

I agree that it might seem that the code above has "divitis." As a matter of fact, not even with CSS3 is it always possible to create a certain layout or style using semantic HTML only. So since the divs exist exactly for that, and using a framework might reduce development time by scales, I don't see anything bad with the code above. It's completely semantic, correct as of bootstrap, and apart from bootstrap itself contains no redundancy.


I have started to interest myself in artificial intelligence a while ago, especially within the game industry. I have started with state machines moved on to fuzzy logic and now I want to learn and implement a neural network which will also work for games.

It's great that you're exploring different approaches! While applying state machines or say behavior trees to games is straightforward, applying "neural networks" to games does not make too much sense: imagine you were saying "I'm going to apply Python to games": the language is important, but much less important than what you're going to do with it. However, learning as you're doing here is a good way to move forward, so keep it up! You've gone further than many people here.

  However to not overwhelm my tiny little head I wanted to start small.

Great!

  Is this class useful for a later neural network (keeping in mind that this class only represents a neuron) so that I than can use this class inside a neuronal network?

Unfortunately, no. Neural networks are not implemented like this in practice. Neurons are not considered individually: the libraries model all the weights of the connections between one layer and the next, because it's much faster to train, and speed is crucial.

  Are there any bad issues which I haven't seen?

No, the only issue is that it won't be easy to do more things with the current structure.

import numpy as np
import math

# From Stackoverflow
def find_nearest(array,value):
    idx = (np.abs(array-value)).argmin()
    return array[idx]

Unused code.

def hlim(x):
    return 0.5 if x == 0 else 0 if x < 0 else 1

The threshold activation function is not very good, consider using at least a sigmoid or a ReLU (very easy to implement, works very well in practice). But it will only matter when you will start thinking about backpropagation.

class Synapse(object):
    def __init__(self, origin, destination, weight = 0):
        self.weight = weight
        self.origin = origin
        self.destination = destination

        self.origin.synapse = self
        self.destination.synapse = self

Notice that you never use .origin because you always go from the Input to the Synapse, not the other way around.

So this is nice object-oriented code, but I think this is overly complex: most of the code ties the objects together: you could get something much shorter:

def neuron_score(bias, weight_list, input_list):
    score = 0
    for weight, input in zip(weight_list, input_list):
        score += weight * input
    score -= bias

    return "fired" if hlim(score) > 0 else "not fired"

if __name__ == "__main__":
    print(neuron_score(1.5, [1, 1], [1, 1]))
    print(neuron_score(0.5, [1, 1], [0, 0]))
    print(neuron_score(-0.5, [0], [-1]))

See how this gets down to the essence of it? Of course this can be made much faster by using numpy arrays (and ndarray for more than one more neuron).

So, now, how do you implement XOR? :) Use the Tensorflow playground to try and get intuition about this.


Just a few ideas

You could use tuple unpacking to make parse more concise.

class LogRecord:
    def __init__(self, line):
        self.parse(line)

    def parse(self, line):
        fields = line.split('\t')
        self.version, self.date, time, self.ipAddress, self.url, self.userAgentString, properties, self.customerId = fields
        self.time = long(time)
        self.properties = ast.literal_eval(properties)

    def select(self, *fields):
        d = { key: getattr(self, key) for key in fields }
        Tuple = namedtuple('Tuple', fields)
        return Tuple(**d)

Alternatively, you could define a list of (name, function to apply) and iterate through both lists in the same with zip to fill a dictionary.

class LogRecord:
    def __init__(self, line):
        self.parse(line)

    def parse(self, line):
        identity = lambda x: x
        desc = [('version', identity), ('date', identity), ('time', long), ('ipAddress', identity), ('url', identity), ('userAgentString', identity), ('properties', ast.literal_eval), ('customerId', identity)]

        fields = line.split('\t')
        assert len(desc) == len(fields)
        self.values = {name: func(field) for (name, func), field in zip(desc, fields)}

    def select(self, *fields):
        d = { key: self.values[key] for key in fields }
        Tuple = namedtuple('Tuple', fields)
        return Tuple(**d)


A class to add and select players within a database

Calling get_player twice is not a good idea, as each time a db query is necessary.

As you are asking about OOP: You could add an actual Player object, which contains playername, position, etc as fields. Your current class could then be renamed PlayerDAO or something, and would then return a player object.

The main advantage would be that a concrete object is easier to use than an anonymous one (classes are to some degree self-documenting, while you can't be sure what an anonymous object actually contains).

Misc

don't die or echo in classes, it makes code less flexible and harder to reuse, as the calling code cannot try to recover.
get_player and set_player could be renamed to get and set as the class is already called player.
It would probably also be good to rename set to save or similar, as it makes more explicit that there is some kind of database interaction (set sounds as if a private field is set).


First of all, well done on building a working area calculator. Lets see how we can improve it!

To start off, you have quite a few indentation problems. The definition of the class should not be indented at all, and the methods inside the class should be indented once. For each nesting level, you indent another time.

Also, your class is named calc, but Java classes are supposed to be PascalCase, meaning it should be Calc, with an uppercase c.

Functions

You are using too much vertical space. Not every line needs to have an empty line all around it. Try to group blocks of related lines of code together.

Most, if not all of your functions, do more than one thing. In programming we strive for functions that perform a single task and do so very well. For example, your main function is also in charge of how the user interface is presented to the user. This should be offloaded to another function like so:

private static void showUserOptions() {
    System.out.println("What would you like to do? Type the number of your desired function.");

    System.out.println("1. Area of a Circle");
    System.out.println("2. Area of a Square");
    System.out.println("3. Area of a Triangle");
    System.out.println("4. Area of a Rectangle");
    System.out.println("5. Quit");
}

Now we can simply call this function from the main method. As you can see, I have also grouped the System.out.println() statements that specify the options very close to each other. This helps with readability a lot.

Your functions also contain a lot of code duplication, such as printing the area of the selected shape and creating a new Scanner instance in every function, which is totally unnecessary and can be replaced with a single static instance like so:

private static Scanner inputScanner = new Scanner(System.in);

Furthermore, your variable names are not very clear. a_r is a useless variable name. How about rectangleArea?

User Input

For the user input of your program, we can user Java enums:

private enum UserInput { CIRCLE, SQUARE, TRIANGLE, RECTANGLE, QUIT, INVALID }

Here I have created 4 enum values for the different shapes, a QUIT enum value for the quit command and an INVALID value for any user input that is invalid.

Now we do have to change the showUserOptions() function a bit to make it correspond with the new enum values. This is done as follows:

private static void showUserOptions() {
    System.out.println("What would you like to do? Type the number of your desired function.");

    System.out.println(UserInput.CIRCLE.ordinal() + ". Area of a Circle");
    System.out.println(UserInput.SQUARE.ordinal() + ". Area of a Square");
    System.out.println(UserInput.TRIANGLE.ordinal() + ". Area of a Triangle");
    System.out.println(UserInput.RECTANGLE.ordinal() + ". Area of a Rectangle");
    System.out.println(UserInput.QUIT.ordinal() + ". Quit");
}

Calling ordinal() on an enum will give you the index it has in the list of enum values. Meaning that UserInput.SQUARE.ordinal() will result in 0 and UserInput.QUIT.ordinal() will result in 4.

To retrieve an actual enum object from the integer input provided by the user, the following code can be used:

int input = inputScanner.nextInt();
UserInput userInput = UserInput.values()[input];

UserInput.values() creates an array of the enum values, which looks like this: [CIRCLE, SQUARE, TRIANGLE, RECTANGLE, QUIT, INVALID]. Indexing it with the integer input from the user gives us the actual enum value. The UserInput.values() call actually creates a new array every time it is called, so we will be caching it as a static variable right underneath the declaration of the enum itself:

private enum UserInput { CIRCLE, SQUARE, TRIANGLE, RECTANGLE, QUIT, INVALID }
private static UserInput[] userInputs = UserInput.values();

Since the user can enter any integer value, even ones that are outside the range of the userInputs() array, we create a special function to deal with this and ensure that we always get a UserInput enum:

private static UserInput getUserInputFromInt(int userInput) {
    if (userInput >= 0 && userInput < userInputs.length) {
        return userInputs[userInput];
    }

    return UserInput.INVALID;
}

Since your code contained a lot of duplication of retrieving user input, I have created this function:

private static double askUserForValue(String valueName, UserInput userInput) {
    System.out.println(String.format("Please enter the %s of your %s.", valueName, userInput.toString().toLowerCase()));

    return inputScanner.nextDouble();
}

Which we can call like this:

double radius = askUserForValue("radius", userInput);

To ask the user to provide us the radius of a circle.

Main method

The main method of your program should be concise and clear. Also it should definitely not be called manually from other functions. These other functions have no business calling the main method, as they should only be looking to fulfill their single task. I would therefore suggest a rewrite of your main() function:

public static void main(String[] args) {
    while (true) {
        showUserOptions();

        UserInput userInput = getUserInputFromInt(inputScanner.nextInt());
        actOnUserInput(userInput);
    }
}

A few things stand out here. I have renamed your scanner to inputScanner, as readc isn't that good of a name for a Scanner object. Also I am calling a method that we have not yet defined, called actOnUserInput(). I will show this function in detail below. Finally, I have wrapped these two function calls in a while loop, to ensure that they will repeatedly be called. This makes it so that we can remove the calls to main() from all other places in the code.

Object Oriented Programming

Why not practice some object oriented programming while we are at it?

What we are dealing with here is a bunch of shapes. This allows us to create an abstraction of a Shape object. This is achieved by defining a common interface that all shapes share:

interface Shape {
    public double getArea();
}

Now that we have the Shape interface, we can create some concrete implementations of it. Lets start out with the circle object:

private static class Circle implements Shape {
    double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double getArea() {
        return Math.PI * this.radius * this.radius;
    }
}

Now we can do the same for the triangle and rectangle shapes:

private static class Triangle implements Shape {
    double height;
    double base;

    public Triangle(double height, double base) {
        this.height = height;
        this.base = base;
    }

    @Override
    public double getArea() {
        return 0.5 * this.height * this.base;
    }
}

private static class Rectangle implements Shape {
    double length;
    double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    public double getArea() {
        return this.length * this.width;
    }
}

All that is missing now is the Square class. However, in mathematics, a square is a subclass of rectangle. Implementing this using inheritance would look like this:

private static class Square extends Rectangle {
    public Square(double sideLength) {
        super(sideLength, sideLength);
    }
}

Here, the square class only calls the parent constructor using the same length parameter for the width and height. The getArea() functionality is inherited from the Rectangle class and doesn't need to be implemented again.

Whether or not it is a good idea to have Square inherit from Rectangle is debatable and often discouraged, since inheritance can become quite messy. However, for the sake of this example I believe it is justified.

Now that we have defined a bunch of concrete Shape implementations, we would like to create them!

We can use the UserInput enum to determine which type of shape we want to create. This can be put into a single factory-like function that will simply return a Shape object:

private static Shape createShapeFromUserInput(UserInput userInput) {
    switch (userInput) {
        case CIRCLE:
            double radius = askUserForValue("radius", userInput);

            return new Circle(radius);
        case SQUARE:
            double sideLength = askUserForValue("side length", userInput);

            return new Square(sideLength);
        case TRIANGLE:
            double height = askUserForValue("height", userInput);
            double base = askUserForValue("base", userInput);

            return new Triangle(height, base);
        case RECTANGLE:
            double length = askUserForValue("length", userInput);
            double width = askUserForValue("width", userInput);

            return new Rectangle(length, width);
    }

    return null;
}

Now we can incorporate this function into the yet to be defined actOnUserInput() function:

private static void actOnUserInput(UserInput userInput) {
    switch (userInput) {
        case CIRCLE:
        case SQUARE:
        case TRIANGLE:
        case RECTANGLE:
            Shape shape = createShapeFromUserInput(userInput);

            if (shape != null) {
                System.out.println("The area is equal to: " + String.valueOf(shape.getArea()));
            }
            break;
        case QUIT:
            quit();
            break;
        case INVALID:
            System.out.println("I'm sorry, you didn't select a function.");
            System.out.println("Please choose again");
            break;
    }
}

Here we can see the purpose of the Shape interface come through. After calling createShapeFromUserInput(), we don't care whether a Rectangle, Circle, or whatever type of shape is returned, only that it is a Shape instance. This is because now we can simply call the getArea() method defined on the Shape interface and rely on that.

The entire program now looks like this:

import java.util.Scanner;

public class Calc {
    private enum UserInput { CIRCLE, SQUARE, TRIANGLE, RECTANGLE, QUIT, INVALID }
    private static UserInput[] userInputs = UserInput.values();

    private static Scanner inputScanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            showUserOptions();

            UserInput userInput = getUserInputFromInt(inputScanner.nextInt());
            actOnUserInput(userInput);
        }
    }

    private static void showUserOptions() {
        System.out.println("What would you like to do? Type the number of your desired function.");

        System.out.println(UserInput.CIRCLE.ordinal() + ". Area of a Circle");
        System.out.println(UserInput.SQUARE.ordinal() + ". Area of a Square");
        System.out.println(UserInput.TRIANGLE.ordinal() + ". Area of a Triangle");
        System.out.println(UserInput.RECTANGLE.ordinal() + ". Area of a Rectangle");
        System.out.println(UserInput.QUIT.ordinal() + ". Quit");
    }

    private static UserInput getUserInputFromInt(int userInput) {
        if (userInput >= 0 && userInput < userInputs.length) {
            return userInputs[userInput];
        }

        return UserInput.INVALID;
    }

    private static void actOnUserInput(UserInput userInput) {
        switch (userInput) {
            case CIRCLE:
            case SQUARE:
            case TRIANGLE:
            case RECTANGLE:
                Shape shape = createShapeFromUserInput(userInput);

                if (shape != null) {
                    System.out.println("The area is equal to: " + String.valueOf(shape.getArea()));
                }
                break;
            case QUIT:
                quit();
                break;
            case INVALID:
                System.out.println("I'm sorry, you didn't select a function.");
                System.out.println("Please choose again");
                break;
        }
    }

    private static Shape createShapeFromUserInput(UserInput userInput) {
        switch (userInput) {
            case CIRCLE:
                double radius = askUserForValue("radius", userInput);

                return new Circle(radius);
            case SQUARE:
                double sideLength = askUserForValue("side length", userInput);

                return new Square(sideLength);
            case TRIANGLE:
                double height = askUserForValue("height", userInput);
                double base = askUserForValue("base", userInput);

                return new Triangle(height, base);
            case RECTANGLE:
                double length = askUserForValue("length", userInput);
                double width = askUserForValue("width", userInput);

                return new Rectangle(length, width);
        }

        return null;
    }

    private static double askUserForValue(String valueName, UserInput userInput) {
        System.out.println(String.format("Please enter the %s of your %s.", valueName, userInput.toString().toLowerCase()));

        return inputScanner.nextDouble();
    }

    private static void quit() {
        System.out.println("Quiting....");

        System.exit(0);

    }

    private interface Shape {
        double getArea();
    }

    private static class Circle implements Shape {
        double radius;

        public Circle(double radius) {
            this.radius = radius;
        }

        @Override
        public double getArea() {
            return Math.PI * this.radius * this.radius;
        }
    }

    private static class Triangle implements Shape {
        double height;
        double base;

        public Triangle(double height, double base) {
            this.height = height;
            this.base = base;
        }

        @Override
        public double getArea() {
            return 0.5 * this.height * this.base;
        }
    }

    private static class Rectangle implements Shape {
        double length;
        double width;

        public Rectangle(double length, double width) {
            this.length = length;
            this.width = width;
        }

        @Override
        public double getArea() {
            return this.length * this.width;
        }
    }

    private static class Square extends Rectangle {
        public Square(double sideLength) {
            super(sideLength, sideLength);
        }
    }
}


I think you can really simplify your code with the use of lambdas.

template<typename T, typename... Args>
auto make_lazy(Args&&... args)
{
    return [=]{return T(std::move(args)...);};
}

Usage example:

#include <iostream>
class T
{
    int v;
    public:
        T(int v): v(v) {std::cout << "Building T\n";}
        friend std::ostream& operator<<(std::ostream& s, T const& out) {return s << "T: " << out.v << "\n";}
};
class S
{
    int v;
    public:
        S(int v): v(v) {std::cout << "Building S\n";}
        friend std::ostream& operator<<(std::ostream& s, S const& out) {return s << "S: " << out.v << "\n";}
};

template<typename T, typename... Args>
auto make_lazy(Args&&... args)
{
    return [=]{return T(std::move(args)...);};
}

int main()
{
    auto lazyT = make_lazy<T>(1);
    auto lazyS = make_lazy<S>(2);

    std::cout << "Building\n";
    std::cout << lazyT() << "\n";
    std::cout << lazyS() << "\n";
}


changing from function based view to class based view in Django

Since both the functions are performing same action, you can just say post = get:

class ResetPassword(View):
    def get(self, request):
        return password_reset(self.request, template_name='login/reset.html',
            email_template_name='login/reset_email.html',
            subject_template_name='login/reset_subject.txt',
            post_reset_redirect=reverse('success')
        )
    post = get


Sorting alphabetically ascending and descending using .sort()

Some of the things I'd point out in your code for improvements:

Arrays can be a const since you will not modify the array itself but just push new elements to the array.
In your functions sortAsc, sortDesc, you are iterating through arr just to make it lowercase and iterating through the array again in sortedList.sort(). In such scenarios, think about how you can reduce number of iterations.
sort() does in-place sorting, so no need to create a new array.
In function populateList by running arr.map you are creating another new array which I don't think is necessary.

const listArea = document.getElementById('listArea');
const btnAsc = document.getElementById('asc');
const btnDes = document.getElementById('des');

const architects = [
  "Lloyd Wright",
  "Hadid",
  "Mies van der Rohe",
  "Le Corbusier",
  "Foster",
  "Gaudi",
  "Piano",
  "Gropius",
  "Niemeyer",
  "Aalto",
  "Saarinen",
];

function sortAsc() {
  architects.sort();
  populateList();
}

function sortDes() {
  architects.sort().reverse();
  populateList();
}

function populateList() {
  listArea.innerHTML = '';
  architects.forEach( (a) => {
    const list = document.createElement('li');
    list.innerText = a;
    listArea.appendChild(list);
  });
}

btnAsc.addEventListener('click', sortAsc);
btnDes.addEventListener('click', sortDes);

window.addEventListener('onload', populateList());

    <button id="asc">Sort Ascending</button>
    <button id="des">Sort Descending</button>


Critique some Ruby + RSpec Code for a SERP checker

I see you haven't got any response on this for a long while, so I'll give it a try.

I don't really see anything to pick on when it comes to style or technique. To me this looks very good. A few questions though:

why do you require "rspec" in the controller code? Shouldn't this be in the test code instead?
You don't do any attempt to sanitize or verify that the code works with non-english characters, or other characters that may cause trouble. What if someone type "tørris&message=<script>alert("Hoy there");</script>" in the input form? (I guess google will sanitize it, but it would probably be better to do it before passing the url to them.)


Calculating every permutation is very expensive so you want to avoid doing that. There are some ways to handle this:

1) Sort the characters before you run your algorithm. That way you are sorting a few characters not billions of permutations.

2) If the string has an even number of characters (say abcd) remove the almost middle character (b) and rewrite as something like 'b' + 'acd'.reverse

3) If the string has an odd number of characters (say abcde) you can remove the middle character (c) leaving abde and simplify the result as 'c' + middle_permutation('abcd')

(3) Will always be followed by (2)

So you could rewrite your code as:

def middle_permutation2(string)
  string = string.chars.sort.join("")
  return string if string.length <= 2

  if string.length.even?
    middle = string.length / 2 - 1
    remainder = string[0...middle] + string[middle+1..-1]
    string[middle] + remainder.reverse

  else
    middle    = string.length / 2
    remainder = string[0...middle-1] + string[middle+1..-1]
    string[middle] + string[middle-1] + remainder.reverse

  end

end


if your number of digits is always going to be less than about 10, then you can use a single random operation and a string format, to do all the work without the loop.

Consider a method like:

def generate(digit: Int): String = {
    var randVal = rand.nextInt(math.pow(10, digit).toInt)
    var fmt = "%0" + digit + "d"
    fmt.format(randVal)
}

The randVal pulls a value with the limited number of digits (perhaps fewer than the limit). The format operation 0-pads the value to the right number, though.

This is not so much a scala way of doing it, but it is closer, and probably more efficient.

I would consider creating instances to handle each length of digits to avoid having to create the format each time, though.

See it running in ideone


`ls` indicates when directory is empty/full of dotfiles

Portability issues

The function collects the given options and when it finally calls ls,
it puts the options at the end.
Unfortunately this doesn't work on OSX,
where the options must come before the filenames.

Your remarks

  seems over-complicated

Yes. Unfortunately, to get the behavior that you want,
I don't think this can get much simpler.

  non-perfect handling of some ls options, notably -l in case of only-dotfiles directory (print total 0)

Unfortunately, the only way to avoid that will only make the script even more complicated.

  if a directory contains only dot files, the ls command is runned twice. Could be costly if the directory contains a lot of dot files.

Perhaps you forgot to count the 2 runs of command ls in the if-else chain.
So in fact for each file the ls command is executed 4 times.

Filenames with spaces

This will not work when the filenames have spaces:

ls_filepaths="$ls_filepaths $filepath"

You can make it work with filenames with spaces,
and at the same time cleaner,
by using arrays.

"Remove options surrounding spaces"

I'm not sure what's going on here:

# remove options surrounding spaces
ls_options=$(echo "$ls_options" | tr -d "[:space:]")

For example -l -a would become -l-a which will not work.

Avoid negatives in variable names

It's generally not recommended to use negatives in variable names like isnotfirst,
because it could lead to strange conditions like not isnotfirst,
which is hard to read and confusing.
I suggest to rename it to first and use ! "$first" in conditions for a negative meaning.

Terminology

# Wrapper around ls function, printing dedicated messages

ls is not a "function", it's a command.
For example, verbosels is a function.

Looping over "$@"

When looping over "$@",
you can omit the "$@".
So instead of this:

for parameter in "$@"; do

You can write simply:

for parameter; do

Pattern matching

Instead of matching by regular expressions like this:

if [[ "$parameter" =~ ^-.* ]]; then

It would be slightly simpler to use pattern matching like this:

if [[ "$parameter" == -* ]]; then

Setting a variable to empty

Instead of this:

ls_options=""
ls_filepaths=""

You can simplify as:

ls_options=
ls_filepaths=

echo is the same as echo ""

You can replace echo "" with simply echo with no parameters.


Raku / Perl6: A module to enable escape codes in the win32 console, naming suggestions

Since no one else has replied, here's somewhat of a "rubber duck code review" given that I don't know much about Windows, vt, and NativeCall. Plus I've got a suggestion about the API and module name.

It looks like the not-explicitly-initialized $input-mode and $output-mode variables are actually constants implicitly initialized to zero. I think the code would be less confusing if they were declared as constants or even if you used literal 0s instead of them. Perhaps other code or configuration you have, or have in mind, will vary these values? Anyhow, at the very least, I think a comment making it clear the values the user passes to vt-on don't alter these, and vt-off is resetting them no matter what vt-on did, would be helpful.

From an API perspective, aiui, if one calls vt-on it turns the vt stuff on for both input and output. You have to pass :vt-input(False) if you only want vt-output and vice-versa. And vt-off always turns both off.

To me, having to write vt-input(False) is a bit ugly because:

It repeats the vt;
Mentions input when what one is trying to do is control output;
Requires explicit use of False.

It seems to me it could be more ergonomic to have just one routine, vt. To switch both input and output on use vt :on. To switch both off use vt :off. To switch just one on and leave the other as it is, use vt :on<input> or vt :on<output>. To switch just one off and leave the other as it is, use vt :off<input> or vt :off<output>.

I've never used vt stuff and could imagine one doesn't need the extra flexibility of the API I suggest but my suggestion is really more about keeping the API sweet than it is about the additional flexibility.

As for the module name...

I currently think we should shift all of our emphasis related to module discovery to an assumption of widespread use of global search via keywords, tags, etc. For now that means eg 'terminal' tag search or 'terminal' keyword search but one day there'll surely be search of a module's Pod and other aspects as well. In summary, imo, don't worry about a name's discoverability.

To the degree that a module's name matters, I think it's beyond discoverability. I think the two key things are considering clustering with names already chosen or likely to be chosen by other module authors, and making a name nice in a use statement. For these latter aspects I'd say:

Consider following accepted hierarchical namespace norms already established for modules.perl6.org. But don't sweat it.
If there are no obvious relevant norms to follow then keep a module name fairly short and sweet. Do you really need bumpy case or hyphens? Do you really need more than one :: divider? Then again, don't pick something egregiously short-sighted. You could name it just VT but a module such as yours doesn't warrant such a name.

Other than that the code all makes sense to me and looks fine to me from a pure P6 perspective.


Reading a controll character in a loop in Python

Another way would be using a generator expression. This has the effect of separating the 'control logic' and the 'action logic' (and are extremely useful!).

def getchar_until_quit():
    while True:
        ch = getch()
        if ch != "q":
            yield ch
        else:
            raise StopIteration

for ch in getchar_until_quit():
    do_something()
do_something() # to process the 'q' at the end


Random random = new Random();
random.setSeed(System.nanoTime());

Don't put this inside here. I'm assuming that this method will end up being called more than once. If so, you don't want to be seeding and re-seeding the Random every call.

random should be moved to a field of the class. Also, I don't think you need to manually call Random.setSeed. See here for more details.

I don't know my Java 100%, but I think this might be a typo:

Pair<SlideContent.SlideContentType, List<SlideContent>>... pairs

I think it should be:

Pair<SlideContent.SlideContentType>, List<SlideContent>... pairs


•After I learned about macros, I started to use them a lot. Am I using them in place of headers (and is this bad), or is how I am using them fine?

Looks OK to me.

•Am I over-using/misusing %defines (more specifically, KERNEL_CALL)?

I wouln't use KERNAL_CALL in stead of int 80h. The latter is shorter and the value involved will not change any soon in the future.

•Do I have too many or too few comments?

I find commenting on .subtract: a bit stating the obvious.

•Are my comments unclear?

No, they are very readable.

•Are there any unnecessary lines? I'm a little worried about the popping at the end of put_num...

The popping at the end of put_num is correct (pushing/popping 2 words in a row nicely keeps the stack aligned at dwords) but a few lines seem unnecessary to me. You do not need to compare AX with 0 since subtracting already defines the flags.
You could also shave off an extra jump.

sub ax, 1;      subtract 1
cmp ax, 0;      compare ax with 0...
je .blast_off;  if equal, jump to .blast_off
jmp countdown;  if not equal, go back to countdown
.blast_off:

Better code:

sub ax,1
jnz countdown
.blast_off:

•Am I following convention, or are there more things I should do?

The ordering of the sections of the program is a matter of taste. But I see most people put the .data section before the .text section.

•Is my code understandable?

Very understandable.


I cannot offer any optimization, only a few comments on best practice (as I
see it). There's very little to say; the code is nice.

Use of register is unnecessary (and hence rare).  The compiler may well
ignore it and it probably has a better idea of what to put in registers than
you or I.
It is best to define variables nearer to where they are first used.  This
reduces their scope and makes for easier reading. For example in
insertion_sort I would do:

for(int j = 1; j < length; j++)
{
    int temp = arr[j];
    int k = j - 1;
    while (k >= 0 && arr[k] > temp)
    ...

So I defined the loop variable j in the loop and temp and k at the
point of first use.  (This makes even more sense in C++ where an early definition incurs the overhead of a default construtor call.)
Your while-loop could arguably be a for-loop.  A for-loop makes the loop
conditions more immediately obvious, but in such a short loop it makes no
difference.
In main you cast the return from malloc.  This is necessary in C++ but
not in C.  And on an error in system and library calls that set the global
errno, such as malloc, I would use perror("malloc") which will print a
relevant error message to stderr, instead of rolling your own with printf (which prints to stdout).
Again your for-loops in main would be better defining loop variable i
in the loop.  Also these loops should have braces:

for (int i = 0; i < length; i++) {
    scanf("%d", &arr[i]);
}

Strictly speaking braces are not necessary but they are considered good
practice, as they prevent a class of error such as someone adding a printf:

for (int i = 0; i < length; i++)
    scanf("%d", &arr[i]);
    print("%d", &arr[i]);

For safety, you should always check user input before using it, such as
length here.
Your comments in main are really just stating the obvious and as such
could be considered 'noise'.  The comment in insertion_sort on the other
hand is more useful, although 'non-decreasing' and 'non-increasing' are odd
ways to say 'increasing' and 'decreasing' respectively.
Really nit-picking, I prefer a space after for and while and no space
between brackets in the expression if ((arr = malloc(sizeof...


Just recoded it, doing simply what your explanation said

  Except keep the first char if it is 'a' and keep the second char if
  it is 'b'.

Since a possible deletion of a character will affect indices, we check the second character before we check the first.
The resulting code is much simpler and readable simply because the extracted method deleteCharIfNotEqualTo() does away with some code duplication and at the same time heightens readability of the deFront() method, by explaining what is happening.

public String deFront(String str) {
    StringBuilder builder = new StringBuilder(str);
    deleteCharIfNotEqualTo(builder, 1, 'b');
    deleteCharIfNotEqualTo(builder, 0, 'a');
    return builder.toString();
}

private void deleteCharIfNotEqualTo(StringBuilder builder, int index, char character) {
    if (builder.length() > index && character != builder.charAt(index)) {
        builder.deleteCharAt(index);
    }
}


Checking whether a given timestamp is more than two weeks old

You're already using <chrono> (and just that), so you don't need <ctime>.  Including it anyway won't automatically allow compilation in pre-C++11 (if that was your intent here).

Also, since you're using uint64_t, you must include <cstdint> as well.
Each variable can be const since they're not being modified.  This would still be a good idea for ensuring const-correctness, even though the entire scope is within main().
The \ characters for line-continuations are useless here; the wrapping still works.
Since you're not needing to flush the buffer, std::endl should be replaced with "\n".  This may also give you a slight performance boost.
The "hello world" output can be shortened to a single-line ternary statement:

std::cout << ((data_timestamp < millis) ? "Hello" : "World");

Regarding this comparison: my tests give a signed/unsigned mismatch warning.  You have already given data_timestamp an unsigned type, so auto must be deducing a signed type for millis based on the function's return type.

One way to fix this could be by changing data_timestamp to a signed type such as int64_t, though <chrono> may offer more appropriate alternatives to help avoid uncertainty for this.
You don't need your own return 0 at the end of main().  The C++ standard should guarantee that the compiler will do this return for you since success is implied.


Bash script that creates a local environment for CHICKEN scheme (like virtualenv for Python)

I don't understand why the $(pwd)/ prefix is needed in this condition:

elif [ -e "$(pwd)/${1}" ]; then

If ${1} is an absolute path, the condition may not match the directory, even if it exists. Why not write simply [ -e "${1}" ], which should work well with both relative and absolute paths.

OLDPWD is automatically set by Bash when you change directories,
no need to set it manually.
In any case, since the script is intended to be executed instead of sourced,
there's no need to cd back to $OLDPWD.

As for $(dirname $(dirname ${CHICKEN_HOME})), I think that's nicely readable. For the record, you could use ${CHICKEN_HOME%/*} twice to strip suffixes until the grandparent (+ an extra check for the special case of /). Since parameter expansion is a built-in, this would be faster than executing dirname twice. The performance would make a difference if you called dirname a thousand times in a loop, but that's not the case here. And since using dirname is simpler and more readable, I would stick with that.


One may use the following closed formula to compute numFlashes:

numFlashes = 5 * mAccumulatedTime / pi.

This follows from the fact that the period of the function abs(cos(x)) is pi and, if an oscillating function in variable x has a period T, then the number of oscillations, n, is given by the formula:

n = x / T.

Thus, your function definition may be corrected, and even simplified, as follows:

const float PI = acosf(-1);

void Player::update(const float& deltaTime)
{
    mAccumulatedTime += deltaTime;
    float opacity = abs(cosf(5*mAccumulatedTime)) * 255;
    int numFlashes = 5 * mAccumulatedTime / PI;
    cout << numFlashes << endl;
    mSprite.setFillColor(sf::Color(255, 255, 255, opacity));
}


Replacing each letter with the letter that is in the corresponding position from the end of the English alphabet

With

final static int lower_case_a = 'a';
final static int lower_case_z = 'z';

While it's arguably good that you have 'a' and 'z' stored as variables and not floating around, I don't think they're named well. lower_case_a tells you exactly as much as 'a' itself, so you aren't really gaining much. The purpose of the variable would make for a better name. Also, since those are constants, they should be upper case, and underscore-separated. I'd change those lines to:

final static int ALPHABET_LOWER_BOUND = 'a';
final static int ALPHABET_UPPER_BOUND = 'z';

Also, as mentioned in the above link, Java uses camelCase, not snake_case.

if ((int)c >= lower_case_a && (int)c <= lower_case_z)
    reverse.append((char)(lower_case_z - c + lower_case_a));
else
    reverse.append((char) c);

This has a few notable things:

Do not omit braces here. I won't go as far as to say that they should never be omitted, but the cases where it's appropriate to not use them are pretty slim. If you ever make changes to those lines and don't notice that you didn't use braces, at best you'll need to deal with syntax errors, and at worst you'll get weird behavior that you'll need to debug. Just use them. It costs next to nothing and prevents a range of errors.
Instead of writing (int)c in a few places, I'd probably instead save that in a variable.
(char) c isn't necessary. c is already a char.
You could use a ternary since each branch is just giving its data to append.

Something closer to:

int code = c;
char newChar = (code >= ALPHABET_LOWER_BOUND && code <= ALPHABET_UPPER_BOUND)
                 ? (ALPHABET_UPPER_BOUND - c + ALPHABET_LOWER_BOUND) : c;

reverse.append(newChar);

Although whether you'd want to use a ternary here is subjective. That line is a little long.

I also agree with @dariosicily though. You never use i for anything other than indexing, so you might as well just use a foreach loop and iterate the string directly.


This:

...
while (current_class.__name__ != "Template"):
...

is weird. Do this:

...
while current_class != Template:
...

it does the same, except comparing classes instead of strings.

This is strange as well:

for i in reversed(inits):
     i(self)

i is used for iteration so it becomes obsucre, are you calling an int? This:

for init in reversed(inits):
    init(self)

is more explanatory.

I don't really know about this next part, but you could define a small lambda

extract_first = lambda x: x[0]

with an explanatory name, leaving that part of the code as this:

extract_first = lambda x: x[0]

while current_class != Template:
    inits.append(current_class.init)
    current_class = extract_first(current_class.__bases__)
for init in reversed(inits):
    init(self)

It leaves it with more words and text but less programming lingo. Might be good.

Now what I would do if this was for someone new to programming is relay on something else then abstraction of the init and abstract in something like biology:

class Exists(object):
    perceptible = True

class Alive(Exists):
    can_use_sustenance = True

class Vertebrate(Alive):
    can_move = True

class Mammal(Vertebrate):
    heat_generation = True

class Dog(Mammal):
    pass

class Cat(Mammal):
    pass

Tested on my significant other :-)


Displaying a greeting to one user selected from a database

The question is I know the size of the $getUser array to always be one.

No you don't. You assume it is - and it's probably a safe assumption to make. But actually knowing that user_id is a primary key is the job of the underlying database, not of your application.

You would know that 1 record is returned, if the query you send to the database says "give me one record where user_Id is equal to..." - if your backend is mysql that's done with a LIMIT clause.

Your query is missing a terminating semicolon... but the worst offense is the concatenation of the .$user_id into the WHERE clause. Where's that value coming from? Is there any slightest chance that it might not be containing the value you're expecting, and that concatenating it could result in unexpected SQL statements being injected into your query? If that's the case, then your query might actually be returning all rows, not just one.

See give me parameterized SQL, or give me death! (or many, many, many other online resources) for more details.


Decorator to return default argument values

I am not sure how critical this use case is, but when any of your arguments have a dictionary value, you have that dictionary items used as keyword arguments for the function:

In [1]: @return_kwargs
   ...: def example(arg1):
   ...:     pass
   ...:

In [2]: arg1_value = {'arg3': 'value'}

In [3]: print(example(arg1_value))
{'arg3': 'value'}

In other words, arg3 here is printed as a keyword argument for the function but it was not actually unpacked into keyword arguments to the function at all - it was "sitting" inside the value of an arg1 positional argument.


I think you need different approach to this. It's good practice when you don't have much of business logic in your controller. Maybe you should try creating a different class that will fill pages with content, based on something, like a template.

Now answering to your question:

You can create method with annotation @PostConstruct, which Spring will execute after done with his setup. In this method initialize field that you need, or in your case set application scope attribute with data that you need.

Also, I don't know if you knew it, you can create jpsf - jsp parts, that you can include in any of your jsp. As an example, you can create part with menu, CSS link or other parts, that share all pages, and just include it in your pages - makes jps look much more cleaner.

Here how u can bind objects to any response of your controller:

@ModelAttribute(value = "foo")
public String addAttribute(){
return "string";
}

Or:

@ModelAttribute()
public void addAttribute(Model model){
   model.addAttribute("roo", "one");
   model.addAttribute("loo", "two");
   model.addAttribute("moo", "some");
}

this how you bind for every response of your application:

@ControllerAdvice
public final class GlobalController {
    @ModelAttribute
    public void addAttributes(Model model) {
       model.addAttribute("msg", "Welcome to My Country");
    }
}


just a few ideas from the top of my head.

I would define a variable with your start directory at the top of the script, so to that you can always refer to absolute paths in contrast to using cd ../ often. In case you ever change the structure of your script, this will ensure that everything keeps working.

MODULE_DIR=$(readlink -f $lowercaseModuleName)

Now the directory creation can be simplified:

# Add open folder
echo "Adding open folder..."
mkdir -p ${MODULE_DIR}/open/{css,js}/

# Add views folder
echo "Adding view folder..."
mkdir ${MODULE_DIR}/views

As for the structure, I'd probaly create all the directories in one 'paragraph' and add the templates in a second step, just so that you one place where you can clearly see which directories are being created. But that might just be my personal tast.

In the template creation I'd use absolute paths here as well, using the new MODULE_DIR variable. Keeps you from having to navigate around a lot using cd which might cause confusion later on.

Hope this helps!


Monitor, read and display data from a dynamic log file

LogToolWindowLoader.java

Constant or user property

Thread.sleep(1000);

This is a nice example of magic number.
It's better that you create at least a private static final int for it, but even better could be the possibility to change that value by a property file, with a default of 1000 if the property isn't there.
Like this you could give the users easily control that value, because in mine opinion there could be people who want it slower or faster.

To the infinitive

while(true){

I never like to see this hack.
It's a infinitive loop with no possibility to stop it.
Why not make it a variable and give the user a possibility to stop loop?

UIOperations.java

Constants

private final String headers[]= {"header1","header2","header3","header4","header5","header6"};

A good usage of the final word and array but you create this array for each instantiation of the class.
Better could make that field also static so you have instantiated this variable once for all the different instantiations of UIOperations.

Final keyword in other situations

private ToolWindow toolWindow;

This field could be final because you set it in the constructor and there is no setter for setting this at a later point.

LogFileFunctions.java

Javadoc preffered

//reads the log file to retrieve data.

//connect FileReader to log file

This could be better set as java doc in stead of normal comments.
Like this if you generate the javadoc, people who read that will also see your comment.

same or not the same

if (!(str == null)) {

What the hell?
I hope this is old code created by resolving problems because otherwise this is actually your biggest issue (In mine personally insight).
For the moment you check if it's equal and then reverse the result.
There is nothing wrong with just checking for not equal :

if (str != null) {

Naming

String str; //holds string read from file
String[] result=null; //holds tokenized string

Code should be self explaining, so if you need to put comment behind a variable name to explain it, there is something wrong.
Mine suggestion is :

String lineFromFile;
String tokenizedLine=null;

Opening and closing resources

As last in this class is for me the absence of closing your resources.
This is just a nice example to create memoryleaks.

Summary

You see you have good experience in programming, it's a nice and readable code with really tiny things I could point out.
I hope this review could help you in one or more points.


Removing C++ template arguments from a C++ function name

For that kind of parsing itertools.groupby is the right tool.
With groupby, as I used it down below, every group is either: <,> or an actual piece of code (like foo). So the only thing left to do is to increment/decrement the depth level and decide if the group should be appended or not to the final result list.
from itertools import groupby

def remove_arguments(template, depth):
    res = []
    curr_depth = 0
    for k,g in groupby(template, lambda x: x in ['<', '>']):
        text = ''.join(g)    # rebuild the group as a string
        if text == '<':
            curr_depth += 1

        # it's important to put this part in the middle
        if curr_depth < depth:
            res.append(text)
        elif k and curr_depth == depth:   # add the inner <>
            res.append(text)

        if text == '>':
            curr_depth -= 1

    return ''.join(res)   # rebuild the complete string

It's important to put the depth-level check in between the increment and decrement part, because it has to be decided if the </> are in or out the current depth level.
Output examples:
>>> remove_arguments('foo<int>()', 1)
foo<>()
>>> remove_arguments('foo< bar<int> >()', 1)
foo<>()
>>> remove_arguments('foo< bar<int> >()', 2)
foo< bar<> >()
>>> remove_arguments('foo< bar >()', 2)
foo< bar >()

Also, a couple of quick style notes:

Don't use str as variable name or you'll shadow the builitin str.
Don't use CamelCase for functions/variable names (look at PEP8).

Inspired by lvc comment, I've grouped here possible lambdas/functions to be used in groupby:
groupby(template, lambda x: x in ['<', '>'])    # most obvious one
groupby(template, lambda x: x in '<>')   # equivalent to the one above
groupby(template, '<>'.__contains__)    # this is ugly ugly
groupby(template, '<>'.count)    # not obvious, but looks sweet

Update
To handle cases like: foo<bar<int>>(), you'll need a better groupby key function. To be specific, a key function that return the current depth-level for a given charachter.
Like this one:
def get_level(ch, level=[0]):
    current = level[0]
    if ch == '<':
        level[0] += 1
    if ch == '>':
        level[0] -= 1
        current = level[0]

    return current

That take advantage of the mutable argument level to perform some kind of memoization.
Observe that remove_arguments will now be more simple:
def remove_arguments(template, depth):
    res = []
    for k,g in groupby(template, get_level):
        if k < depth:
            res.append(''.join(g))
    return ''.join(res)


Given a string, return a string where every character in the original is doubled

No reason to write anything when string is empty.

public string RepeatAString(string sInputString, int repeatCount)
{
    StringBuilder sOutputString = new StringBuilder();

    foreach (char c in sInputString)
        sOutputString.Append(new String(c, repeatCount));

    return sOutputString.ToString();
}

I think your solution is the best. Obviously you can use LINQ if you want but IMO it doesn't bring anything to table.

public string RepeatAString(string input, int count)
{
    return String.Concat(input.Select(c => new String(c, count)));

}


A simple function that removes empty or tags containing just ' '

There is a bug

You need to run the script several times to remove all empty elements.

Two points

You say remove empty tags that contain "" or a single space "&nbsp;". Does that include " " or "  " two or more spaces. What about other white space characters?
Your element removal is order dependent because you use getElementsByTagName which returns a live list.

Consider the html

  You first check all the p tags which fail the empty test, then you test the span tags which passes and you get

 which is, by your definition, empty and should have been removed.

On the other hand the html

 will first remove the p then remove the span.

The removal process is order dependent. Not what your question indicates.

Changes

For the first point you could use element.textContent to check for empty elements. It will ignore the HTML and convert the &nbsp; to a space for you. You could even use element.textContent.trim() and thus get all blank elements (like the pseudo-class :blank (Which has very limited support FF only))

This also covers the second point.

Example Mark and remove

To reduce the DOM calls you can mark and remove deleting the marked elements only.

const isNotMarked = el => {
    while (el && el.parentNode && !el.parentNode.marked) {
       el = el.parentNode;
       if (el.marked) { return false }
    }
    return true;
}
[...document.querySelectorAll("span, p, strong")]
    .filter(el => el.textContent.trim() === "" && isNotMarked(el) ? el.marked = true : false)
    .forEach(el => el.parentNode.removeChild(el));

Example simple brute force

Mark and remove saves you attempting to delete already deleted elements but you may not care, as the shorter form, is a two liner, and thus could be argued to be the better solution.

document.querySelectorAll("span, p, strong")
    .forEach(el => el.textContent.trim() === "" && el.parentNode.removeChild(el))

The following snippet shows the HTML after using your function and then the two example functions

   /*=================================================================================
OP ver modified for example
 =================================================================================*/

var ps = cleaned.getElementsByTagName('p'),
    spans = cleaned.getElementsByTagName('span'),
    strongs = cleaned.getElementsByTagName('strong');

    for (let el of ps) { cleaner(el); }
    for (let el of spans) {  cleaner(el); }
    for (let el of strongs) { cleaner(el);  }

    function cleaner(el) {
        if (el.innerHTML == '&nbsp;' || el.innerHTML == '') {
            el.parentNode.removeChild(el);
        }
    }
    content.textContent = cleaned.innerHTML;

/*=================================================================================
 Mark and remove
 =================================================================================*/
const isNotMarked = el => {
    while (el && el.parentNode && !el.parentNode.marked) {
       el = el.parentNode;
       if (el.marked) { return false }
    }
    return true;
}
[...cleanerClean.querySelectorAll("span, p, strong")]
    .filter(el =>  el.textContent.trim() === "" && isNotMarked(el) ? el.marked = true : false)
    .forEach(el => el.parentNode.removeChild(el));

contentA.textContent = cleanerClean.innerHTML;

/*=================================================================================
 Brute force remove
 =================================================================================*/
simplerClean.querySelectorAll("span, p, strong")
    .forEach(el => el.textContent.trim() === "" && el.parentNode.removeChild(el))

contentB.textContent = simplerClean.innerHTML;
#content {
   display: block;
}

text

&nbsp;

text

text

text

text

&nbsp;

text

&nbsp;

text

&nbsp;

text

&nbsp;

text

<fieldset>
<legend>Original OPs script & Resulting HTML</legend>

</fieldset>

text

&nbsp;

text

text

text

text

&nbsp;

text

&nbsp;

text

&nbsp;

text

&nbsp;

text

<fieldset>
<legend>Mark and remove</legend>

</fieldset>

text

&nbsp;

text

text

text

text

&nbsp;

text

&nbsp;

text

&nbsp;

text

&nbsp;

text

<fieldset>
<legend>Brute force remove</legend>

</fieldset>


Answer to questions:

  I think priority queues will give the optimal solution so i implemented using that.

I would bet a heap is better for anything bigger than test data. Note that in a priority queue you are keeping all the data. So every time you add an item you are adding to its size and the length of time it takes to insert.

In real terms a heap would be better because you only keep the top 10 (or hover many you actually require). So each new value is only being compared against the top 10 items.

See:

http://en.cppreference.com/w/cpp/algorithm/make_heap
http://en.cppreference.com/w/cpp/algorithm/push_heap
http://en.cppreference.com/w/cpp/algorithm/pop_heap

  The code works and compiles. Could anyone please review this and suggest some more C++11/14-ish things to do?.

Covered in the next section:

  Is there way in c++11 or c++14 to avoid using an iterator to find whether an element exists or not in a map ?

if(it != word_map.end()) {
  word_map[word] = ++word_map[word];
}
else {
  word_map[word] = 1;
}

Yes. This can be replaced by

++word_map[word];

If the item does not exist in the map then using operator[] will insert the key and set the default value to zero. We then apply the ++ operator and increment it. So when a value is first inserted it gets the value 1, subsequent increments increase the stored value appropriately.

  I saw a weird behavior for this : while(input_file>>word) { //.... }

  this loop gives the correct count. But if i do while(input_file.good()) { //.. } this gives the count with an additional 1 added if the word is present on two different lines. For example :

This is correct. In all languages you test the result of the read operation (the behavior when you use while(input_file>>word)).

In all languages this is wrong while(input_file.good()) {.

The reason is that the EOF flag is not set until you read past the actual eof. BUT the last successful read reads up-to but not past the EOF. So when you read the last word, there is no more data on the input but the EOF flag is not set because you have not read past the end of file.

So if you use while(input_file.good()) you will re-enter the loop after you have read all the data. It is not until you try and read data from the stream that the EOF will be set.

You can do it this way but you must test the state of the read as well:

while(input_file.good())
{
    if (input_file >> word)
    {
        // read worked so you can processes the data
    }
}

It seems much easier to write:

    while(input_file >> word)
    {
        // Only enter the loop if the read worked.
    }

This is because operator>> reads a word from the stream and returns as a result a reference to the stream. So you are now using the stream as the condition of the while(). When used in this context the stream is converted to a boolean by calling good(). So in this case you have done the read and then tested the state of the stream to see if the read worked.

  while give count of this as 3.

Yep you entered the loop again when there was no data to read and counted the extra entry into the loop.

I think i need to write a custom comparator for the priority queue to compare only the second part of the "pair".

Yep

Code Review

Don't do this:

using namespace std;

See every other C++ reviewed question for why.
And Why is “using namespace std;” considered bad practice?.

Don't use unsigned int.

void getTopKWords(const map<string, int>& word_map, const unsigned int k) {

I know it seems logical that the your input should be a positive value. But unfortunately if somebody calls the function and accidentally passes a negative number it will still work; It just passes a very large positive value instead (stupid auto-conversions).

The general consensus is that you should always used signed integers. The only time that using unsigned is useful is when your integer is holding a set of bit flags.

To make this work as required you would need to define a custom ordering.

  priority_queue<pair<string, int> > pq;

Why not create and open the file in a single line:

  ifstream input_file;
  input_file.open(filename);

  // Easier to read as:
  ifstream input_file(filename);

String defaults to the empty string.

  std::string word = "";
  // Easier to write as:
  std::string word;

This we mentioned above:

    auto it = word_map.find(word);
    if(it != word_map.end()) {
      word_map[word] = ++word_map[word];
    }
    else {
      word_map[word] = 1;
    }
    // Can all be replaced with:
    ++word_map[word];

Don't manually close a file.

  input_file.close();

The exception is if you want to check that the close worked and potentially report a problem to the user. Since you are not doing this check then let the destructor of the file call close() for you. This way it caches all errors cleanly and discards them.

Code to use Heap to get top - N Items

struct CountTester
{
    bool operator()(std::pair<std::string, int> const& lhs, std::pair<std::string, int> const& rhs) const
    {
        return lhs.second > rhs.second;
    }
};

void topNFromMap(std::map<std::string, int>  const& wordData, int count)
{
    CountTester                                 countTester;
    std::vector<std::pair<std::string, int>>    heap;
    heap.reserve(count+1);                              // +1 is for the item we will add next.

    auto loop=std::begin(wordData);
    // Push the first `count` items into the vector.
    for(; loop != std::end(wordData) && heap.size() < count; ++loop)
    {
        heap.push_back(*loop);
    }

    // Make a heap so the smallest value is on top.
    std::make_heap(std::begin(heap), std::end(heap), countTester);

    // Add any more items.
    // Only need to keep the ten top 'count' items.
    // Note: the complexity is 2 x O(log(count)) => O(1) (since count is fixed)
    //       So this pushes the new item into the heap.
    //       Pops the smallest value of the top of the heap
    while (loop != std::end(wordData))
    {
        heap.push_back(*loop);
        std::push_heap(std::begin(heap), std::end(heap), countTester);
        std::pop_heap(std::begin(heap), std::end(heap), countTester);
        heap.pop_back();        // remove smallest item.
        ++loop;
    }

    // Pop Values from the heap.
    // This will put them in the correct order.
    for(auto popPos = std::end(heap); popPos != std::begin(heap); --popPos)
    {
        std::pop_heap(std::begin(heap), popPos, countTester);
    }

    // Now we can print all the items.
    for(auto const& item : heap)
    {
        std::cout << item.first << " " << item.second << "\n";
    }
}


A custom Java collection which doesn't support nulls

Throwing NullPointerException from methods like add, set are OK, cause the element to be added can't be null. But throwing NPE from addAll method is not cool. From Javadoc

  Throws: NullPointerException - if the specified collection is null

that means if there exists a null value in the Collection throwing NPE doesn't make sense. You can throw IllegalArgumentException or a custom exception like FoundNullValueInCollectionException(I think this is better).

In your defense you can point towards the Map.containsKey Javadoc, where it throws NPE if the specified key is null and this map does not permit null keys (optional).

  I want to prevent code from using the clone() method

So you can throw a UnsupportedOperationException or CloneNotSupportedException(as JohnMark13 suggested).


An R function for checking whether a variable is binary or continuous

Using the return statement is not recommended.
You can get the same effect by rewriting with else if and else, like this:

checkBinaryTrait = function(v, naVal="NA") {
  if (!is.numeric(v)) stop("Only numeric vectors are accepted.")
  vSet = unique(v)
  if (!missing(naVal)) vSet[vSet == naVal] = NA
  vSet = vSet[!is.na(vSet)]

  if (any(as.integer(vSet) != vSet)) "con"
  else if (length(vSet) > 2) "con"
  else "bin"
}

I also removed the unnecessary which calls.
This code still passes all your tests.

Actually the last statement can be further simplified to:

  if (any(as.integer(vSet) != vSet) || length(vSet) > 2) "con"
  else "bin"

You might also want to change the return type to TRUE or FALSE,
in which case the last statement would become simply:

  !(any(as.integer(vSet) != vSet) || length(vSet) > 2)

And then, how about renaming checkBinaryTrait to is.binary?

Finally, the <- operator is more common than =.
For example Google's style guide explicitly forbids using =.


I'm unsure if the posted code is exactly what's intended functionally, but the following would do the equivalent:

do
{
    printf("Enter 1 for the First Screen\n");
    printf("Enter 2 for the Second Screen\n");
    printf("Enter 3 for the Third Screen\n\n");

    scanf("%d", &selection);

    if ( selection < 1 || selection > 3 )
        break;

    switch (selection)
    {
    case 1:
        //do and print stuff here
        break;

    case 2:
        //do and print stuff here
        break;

    case 3:
        //do and print stuff here
        break;
    }
}
while ( GetAsyncKeyState(VK_TAB) );

I really can't remember the last time I used a goto. I think it was in a FORTRAN class.


HTML and JS to dynamically load, refresh, and execute JavaScript from external file

This code is very clean, and I believe that it is a very useful tool for any JavaScript developer.

This is not very efficient:

<body onload="document.getElementById('refreshButton').click()">

Why? Well, think about what your code has to do:

Locate refreshButton.
Wait for refreshButton to load.
Find its onclick method and call it.

Sure, this isn't terribly inefficient, but it can be made simpler.

I see what you are trying to do by not having the HTML code memorize anything; everything is handled in references which all boils down to a few elements.

While this is nice, it would be much more efficient if you called refreshButton's onclick method itself. So, you would just call loadScript:

<body onload="loadScript('sandbox.js')">

This:

if(js !== null)

Can be reduced to this:

if(js)

I think the way I wrote it is better, because the way I read your code is like this:

  If the functions that JS is loaded with returned null...

And I read what I wrote as:

  If JS exists...

This may just be me, however.

The reason why you can make this change is because, in JavaScript, null is a falsey value and therefore can be treated as though it were false.

Be careful with that runButton button. If the user acts too fast by quickly reloading the script and then trying to run it, there could be some problems; what if the script has not loaded yet?

Rather than silently failing and leaving a non-technically inclined user dumbfounded, it would be better to notify the user of problem (and prevent failing due to an attempt at trying to run a currently non-existent function).

Read this StackOverflow post for some ways you could check if the script has loaded.

In your case, you already have your work laid out for you: the sandbox.js source file creates a global sandbox function that you try to call.

Therefore, you can write this to make sure that the script has loaded:

if(typeof sandbox !== "undefined") {
    sandbox();
} else {
    window.alert("The script has not been loaded yet!");
}

In response to this comment:

  "append the newly-created script element to the head": I'm following
  the JS book I'm studying from (I'm a neophyte at JS and the DOM,
  coming from C++). In fact, JS may not necessarily be best in head.
  (//stackoverflow.com/q/10994335)

This is a different response to that comment.

It doesn't matter where you put the scripts now that the browser has already fully loaded. The browser is not going to stop again and load the code (even if it did, that would be good (referencing to my response comment)).