Test Scores and Summary Statistics from a file

Some general issues first:

Indent methods and method blocks. Makes your code more readable
Avoid resource leaks. Close the Scanners in a finally block.

This program has only one method. Split the functionality into many small methods, one for each purpose. For example: reading the scores from the file. This is easy to extract as a method:

    int[] scores = readScoresFromFile(fileName);

...

private static int[] readScoresFromFile(String fileName) throws FileNotFoundException {
    File inputFile = new File(fileName);
    Scanner data = new Scanner(inputFile);
    try {
        //declaring that whatever the first number in the document is is how many indices the document has
        int scores[] = new int[data.nextInt()];

        int i = 0;
        while (data.hasNext())
        {
            scores[i] = data.nextInt();
            i++;
        }

        Arrays.sort(scores);
        return scores;
    }
    finally {
        data.close();
    }
}

I also added the finally block, so the Scanner gets closed. data is a bad name (it could by anything), so let's call it just scanner. Simple and understandable. The method is still too long, so I'd extract one more method, so that the try{} block contains just readScoresFromScanner(scanner);.

As you are using arrays, you need to know the total number of scores in advance. That's not necessary. Collections make your life easier. Assuming you remove the number-of-scores from your input file, you can write:

private static List<Integer> readScoresFromScanner(Scanner scanner) {
    List<Integer> scores = new ArrayList<>();
    while (scanner.hasNext())
    {
        scores.add(scanner.nextInt());
    }
    Collections.sort(scores);
    return scores;
}

Of course, now you need to make some changes to the rest of the code. It will make the code more readable:

    List<Integer> scores = readScoresFromFile(fileName);
    //Highest and Lowest score
    System.out.println("Lowest score: " + Collections.min(scores));
    System.out.println("Highest score: " + Collections.max(scores));

With good refactoring, the comments become unnecessary:

    System.out.println("Mean score: " + calculateMean(scores));

The method becomes very understandable; consider using enhanced loops:

private static double calculateMean(Collection<Integer> scores) {
    double gradesTotal = 0;
    for (int score : scores) {
        gradesTotal = gradesTotal + score;
    }
    return gradesTotal / scores.size();
}

With Java 8, you can also write:

private static double calculateMean(Collection<Integer> scores) {
    return scores
        .stream()
        .mapToInt(Integer::intValue)
        .average()
        .getAsDouble();
}

The code that sums up the grades is very verbose and redundant; try to avoid if-else chains and replace them with, for instance, loops. Use an array or list instead of gradeA, gradeB, etc. A hint:

private static int gradeByScore(int score) {
    int[] scoreForGrade = { 90, 80, 70, 60 };
    for (int grade = 0; grade < scoreForGrade.length; grade++) {
        int requiredScore = scoreForGrade[grade];
        if (score >= requiredScore) {
            return grade;
        }
    }
    return 4; // grade F
}


Comparing equivalent Scala and C# string-manipulation code - with Scala running much slower

There is no reason for Scala code to be slower than C#.
The different is probably the time that it take to the JVM to load.
To verify that I suggest you to write simple code in C#, Scala & Java which just print "Hello World" and see the different.  My guess is that the Java & Scala will take the same time while the C# will be faster.
Then just do something which do long calculations and see the different again.


Proper naming for objects which have a position and bounds on a plane

Everything is an Entity!

If you would follow the Entity Component System approach, that is. The idea is that all objects are entities, and each Entity has several components. Size, Position, Movable - all this are different aspects of what an Entity possibly could do and are therefore each it's own Component. As for Systems, that's where most of the logic is.

Names like PositionableBoundable and MovableBoundable sound weird because it is weird, you are trying to use one name for two things. Composition over inheritance is the key here.

As for the name Boundable, I would probably have gone for just Box or Rect which are more well known.


Well here is a tidied up version that shouldn't change the functionality at all:

$(function() {
    $('#clientLoginText').mouseenter(function() {
        $('#clientLoginBox').stop().animate({ "height" : '80px'}, 700);
    });

    $('#clientLoginBox').mouseleave(function() {
        $(this).stop().delay(500).animate({ "height" : '0px'}, 700);
    });
});

About the changes:

You only need a single document.ready function: the only good reason I can think of for having two is if you need to put them in separate JS files.
You had used the .hover() function, which is shorthand for .mouseenter() and .mouseleave(), but in the first use you passed an empty function for the mouseleave part and in the second use you passed an empty function for the mouseenter part, so why not just code the first directly as .mouseenter() and the second as .mouseleave()?
Within an event handler you can refer to the element that triggered the event as this, or $(this) if you need it as a jQuery object. More efficient than getting jQuery to find it again from its id.


Can my responsive-tables JS code be made more performant?

I know the people on here can do a way better job, but here it is without jQ and those array function things. Hopefully someone here will give you some real advise.  I just wanted to get rid of the jQ.

One note, you don't need to array.join strings any more.

...only found that out about a year ago myself.

Your main bottle necks will be in how you alter/touch the dom, but I'm no good at those points... google I guess.

All this does give you more speed, but I bet theres people here that would hate me not using array function stuff.  But you seemed to be into speed so that's what I gave you.  Me I can go either way...speed this, comfort that.

function initResponsiveTables() {
  //does this enhance performance at all?
  'use strict';

  //get an array of <th> elements
  var th = document.getElementsByTagName('th');

  //initialise in top scope
  var priorities = [];

  //iterate over the <th>s, extracting their column priorities
  for (var i = 0, end = th.length; i < end; i += 1) {

    var priority = th[i].getAttribute('data-priority');

    //TODO: this seems very messy, I feel there must be a cleaner way?
    if (priorities[priority] === undefined) {
      priorities[priority] = i;
    } else {
      priorities[priority] += ',' + i;
    }
  }

  for (var spot = 0, i = 0, end = priorities.length, x; i < end; i += 1) {
    x = priorities[i];
    if (x !== undefined && x !== null) {
      priorities[spot] = x;
      spot += 1;
    }

  }
  priorities.length = spot;

  //initialise all of these outside of the loop
  var sCols = '';
  var aCols = [];
  var aSelectors = [];
  var sSelectors = '';
  var i;

  var table = document.getElementById('table');

  while (table.getBoundingClientRect().width > window.document.documentElement["clientWidth"] - 40 && priorities.length > 0) {

    //get the lowest priority
    sCols = (priorities.pop() + '');

    //split it, in case we have more than one column on the same priority
    //in this case we prefer to remove them as a group, rather than one at a time
    aCols = sCols.split(',');

    //clear the string from previous iteration
    aSelectors = '';
    for (i = 0; i < aCols.length - 1; i += 1) {
      //build up the selectors
      aSelectors += ('td:nth-child(' + aCols[i] + '), th:nth-child(' + aCols[i] + ')') + ', ';
    }
    aSelectors += ('td:nth-child(' + aCols[i] + '), th:nth-child(' + aCols[i] + ')');

    var els = table.querySelectorAll(aSelectors);
    for (var i = 0, end = els.length; i < end; i += 1) {
      els[i].style.display = 'none';
    }
  }
}

var start = performance.now();;

initResponsiveTables();

alert(performance.now() - start);

EDIT:
Couldn't sleep its like 40 degrees C here right now so thought Id make you an example to show the difference when you dont thrash the dom.  I think the technical term (bad memory) would be trying to avoid reflows.

Where yours is is pretty obvious, this....
while (table.getBoundingClientRect().width > window.document.documentElement["clientWidth"] - 40 && priorities.length > 0) {
...specificly....
table.getBoundingClientRect().width for sure and maybe window.document.documentElement["clientWidth"]
...combined with...
els[i].style.display = 'none';

Your, in a loop, changing the dom and then asking for a prop that definitely causes a reflow/repaint/wotevaitscalled if the dom has changed since last call and that stuff is real costly.

So what if we knew the width of the cells and only had to get the width of the table and window once?  Well youd end up with code like below and if you test it youll see it is faster, ESPECIALLY in FireFox (didnt test IE).

I pre picked the width of the cells, but you could look into maybe getting it from the already rendered table (hate that by the way) or other options, or just stick with a set width which the browser would like anyway (easier to paint).

http://plnkr.co/edit/oeJpGK?p=preview      I prfr plnkr ;)

function initResponsiveTables() {
  //does this enhance performance at all?
  'use strict';

  var th = document.getElementsByTagName('th');
  var priorities = [];
  for (var end = 0, i = th.length - 1; i >= end; i -= 1) {

    var priority = th[i].getAttribute('data-priority');

    //TODO: this seems very messy, I feel there must be a cleaner way?
    if (priorities[priority] === undefined) {
      priorities[priority] = [
        i
      ];
    } else {
      priorities[priority].push(i);
    }
  }

  var removeCols = [];
  // Looking at the idea of having a set width
  // Im not great at html, depending on how tables work you might be able to get the width after the table is created instead of using a set width. worse come to worse scan each row for biggest cell
  // its also set in the css
  var colWidth = 85;

  var table = document.getElementById('table');
  var tableWidth = table.getBoundingClientRect().width;
  var targetDiff = table.getBoundingClientRect().width - window.document.documentElement["clientWidth"] - 40;
  var currentDiff = 0;
  var colIndex = priorities.length - 1;
  var cols;

  if (targetDiff > 0) {
    // var atLeast = Math.ceil(diff / colWidth); // how many cols to remove
    while (currentDiff < targetDiff && colIndex >= 0) {

      cols = priorities[colIndex];

      if (!cols) {
        //skip sparse bits
        while (cols === undefined && colIndex >= 0) {
          cols = priorities[colIndex--];
        }
      }

      if (cols) {
        cols.forEach(function(index) {
          table.tHead.rows[0].children[index].style.display = 'none';
          for (var i = 0, end = table.children[1].children.length; i < end; i += 1) {
            var row = table.children[1].children[i];
            row.children[index].style.display = 'none';
          }
        });
        currentDiff += colWidth * cols.length;
      }
      colIndex--;
    }
  }
}

var start = performance.now();;

initResponsiveTables();

alert(performance.now() -

start);


Kattis Challenge - Animal Classification

This isn't really what you're looking for, just some general feedback on your code.  I find the code quite difficult to follow, resolving some of the issues below to help with readability might make it more likely that you will get feedback that aimed at your algorithm.

Naming

Your names seem overly concise.  A few extra letters won't make any difference to the speed of your application, but make it a lot more readable.  Variables in main are n,x,y,c,A,B,i,c,tmp,t1,t2,res.  Without looking at the context, these names are meaningless.

Your mt method is similarly nondescript.  Perhaps make_tree might be more appropriate?

Consistent expecatations

In main, you reuse the variable name i for both an int and an unordered_set<unordered_set<int>, hash_X>.  Switching variable types like this makes your code harder to follow than necessary and illustrates that you could benefit from more meaningful names.

Indentation

Your indentation is all over the place.  This makes it difficult to read.  Sometimes you have indentations next to each nesting level, sometimes you don't.  If it looks like this in your development environment, you should fix it.  If it doesn't, then you need to check the preview when adding code to questions.  Usually copying the whole thing from your IDE, selecting it and clicking the {} icon will format the code correctly.

Consider this:

if(*it == "("){
    int i = 1;
    while(i != 0){
        it++;
        if(*it == ")"){i = i-1;}
        else if(*it == "("){i=i+1;}
        }
    }

At first glance, the final closing brace belongs to the while loop, not the if statement.  This is unnecessarily confusing.

Don't be afraid of using an extra line

Consider the following line or two:

for(string s: K){if( s!="(" and s!=")" ){int i = stoi(s); tmp.insert(i);}}

There's a lot going on there for a single line.  It's a lot easier to read spread across multiple lines:

for(string s: K) {
    if( s!="(" and s!=")" ) {
        int i = stoi(s);
        tmp.insert(i);
    }
}


Consider using the string concatenation operator + instead. The reason why this works and is not bad is because behind the scenes the method String.Concat is being called.

While String.Format will have to do a lot of different things, such as parsing, getting the string after and before placeholders to be able to join them and so on.

This is important both on the callback and implementation.

private string Apply(int k, int n)
{
    var diff = n - k;
    if (diff == 0)
        return "0";
    if (diff == 1)
        return _appFunc(k);
    if (diff == 2)
        return _function + "(" + _appFunc(k) + ", " + _appFunc(k + 1) + ")";
    int half = (n + k) / 2;
    return _function + "(" + ApplyB(k, half) + ", " + ApplyB(half, n) + ")";
}

var rec = new Recursion("Math.Max", i => "source[" + i + "]");

By applying this changes I could measure a 0.5s difference on my machine over 60000 iterations calling apply with 8 which previously took 3s so it was a 17% improvement.

Going with StringBuilder

I was a bit reluctant going with a StringBuilder because it seemed an hard job but when we think two more times about it solutions come. My idea was to put a StringBuilder on a field, so I don't have to pass it has a parameter to the function, and make the method return void.

The StringBuilder is the ideal class to build large strings, it is efficient because it manages an array of characters. It's like having mutable strings.

    class Recursion
    {
        private readonly string _function;
        private readonly Func<int, string> _appFunc;
        private readonly StringBuilder _builder;
        public Recursion(string function, Func<int, string> appFunc)
        {
            _function = function;
            _appFunc = appFunc;
            _builder = new StringBuilder();
        }
        public string Apply(int n)
        {
            Apply(0, n);
            var result = _builder.ToString();
            _builder.Clear();
            return result;
        }

        private void Apply(int k, int n)
        {
            var diff = n - k;
            if (diff == 0)
            {
                _builder.Append("0");
                return;
            }
            if (diff == 1)
            {
                _builder.Append(_appFunc(k));
                return;
            }
            if (diff == 2)
            {
                _builder.Append(_function)
                .Append('(')
                .Append(_appFunc(k))
                .Append(", ")
                .Append(_appFunc(k + 1))
                .Append(')');
                return;
            }
            int half = (n + k) / 2;
            _builder.Append(_function).Append('(');
            Apply(k, half);
            _builder.Append(", ");
            Apply(half, n);
            _builder.Append(')');
        }
    }

This decreased execution 0.9s upon my previous attempt, on the same circumstances, giving it a total of 46% improvement.


Generate array with random numbers and search for an element in it

Do not using using namespace std

bringing in entire namespaces can be convenient, but in the long run, it's a really bad habit.

You should explicitly use std::cout and the like instead.

Declare variables as close as possible to their first use.

int inp, zuf, i, num, trig=0;

This means very little out of context.

Prefer using std::array instead of regular c-style arrays.

std::array<int, amount> arr;

This plays better with the rest of the standard.

Do not use 1-based indexing unless you really need it.

And in your case, you definitely do not want it, as you are doing an out-of-bounds access on arr[i] when i == amount;

for (int i = 1; i < amount + 1; i++) {

should be

for (int i = 0; i < amount; i++) {

But it doesn't matter because:

prefer using ranged-based for unless necessary

for(auto& val : arr) {
  val = ...
}

Do not use srand()/rand()

They are terrible. It's slow and not particularly random. You should use the random number genreator provide by <random> instead:

https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution.

Separate your concerns:

I suspect you are not respecting the "spirit of the exercise", since filling the array doesn't serve a purpose in your example.

You probably want to first fill the array, and then ask the user (possibly multiple times) to provide a number to find.


How to refactor this complicated html generator in Ruby?

This needs some tweaking, but I hope it helps you identify the main issues to address in your code (IMHO):

objects = [:content, :answers, :comments].flat_map do |type|
  questions = Question.search_tank('', {
    :page => 1,
    :per_page => 5,
    :conditions => conditions.merge(type => search_term),
  })
  questions.map { |q| [q, type] }
end.uniq_by(&:first).take(MAX_RESULTS)

results = objects.map do |q, type|
  label = case type
  when :content
    highlight_matched(search_regex, q.content) +
      content_tag(:span, "Question", :class => "search-type")
  when :answers
    content_tag(:span, "Answer", :class => 'search-type snippet'>) +
      [q.content, get_snippet(search_regex, q.answers)].compact.join(tag(:br))
  when :comments
    comments = get_snippet(search_regex, q.answers.flat_map(&:comments))]
    content_tag(:span, "Comment", :class => 'search-type snippet'>) +
      [t, q.content, comments].compact.join(tag(:br))
  end
  {:title => q.content, :value => app_question_url(q.app, q.id), :label => label}
end

Notes:

Avoid stateful variables whenever possible (that's it, don't update inplace), work with expressions.
Use Rails helpers (content_tag, tag, ...).
Use symbols for key-like values, not strings.
"#{something}" -> something.to_s
map + flatten = flat_map. Even though you should able to write q.answer_commments in Rails 3.1 will the correct model settings.
Use case, not a chain of if/elsif if the condition is on the same value.


Applying a set of styles both with a media query and with nested rules

You usage of the mixin will work and although it is not pretty there is not much else that can be done as far as valid LESS / CSS output.

I've written up an example of complex mixins like below.
LESS lazy mixin for element width/height/float

As well as one that might be on track with what you are trying to accomplish.
https://stackoverflow.com/questions/39338429/less-outputs-extra-semicolon

Keep in mind that this using a JavaScript array in a hacky type mannor and the output would still need to be sanitized of the extrenious code that is not valid. But I think we are both headed in the same direction.


Find all collection properties of an object and get their values

First up, let's clean up the formatting a bit.

public class DependencyValidator<TEntity> :
    IDependencyValidator<TEntity>
    where TEntity : class
{
    private readonly Type IEnumerableType = typeof(IEnumerable);
    private readonly Type StringType = typeof(String);

    public IEnumerable<KeyValuePair<string, IEnumerable<string>>> Dependencies(TEntity entity)
    {
        if (entity == null)
        {
            return Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>();
        }

        ICollection<KeyValuePair<string, IEnumerable<string>>> dependents = new List<KeyValuePair<string, IEnumerable<string>>>();

        entity.GetType().GetProperties().Where(
            p =>
                this.IEnumerableType.IsAssignableFrom(p.PropertyType)
                && !this.StringType.IsAssignableFrom(p.PropertyType)).ForEach(
            p =>
            {
                IEnumerable values = (p.GetValue(entity) as IEnumerable);
                ICollection<string> children = new List<string>();

                foreach (var value in values)
                {
                    children.Add(value.ToString());
                }

                dependents.Add(new KeyValuePair<string, IEnumerable<string>>(p.Name, children));
            });

        return dependents;
    }
}

Now let's use the var keyword to make it less verbose.

public class DependencyValidator<TEntity> :
    IDependencyValidator<TEntity>
    where TEntity : class
{
    private readonly Type IEnumerableType = typeof(IEnumerable);
    private readonly Type StringType = typeof(String);

    public IEnumerable<KeyValuePair<string, IEnumerable<string>>> Dependencies(TEntity entity)
    {
        if (entity == null)
        {
            return Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>();
        }

        var dependents = new List<KeyValuePair<string, IEnumerable<string>>>();

        entity.GetType().GetProperties().Where(
            p =>
                this.IEnumerableType.IsAssignableFrom(p.PropertyType)
                && !this.StringType.IsAssignableFrom(p.PropertyType)).ForEach(
            p =>
            {
                var values = (p.GetValue(entity) as IEnumerable);
                var children = new List<string>();

                foreach (var value in values)
                {
                    children.Add(value.ToString());
                }

                dependents.Add(new KeyValuePair<string, IEnumerable<string>>(p.Name, children));
            });

        return dependents;
    }
}

Your ForEach method seems to be non-standard, so I'd like to get rid of that.

public class DependencyValidator<TEntity> :
    IDependencyValidator<TEntity>
    where TEntity : class
{
    private readonly Type IEnumerableType = typeof(IEnumerable);
    private readonly Type StringType = typeof(String);

    public IEnumerable<KeyValuePair<string, IEnumerable<string>>> Dependencies(TEntity entity)
    {
        if (entity == null)
        {
            return Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>();
        }

        var dependents = new List<KeyValuePair<string, IEnumerable<string>>>();

        var properties = entity.GetType()
            .GetProperties()
            .Where(p => this.IEnumerableType.IsAssignableFrom(p.PropertyType) && !this.StringType.IsAssignableFrom(p.PropertyType));

        foreach (var property in properties)
        {
            var values = property.GetValue(entity) as IEnumerable;
            var children = new List<string>();

            foreach (var value in values)
            {
                children.Add(value.ToString());
            }

            dependents.Add(new KeyValuePair<string, IEnumerable<string>>(property.Name, children));
        }

        return dependents;
    }
}

ReSharper suggests replacing the inner loop with a LINQ expression, which I think looks alright.

public class DependencyValidator<TEntity> :
    IDependencyValidator<TEntity>
    where TEntity : class
{
    private readonly Type IEnumerableType = typeof(IEnumerable);
    private readonly Type StringType = typeof(String);

    public IEnumerable<KeyValuePair<string, IEnumerable<string>>> Dependencies(TEntity entity)
    {
        if (entity == null)
        {
            return Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>();
        }

        var dependents = new List<KeyValuePair<string, IEnumerable<string>>>();

        var properties = entity.GetType()
            .GetProperties()
            .Where(p => this.IEnumerableType.IsAssignableFrom(p.PropertyType) && !this.StringType.IsAssignableFrom(p.PropertyType));

        foreach (var property in properties)
        {
            var values = property.GetValue(entity) as IEnumerable;
            var children = (from object value in values select value.ToString()).ToList();

            dependents.Add(new KeyValuePair<string, IEnumerable<string>>(property.Name, children));
        }

        return dependents;
    }
}

Finally, we can make the fields static. ReSharper warns about this, but I think it's fine in this case.

 public class DependencyValidator<TEntity> :
    IDependencyValidator<TEntity>
    where TEntity : class
{
    private static readonly Type IEnumerableType = typeof(IEnumerable);
    private static readonly Type StringType = typeof(string);

    public IEnumerable<KeyValuePair<string, IEnumerable<string>>> Dependencies(TEntity entity)
    {
        if (entity == null)
        {
            return Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>();
        }

        var dependents = new List<KeyValuePair<string, IEnumerable<string>>>();

        var properties = entity.GetType()
            .GetProperties()
            .Where(p => IEnumerableType.IsAssignableFrom(p.PropertyType) && !StringType.IsAssignableFrom(p.PropertyType));

        foreach (var property in properties)
        {
            var values = property.GetValue(entity) as IEnumerable;
            var children = (from object value in values select value.ToString()).ToList();

            dependents.Add(new KeyValuePair<string, IEnumerable<string>>(property.Name, children));
        }

        return dependents;
    }
}


There can be two improvements in above code block initially as below:

Method should be async, this will help your application in terms of performance for parallel requests
In order to delete the large file, one should always prefer to download the file in chunks, again we are talking about parallel programming.


Replacing multiple substrings in a string

Variable naming

N0OfIterationOverTemplate is not only a mouthful, but anyone will also start to wonder about that weird spelling choice of combining a zero 0 with a capital O together. countIterationOverTemplate is much easier to follow.

null handling

Erm, consider how you want to handle potential null values safely.

Biggest difference

Test case: "template", "a", "b", "a", "c"

In the first method, it immediately replaces the "a"s with "b"s, so the second substitution to "c" is effectively a no-op. You end up with "templbte".

In the second method, there's only one substitution being performed, due to how Map.put(K, V) works. Not only that, it's indeterministic which substitution will happen due to how HashMap.keySet() has no predictable iteration order.

Interfaces over implementations declaration

This is the least of your concern here given the biggest difference above, but you are highly recommended to declare map as a Map instead of HashMap because where it's used, it does not need to be known about its actual Map implementation.


Beginner user registration and login program

Not a full review, but too long for a comment

I'm not a C++ developer, but there are a few common foundational programming mistakes that you've made that I saw:

using namespace std is a bad practice. This imports the entirety of the namespace into the current namespace, which can cause a multitude of problems. Here is an article that explains the possible problems, going more in-depth than I could ever. *Note: I didn't change anything that would require std:: at the beginning by removing the namespace, merely for the fact that I don't have the time right now. That can be a good exercise for you :).
Instead of return true; } else { return false; }, simply return the expression you're evaluating. For example in your code, return (un == user && pw == pass).
When a user enters an already existing username/incorrect username or password/username not registered, you call main() again. This can fill the stack pretty quickly with these recursive calls. What if a user keeps making mistakes? Then you have tens or even hundreds of main calls in the stack. Not good. You can wrap all the code in main in a while loop. If a user makes a mistake, simply do nothing and let the loop reset. If a user makes a valid choice, do what you need to do, then break. Note: Didn't implement this either because of time, this one is for you :).

Barely changed but still changed code

#include <iostream>
#include <fstream>
#include <string>

//ADD "std::" TO ALL THINGS THAT COME FROM STD NAMESPACE

bool IsLoggedIn()
{
    string user, pass, un, pw;
    cout << "Username: " << std::endl;
    cin >> user;
    cout << "Password: " << endl;
    cin >> pass;

    ifstream read(user + ".txt");
    getline(read, un);
    getline(read, pw);

    return (un == user && pw == pass);

}

inline bool does_file_exist(const string& name)
{
    ifstream filename(name +".txt");

    return filename;

}

int main()
{
    system("clear");

    int input;
    cout << "(1) Create Account \n" << "(2) Log in \n"<< "(3) Change password" << endl;
    cin >> input;
    if (input == 1 || input == 2 || input == 3)
    {
        if (input == 1)
        {
            system("clear");

            string user, pass;

            cout << "Create Account \n" << endl;
            cout << "Username: " << endl;
            cin >> user;

            if (does_file_exist(user))
            {
                cout << "Username already registered \n" << "Press enter to retry...";
                cin.ignore();
                cin.get();
                main();
            }

            cout << "Password: " << endl;
            cin >> pass;

            ofstream file;
            file.open(user + ".txt");
            file << user << endl << pass;
            file.close();

            main();
        }

        else if (input == 2)
        {
            system("clear");

            cout << "Log In \n" << endl;

            bool status = IsLoggedIn();

            if (!status)
            {
                cout << "Incorrect username or password!" << endl << "Press enter to retry...";
                cin.ignore();
                cin.get();
                main();
                return 0;
            }
            else
            {
                cout << "Successfully logged in!" << endl;
                cin.get();
                return 1;
            }

        }

        else if (input == 3)
        {
            system("clear");

            string user, pass;

            cout << "Change password \n" << endl;
            cout << "Username: " << endl;
            cin >> user;
            if (does_file_exist(user))
            {
                cout << "New Password: " << endl;
                cin >> pass;

                ofstream file;
                file.open(user + ".txt");
                file << user << endl << pass;
                file.close();

            main();
            }
            else
            {
                cout << "Username not registered \n" << "Press enter to retry...";
                cin.ignore();
                cin.get();
                main();
            }

        }
    }
    else
    {
        system("clear");
        cout << "Invalid input" << endl;
        main();
    }
}


github page/ DHH Score Challenge in ruby

The major thing I see is, the code is imperative. But things will be lot more easier to read and follow, if you practise declarative way of writing code.

I would not name the class as DHHScoreChallenge. It should be ScoreChallenge, so that it can be used for any user that we pass in :)

I would make the method getData private, in order to externalise the service layer dependency.

Also I would move the type_and_score into a class level map

This logic is too complex to read

if type_and_score.has_key? commit_type.to_sym
  score = score + type_and_score[commit_type.to_sym]
else
  score = score + 1
end

This could have eliminated by using a combination of dig and fetch. Dig will return nil if you cannot find the key in hash and fetch on a hash can return a value if the value of the key returns nil

Also I see that you are converting the event key to symbol and trying to find the symbol in hash. Instead you might as well have created a hash with strings as symbols, it won't be much of a over head if you freeze the hash.

Something like this

  EVENTS_SCORE_MAP = {
    'IssuesEvent' => 7,
    'IssueCommentEvent' => 6,
    'PushEvent' => 5,
    'PullRequestReviewCommentEvent' => 4,
    'WatchEvent' => 3,
    'CreateEvent' => 2
  }.freeze

 EVENTS_SCORE_MAP.fetch(event.dig('type'), 1)

I rewrote the whole thing in a manner which I would in my production system

require 'typhoeus'
require 'json'

# Github service dealing with all the requests to github
class Github
  def events(user_name)
    url = "https://api.github.com/users/#{user_name}/events/public"
    send_request(
      lambda {
        Typhoeus.get(url)
      }, url
    )
  end

  private

  def send_request(request, path)
    request.call
  rescue Timeout::Error
    raise GatewayTimeoutError.new(gateway: 'github api timed out', path: path)
  end
end

# This class deals calculating the score
class ScoreChallenge
  EVENTS_SCORE_MAP = {
    'IssuesEvent' => 7,
    'IssueCommentEvent' => 6,
    'PushEvent' => 5,
    'PullRequestReviewCommentEvent' => 4,
    'WatchEvent' => 3,
    'CreateEvent' => 2
  }.freeze

  def initialize(user_name, score = 0)
    @user_name = user_name
    @score = score
  end

  def pretty_score
    calculate
    puts "#{@user_name} github score is #{@score}"
  end

  private

  def calculate
    events_of_user = JSON.parse(github_service.events(@user_name).body)
    events_of_user.each do |event|
      @score += EVENTS_SCORE_MAP.fetch(event.dig('type'), 1)
    end
  end

  def github_service
    @github_service = Github.new
  end
end

score_challenge = ScoreChallenge.new('DHH')
score_challenge.pretty_score

As you can see, I have exposed only one method called pretty_score. Which does everything that we need. This is the declarative style of programming I was talking about. I am letting my code figure out what to do, rather than me telling it do something step by step

Also Github is a service class I have created. It should ideally sit under a services folder. I have not implemented GatewayTimeoutError here, but for all practical purposes we should assume that these third party services can timeout/error out we should be able to handle them. You can also look into passing blocks, and custom errors as part of the above code.


My suggestion is to reduce the code:

var page = {
  init: function(selector) {
    $(selector).on('change paste keyup', page.onPageChange);
  },
  onPageChange: function(e) {
    console.log($(e.target).val());
  }
};

page.init('#pNo');


Maintaining state in a pagination handler

I think you have the right approaches, however, you can generalize your implementations, for example, on the second approach:

function installHandler ( that, eventName, userOneTime, userRegular ) {
    that.on(eventName, function ( event ) {
        that.off(eventName).on(eventName, userRegular);
        userOneTime ( event );
        userRegular ( event );
    });
}

installHandler ( $(this), "click",
    function () { alert ("special click"); },
    function () { alert ("regular click"); } );


The code itself is fine, though I would flip it, first html, then the javascript (without the window.onload).

AN example to explain why: If you have a huge image and a slow connection the loading takes say 5 seconds. These 5 seconds all your anchors don't have the target="_blank" and if a user clicks they still leave your website.

I would not use this method meself (unless I have to) .
If you use AJAX to load content with anchors, those anchors will not have the target="_blank" either. This will require a bit more advances problem solving. If you want some links to be ignored, you can't with the current code. There are more small problems that will pop up which are all to minor to sum up here, but in the end are all just very ennoying.

I recommend that you do not rely on this method. Just take some time and update the content. I assume you have that in a datase, just FIND() and REPLACE(). Make it permanent.


Unfortunately in my position I don't have anyone to look over my shoulder and review by Bash code so I thought I'd take advantage of this community.

My first reaction (as usual with any Bash review) was to copy-paste your code into shellcheck.net, and say that you do have someone to check your back, but your code passes with flying colors, so congrats! And yeah, we all have this issue, I hope that Code Review can make a difference for you.

It's a nice script and it runs well, but it can be better.

seq is not recommended, because it's not portable. It's not needed anymore anyway, because any modern Bash natively supports traditional for (( ; ; )) loops as in other languages, without having to spawn a sub-process. So the main loop can be written as:

for ((i = panlen - 1; i >= 0; i--)); do

Notice there I wrote spaces around operators. It's not an official recommendation, but I like this writing style, as recommended in other languages for increased readability. You can apply this style for all the code within ((...)), so for example instead of this:

 ((digit*=2))

I would write:

 ((digit *= 2))

Since you are already using ((...)) and as such the script is not POSIX compliant, I recommend all the way, and use it more aggressively for a simplified and more natural writing style.

For example instead of this:

  if [ $(((panlen-i) % 2)) -eq 0 ]; then

You can write like this:

  if (((panlen - i) % 2 == 0)); then

Comparisons with numbers are more natural in an arithmetic context within ((...)) than the -eq operator within [ ... ].

The final line of the program can be changed from this:

[ $((sum % 10)) -eq 0 ] || exit 1

To this:

((sum % 10 == 0))

That is, using a natural arithmetic context,
and taking advantage that the exit code of the program will be the exit code of the last command, making the || exit 1 redundant.
You may still want to leave the || exit 1 for clarity, it's up to you.


Least common ancestor for binary search tree

Most of the code is pretty good!

I find your interface a bit weird.  Instead of public void makeBinarySearchTree(Integer[] a), I suggest public void addElements(int[] elements) to be consistent with your addElement(int) method.  There's no need to tell everyone that you're making a binary search tree, since that information is encoded into your class name already.

You might want to generalize the code to handle any Comparable, not just ints.  You would get more flexibility for little additional effort.

Instead of throwing IllegalArgumentException, I would throw NoSuchElementException.  In fact, I would change doesExist() to

private TreeNode find(TreeNode start, int element) {
    if (start == null) {
        throw new NoSuchElementException(Integer.toString(element));
    }
    if (element < start.item) {
        return find(start.left, element);
    }
    if (element > start.item) {
        return find(start.right, element);
    }
    // Assertion makes the code more readable
    assert element == start.item;
    return start;
}

That way, you can let the exception propagate up all the way, and it would tell you which of the two numbers passed to leastCommonAncestor() is missing.

Your addElement() is a bit repetitive and can be simplified:

public void addElement(int element) {
    // No matter what happens, we're going to attach this
    // new node somewhere.
    TreeNode newNode = new TreeNode(null, null, element);

    if (root == null) {
        root = newNode;
        return;  // Return early to avoid a layer of nesting
    }

    TreeNode node = root;
    while (true) {
        if (element <= node.item) {
            // Test for null before following the pointer.
            // That relieves you from having to keep track
            // of the parent node, and also avoids having
            // to decide again whether to attach to the
            // left or right.
            if (node.left == null) {
                node.left = newNode;
                return;
            }
            node = node.left;
        } else {
            if (node.right == null) {
                node.right = newNode;
                return;
            }
            node = node.right;
        }
    }
}

Follow-Up Q & A

  Not understanding your feedback - I suggest public void
  addElements(int[] elements) to be consistent with your addElement(int)
  method.

In Java, you use unboxed primitives most of the time.  Boxed types are rare: generally they are only used in Collections (which can't store primitives) and when you want to store a value that might be null.  An Integer[] array is therefore rather unnatural — it's neither an int[] nor a List<Integer>, both of which would be more likely to occur.

  As regards to cleaning up addElement() I had few concerns

  while(true) is said to be bad
  more checks in your method (a) while(true) (b) null check
  (c) comparison, while my code does only 2 of them for most traversal
  part (a) null and (b) compare.

There are two common objections to while (true): one invalid concern about efficiency, and one legitimate concern about style.

Many decades ago, simplistic C compilers might take while (true) literally, and generate code to load 1 into a register, check whether the register was non-zero, and execute a conditional jump.  Modern C compilers and all Java compilers are smart enough to handle while (true) efficiently, generating nothing but an unconditional goto at the end of the loop.  You can verify this by inspecting the bytecode:

$ cat WhileTrue.java
public class WhileTrue {
    private WhileTrue() {}  // Suppress default constructor

    public static void main(String[] args) {
        System.out.println("Before while loop");
        while (true) {
            System.out.println("In while loop");
        }
        // Compiler would detect this as unreachable
        // System.out.println("After while loop");
    }
}

$ javap -c WhileTrue
Compiled from "WhileTrue.java"
public class WhileTrue extends java.lang.Object{
public static void main(java.lang.String[]);
  Code:
   0:   getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   3:   ldc #3; //String Before while loop
   5:   invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   8:   getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   11:  ldc #5; //String In while loop
   13:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   16:  goto    8

}

That means that your second objection is invalid, since while (true) is not a check.  In fact, your original version had more conditionals since you had to decide which side to append to after exiting the loop.

As previously mentioned, there is another problem with while (true), which is that it keeps the reader in suspense.  Most programs are not intended to run in an infinite loop.  Therefore, when you see while (true), you immediately suspect that something within the loop must eventually cause it to terminate: a break, a return, or an exception.  Therefore, whenever you feel the urge to write while (true), it's always worthwhile to think about whether it is possible to restructure the code such that the termination condition can be expressed in the loop header, rather than buried in the loop body.  In many instances, it is possible, but here, I think that my proposal is already optimal.


Optimize Implementation - Wait for all threads using LINQ

It's better to use new asynchronous API since it provides more features for combining asynchronous tasks.

Ideally Mainboard, CentralProcessingUnit and DeviceService should expose asynchronous API if a certain operation is not trivial, so (as you mentioned in comments you wrote them) I would implement asynchronous API for them first, e.g.:

public class Mainboard
{
    public Task<string> GetInformationAsync()
    {
        //TODO: extract long-term operation into Task. Try not to span extra threads here
    }
}

Then your method would look like:

Task.WaitAll(
    new Mainboard().GetInformationAsync().ContinueWith(task => c.Mainboard = task.Result),
    new CentralProcessingUnit().GetInformationAsync().ContinueWith(task => c.ProcessorList = task.Result),
    DeviceService.ScanServicesAsync());

If you decide not to implement async API the code can look like:

var c = new Computer();

Task.WaitAll(
    Task.Factory.StartNew(() => c.Mainboard = new Mainboard().GetInformation()),
    Task.Factory.StartNew(() => c.ProcessorList = new CentralProcessingUnit().GetInformation()),
    Task.Factory.StartNew(() => DeviceService.ScanServices()));


Yes, this can be faster. Adding strings using + is usually a bad idea in Python, since strings are immutable. This means that whenever you add two strings, a new string needs to be allocated with the size of the resulting strings and then both string contents need to be copied there. Even worse is doing so in a loop, because this has to happen ever time. Instead you usually want to build a list of strings and ''.join them at the end (where you pay this cost only once).

But here you can just use the fact that strings can be sliced and you can specify a negative step:

def reverse_g(s):
    return s[::-1]

Here is a timing comparison for random strings of length from one up to 1M characters, where reverse is your function and reverse_g is this one using slicing. Note the double-log scale, for the largest string your function is almost a hundred thousand times slower.

The reverse_s function uses the reversed built-in, as suggested in the (now deleted, so 10k+ reputation) answer by @sleblanc and assumes you actually need the reversed string and not just an iterator over it:

def reverse_s(s):
    return ''.join(reversed(s))

The reverse_b function uses the C implementation, compiled with -O3, provided in the answer by @Broman, with a wrapper to create the string buffers and extract the output:

from ctypes import *

revlib = cdll.LoadLibrary("rev.so")
_reverse_b = revlib.reverse
_reverse_b.argtypes = [c_char_p, c_char_p, c_size_t]

def reverse_b(s):
    stri = create_string_buffer(s.encode('utf-8'))
    stro = create_string_buffer(b'\000' * (len(s)+1))
    _reverse_b(stro, stri, len(s) - 1)
    return stro.value.decode()

In the no interface version, just the call to _reverse_b is timed.


Way way too complex

One way to help workout how to solve a problem is to solve it in your head (or on paper) first. That way you know the problem from the top to the bottom. Then use that approach in your script.

The code looks like you started at the top with no clear idea of the solution, and solve many separate problems as you encountered them. The result is unreadable and way to complex.

I could not make a good assessment due to its complexity and bugs.

Your code does not run.

The name aggregateScope in aggregates should be aggregate
sum throws TypeError map is not a function

Patching those problems it still did not run.

The hell of a zillion iterators is not easy to traverse so I stopped trying to work it out at that point.

Questions.

You have some questions.

  what are alternative ways of breaking down the problem?

Its just a set of nested arrays and named objects. The names are fixed, so its just a process of stepping over each array in turn storing the counts in a named map (see example)

  what is it's Big O complexity?

I am guessing its It more than \$O(n)\$ and less than or equal to \$O(n^2)\$ where \$n\$ is the number of category items. As there is only a small sample dataset and the code does not work I can not give a accurate evaluation.

I did count 18 different iteration function calls throughout your code. With 2 or 7 iterations each, nested to about 6 levels. If I use that and average (2 + 7) / 2 = 4.5 per iterator then its 4.56 approx steps, so that's a big \$O(n^3)\$ for the given dataset of 11 category items

  Can it be reduced?

Yes, it can be O(n) as there is no need to search, and no need to compare items (see example).

  are there language features (JS/ES6) that can make this more idiomatic?

Use for of loops to iterate.
Use bracket notations to create named properties.
Keep your functions ordered. From bottom to top, it makes it easier to locate functions and follow the code.
No more than one iterator per line. You quickly lose track of how complex it gets.

Is all that comes to mind, that and  K.I.S.S.

An alternative example solution

I am not that conventional when it comes to code, so not quite idiomatic. less is good in my book and helps find the optimal \$O(n)\$ solution.

function aggregateTransactionCategories(data, types) {
  const result = {};
  const mapCategories = (type, transactions) => {
    for (const cats of transactions) {
      const name = type + "_" + cats.category;
      result[name] = result[name] ? result[name] + 1 : 1;
    }
  }
  for (const type of types) {
    for (const entries of data) {
      for (const entry of entries[type]) {
        mapCategories(type, entry.transactions);
      }
    }
  }
  return result;
}

setTimeout(() =>
    log(aggregateTransactionCategories( data,  ["groups", "users"]))
    ,0
);

const data = [{
    users: [
      { id: "07bd", transactions: [{category: "purchase"}, {category: "unknown"}] },
      { id: "40aa", transactions: [{category: "sale"}, {category: "unknown"}] }
    ],
    groups: [
      { id: "00c6", transactions: [{category: "atm"}, {category: "cash"}] },
      { id: "eb95", transactions: [{category: "atm"}, {category: "cash"}] }
    ]
  }, {
    users: [
      { id: "af09", transactions: [{category: "bill"}] }
    ],
    groups: [
      { id: "c5ba", transactions: [{category: "fee"}, {category: "cash"}] }
    ]
  }
];

//Just displays the result and not related to the problem
function log(data) {
  for(const [name, value] of Object.entries(data)) {
    displayResult.appendChild(Object.assign(
      document.createElement("div"),{
        textContent : name + ": " + value + ","
      }
    ))
  }
}


Creating multiple new child forms from a single form

Your code is very small for a good review, but a few things can be mentioned:

1) naming - it is better to name your variables by what they represent. E.g. DemoTabContentMiniGraph1, 2, 3 should can be named something like MiniGraphFS1View, MiniGraphPs1Ps2View etc.

Also, F_CWndw_GraphFS1 can be adjusted to Pascal/Camel notation used in C# (they look to have C++ naming style)

2) passing parameters to instances - providing many parameters to a constructor works, but it may render maintainability problems in the future:

it is very hard to know what the third false in F_CWndw_GraphFS1(true, false, false, false, 0.5, 100, 0.5, 10, "Time (s)", 20, 100, 100, "Flow Rate (l/s)", 2, true, "DEMO"); means
if a new parameter must be added to the graphic, you may have to change in multiple places (constructor prototype, callers have to provide the new parameter, if it does not have a default value).

A better way is to define a class named GraphOptions or similar to encapsulate your options:

class GraphOptions
{
   float MinValue { get; set; }
   float MaxValue { get; set; }
   String XLabel { get; set; }
   // other properties come here

   // you can also define a constructor to assign default values
}

Your construction code will look something like this (much longer, but much easier to understand):

var FormMiniGraph1 = new F_CWndw_GraphFS1(new GraphOptions()
   {
      Prop1 = true,
      Prop2 = false,
      Prop3 = false,
      MinValue = 0.5,
      MaxValue = 100,
      XLabel = "Time (s)"

      // all other properties remain to their default value or their value does not matter for current graph
   }

3) (possible) AddRange optimization:

If Children implements IEnumerable, AddRange can be used

Grid_miniGraph1.Children.Add(DemoTabContentMiniGraph1);
Grid_miniGraph2.Children.Add(DemoTabContentMiniGraph2);
Grid_miniGraph3.Children.Add(DemoTabContentMiniGraph3);

becomes

Grid_miniGraph1.Children.AddRange(new List<WindowsFormsHost>() { DemoTabContentMiniGraph1, DemoTabContentMiniGraph2, DemoTabContentMiniGraph3 };

Other aspect is the harcoded number of possible graphs. Are they so different that they must be defined one by one? Do they share common functionality?


If you're optimizing for performance it does not get much better than that. In particular it is a valuable optimization to compute the exact result array length.

I'm not sure why you used ConstrainedCopy which is a very esoteric feature. Copy is faster. ConstrainedCopy is, I believe, used for code that must not be interrupted by a ThreadAbortException. The concept is called a constrained execution region and it's useless in practice because programming in the presence of thread aborts is essentially impossible. The consensus is to never abort a thread except your own (ASP.NET violates that rule which must be very unsafe).

The code is of good quality as well. I'd use foreach to traverse the list. It compiles to the same code that you wrote but is nicer.

Answers have been proposed that use List<byte> or LINQ. These will be far slower (e.g. 10-100x). This is because Array.Copy is a facade over memmove (which is similar to memcpy but it handles overlapping regions as well). The difference becomes noticeable even with common network speeds (10MB/s) and certainly with disk speeds (100MB/s and up).

If you don't care about performance or the amount of data processed is small than you can use slower approaches. Some people find such code better and I'd certainly understand why. The LINQ approach using Concat is extremely concise and self-documenting.


Recursive Matrix Multiplication Algorithm

All of the endpoints are redundant. If anyone can add anything else I'd still appreciate it.
#include <stdio.h>

void matrix_addition_partition(size_t n, size_t m, int A[m][m], int B[m][m], int C[n][n], size_t start, size_t end) {
    for(size_t i = 0; i < m; ++i) {
        for(size_t j = 0; j < m; ++j) {
            C[i+start][j+end] = A[i][j] + B[i][j];
        }
    }
}

void recursive_matrix_multiply(
        size_t l, size_t n, int A[l][l], int B[l][l], int C[n][n],
        size_t ar, size_t ac, size_t br, size_t cb
    ) {
    if(n == 1) {
        C[0][0] = A[ar][ac]*B[br][cb];
    } else {
        int m = n>>1;
        int C1[m][m], C2[m][m];

        recursive_matrix_multiply(l, m, A, B, C1, ar, ac, br, cb);
        recursive_matrix_multiply(l, m, A, B, C2, ar, ac+m, br+m, cb);

        matrix_addition_partition(n, m, C1, C2, C, 0, 0);

        recursive_matrix_multiply(l, m, A, B, C1, ar, ac, br, cb+m);
        recursive_matrix_multiply(l, m, A, B, C2, ar, ac+m, br+m, cb+m);

        matrix_addition_partition(n, m, C1, C2, C, 0, m);

        recursive_matrix_multiply(l, m, A, B, C1, ar+m, ac, br, cb);
        recursive_matrix_multiply(l, m, A, B, C2, ar+m, ac+m, br+m, cb);

        matrix_addition_partition(n, m, C1, C2, C, m, 0);

        recursive_matrix_multiply(l, m, A, B, C1, ar+m, ac, br, cb+m);
        recursive_matrix_multiply(l, m, A, B, C2, ar+m, ac+m, br+m, cb+m);

        matrix_addition_partition(n, m, C1, C2, C, m, m);

    }
}

void matrix_multiply(size_t n, int A[n][n], int B[n][n], int C[n][n]) {
    recursive_matrix_multiply(n, n, A, B, C, 0, 0, 0, 0);
}

int main()
{
    int A[4][4] = {{1, 2, 3, 4}, {4, 3, 2, 1}, {0, 0, 1, 1}, {1, 1, 0, 0}};
    int B[4][4] = {{2, 2, 4, 4}, {4, 1, 1, 4}, {1, 0, 1, 0}, {1, 0, 1, 0}};
    int C[4][4];

    matrix_multiply(4, A, B, C);

    for(size_t i = 0; i < 4; ++i) {
        for(size_t j = 0; j < 4; ++j) {
            printf("C[%i][%i] = %i, ", i, j, C[i][j]);
        }
        printf("\n");
    }

    return 0;
}


Finding all pairs of elements in an array that sum to a target value

No, each number requires a second pass to determine whether combined with an existing one it is a match - doesn't mean it can't be short though e.g.

const checkIfSumFromTwoNumbers = (arrayOfNums, targetValue) =>
  arrayOfNums.reduce((matches, val) => {
      const target = arrayOfNums.find(x => (val + x) === targetValue);
      target && matches.push([val, target]);
      return matches;
   }, [])

I was actually ignorant to the fact your code actually works which means it can be done in one pass :) here's a slightly neater / more concise version of what you already have:

const checkIfSumFromTwoNumbers = (arrayOfNum, targetValue) => {
  const seen = {};
  return arrayOfNum.reduce((matches, val) => {
    const delta = targetValue - val;
    seen[delta] && matches.push([delta, val]);
    seen[val] = true;
    return matches;
  }, []);
};


Correct control of execution of Java thread

Lets start with the instance variables.

public class Mp3PlayerThread extends Thread
{
    public  volatile boolean playing = false;
    public  volatile boolean abort   = false;
    private Player   player;
    private String   path;
    //...
}

You shouldn't be directly exposing playing and abort. Doing this hinders your ability to change the internal implementation of your class and remain backwards compatible.
Trying to line up you variable declarations will be a losing battle. It looks nice now, but when you add a new variable, you might have to completely change everything. This will make looking at diffs harder because some lines will be changed even though they are not directly involved in the new functionality. Additionally, an argument could be made that all of the variable names should be lined up instead of having player line up with boolean.
path is set once in the constructor and never changed. Setting it to be final could prevent you from accidentally changing it later with the expectation of it having an effect.

The URL at the beginning of the run method is not helpful. There is no context explaining why it is relevant to this piece of code. The post asks about something that this code is not doing. The general consensus of the post is "there is no reason to do that and I have never seen that done."

public void run() {
    FileInputStream     fis = new FileInputStream(this.path);
    BufferedInputStream bis = new BufferedInputStream(fis);
    this.player             = new Player(bis);
    //...
}

By writing your class this way, it is always forced to read a file from disk. What happens if you want to stream the song over a socket? Passing the input stream in to the constructor (or even the Player instance) would make your class more flexible and easier to test.

while (!abort)
{
    if (playing)
        player.play(1);
}

If playing is set to false, this thread will spin and waste cpu time.

There is no reason Mp3PlayerThread to be a subclass of Thread. Making it a simple class that implements Runnable would allow you to use it in more contexts and not incur the heavy costs of creating a thread every time an instance is instantiated. An example of the expanded context would be to create a thread pool of size one. Then you can schedule multiple songs to be played just by adding an instance to the execution pool for each new song.

public Mp3Player(String filename)
{
    song = filename;
}

public Mp3PlayerThread(String file)
{
    this.path = file;
}

Why are the variable names changing when they are all the same thing? Variable shadowing is not a valid excuse as you can use this. or prefix your member variables with an underscore.

In general, you should decide if you want to use this. or not and be consistent.


Python - 'if name in dict:' OR 'try:/except:'

It depends.

Mostly, it depends on whether it'll generally be in the dictionary or not. If it's nearly always in the dictionary, then the try/except method would win out, while if it's in there as often as not, then checking would be somewhat faster.

However, python already anticipated your need. There's a better option:

def GetSlot(self, slot_name):
    return self.Slots.get(slot_name)

All mappings support get, which has a default optional argument that defaults to None. This should be the best option. However, that said...

GetSlot is not a PEP8-compliant name. It should be get_slot.
self.Slots should probably be self.slots.
NOTE: Since you confirmed in a comment that you are in fact using externally defined names, I think it is best practice to follow those names as well as their naming conventions when appropriate.
This should probably not be a method at all. In python, accessor functions are somewhat frowned upon. If you really need to do something like this, use properties. However, anything wanting to get slot_name from self.Slots should just use self.Slots.get(slot_name). Even if you're reaching into the object from outside. Java and other languages that advocate getter/setter methods do so because it later allows you to change how it is gotten, but Python is better and doesn't require workarounds like this to influence how you access a variable. Read more here.

A note on Python getters and setters

Python descriptors are a powerful tool. It's not actually an object, it's a protocol of how python retrieves variables when they're used as object attributes. The classic example is python's property, but in truth methods on a class are also descriptors. An object implements this protocol by having __get__, __set__ or __delete__ methods on it. Not all are required for every type of descriptors - please follow the link for in-depth classification and usages.

What this all means in practice is that python objects can change how they are retrieved. This is impossible in languages like Java, which can cause engineering issues.

Let's first figure out why people use getters and setters in Java, because the reasons they have are quite important.

So I have a class with an attribute that I want to expose to the public for usage.

(NOTE: Java users please don't take offense. I'm writing just Python here since I've honestly never used Java. All my knowledge of it is second-hand at best.)

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.distance_to_orgin = pythagoras(x, y)
# Later...
instance = Point(a, b)
instance.distance_to_orgin

Now, everyone can access it. So I publish my library, and everyone's code works fine.

But then, I get a better idea - every point already knows it's x and y, so I can always calculate the distance_to_orgin if I need it.

In Java, I now have a problem. Because to calculate something on retrieval, I NEED a function - but everyone accesses it by attribute access. I cannot make this change in a backwards compatible manner. So, programmers learn to make getter and setter methods. Compare to before:

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.distance_to_orgin = pythagoras(x, y)

    def get_distance_to_orgin(self):
        return self.distance_to_orgin

# Later...
instance = Point(a, b)
instance.get_distance_to_orgin()

Now, if I want to change how it works, I can just write a different get_distance_to_orgin method and I can make the change - fully backwards compatible!

So why isn't this a problem in Python?

Because we have descriptors. In 99.9% of cases, the builtin property() does everything you want. I can just amend my class definition like this:

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
        # self._distance_to_orgin = pythagoras(x, y) No longer needed

    @property
    def distance_to_orgin(self):
        return pythagoras(self.x, self.y)

# Later...
instance = Point(a, b)
instance.distance_to_orgin

And the external usage is exactly the same as it was at the very start, back when we were building a class in a naive way!

So that is why getters and setters are important for many languages, but why we don't need them in Python.


Why is this divide and conquer algorithm inefficient?

I don't know for sure why your program is running out of time (since I know nothing about the target platform), but my guess is that it's either item (1) or (2) in the list below. These errors lead to undefined behaviour, and then, well, anything could happen (that's what undefined means), including an infinite loop.

This line computes the wrong size for the allocation:

bul = (int **) malloc(num * sizeof(int));

You want an array of num pointers to integers but you are allocating space for num integers. So this will only work if an integer is the same size as a pointer. On my platform/compiler (x86-64/Clang) an integer is 4 bytes long but a pointer is 8 bytes long so this computes a size that is too small, and then the loop writes off the end of the array, which results in undefined behaviour. (On my platform this causes the program to crash with a segmentation fault.)

You need to write:

bul = malloc(num * sizeof(int *));

or:

bul = malloc(num * sizeof *bul);

instead. Note that there's no need to cast the result of malloc() since the function returns void * and that type is convertible to any object pointer type without a cast.
The total area might be close to 1018 units. For example if the input was

1
1 1000000000 1000000000

then your program would need to output

999999999000000000

and yet you are accumulating the area in the variable square, which is an int. Is int large enough on the target platform/compiler to store a number of this size? It certainly isn't on mine (x86-64/Clang) where INT_MAX is 2147483647.

This means that your program causes integer overflow, which yields undefined behaviour. (John Regehr has a good explanation here.)

On my platform (with item (1) above fixed) this bug causes mergebuilding() to run off the end of the array in an infinite loop (because the comparison with INF goes wrong) and this eventually hits unmapped memory and crashes with a segmentation fault.

I'm surprised that you didn't spot this at compilation time. I get these warnings from Clang:

cr26938.c:46:21: warning: implicit conversion from 'long' to 'int' changes value
      from 10000000000 to 1410065408 [-Wconstant-conversion]
    r[r_move].pos = INF;
                  ~ ^~~
cr26938.c:4:13: note: expanded from macro 'INF'
#define INF 10000000000
            ^~~~~~~~~~~

And these from gcc:

cr26938.c: In function ‘mergebuilding’:
cr26938.c:26: warning: comparison is always true due to limited range of data type
cr26938.c:26: warning: comparison is always true due to limited range of data type
cr26938.c:46: warning: overflow in implicit constant conversion

Perhaps you can say what compiler you are using?

You need to use a type that's large enough on the target platform to store numbers of the required size. If the target platform conforms to C99, then you can

#include <stdint.h>

and then use int64_t, which is guaranteed by the standard to be a signed integer type with exactly 64 bits. But if the target platform does not conform to C99, then, well, I guess you need to read the compiler manual to find out what type is big enough (but probably long or long long would work).
You write

#include <malloc.h>

which is non-standard: in Standard C, malloc() is declared in stdlib.h. Unless your platform is really non-standard, I'd stick with stdlib.h.
What is the role of the bul array? You only ever use one element at a time, and then only to read some numbers which you immediately copy out again. Why not read the input into variables on the stack instead? Perhaps like this:

for (int i = 0; i < num; i++) {
    int a, b, h;
    scanf("%d %d %d", &a, &b, &h);

You don't check the return values of the functions you call. malloc() returns NULL if it can't allocate, and scanf() returns the number of input items assigned, which might be less than the number of format specifiers if there was an error. I know this is only a simple program that doesn't require much in the way of error handling, but it's still an opportunity for you to practice your skills. And it doesn't have to be burdensome: you can write

if (p[i] == NULL) error("out of memory");
if (scanf("%d %d %d", &a, &b, &h) != 3) error("malformed input");

with error() defined like this:

void error(const char *message) {
    fprintf(stderr, "%s\n", message);
    abort();
}


Prompt user for input then create an acronym from it

The procedure name acronym does not tell you what this procedure is doing. Naming it create_acronym would make the code more obvious.
Error checking: You assume that the user only enters a single space between words. This will cause problems if the user enters more than one space by accident, introducing spaces in your acronym
Most times acronyms are capitalized. You might want to capitalize each letter before adding it to the phrase.
With renaming your procedure create_acronym, you can rename the phrase variable to acronym, which is more appropriate since an acronym is not a phrase. A phrase is one or more words.
Pausing execution: Some say using system("PAUSE") is bad. Instead, just read from cin to a variable and discard the value. That way the application will hang waiting for input until the user presses the ENTER key.


C++ - Graph implementation for data types other than int

Pass parameters by const &

In print_list and your Graph constructor, you pass in the parameters by value.  This will make unnecessary copies of the vectors.  Passing in the values by const reference will avoid making these copies.

Make use of the auto keyword or range-based for loops

You have several places with a long type name to get the type to use for an iterator.  These would be great spots to make use of the auto keyword.  For example, auto it = l.cbegin().

However, in these cases, you can do better.  You can use the range-based for statement instead.

Combining these for the print_list function gives us

template<typename T>
void print_list(const std::list<T> &l)
{
    for (auto v: l)
        std::cout << v << '\t';
    std::cout << std::endl;
}

Similar changes can be made to your Graph constructor and print_adj_list.

You can also pass the pair to add_edge by const reference, although with the small types you're using that won't really gain much.

add_edge assumes that all your edges are bidirectional.  Some adjacency lists have edges that only go in one direction.

Do you need that cout in size?  All it is really doing is telling you that the function has been called.

You should be able to call print_list without having to specify the type.  The compiler should be able to deduce the template type to use.


On the style of the code:
While I'm not saying the code is or isn't correct, there's some small tweaks you could make it to improve it's legibility:
Spacing
Write code like you would write English (in some sense :P). After commas you needs spaces, so do

def crossover(p1, p2): instead of def crossover(p1,p2):;
random.uniform(b[i][0], b[i][1]) instead of random.uniform(b[i][0],b[i][1])
same thing around binary ops: if locii[i] > 4: instead of if locii[i]>4:
etc.

List comprehensions often do not need a leading space, so you can go with
p = [random_param(geno_size, bounds) for i in range(p_size)]

instead of
p = [ random_param(geno_size,bounds) for i in range(p_size)]

crossover
You have written:
def crossover(p1,p2):

    crossover = []
    locii = [random.randint(0,8) for _ in range(len(p1))]

    for i in range(len(p1)):
        if locii[i]>4:
            crossover.append(p2[i])
        else:
            crossover.append(p1[i])

    return crossover

Consider this alternative definition:
def crossover(p1, p2):

    crossover = []
    for p1_elem, p2_elem in zip(p1, p2):
        if random.randint(0,8) > 4:
            crossover.append(p2_elem)
        else:
            crossover.append(p1_elem)

    return crossover

Notice I don't precompute all locii, although you could do that, of course. Also note the usage of zip which means I can traverse both p1 and p2, instead of having to use indices to later grab the values. (You can read more about zip and find other tips and tricks here.
random_param
In line with one of the things I showed above, instead of doing
def random_param(g,b):
     return [random.uniform(b[i][0],b[i][1]) for i in range(g)]

you could iterate directly over b:
def random_param(g, b):
     return [random.uniform(bs[0], bs[1]) for bs in b]

(More on better iterating in Python here.)
Then, take that and unpack bs with * instead of with indices:
def random_param(g, b):
     return [random.uniform(*bounds) for bounds in b]


Here is a review of the code. While some my comments / suggestions are related to JavaScript and not to react specifically, these do reflect common practices in React code.

I put a live version with the changes on codesandbox. I created a small API to have some data for the fetch request. I also added a css file to test the active behavior for the selected filter topics.

Library.jsx

componentDidMount():

It is a common practice in react to use the map function to create a new array. Also, you can change the code so that setState is only called once (for conciseness):

componentDidMount() {
  fetch("https://demo5925186.mockable.io")
    .then(res => res.json())
    .then(data => {
      const topics = data.topics.map((name, index) => ({
        name,
        id: index,
        active: false
      }));

      this.setState({
        lib: data.lib,
        filteredLib: data.lib,
        topics
      });
    })
    .catch(err => console.log(err));
}

render()

It can make your JSX easier to read if you extract properties from the state on the first line using object destructuring assignment:

const { filteredLib, topics } = this.state;

It seems like you would always want to show the Filters component (the topic selection), even if filteredLib.length is equal to 0.

render() {
    const { filteredLib, topics } = this.state;
    return (

        <Filters topics={topics} handleClick={this.handleFilters} />
        {filteredLib.length === 0 ? (

Wir konnten leider nichts finden :(

        ) : (

              {filteredLib.map(item => (
                <LibraryItem key={item._id} {...item} />
              ))}

        )}

    );
}

handleFilters

I changed state.filter to state.selectedTopic and the input argument name from topic to newTopic.

Similarly to componentDidMount, the newTopics array can be created with map (you could convert the ternary to an if-else statement). You can use the spread operator on each object to create a new object.

It seems like state.filter would never be an empty string because handleFilters always sets state.filter to whichever topic was selected.  To fix this, you can compared the new selected topic to the existing one. If they are the same, the new selected topic should be set to an empty string.

handleFilters = newTopic => {
    const { topics, selectedTopic } = this.state;

    const newTopics = topics.map(
      topic =>
        topic.id === newTopic.id
          ? { ...topic, active: !topic.active }
          : { ...topic, active: false }
    );

    // If the new selected topic is same as the old one
    // We will set state.selectedTopic to ""
    const newSelectedTopic =
      newTopic.name === selectedTopic ? "" : newTopic.name;

    this.setState(
      {
        topics: newTopics,
        selectedTopic: newSelectedTopic
      },
      () => {
        this.filterLib();
      }
    );
  };

Filters.jsx

It is common to define functional components with const, and the parameters can be destructured in the function definition.

There is no need for the handleClick method. You can change the name of props.handler to props.handleClick, and call it directly.

const Filters = ({ topics, handleClick }) => (

Filter

      {topics.map(topic => (

 handleClick(topic)}
        >
          {topic.name}

      ))}

);

export default Filters;


Hmm... the generalFizzBuzz method is a mix of business logic and output, I think this should rather be separeted.

Thus, I'd rather have a business logic conversion number, which converts a given number to test to the output string:

private static String convertNumberForOutput(Map<Integer, String> numberReplacement, int num) {
    // not necessarily better than a loop, but to show a different approach
    // (attn: I have not tried to compile this ;-))
    return numberReplacement.entrySet().stream()
        .filter(e -> (num % e.getKey()) == 0)
        .map(Map.Entry::getValue)
        .collect(Collectors.joining());
}

In the generalFizzBuzz method, replace the inner loop with a call to that function.

Naming: "map" is a no-go-name. This is like calling start and stop "numberA" and "numberB". The map has a logical purpose, so you should reflect this in its naming.


Find no of swaps needed to club identical elements of array together

Bug

Your method doesn't calculate the correct number of swaps. Using the input string oozzoo the correct result should be 4 but your algorithm gets a result of 2.

Single resopsonsibility principle

The findNumberOfTurns() method is calculating the number of swaps and prints the output which is too much. Let the method return the number of swaps needed. Printing the result shouldn't be in that method.


Random range with no repeat and efficient for small subset

Before I start, let me say that this code looks pretty good. You seem to have tested your algorithm pretty well and I've never read about shuffling algorithms other than the Fisher-Yates, so I won't comment on it.

First, this code seems a little squished together. I would put newlines between my methods to make it a little clearer where one unit of responsibility starts and the previous one stops.

Second, please use your braces. And if you aren't going to use braces, then consistently don't use them:

if (!HasNext)
    return -1;

while (used.Contains(next))
{
    next = rand.Next(start, range + start);
}

Third, parameters are named with camelCase by convention in C#:

public void Reset (int RangeCount = 100, int Start = 1)

Fourth, please put spaces around your operators:

if (RangeCount< 1)

In the if/else if block in Next(), you do range-- at the top of each block. You should move this to just above the conditional if it is going to happen either way. However, I'm not quite sure if it is supposed to use the -- operator in each given that the comment for the first says you are trimming the top of the range and the comment for the other says you are trimming the bottom.

//in .NET end is not inclusive

This comment is not really needed, unless you are reminding yourself about it. Robert C. Martin states in Clean Code that every time you use a comment to explain your code, what the comment is really saying is that you failed to write your code so it explains what it does itself. After reading and writing many comments myself, I have to agree with him.

C# 6 would allow you to use the => expression for your one-line calculated properties:

public bool HasNext => CountLeft > 0;

Instead of:

public bool HasNext { get { return (CountLeft > 0); } }


There are a few problems with this code.

In disp_intro() you're using global HIGHSCORE, but it should actually be global HIGHSCORE_DATA
In case highscore.txt doesn't exist, the whole code will fail when trying to access HIGHSCORE_DATA[0] and HIGHSCORE_DATA[1], so you should have some defaults, like HIGHSCORE_DATA = ['', 0]
You're not closing the highscore.txt file when reading (use with) and f is not a nice name (the same goes when writing it).
You don't need another variable for the high score, it's already what you need
When reading the highscore file you probably want rstrip() to remove the extra newline you may (or may not) have

I think it's better:

if os.path.isfile('./highscore.txt'):
    with open("highscore.txt", "r") as highscore_file:
        HIGHSCORE_DATA = highscore_file.readline().rstrip().split(',')

In disp_intro() you also need global NUM_DIGITS
You don't need your own function to check if it's all digits, you have the isdigit() function
Put the main loop in a main() function.

Call it with:

if __name__ == '__main__':
    main()

See here

I think the get_clues() function is a bit chaotic. It's not consistent because you're returning either a code (ERROR_LENGTH_TOO_LONG) or a description (You got it!). You're also using the same function to determine if you need to increment the difficulty or not. Also, the caller uses the returned description to check if the player has guessed correctly, which is actually the same check you're doing inside of the function.

You're probably better off having a function called compare_guess() which only returns code and the print the description of those codes using a dictionary.

If this is a school exercise and you still haven't learnt how to use dictionaries, you can still do it with two arrays, one for the codes and the other for the descriptions. I think that would still be better than mixing the two things.

There are also quite a few pep8 things to fix, but that's a minor concern right now, you should first fix the other issues.


I believe you could improve your code by using prototypes like this:

function handler(anchorIndex, anchor) {
    this.anchorIndex = anchorIndex;
    this.anchor = anchor;
}

handler.prototype = {
    handleResult: function(aResultSet) {
        for (let row = aResultSet.getNextRow();
        row;
        row = aResultSet.getNextRow()) {

            let value = row.getResultByName("url");
            if (value == anchor) {
                anchor.innerHTML += "+";
            }
        }
    },

    handleError: function(aError) {
        print("Error: " + aError.message);
    },

    handleCompletion: function(aReason) {
        if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) {
            print("Query canceled or aborted!");
        }
    }
};

Instead of creating a new object, which has to create new instances of the same functions, you create those functions once. This will improve performance and reduce memory usage across the board verified using http://jsperf.com/new-function-vs-object

Your for loop would be drastically reduced to look like

for (var i = 0; i < anchors.length; i++) {
    statement.bindStringParameter(0, anchors[i].href);
    statement.executeAsync(new handler(i, anchors[i]));
}

EDIT:
You'll find this method of creating new instances of objects is faster in IE7-9 by ~3x, and roughly 2x as fast in FF5. My dev Chrome shows strange results in that the original method is 20% as fast as IE, yet shows ~155x improvement (10x faster than all other browsers) when using the prototype way.


Definitely extract method for the following code:

if ( rtChild.right() < rtParent.left() )
{
    if ( ( ( rtParent.left() - rtChild.right() ) <= ENABLE_STICK_VALUE )
        && ( rtChild.top() >= ( rtParent.top() - ENABLE_STICK_VALUE ) )
        && ( rtChild.top() <= ( rtParent.bottom() + ENABLE_STICK_VALUE ) ) )
    {
        isNear = true;
        ptMoveTarget = QPoint( rtParent.left() - rtChild.width() , rtParent.top() );
    }
}

Where you can pass through a left/right variable however you want and then change:

rtParent.left() - rtChild.width() to rely on the given parameter, falling back onto rtParent.right()

The same can be said for any other small changes in the code, such as

rtChild.right() < rtParent.left()
versus
rtChild.left() > rtParent.right()

I'm not going to give you the exact solution, but that if condition holds most of the repeated code and can be brought out into something like snapTo(right/left)


My assumption is that you want to keep the maximal count so that if 2 occurs 4 times in one list and 2 occurs 3 times in another, 2 will appear 4 times in the result.

In this case, I would write the following:

(defn elem-counts [coll]
   (reduce (fn [acc val] (assoc acc val (inc (acc val 0)))) {} coll))

With this, I can get the map from values in the collection to the number of times it occurs.

Now, for a way to reverse this process (from a map of counts to the list that would create the map):

(defn seq-from-counts [count-map]
   (flatten (for [[k v] count-map] (repeat v k))))

Finally, your intersect becomes:

(defn absorb [list1 list2]
   (seq-from-counts (merge-with max
                                (elem-counts list1)
                                (elem-counts list2))))


First off, don't use 1 over True in while loops. While 1 works, using True is much clearer.
Secondly, you have inconsistent indentation. While in Python 2.x, this doesn't affect much, Python 3.x will throw an error.
Never use try-except without a specific error to catch. There could easily be an error that goes un-noticed.
Most of your names are okay, but there are some like c, or e that should be clearer. Variable and function names should also be in snake_case, and classes should be in PascalCase. Names like conn should be renamed to something else, like connection, for example.
You need more blank lines. There should be two blank lines in between each code block/function/class on the top level.
Finally, you should avoid wildcard imports like this: from thread import *. You should either import the entire module, or any classes/functions/variables that you need.

Here's Python's official style guide, PEP8


The importance of consistency in percentage returns when investing

For me the code looks rather okay, I have just a few small remarks:

 Formatting

The line

print('\n'.join(('dev=' + str(round(result.deviation, 2)) + ', ' + 'CAGR=' + str(round(result.CAGR, 2))) for result in results))

is very hard to read, could you possibly split it or use a function?

def format_result(result):
    dev = round(result.deviation,2)
    cagr = round(result.CAGR,2)
    return f'dev={str(dev)}, CAGR={str(cagr)}'

and then just

print('\n'.join(format_result(result) for result in results))

 Performance

I'm unsure whether you need an extreme performance but it seems that potentially you might want to run the code large number of iterations.

namedtuple

namedtuple datastructure is extremely handy if you want to use it to make your code looks better. However, if you care about performance (i.e. you will be using many of them) you might be better off with usual tuple.
Reference: link1, link2, link3.

list.append

In this section I'll be referring to results.append(net_returns(deviation, avg_returns)). append is rather a slow operation if you know a list size before the appending. I think your code would be faster if you allocated results list first and then just put each net return on it's place.

reverse=True

As tempting it is, it might have a performance hit as well. As one might see in source code the list is actually reversed to keep the stability. It should be better just to pass a negative value to your lambda:

return sorted(results, key=lambda x: -x.CAGR)


Transforming an array of arrays into an array with joins

The approach seems just fine to me.

However, I noticed that your fieldnames variable isn't actually used for anything. So that can go.

You can also use some shortcuts in underscore.js:

var groups, strings;

groups = _.groupBy(filters, 1); // group by index 1 (no need for a callback)

strings = _.map(groups, function (group) {
  return _.pluck(group, 0).join(" or ") + " [x]"; // pluck index 0 and join
});

As much as I like functional style, it does get a bit dense, so I've spread it out a tiny bit, rather than have it all as a run-on var declaration. (If it's an enterprise-level app, I imagine maintenance is a high-priority, so better to err on the side of clarity.)

You could also go the opposite way, and inline the _.groupBy, but I wouldn't recommend it. There's no performance gain, only readability pain.

A compromise might be undescore's chaining system:

var strings = _.chain(filters)
  .groupBy(1)
  .map(function (group) {
    return _.pluck(group, 0).join(" or ") + " [x]";
  })
  .value();

But again, there's little need.


Your code can be improved in many aspects, so it is easier to write my own solution rather to rewrite your.

Differences from your:

I suggest to use glob() function to find all files, which are matching to a pattern.
Singular Move(move_direction) function is enough, a duplication is not needed.
Not only new files are opened, but switching between already opened buffers are supported.

function! s:MyCompare(i1, i2)
    let l:f = str2nr(matchstr(a:i1, '[0-9]\+'))
    let l:s = str2nr(matchstr(a:i2, '[0-9]\+'))
    return l:f == l:s ? 0 : l:f > l:s ? 1 : -1
endfunc

function! s:Move(step)
    let l:current_filename = bufname('%')
    let l:common_part = matchstr(l:current_filename, '[^0-9]*')

    "" sort() is needed for numerical order
    let l:matched_file_list = sort(glob(l:common_part . '*', 0, 1), 's:MyCompare')

    let l:list_size = len(l:matched_file_list)
    let l:cur_idx = index(l:matched_file_list, l:current_filename)

    let l:next_idx = (l:cur_idx + a:step) % l:list_size
    let l:next_buf_name = l:matched_file_list[l:next_idx]

    if !bufloaded(l:next_buf_name)
        execute 'e' l:next_buf_name
    endif

    execute 'buffer' l:next_buf_name
endfunction

command! Fwrd call s:Move(1)
command! Bwrd call s:Move(-1)

noremap <Leader>c :Fwrd<CR>
noremap <Leader>d :Bwrd<CR>

Directory content

ls -1

long_boring_filename_del_101.tex
long_boring_filename_del_1.tex
long_boring_filename_del_202.tex
long_boring_filename_del_2.tex
long_boring_filename_del_3.sty
long_boring_filename_del_4.tex
long_boring_filename_del_5.tex

Demonstration

, is a Leader key.


Input reading: two values (separated by whitespace) per line

I can think of two more ways of doing it.

1. Using iostream iterators. (Following code is from here)

#include <iostream>
#include <iterator>
using namespace std;

int main () {
  double value1, value2;
  cout << "Please, insert two values: ";

  istream_iterator<double> eos;         // end-of-stream iterator
  istream_iterator<double> iit (cin);   // stdin iterator

  if (iit!=eos) value1=*iit;

  iit++;
  if (iit!=eos) value2=*iit;

  cout << value1 << "*" << value2 << "=" << (value1*value2) << endl;

  return 0;
}

2. Converting string to int using atoi() rest everything will be same.


SQL query to obtain totals and subtotals

how about using CASE

SELECT  tz.ZoneId,
        qn.QuestionId,
        SUM(CASE WHEN Event >= 201201 AND Event <= 201212
                THEN 1
                ELSE 0
            END) as Count1,
        COUNT(*) AS ZoneTotal
FROM    Customers cust
        INNER JOIN Shops td
            ON td.ShopCode = cust.ShopCode
        INNER JOIN Zones tz
            ON tz.Id = td.SlsZone
        INNER JOIN Responses res
            ON res.SampleId = cust.SampleId
        INNER JOIN QstNodes qn
            ON qn.QuestionId = res.QstNodeId
GROUP   BY tz.ZoneId, qn.QuestionId

UPDATE 1

The following illustrated on the demo has different records but that thought is the same.

SQLFiddle Demo Link


(Proper answer from my comment in OP's question)

My proposal:

getLanguageNameInNativeLanguage

Other than that, there's a term for that: Endonym. See wiki: https://en.wikipedia.org/wiki/Exonym_and_endonym

Quote:
An endonym or autonym is an internal name for a geographical place, or a group of people, or a language or dialect.

For instance, "Germany" is the English language exonym, "Allemagne" is the French language exonym, and "Deutschland" is the endonym for the same country in Europe.

getLanguageEndonym() or something similar would look prettier, but a layman of the app doesn't understand it. If language is something important in the app, I would use the "academic" term.


Applying PEP8 recommendations about naming and formatting,
as well as wrapping the main logic in a main function and calling from within a if __name__ == '__main__': guard,
the code would become easier to read and possible to import and test:

import requests
from lxml import html

url_format = "https://www.yellowpages.ca/search/si/{0}/pizza/Toronto"

def main():
    with requests.session() as session:
        page_num = 1
        while True:
            response = session.get(url_format.format(page_num))
            if response.status_code == 404:
                break
            tree = html.fromstring(response.text)
            for titles in tree.xpath("//div[@itemprop='itemListElement']"):
                try:
                    title = titles.xpath(".//h3[@itemprop='name']/a/text()")[0]
                except IndexError:
                    title = ""
                try:
                    phone = titles.xpath(".//h4[@itemprop='telephone']/text()")[0]
                except IndexError:
                    phone = ""
                print(title, phone)
            page_num += 1

if __name__ == '__main__':
    main()

I'm not a huge fan of using exceptions in situations that are not really exceptions, like here:

try:
    title = titles.xpath(".//h3[@itemprop='name']/a/text()")[0]
except IndexError:
    title = ""

What if a titles.xpath(...) call would raise an IndexError due to a bug? It would be inadvertently caught and unnoticed.
Catching IndexError here is an indirect way of the real intention,
which is getting the first title if it exists.
It would be better to write the code in a way that expresses the intention directly, for example:

for item in tree.xpath("//div[@itemprop='itemListElement']"):
    title = get_first_or_empty(item, ".//h3[@itemprop='name']/a/text()")
    phone = get_first_or_empty(item, ".//h4[@itemprop='telephone']/text()")
    print(title, phone)

Where get_first_or_empty is:

def get_first_or_empty(item, xpath):
    matches = item.xpath(xpath)
    if matches:
        return matches[0]
    return ""


Naming
Renaming your instance variable _V and _E to nbVertices and nbEdges respectively allows you get rid of two unnecessary comments and also makes the rest of the code much clearer, especially to someone who's not too familiar with graph notation.
I'm also not a big fan of prefixing private instance variables with underscores, but that's just my personal opinion.
Similarly, you could give most of your methods' arguments much clearer names.
The standard naming convention for C# is to use PascalCase for methods & properties, and camelCase for fields, so I would rename getAdjacency() and addEdge() to GetAdjacency() and AddEdge().
Properties
    // number of vertices
    public int V
    {
        get { return this._V; }
    }

    // number of edges
    public int E
    {
       get { return this._E; }
    }

can be changed to
    // number of vertices
    public int V
    {
        get => this._V;
    }

    // number of edges
    public int E
    {
       get => this._E;
    }

which can further be simplified to
    // number of vertices
    public int V => this._V;

    // number of edges
    public int E => this._E;

You could go one step further and merge V and _V into a single property, like this :
public int V { get; private set; }

public int E { get; private set; }

and since V doesn't change after being set in the constructor, you can go even further beyond and make V into a read-only property :
public int V { get; }

This makes it so that V can only be set once in the constructor.
Comments
Personal opinion again, but I don't like comments, especially when they can be made useless by simply changing a variable or a method's name, as was the case with your declarations of _V or _E.
I also really don't like comments that just say what the code is doing, like in your addEdge() method :
public void addEdge(int v, int w)
{
    // validate given node numbers
    if ((v > this._adj.Length) || (w > this._adj.Length))
        throw new ArgumentException("Invalid node number specified.");

    // add to adjacency lists
    this._adj[v].Add(w);
    this._adj[w].Add(v);
    // increment edge count
    this._E++;
}

These comments add nothing more than redundant, distracting text that makes the code harder to read. If you see a line of code that says NbEdges++;, do you really need a comment to say // increment edge count ?
Exceptions
I'd recommend always throwing the exception that most closely fits the issue, which in this case would be an ArgumentOutOfRangeException (which is derived from ArgumentException).
Additionally, I would make the exception message more clear and give more information about what actually went wrong. Imagine being a user and seeing "Invalid node number specified."; which argument was wrong? Was it v or w? Why was the value wrong?
You could go even further and create your own exception class that inherits said exception, in order to reduce code repetition and give your exceptions meaningful names which would help your users.
if (v < 0 || v > this._adj.Length)
{
    throw new ArgumentOutOfRangeException($"Error, the value provided for 'v' should be" +
        "between 0 and {this._adj.Length - 1}\n" +
        "\tv = {v}\n");
}

if (w < 0 || w > this._adj.Length)
{
    throw new ArgumentOutOfRangeException($"Error, the value provided for 'v' should be" +
        "between 0 and {this._adj.Length - 1}\n" +
        "\tv = {v}\n");
}