jQuery looping on fields after validation

Why not just iterate over the inputs, and if the values of the id attribute exists in data then add the error class and show the affiliated error message, otherwise add the valid class and clear the error message?

When the DOM is ready, the input values can be stored in a variable:

$(function() { //DOM-ready
    //cache the inputs from the DOM so as to minimize DOM queries.
    const inputs = $(":input");

Note that texetarea, select were removed from the selector because the jQuery :input selector includes those.

Then inputs can be used for registering the blur callback:

inputs.on('blur', function(ev) {

And then in the success callback of the AJAX request, inputs can be used again with $.each():

success: function(data) {
    if (data) {
      $.each(inputs, function(index, input) {

Then to determine if the field is invalid, check if the id
 attribute exists as a property of data. jQuery(input).prop() can be used to get the id property. Then data.hasOwnProperty() can be used to determine if the id property is set on data.

const id = jQuery(input).prop('id');
if (data.hasOwnProperty(id)) {
  jQuery(input).addClass('input-error')
      .removeClass('input-valid'); //chain calls for efficiency
  jQuery("#" + id + "-error").text(data[id]);
}
else {
  jQuery(input).removeClass('input-error')
      .addClass('input-valid');
  jQuery("#" + id + "-error").text("");
}

For a demonstration of this, see this plunker. Note that the AJAX response is not dynamic.

Actually, that last block could be re-written to utilize jQuery's toggleClass() method.

let message = '';
if (data.hasOwnProperty(id)) {
    message = data[id];
}
jQuery(input).toggleClass('input-error', message !== '')
    .toggleClass('input-valid', message === '');
jQuery("#" + id + "-error").text(message);

See a demonstration of that in this plunker.


Program for printing all numbers that user inputs till 42 in Clojure

I see a few things worth pointing out:

Lazy sequences and side effects

First and foremost, you should be careful about mixing side effects (printing using println) and lazy sequences (such as map, repeatedly, and many more). It may not work the way you expect. Here's an example of side effects just disappearing:

(let [lazy-effects (map println [1 2 3])]
  1)

This doesn't print anything as lazy-effects is never evaluated. There's no need to traverse the lazy sequence, and hence no need to evaluate println on each of the elements. To be sure, your code doesn't suffer from this, as you're evaluating map right in the REPL (or where ever else you're running it), but as soon as you put it inside def or any number of other hidden dangers, it'll no longer get evaluated. Just something to keep in mind.

Using doseq and friends for forcing side effects

With the above in mind, your code would work equally well, but not carry the hidden risk of postponing side effects inside a lazy sequence, if it made use of doseq or some of the other do-like constructs in Clojure. doseq could be used as follows:

(doseq [input (take-while #(not= % "42") (repeatedly read-line))]
  (println input))

If you think this feels slightly less "Clojure-like" in nature, you're right! Side effects generally mix poorly with many of Clojure's core constructs, and special care often needs to be taken. doseq, doall and a few other are provided to help in the case where you really want to force the evaluation of something.

Using read-line from Clojure core

As you probably noticed I managed to sneak in a reference to read-line above, which you might as well be using for this scenario. There is no inherent benefit except the removed need for Java interop.

Otherwise I'd say you're on the right track. The concept of generating an infinite lazy sequence using repeatedly, limiting its length using take-while, and transforming it using map is spot on. It just so happens that this works more painlessly with pure functions that do not cause side effects.


Solution to LeetCode Next Greater Element Ⅰ in Python

Since list one is a subset of list two, iterating over two lists can be avoided. This can be achieved by finding the next greater element of each element for the bigger list and storing the result in a hash table.

To calculate the next greater element of each element in a list we can iterate the list. For each element, we can find the next greater element by again iterating the list. This approach is simple but will have O(n^2) complexity.

Another approach is by using stack.

First, push the first element of the list int the stack.
Now iterate the list and compare the top element of the stack with the current element of the list.
If the current element is greater than the top element then that means the current element is the next greater element of the top element of the stack. Store this result in a dictionary. Pop the top element out of the stack.
Repeat above two steps until the stack top element is greater than the current element or stack is empty.
At the end of each iteration push the current element in the stack.

The code will make things clearer:

def calculate_nge_dict(arr):

    nge_dict = {}
    stack_ = []
    stack_.append(arr[0])
    nge_dict[arr[0]] = -1
    for i in arr[1:]:
        next_ = i
        nge_dict[next_] = -1
        while stack_:
            top_ = stack_.pop()
            if next_ <= top_:
                stack_.append(top_)
                break
            else:
                nge_dict[top_] = next_
        stack_.append(next_)
    return nge_dict

def next_greater_element(nums1, nums2):
    nge_dict = calculate_nge_dict(nums2)
    return [nge_dict[i] for i in nums1]

You can get a better understanding of the algorithm from this answer.


First of all, your locking seems ok, I don't expect any drawbacks by using multiple threads.

That being said, let us review this from bottom to top.

public enum Tryb
{
    FILE = 0,
    CONSOLE = 1,
    FILEANDCONSOLE = 2
}

The name of that enum is at the nicest say unclear. A name like LogTarget would be more clear and its meaning would be obvious to any reader/user of this code.
Because it only has 3 members you should consider to add the [Flags] atribute to that enum which would result in a much shorter code, because you could omit the switch statement in ProcessLogMessage method.

This would look like so

[Flags]
public enum LogTarget
{
    FILE = 1,
    CONSOLE = 2,
    FILEANDCONSOLE = FILE | CONSOLE
}

static void WriteLogToFile(string strLogMessage, string strLogFile)
{
    StreamWriter swLog = null;

    try
    {
        if (!File.Exists(strLogFile))
            swLog = new StreamWriter(strLogFile);
        else
            swLog = File.AppendText(strLogFile);

        swLog.WriteLine(strLogMessage);
    }
    finally
    {
        if (swLog != null)
        {
            swLog.Close();
            swLog.Dispose();
        }
    }
}

instead of having a Try..Finally and 2 different ways of creating the StreamWriter you should use the overloaded constructor StreamWriter(string, boolean) and enclose its usage in a using block which takes care of disposing and closing automatically.

Based on the valid comment of @Heinzi

  You don't need bool append = File.Exists(strLogFile);, just use new
  StreamWriter(strLogFile, true). According to the documentation, the
  Boolean parameter has no effect if the file does not exist

you can just use true for append so no need to check if the file exists.
although braces {} are optional for single line if..else statements you really should use them because they will make your code less error prone.

Applying this will lead to

static void WriteLogToFile(string strLogMessage, string strLogFile)
{
    using (StreamWriter swLog = new StreamWriter(strLogFile, true))
    {
        swLog.WriteLine(strLogMessage);
    }
}

static void ProcessLogMessage(Tryb tryb, string rodzaj, string caller, string message, string messageExt, string file)
{
    string dane = String.Format("{0}, {1}, {2}, {3}, {4}", DateTime.Now, rodzaj, caller, message, messageExt);
    switch (tryb)
    {
        case Tryb.FILE:
            lock (_diskDriveLocker)
            {
                WriteLogToFile(dane, file);
            }
            break;
        case Tryb.CONSOLE:
            lock (_consoleLocker)
            {
                Console.WriteLine(dane);
            }
            break;
        case Tryb.FILEANDCONSOLE:
            lock (_consoleLocker)
            {
                Console.WriteLine(dane);
            }
            lock (_diskDriveLocker)
            {
                WriteLogToFile(dane, file);
            }
            break;
    }
}

Now we can use the enum by calling the HasFlags() method which results in only 2 if statements.

static void ProcessLogMessage(LogTarget target, string rodzaj, string caller, string message, string messageExt, string file)
{
    string logMessage = String.Format("{0}, {1}, {2}, {3}, {4}", DateTime.Now, rodzaj, caller, message, messageExt);

    if (target.HasFlag(LogTarget.FILE))
    {
        lock (_diskDriveLocker)
        {
            WriteLogToFile(logMessage, file);
        }
    }

    if (target.HasFlag(LogTarget.CONSOLE))
    {
        lock (_consoleLocker)
        {
            Console.WriteLine(logMessage);
        }
    }
}

The composition of the error.txt and log.txt filenames should be done in separate methods and be assigned to class level variables so they could be reused.


If you decide to implement this without using a class you can simply write:

def get_starlist():
    ...
def get_inputkey():
    ...

if __name__ == "__main__":
    get_starlist()
    get_input_key()
    define_lists_and_arrays()
    determine_normalization_point()
    create_fobs_fobserr()
    search_DUSTY_models()
    calculate_chi2()
    delete_null_components()
    dust_whittet_sub()

But if you find that some of your functions are sharing data a lot you may want to attach them to a class, or pass instances of a class (objects) between the different functions. It's hard to say more without knowing what you're trying to do.


How do I add JDBC and Queue functionality to a simple server?

Using imports:

catch(java.net.SocketException se) { /* [...] */
throws java.net.SocketException { /* [...] */

fully qualifying these is unnecessary:
import java.net.SocketException;

catch(SocketException se) { /* [...] */
throws SocketException { /* [...] */

I feel that this code is much more concise, while containing the same information.
Using try-with-resources:
First: You are using try-with-resources. Good. That's the way to go.
Second: You're doing it wrong.

    try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream())) {
        objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        recordFromClient = (MyRecord) objectInputStream.readObject();
    }
    objectOutputStream.flush();
    objectOutputStream.close();

try-with resources does the last two things for you. You achieve the exact same result when you leave those out. The last two statments become useless clutter if you used try-with-resources:
try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())) {
     recordFromClient = (MyRecord) objectInputStream.readObject();
}

Apart from that... You don't use your objectOutputStream anywhere. Why do you have it?
Using exceptions / logging:
Why is your ClassNotFoundException only logged as INFO? I'd expect a ClassNotFoundException to be minimum ERROR, if not FATAL! If you "expect" ClassNotFoundExceptions, then your design might be flawed.


As pointed out by Blindman67: in render(wrapper, items);, items is not defined.

const url = 'http://moviedatas.com/movies';

Const variable used only one time, you can remove it and write url: http://moviedatas.com/movies

Same for

const wrapper = $(this);

Use ES6 arrow function shortcut syntax () =>

    success: function(response) {
        movieList.each(function() {
            const wrapper = $(this);

            render(wrapper, items);
        });
    },

7 lines in one, shorter is cleaner.

success: (response) => movieList.each(() => render($(this), response.items)),

error: function(error) {
    onError(movieList);
}

If you don't use error XHR response, just write

error: () => onError(movieList)

Write jsDoc docstring above functions to help developers and IDE understanding what is happening.
If functions are becoming inline, you may write them directly in caller function.

Full review (without docstring)

function loadMovies() {
   const movieList = $('.movie_list');

   // setOnLoading
   movieList.each(() => $(this).html('Loading...'));

   $.ajax({
       method: 'GET',
       url    : 'http://moviedatas.com/movies',
       data   : { count: 10 },
       success: (response) => movieList.each(() => render($(this), response.items))
       error  : () => movieList.each(() => $(this).html(''));
   });
}

function render(wrapper, items) {
   const template = `

{title}

{description}

`;

   let movies = '';

   for (let i = 0; i < items.length; i++) {
       movies += template
           .replace('{title}', items[i].title)
           .replace('{description}', items[i].description);
   }

   wrapper.html(movies);
}

Also, I don't understand the logic of getting a movie list data and then iterating over a movie list HTML to put movies in. It becomes a list of list of movies...


First of all: If you want execution speed, an iterative approach to fibonacci is faster. That said, implementing a recursive solution is a nice exercise.

Some other remarks:

Code that does something should not perform IO. Separate computations from UI. This will also allow you to output values only once, which is faster.
Your function is very specialized. What if I want to calculate only fib(5)? Or up o fib(65)? Strive to write reusable components.
Note that std::endl flushes the output buffer, which takes time. If you just want to output a newline, use std::cout << last + now << '\n'; instead.
Instead of

static unsigned long last = 0, tmp = last;

write

static unsigned long last = 0, tmp = 0;

It's clearer, and you won't have to change anything in case you remove last at some point.
I would pass state around, rather than use static variables.

Maybe something like this:

// Helper function
int fib_do(int max, int curr, int one_before, int two_before)
{
    if (curr == max-1) return one_before+two_before;

    return fib_do(max, curr+1, one_before+two_before, one_before);
}

int fib(int n)
{
    if (n <= 1) return 1;

    return fib_do(n, 1, 1, 0);
}

However, this snippet (and your second version) is basically just the iterative solution implemented using recursion.

Note that this snippet has not in any way been optimized for speed. However, it facilitates the Return Value Optimization.

Finally: Consider using some form of caching to increase the speed of your recursive function.


"Have a safe trip"… or not, depending on four conditions

When it comes to long and complex logic summation I recommend, as Legato says, to use one row for each condition.
I also think it is more readable if you sum all the conditions to a new variable that explains the result with a meaningful name like this:

boolean isTripPossible =
   !isNameBlank &&
   !isDestinationBlank &&
   isDestinationValid &&
   isAmountValid;

String message = isTripPossible ? "Have a safe trip!" : "Please try again!";


I think you're overcomplicating the solution a bit. Since you're making copies of what is the maximum in the range, all you need is something that keeps a value to store the current max, and another which keeps a count of the number of maximum values that have been found in the input data. For example:

#include <iterator>

template <typename InputIter, typename OutputIter>
void copy_if_max(InputIter begin, InputIter end, OutputIter out_begin)
{
    std::size_t count = 1;
    typedef typename std::iterator_traits<InputIter>::value_type T;

    if(begin == end) return;

    T current_max = *begin;
    ++begin;

    while(begin != end) {
        if(*begin > current_max) {
            current_max = *begin;
            count = 1;
        }
        else if(*begin == current_max) {
            ++count;
        }
        ++begin;
    }

    for(std::size_t i = 0; i < count; ++i) {
        *out_begin++ = current_max;
    }
}

Note that this solution also uses std::iterator_traits<T>, which you should be using instead of relying on the InputIterator passed having a nested value_type typedef (which will of course be false if it is passed a T*, for example).


Clean up this Ruby code under DRY principle

puts "Blurt out a word"
word_list = []
while word_list.last != ""
  word_list << gets.chomp
end
puts word_list.sort

If you prefer the until:

puts "Blurt out a word"
word_list = []
until word_list.last == ""
  word_list << gets.chomp
end
puts word_list.sort

You can also do it shorter:

puts "Blurt out a word"
word_list = []
word_list << gets.chomp until word_list.last == ""
puts word_list.sort

Remark: The last (empty) line is also returned. To skip the empty line you may use:

puts word_list[0..-2].sort


Number of way to render an amount of money

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


Python stack and queue classes, implemented using lists

There are a few things to mention.

At first, it might be a good idea to initialize both Queue and Stack with empty lists by default:

def __init__(self, queue=None):
    self.queue = queue or []    # if queue is given, it overrides the default

Next, it doesn't make sense to write something like if len(self.queue)!=0 since it is equivalent to if self.queue (empty list is False when it's casted to bool). You can go even further and introduce the property called size using the built-in decorator:

@property
def size(self):
    return len(self.queue)

Now it can be accessed by self.size without a function call.


Java: Find the smallest integer not in the list - Memory Efficiency

So just a few things that I am seeing here.  You are using Math.floor, ceil on integers which is totally unnecessary, integers by definition don't have a decimal portion.  You also don't need to cast an int as an int.

To make this run faster and take up less stack space, in the for loop where you set the bits you don't need to check anything, just do the bit twiddling you want.

int bitMod = 0x1 << (number % 8);
byte b = number / 8;
bitset[b] |= bitMod;

Getting the position of the bit you want to change and then just or ing it won't change any other bits.

Finally, I don't know why you did it the way you did, but your final for loop doesn't work correctly.  It starts with the Most Significant Bit and moves down, instead of the least moving up.  Here is a version that I have tested and found to work.

for (int j=0; j<8; j--) {
    if ((b & (1 << j)) != 0){
        location++;
    } else {
        break;
    }
}

Finally, just to see what kind of memory this might be using, I called the free memory before and after to compare the difference.  It looks like this program uses 56 MB, and takes under 100 ms after my few changes.

actual lowest is 1
(Initial Implementation)
Free Memory: 563760
Smallest number not in the list is 2
Time to execute in milliseconds: 156
2 is in the list true

(Optimized and cleaned up)
Free Memory: 563760
Smallest number not in the list is 1
Time to execute in milliseconds: 93
1 is in the list false

Here is the class I used to test.

public class TestSmallestNumberNotInList {

static final int N = 3000000;
static int[] numbers = null;
static {
    numbers = new int[N];
    for (int i = 0; i < numbers.length; i++) {
        numbers[i] = Math.abs((int)(Math.round(Math.random() * N)));
    }
}

public void testFindSmallestNumberNotInList() {

    Runtime.getRuntime().gc();
    Runtime.getRuntime().gc();
    Runtime.getRuntime().gc();
    long total = Runtime.getRuntime().totalMemory();
    long free = Runtime.getRuntime().freeMemory();
    long startTime = System.currentTimeMillis();

    int byteArrayLength = (int) Math.ceil(N / 8);
    byte[] bitset = new byte[byteArrayLength];

    for (int number : numbers) {
        int byteIndex = (int)Math.floor(number / 8);
        byte b = bitset[byteIndex];
        int bitMod = (int)(number % 8);

        // The bit value will be 1 if we encountered this number before
        int bitVal = b>>>(32-bitMod) & 0x00000001;
        if (bitVal == 1)
            continue;

        //Get a byte mask to OR against the existing byte, flipping just the one bit
        //we are concerned with.
        byte byteMask = (byte)(1<<bitMod);
        b = (byte)(b | byteMask);

        //assign the new byte value for the byte array
        bitset[byteIndex] = b;
    }

    //Scan the byte array for the first 0 bit, this ((index * 8) + bitmodulus) is the smallest
    //integer not in the list.
    int location = 0;
    for (int i = 0; i < bitset.length; i++) {
        byte b = bitset[i];
        if (b == 0xFF) {
            location += 8;
            continue;
        } else {
            for (int j=8; j>=1; j--) {
                if ((b>>>(j) & 0x00000001) == 1)
                    location++;
            }
            break;
        }
    }

    long duration = System.currentTimeMillis() - startTime;

    System.out.println("Total Memory: " + (total - Runtime.getRuntime().totalMemory()));
    System.out.println("Free Memory: " + (free - Runtime.getRuntime().freeMemory()));
    System.out.println("Smallest number not in the list is " + location);
    System.out.println("Time to execute in milliseconds: " + duration);
    boolean isInList = false;
    for (int next : numbers){
        if (location == next){
            isInList = true;
            break;
        }
    }
    System.out.println(location + " is in the list " + isInList);
}

public void testMine() {
    Runtime.getRuntime().gc();
    Runtime.getRuntime().gc();
    Runtime.getRuntime().gc();
    long total = Runtime.getRuntime().totalMemory();
    long free = Runtime.getRuntime().freeMemory();
    long startTime = System.currentTimeMillis();

    int byteArrayLength = numbers.length / 8;
    byte[] bitset = new byte[byteArrayLength];

    for (int number : numbers) {
        int byteIndex = number / 8;
        int bitMod = (1 << (number % 8)) & 0xFF;
        bitset[byteIndex] |= bitMod;
    }

    //Scan the byte array for the first 0 bit, this ((index * 8) + bitmodulus) is the smallest
    //integer not in the list.
    int location = 0;
    for (int i = 0; i < bitset.length; i++) {
        byte b = bitset[i];
        if (b == 0xFF) {
            location += 8;
            continue;
        } else {
            for (int j=0; j<8; j++) {
                if ((b & (1 << j)) != 0){
                    location++;
                } else {
                    break;
                }
            }
            break;
        }
    }

    long duration = System.currentTimeMillis() - startTime;

    System.out.println("Total Memory: " + (total - Runtime.getRuntime().totalMemory()));
    System.out.println("Free Memory: " + (free - Runtime.getRuntime().freeMemory()));
    System.out.println("Smallest number not in the list is " + location);
    System.out.println("Time to execute in milliseconds: " + duration);

    boolean isInList = false;
    for (int next : numbers){
        if (location == next){
            isInList = true;
            break;
        }
    }
    System.out.println(location + " is in the list " + isInList);
}

public void getSmallestNotInList() {
     int lowest = 0;
     boolean notLowest = true;
     while (notLowest){
         int last = lowest;
         for (int i=0; i<numbers.length; i++){
             if (numbers[i] == lowest){
                 lowest++;
                 break;
             }
         }
         if (last == lowest){
             break;
         }
     }
     System.out.println("actual lowest is " + lowest);
}
}


The first thing I look for in an autocomplete widget is how the list is implemented. First, you are using inline styles to display/hide the list. You can simply use CSS :empty to hide the list container when nothing is listed. That way, you don't have to deal with toggling the visibility in JS. All you need to worry is if the list should be empty or not.

.suggestions:empty{
  display: none;
}

My Meteor is rusty, but I remember it had some form of reactive programming by way of session (correct me if I'm wrong) variables and templates. When these variables change, any UI bound to it changes. Suggesting you create an array and bind it to the UI. That way, all you have to care about is populating/unpopulating that array, and not mess around with innerHTML.

function(error, response) {
  if (error) {

  } else {
    displayedSuggestions = response.data.features;
    display(displayedSuggestions);
  }
}

// to

function(error, response){
  if(error) return; // throw new Error('nothing') or console.warn('')
  displayedSuggestions = response.data.features;
  display(displayedSuggestions);
}

So essentially, you're swallowing the error. That's fine, however you can simplify the code by returning early. On the other hand, a few debugging hints won't hurt. Suggesting you throw an error, or log it as a warning.

I see a timer, but it looks weird coupled with the nearby AJAX call. Then I found out it was a form of debouncing. Suggesting you move that function out into a more verbose form to avoid mistaking the timer as a form of asynchronous utility function and making the AJAX look like some synchronous operation. Something like:

function debounce(fn, delay){
  var timer = null;
  return function(){
    if(timer) clearTimeout(timer);
    setTimeout(fn, delay || 300);
  }
}

var search = debounce(function(){
  // Your AJAX code
});

In the above, search (or any function for that matter) will have automatic debounce capabilities once "wrapped" by debounce without the clutter that came with it.


Best way convert byte array to hex string

There are popular topics on StackOverflow that cover this exact question:

How do you convert Byte Array to Hexadecimal String, and vice versa?
byte[] to hex string


Focusing on the specific part of the code that handles translations for English, here's a way of doing it with a dictionary and a function table:

english_swaps = {
    # Dictionary of 1:1 word replacements.
    "is": "oy",
    "are": "argh",
    "he": "hana",
    "she": "hana",
    "it": "hana",
    "his": "hami",
    "her": "hami",
    "ham": "ham!",
    "sausage": "sausage!",
    "bacon": "bacon!",
}

english_rules = [
    # List of arbitrary functions to transform a word.
    lambda w: f"{w}eeh" if w[-1] == "y" else None,
    lambda w: f"{w}ah" if w[-3:] == "ing" else None,
    lambda w: f"{w}ey" if w[-2:] == "sh" else None,
    lambda w: w.replace("oo", "uwu") if "oo" in w else None,
    lambda w: english_swaps.get(w, None),
]

def translate(word: str) -> str:
    if language == "English":
        for rule in english_rules:
            # Attempt to apply each rule in turn, using the first one to match.
            translated = rule(word)
            if translated is not None:
                return translated
        return word
    else:
        # ...

print(" ".join(
    translate(w) for w in "he is eating sausage and loving every bit of it".split()
))
# prints: hana oy eatingah sausage! and lovingah everyeeh bit of hana

You could apply this same pattern to have a dictionary and function table for each language, and put those into another dictionary that maps each language to a function table, so that ultimately you could do something like:

for rule in rules[language]:
   translated = rule(word)
   ... etc ...


Your code's pretty good actually. I don't see any of the typical beginner's syntactical pitfalls. Kudos! (Though I would prefer gameOver, given its name, to be false while the game's running).

Structurally, there are many ways to build it. I'd probably split things into objects or constructors (aka classes).

For instance, I'd make the board an object with its own methods for marking a square, checking for wins, resetting, etc.. Similarly, the players and the turn-taking could be modelled. It may be overkill for a simple Tic-Tac-Toe game, but the resulting code will be simpler to read (I think). It's basically the same strategy as creating views in MySQL to encapsulate complex/reusable queries.

For instance something like this (not a complete implementation)

// Constructor
function Board() {
  this.squares = new Array(9);
}

// Prototype functions (i.e. methods)
Board.prototype = {
  // get number of marked squares
  occupied: function () {
    var i, l, count = 0;
    for( i = 0, l = this.squares.length ; i < l ; i++ ) {
      count += this.squares[i] ? 1 : 0;
    }
    return count;
  },

  // get a row
  row: function (index) {
    var i = index * 3;
    return this.squares.slice(i, 3);
  },

  // get a column
  column: function (index) {
    var i, l, column = [];
    for( i = index, l = this.squares.length ; i < l ; i += 3 ) {
      column.push(this.squares[i]);
    }
    return column;
  },

  // get diagonal squares
  // index 0: from top-left
  // index 1: from top-right
  diagonal: function (index) {
    var step = index ? 2 : 4,
        squares = [];
    index = index ? 2 : 0;
    while( squares.length < 3 ) {
      squares.push(this.squares[index]);
      index += step;
    }
    return squares;
  }
};

Edit: The above code has some issues. One was a straight-up typo on my part (fixed now). The other is a little more subtle: slice() will ignore undefined elements in an array. So (new Array(3)).slice(0) → [] instead of [undefined, undefined, undefined]. This could obviously cause trouble, as the array will be shorter than one might assume. So the array should either be seeded with values (zeros for instance), or the slice-call should be replaced with something similar to what column() is doing in the above: Looping and pushing values, even if they're undefined.

Then you can call new Board() to get a, well, a new board. That board, in turn, provides functions for determining the state of play. (Note that most of these functions can be simplified using array functions like forEach and win-conditions can be checked with reduce or a homemade array-sum function. However, that's an exercise for the reader).

With regard to visual output, you could start by simply "printing" to <pre> element on the page instead of the console. A minor step, yes, but just to get the hang of DOM manipulation/interaction. Actually, using your code, I've done that here. Of course, the real next step is using elements for each square, have them react to clicks, etc..

For that, you could consider simply letting the DOM itself handle the state. I.e. rather than a separate array of values, simply use the elements themselves and their attributes to determine if/how a square is marked.

For now, though, I'll stop here. See if you get something useful out of a more object oriented approach, before moving on the HTML GUI. The reason I'm suggesting this, is that the DOM is object oriented already, so getting the game logic on that footing will likely make creating the GUI easier/simpler. At least you're bound to learn something :)


Functions

you should split a lot more of the small pieces of code to separate functions, For example getting and parsing the input has no place in the make_book

Generators

Instead of using temporary lists, using generators is a lot cleaner.

so instead of

def my_func():
    _ = []
    for i in range(10):
        _.append(i**2)
    return _

with a generator this becomes:

def my_gen():
    for i in range(10):
        yield i**2

This is a lot cleaner, and easier to maintain.

Assembling the booklet

instead of iterating over the indices f and n, you can use a collections.dequeand use pop and popleft

from collections import deque
def assemble_booklet(pages):
    """assembles the booklet according to the order [-1, 0, 1, -2] and going in.

    Assumes an iterable with the length a multiple of 4"""
    pages = deque(pages)
    assert not len(pages) % 4, 'booklet length, must be a multiple of 4'
    while pages:
        selection = pages.pop(), pages.popleft(), pages.popleft(), pages.pop()
        yield from selection

again, the generator style allows us to express this a lot clearer than using the intermediary lists

grouping in pages

grouping the pages can be easily done with the grouper itertools recipe

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    """Collect data into fixed-length chunks or blocks

    grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    https://docs.python.org/3/library/itertools.html#itertools-recipes
    """
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

Then:

for page in pages:
    _.append(page)
    if page % len_booklet == 0:
        _ = arrange_booklet(_[0], _[-1])
        book.extend(_)
        _.clear()

becomes:

def make_book(pages, booklet_length):
    '''Combines all the lists into one and returns the result.'''
    assert not booklet_length % 4, 'booklet length, must be a multiple of 4'
    for group in grouper(pages, booklet_length, fillvalue='blank'):
        yield tuple(assemble_booklet(group))
        # yield from assemble_booklet(group) # dependent on the output you want

If you want the pages in 1 long list instead of separated per booklet, you can change the last line of make_book to yield from assemble_booklet(group)

And in effect, this is the whole code for this method, that gets an iterable of pages, and form booklets out of them

if __name__ == '__main__':
    pages = range(1, 16)
    booklet_length = 8
    result = list(make_book(pages, booklet_length))
    print(result)

[(8, 1, 2, 7, 6, 3, 4, 5), ('blank', 9, 10, 15, 14, 11, 12, 13)]


How to make business logic code maintainable when working with multiple states?

It seems data/feature envy. Move the boolean conditions to the Call object:

public class Call {
    ...

    public boolean isIncomingDirection()
        return callDirection == CallDirection.INCOMING;
    }

    public boolean isIncomingCall() {
        return isIncomingDirection()
            && callState == CallState.INCOMING && !isTannoyCall;
    }

    public boolean isActiveCall() {
        return isActive()
                && callState != InvState.INCOMING && !isTannoyCall;
    }

    public boolean isMissedCall() {
        return isIncomingDirection()
                && callState == InvState.DISCONNECTED
                && callStart == 0
                && !isTannoyCall;
    }
}

See also: Clean Code by Robert C. Martin, G14: Feature Envy


Allocating memory and releasing the same

I could see passing the pointer to another thread, and the other thread deleting the object.  (Gives me the willies, but it at least makes sense.)  But if PostThreadMessage itself is doing the deletion, that feels wrong.  I'm used to having a delete for every new, and PostThreadMessage is currently breaking that all to hell.  Now i have to go rooting around just to figure out who owns an object, so i don't accidentally delete it twice and open up a wormhole or something.

If the pointee doesn't need to outlive the call to PostThreadMessage, then you should be able to put it in a local variable and pass a pointer to the local.  Of course, that also means PostThreadMessage needs to keep its paws off the delete button.  :P

try {
    ...
    NmsMessage nmsMessage(NMS_MODEM_DIAL_NUMBER);
    ...
    {
        pThis->m_pDeviceThread->PostThreadMessage(WM_NMS_MESSAGE, 0, &nmsMessage);
    }
    return NOERROR;
}
catch(...) {
    ...
}

nmsMessage, having "automatic storage duration", will be deleted when control leaves the block.  Ownership and intent are clearer, you don't need to fart around with new and delete, and C++ cleans up for you automatically whether you return normally or throw an exception.

If PostThreadMessage wants the message info to outlive this code, seems to me that it should be making its own copy.  But it kinda sounds like it's already doing that.

(Note, most of this answer assumes that you can change PostThreadMessage.  If you can't -- for example, if it's part of some API you're stuck using -- then the only guarantees you have are the ones the API makes.  If it doesn't promise that pNmsMessage is either deleted or not in each case that may occur, then you have a pretty serious problem; any dynamically allocated object must be deleted, but deleting it twice can cause major problems.)


Why do you have HEAD and TAIL NodeTypes? Doesn't their position on the branch tell you that?
I'm concerned that you have structure traversal code infused into AchievementNode class. Classically the structure - tree, queue, List, etc. - is independent of the objects it holds. I would think greatly upon using something like Dictionary<T>, List<T>, etc. Use that structure's inherent reference/traversal features in the context of NodeType. - wrapping (inheriting?) that structure along with your concept of NodeType into a class that is essentially a MyNodes<AcheivementNode> class. I wonder, is MyNodes<NodeType> what you are really building? In any case I suspect the separation of concerns will make the NodeType idea standout better conceptually and architecturally.
How many palaces do you have NodeType defined I wonder. Why is NodeType enum defined inside AchievementNode? That's unusual. You want it hidden from client code? I don't think so since you have method parameters of NodeType.


Processing a list of pairs of items using promises and functional programming

Does this function break the paradigm of functional programming in JS?

Short answer: It depends

One common response I get from Software Engineering SE on this topic is you don't have to be pure all the time. A function can still act functional even if the implementation isn't written in a functional manner. Take for example the following:

// All return an array with numbers starting from s to e with no
// side-effects and takes all input from args. The first one is
// obviously not "functional" but works just as well as the others.

function range(s, e){
  const array = []
  for(let i = s; i < e; i++){
    array.push(s)
  }
  return array
}

function range(s, e){
  return Array(e - l).fill(null).map((v, i) => s + i)
}

function range(s, e){
  return s == e ? [] : [s, ...range(s + 1, e)]
}

Striking a balance between ideal and practical is also a deciding factor. For instance, recursion is not a foreign concept in JS. But historically, due to stack size limits, loops became more prevalent. You can safely assume people can read loops better than recursion, and are therefore more likely to understand the first sample than the other two.

It looks like the purpose of process function is to batch-process arrays of items. This can be done with recursion. The idea is to process the current item, then concat the results of the next call, which does the same thing until there's nothing in the array. If you use Node or have Babel to transpile, you can use async/await to simplify the syntax.

const process = async (i) => {
  if (!i.length) return []

  const r1 = await Promise.all(i[0].map(action))
  const r2 = await process(i.slice(1))

  return [...r1, ...r2]
}

If you can't do async/await, here's an expanded version with regular promise syntax.

function process(i) {
  if (!i.length) return Promise.resolve([])

  return Promise.all(i[0].map(action)).then(function(r1) {
    return process(i.slice(1)).then(r2 => r1.concat(r2))
  })
}


Leetcode 3Sum problem using hashmap in Python

I think the current way of solving this problem seems an acceptable, albeit naive, way to solve it, but there are some tweaks that can enhance the readability.

variables

len_n, res, n_map, target = len(nums), set(), dict(), 0

is both unclear and unnecessary.

len_n is never used, res is only used far further in the code

collections.defaultdict

You do a lot of n_map.get(s, []). Simpler would be to define n_map as a collectcions.defaultdict(list), and then for example just do n_map[s].append((i, j))

indices

You add (i, j) to n_map, only to later retrieve them as tuple k. It would be easier to use tuple unpacking:

for k, n in enumerate(nums): # i is used
    s = target - n
    for i, j in n_map[s]:
        if k > j:
            res.add((nums[k], nums[i], nums[j]))

Since you only use i and j here to retrieve a and b, why not save them in n_map in the first place?

n_map = defaultdict(list)
for i, a in enumerate(nums):
    for j, b in enumerate(nums[i + 1 :], i + 1):
        n_map[a + b].append((j, a, b))
res = set()
for k, c in enumerate(nums):
    for j, a, b in n_map[target - c]:
        result = c, a, b
        if k > j:
            ...

res and yield

Defining res as a set is a good choice. I think it is easier to only add the tuple to res if it is not present yet, and yield it at the same time, instead of returning list(map(list, res)) at the end

In total this gives:

def three_sum_maarten(nums, target=0):
    """
    :type nums: List[int]
    :rtype: List[List[int]]In total this gives
    """
    if len(nums) < 3:
        return []
    n_map = defaultdict(list)
    nums = sorted(nums)
    for i, a in enumerate(nums):
        for j, b in enumerate(nums[i + 1 :], i + 1):
            n_map[a + b].append((j, a, b))
    res = set()
    for k, c in enumerate(nums):
        for j, a, b in n_map[target - c]:
            result = c, a, b
            if k > j and result not in res:
                yield [c, a, b]
                res.add(result)

With this leetcode boilerplate:

class Solution:
    def threeSum(self, nums: 'List[int]') -> 'List[List[int]]':
        return list(three_sum_maarten(nums))

This passes all but one scenario. The scenario it fails is nums = [0] * 3000

To tackle this scenario, you can filter all numbers so only maximum 3 of each are present in nums. I do this with the help of a collections.Counter:

def prepare_nums(nums):
    counter = Counter(nums)

    for n, c in sorted(counter.items()):
        yield from [n] * min(c, 3)

and then nums = list(prepare_nums(nums)) instead of nums = sorted(nums)

Alternative approach

You make about half of all combinations of 2 numbers in nums. One extra bit of knowledge you can use to reduce this is to take into account that at least 1 negative and 1 positive number need to be present in each triplet.

counter = Counter(nums)
positives = [i for i in counter if i > 0]
negatives = [i for i in counter if i < 0]

for a, b in product(positives, negatives):
    c = -(a + b)
    if c not in counter:
        continue
    result = a, b, c

and then only yield the correct, unique results

    result = a, b, c
    if c == a:
        if counter[a] >= 2:
            yield result
    elif c == b:
        if counter[b] >= 2:
            yield result
    elif a > c > b:
        yield result

and yield 1 (0, 0, 0) triplet if there are 3 or more 0s present

if counter[0] >= 3:
    yield (0, 0, 0)

This solution is about 10 times faster, and uses 30 times less memory.


Elegance is in the eye of the beholder; the following (replacing the duplicated code here part) is certainly less redundant:

for i in xrange(2):
    if headA is not None:
        if ( headB and headA.data<=headB.data) or (headB is None):
            tail.next = headA
            tail = headA
            headA = headA.next
    # When i==0, this will flip headA & headB
    # When i==1, it will restore them
    headA,headB = headB,headA


ProjectEuler.net problem #50, Consecutive Prime Sum

Generation of prime numbers is suboptimal. Use a sieve of Erathosthenes.
isPrime is highly suboptimal. You already generated an array of all necessary primes, so just binary search it.
Breaking the loop in

        if(sumFromTo(cumulativeSums,start,end)>limit)
            break;

looks like a bug. The intention is to loop by decreasing end, yet since the loop starts with the very long sequence, its sum is likely to exceed the limit right away. Shorter sequences with the same start are never tested.

Consider finding the proper end as an upper limit of a sumFromTo(cumulativeSums, start, end) <= limit predicate (hint: another binary search).
You are not interested in all sequences of the primes. Most of the primes execs 2 are odd. Notice that if the sequence has an even number of odd primes, its sum is even, that is not a prime. Once the correct end is established, you may safely decrease it by 2.
Style wise, give your operators some breathing space.

    for (int end = s.size() - 1; end >= start; end--) {

is much more readable than

    for (int end=s.size()-1;end>=start;end--){

PS: I am not aware of any math regarding sums of consecutive primes. It is very much possible that such math exists, and the goal of this problem is to discover it. That would be a true optimization.


Where should I put code which calculates stats which will be sent via mail

So far as I can tell without seeing the rest of your of your application structure this seems fine. I am making the assumption that this is small app and that performance is not a real concern as of yet. One suggestion though, you could take those where statements and internalize them in their respective models as scopes.

scope :task_count, -> (date) { where(:adate => date).count }
scope :profile_count, -> (date) { where(:ad_date => date).count }

This would at least neaten things up a bit and is a good habit to form, because it will insure consistency in behavior. Even though these are simple queries if you are reimplementing them (or any query) everywhere it creates the possibility to introduce errors; this is a benefit of code reuse.


This doesn't feel idiomatic to me.

I would prefer to use an atom or a dynamic variable if you must store the session outside, but really you should probably be passing the session in on each call.


Breaking out the callback function

I would break out that function as well, though I would give it a better name than func, mayhaps drawScaledScreenshot?

Functionality

CR is not the best place to discuss functionality, but why would you not draw the image if the tab size is too small, it does not seem to make sense.
Also, why would you only check for width going over the maximumScaleFactor ? I would check height as well.

Scope

I feel the following vars could have been declared outside of the drawScaledScreenshot function, since they only depend on width and height.

var outputRatio      = width / height;
var maximumCropWidth = width * maximumScaleFactor; //You calc this several times

Paranoia

If you truly think it is impossible, then it should not be in the code

//This should be impossible
if (cropWidth > sourceImage.width) cropWidth = sourceImage.width;
if (cropHeight > sourceImage.height) cropHeight = sourceImage.height;

If you think it is possible, then I would suggest you convert this to the more readble

//This should not be needed
cropWidth  = Math.min( cropWidth,  sourceImage.width);
cropHeight = Math.min( cropHeight, sourceImage.height);

Notice that if width * maximumScaleFactor is exceeded, you can still get a cropHeight > sourceImage.height..

Furtermore, I would be more paranoid that the caller forgets to provide maximumScaleFactor and would add a

maximumScaleFactor = maximumScaleFactor || 10; //Or whatever is reasonable

Finally, since you are dividing by height, I would verify that height is not zero.


This is one of those times when working backwards helps... but, before we get to that...

Nit Picks

Unless you have a really good reason, do not use StringBuffer. Use StringBuilder instead. There are two times to use StringBuffer, when you are modifying the instance from multiple threads, and when you are using a Matcher.appendReplacement() or Matcher.appendTail(). You are doing Neither, so stick with StringBuilder. It's faster.
You should give values some breathing space... use white-space to make things readable. This is not JavaScript where whitespace impacts download time! Lines like:

while(i<=N){

should be:

while (i <= N) {

Having both the variables begin and start is confusing.
It irks me that you hard-code the first result.... why have:

    // populate next number in sequence
    current.append(1);
    current.append(1);

A Better way.

The actual processing for this is simpler if we do some clever backward-forward logic. I spent some time 'doing it differently'... The trick is that you want to extract a function that does it for a single iteration.... so, let's start with the outer function (so it makes sense):

public static final void loopCompute(String input, int count) {
    System.out.println(input);
    for (int i = 0; i < count; i++) {
        input = compute(input);
        System.out.println(input);
    }
}

I have called it loopCompute, and it takes an input String, and a number of times to iterate. It then loops the number of times, and computes the result, and prints the result. It then prints the new result.

So, what about the compute method?

Well, the trick is to count the sequences of digits, but also, the better trick is to start at the end and work backwards, because we can then use those values to build up the output String efficiently working forwards.

private static final String compute(String source) {
    // allocate two mated arrays, one of the digits, the other of the counts.
    // the worst case is that there will be as many counts as input digits
    // so we budget for the worst case.
    char[] digits = new char[source.length()];
    int[] counts = new int[source.length()];

    int pos = -1;
    // work backwards through the input, storing the results forwards in the arrays.
    for (int i = source.length() - 1; i >= 0; i--) {
        if (pos < 0 || source.charAt(i) != digits[pos]) {
            pos++;
            digits[pos] = source.charAt(i);
        }
        counts[pos]++;
    }

    // now work backwards through the counts, and store them forwards in the StringBuilder.
    StringBuilder sb = new StringBuilder(pos * 2);
    while(pos >= 0) {
        sb.append(counts[pos]).append(digits[pos]);
        pos--;
    }
    return sb.toString();
}


Your implementation is incorrect. It fails for all sorts of inputs, but the simplest is

let mut array = [0, 0];
quicksort(&mut array, 0, 1);

Figuring out how to even call quicksort is overly complicated. Why do I have to pass in these numbers; can't the code figure that out?
Run rustfmt. It will automatically tell you things like:

&mut[T] should be written as &mut [T].

Run clippy.  It will automatically tell you things like:

Not to use return at the end of a function.
That you can use a += b instead of a = a + b
That you've re-implemented slice::swap

Since the code doesn't work, I don't know that the transforms I made preserve the existing behavior. The rest is caveat emptor.

You have redundant type declarations. You don't need to say let x: T = y as T, just let x = y as T.
You also don't often need to specify the type at all, type inference can handle it.
Presumably you converted to an isize because you were subtracting one from zero. Instead, increase the values by one to keep it in the range of a usize. To transform, add one to the initial value of i and subtract one from the usages of i, then remove the casts and simplify the math.

fn partition(array: &mut [isize], first: usize, last: usize) -> usize {
    let pivot = array[last];

    let mut i = first;
    let mut j = first;

    while j < last - 1 {
        if array[j] < pivot {
            array.swap(i, j);
            i += 1;
        }
        j += 1;
    }

    if array[last] < array[i] {
        array.swap(i, last);
    }

    i
}


Use sinon-promises to simplify this:

'use strict';
const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const chaiAsPromised = require('chai-as-promised');
const sinonStubPromise = require('./..');

sinonStubPromise(sinon);

chai.use(chaiAsPromised);
chai.use(sinonChai);

const expect = chai.expect;
let stub;

describe('stubbing promises', () => {
  beforeEach(() => {
    stub = sinon.stub();
  });

  it('should not throw an error when invoked', () => {
    stub.returnsPromise();
  });

  it('should allow defining a resolve value', () => {
    stub.returnsPromise();
    stub.resolves(1);

    return expect(stub()).to.eventually.equal(1);
  });

  it('should allow defining a reject value', () => {
    stub.returnsPromise();
    const err = new Error();
    stub.rejects(err);

    return expect(stub()).to.eventually.be.rejectedWith(err);
  });

  it('should allow overwriting a resolves with a reject', () => {
    stub.returnsPromise();
    const err = new Error();
    stub.resolves(1);
    stub.rejects(err);

    return expect(stub()).to.eventually.be.rejectedWith(err);
  });

  it('should allow overwriting a reject with a resolves', () => {
    stub.returnsPromise();
    const err = new Error();
    stub.rejects(err);
    stub.resolves(1);

    return expect(stub()).to.eventually.equal(1);
  });

  it('should be last-write-wins', () => {
    stub.returnsPromise();
    stub.resolves(1);
    stub.resolves(2);
    stub.resolves(3);

    return expect(stub()).to.eventually.equal(3);
  });
});

References

sinon-promises


I would recommend a more generic approach, for example, I use a lot the Twitter’s Bootstrap variant from Nicholas Cerminara.
While your CSS looks like supports every device appropriately in terms of maintainability it is burdensome. For example most of the iPhone rules can be group into one. The same for the iPad and Nexus tablets.

If you take into consideration a responsive and mobile first styles approach, you can use media queries to only accommodate the styles that doesn’t fix into the mobile environment.

For example, the font size default value could be 60%. So this style doesn’t need to be written in the mobile media queries section, just in the desktop and other sizes. Your styles could be reduced to:

font-size: 60%;
/* Smartphones (iPhone portrait and landscape) */
@media only screen and (min-width: 320px) and (max-width: 480px){
    html {
        /* font-size: 60% is the default now */
    }
}

/* Small Devices, Tablets */
@media only screen and (min-width : 768px) {
    html {
        font-size: 90%;
    }
}

/* Medium Devices, Desktops */
@media only screen and (min-width : 992px) {
    html {
        font-size: 120%;
    }
}

/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px) {
    html {
        font-size: 200%;
    }
}

And still covers, (if all others style and tags are properly architectured for responsive design) all previous requirements.


Saving a collection of WPF user control layout into an XPS document

I don't really see the sense of splitting this into different sections. Also some of them only add overhead which isn't needed at all.

For each MyViewModelVM in List<MyViewModelVM> you are creating a MyViewV with it as DataContext which is in the next loop added as a child to a FixedPage which then is added as a child to a PageContent which is then added to the Pages of the FixedDocument.

This can be simplified to

public static void CreatePortableFile(List<MyViewModelVM> myViewModels, string path)
{

    Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
    {
        FixedDocument fixedDoc = new FixedDocument();

        foreach (MyViewModelVM item in myViewModels)
        {
            MyViewV view = new MyViewV() { DataContext = item };

            FixedPage newFixedPage = new FixedPage();
            newFixedPage.Children.Add(view);

            PageContent newPageContent = new PageContent();
            ((System.Windows.Markup.IAddChild)newPageContent).AddChild(newFixedPage);
            pageContents.Add(newPageContent);

            fixedDoc.Pages.Add(newPageContent);
        }
        WriteToXps(path, fixedDoc)

    }), DispatcherPriority.Loaded);
}

EDIT After reading the comment, I digged a little bit more into this. As this is similiar to printing with datacontext this should fix the issue:

public static void CreatePortableFile(List<MyViewModelVM> myViewModels, string path)
{

    FixedDocument fixedDoc = new FixedDocument();

    foreach (MyViewModelVM item in myViewModels)
    {
        MyViewV view = new MyViewV() { DataContext = item };

        FixedPage newFixedPage = new FixedPage();
        newFixedPage.Children.Add(view);

        PageContent newPageContent = new PageContent();
        ((System.Windows.Markup.IAddChild)newPageContent).AddChild(newFixedPage);
        pageContents.Add(newPageContent);

        fixedDoc.Pages.Add(newPageContent);
    }

    Dispatcher.CurrentDispatcher.Invoke (new Action (delegate { }), DispatcherPriority.ApplicationIdle, null);

    WriteToXps(path, fixedDoc)
}

A detailed explaination can be found here


So this solution works:

x = load('data.csv');
windowSize = 10;
b = (1/windowSize)*ones(1,windowSize);
i = 1;

for n = windowSize: length(x)
    m = 0;
    tempSum = 0;
        for j = 1 : windowSize
            temp = b(j)*x(n-m);
            tempSum = tempSum + temp;
            m = m + 1;
        end
    y(i,:) = [tempSum]
    i = i+1;
end

See results below:

Instead of having really inaccurate results in the beginning I just skip these. It's important to note that you are losing an amount of samples equal to the number of b coefficients in this solution. So make sure to rescale the X-axis.

Results were compared using Matlabs C = setdiff(y,yy) function and found no difference between the proposed solution and Matlabs filter(b,a,x) function.


Assigning number of processors

You currently set procs = 3, specifically for your 4-core machine. You can get the number of (logical) cores of your machine using the multiprocessing.cpu_count function:

from multiprocessing import Pool, cpu_count
procs = cpu_count() - 1

Create Pool just once

Rather than creating a new Pool every iteration of your for-loop, it is better to just create it once and keep using the same one. By using the with statement, it also makes sure to close it all neatly when you're done with it.

with Pool(procs) as p:
    for max_iter in max_iter_list:
        jobs = [max_iter] * n_trials
        duration_list = p.map(simulate_game, jobs)
        gambler_stats.update_stats(duration_list)

Hardcoded values in simulate_games function

First of all, you can define your default values in the function definition. This also makes the difference more clear between the hardcoded defaults and initializations like cur_iter = 0

def simulate_game(max_iter,
                  gambler_limit=100,
                  house_limit=200,
                  gambler_win_prob=0.5):

Create different fixed-value alternative using partial

To have a fixed different set of default values, you could use functools.partial:

from functools import partial
simulate_high_roller = partial(simulate_game, gambler_limit=1_000)
with Pool(procs) as p:
    duration_list = p.map(simulate_high_roller , jobs)

Mapping with multiple arguments: starmap

If instead you want to simulate using a whole range of parameter values, Pool.starmap is probably what you're looking for. Just like the 'regular' itertools.starmap, it allows you to pass in a list of tuples that it will unpack and pass to your function.

So if you have pre-defined lists of parameters you want to simulate, you can use zip to create the tuples.

# Example
max_iter_list = [10, 20, 50]
gambler_limits = [50, 100, 200]
house_limits = [150, 200, 250]
win_probabilities = [0.6, 0.5, 0.4]

with Pool(procs) as p:
    for arguments in zip(max_iter_list, gambler_limits, house_limits, win_probabilities):
        jobs = [arguments] * n_trials
        duration_list = p.starmap(simulate_game, jobs)

In case of a full grid-search of your parameters, this combines nicely with itertools.product, although that set of combinations will grow quite fast, so be deliberate about which ones you need to test.

>>> from itertools import product
>>> arguments = list(product(max_iter_list, gambler_limits,
...                          house_limits, win_probabilities))
>>> print(arguments)
[(10, 50, 150, 0.6),
 (10, 50, 150, 0.5),
 (10, 50, 150, 0.4),
 (10, 50, 200, 0.6),
 ...
 (50, 200, 200, 0.4),
 (50, 200, 250, 0.6),
 (50, 200, 250, 0.5),
 (50, 200, 250, 0.4)]
>>> len(arguments)
81


Iterating X times (where X > Y) over Y element dictionary

You can solve this mathematically. Let's suppose there are \$m\$ hosts and \$n\$ jobs. Sort the hosts into ascending order by their slots, so that \$s_i\$ is the number of slots for host number \$i\$, and we have \$s_0 ≤ s_1 ≤ \dotsb ≤ s_{m−1}\$.

Now we can immediately figure out how many jobs host 0 gets. Case (i): if \$s_0m ≥ n\$, then we can distribute jobs evenly across the hosts, so that every host gets either \$\lceil{n \over m}\rceil\$ or \$\lfloor{n \over m}\rfloor\$ jobs. Because jobs are distributed to the hosts with higher capacity first, we can be sure that host 0 gets \$\lfloor{n \over m}\rfloor\$ jobs. Case (ii): if \$s_0m < n\$, then we have to give each host at least \$s_0\$ jobs (and some hosts more).

So host 0 gets \$\min(\lfloor{n \over m}\rfloor, s_0)\$ jobs, and then we can subtract 1 from \$m\$ and go on to host 1. Like this:

import operator

class CapacityError(Exception):
    pass

def schedule(hosts, n):
    """
    Generate a schedule for picking `n` slots from `hosts` (a
    dictionary mapping hostname to capacity). Raise CapacityError if
    no such schedule is possible.

    >>> sorted(schedule({'A': 3, 'B': 7, 'C': 1}, 8))
    [('A', 3), ('B', 4), ('C', 1)]
    """
    if n > sum(hosts.itervalues()):
        raise CapacityError()
    m = len(hosts)
    for host, slots in sorted(hosts.iteritems(), key=operator.itemgetter(1)):
        j = min(n // m, slots)
        n -= j
        m -= 1
        yield host, j
    assert(n == m == 0)

Update 1: generators

I've implemented this function in the form of a generator because that's the most flexible way in Python to produce a sequence of things (here, elements of a schedule). You can easily turn the result into a dictionary:

>>> dict(schedule({'A': 3, 'B': 7, 'C': 1}, 8))
{'A': 3, 'C': 1, 'B': 4}

or a list:

>>> list(schedule({'A': 3, 'B': 7, 'C': 1}, 8))
[('C', 1), ('A', 3), ('B', 4)]

or just process the items one at a time:

>>> for host, slots in schedule({'A': 3, 'B': 7, 'C': 1}, 8):
...     print("{}: {}".format(host, slots))
...
C: 1
A: 3
B: 4

(If you're not happy with using generators, you can easily change the implementation to return a dictionary instead. But it's worth learning to use them. See the Python Tutorial, or this question on Stack Overflow.)

Update 2: job ids

You asked in comments how to assign individual jobs. Well, one idea would be to pass in a list of jobs to the scheduler, and get out a list of jobs for each host, like this:

from itertools import islice

def schedule2(hosts, jobs):
    """
    Generate a schedule for assigning the list `jobs` to `hosts` (a
    dictionary mapping hostname to capacity). Raise CapacityError if
    no such schedule is possible.

    >>> jobs = ['j{}'.format(i) for i in range(8)]
    >>> dict(schedule2({'A': 3, 'B': 7, 'C': 1}, jobs))
    {'A': ['j1', 'j2', 'j3'], 'C': ['j0'], 'B': ['j4', 'j5', 'j6', 'j7']}
    """
    n = len(jobs)
    if n > sum(hosts.itervalues()):
        raise CapacityError()
    m = len(hosts)
    jobs = iter(jobs)
    for host, slots in sorted(hosts.iteritems(), key=operator.itemgetter(1)):
        j = min(n // m, slots)
        n -= j
        m -= 1
        yield host, list(islice(jobs, j))
    assert(n == m == 0)

Update 3: more explanation

You asked in comments for more explanation. Well, I'm going to assume that you know all about Python iterables, iterators, and generators (see the Python tutorial and the answers to this question on Stack Overflow).

So the remaining difficult bit is why I write jobs = iter(jobs) and list(islice(jobs, j)). Remember that jobs is a sequence of jobs, and we want to split it up into lists of jobs assigned to each host. In the line

        j = min(n // m, slots)

we compute the number of jobs to assign to the current host, so what we need to do is to take the next j elements from the list jobs. One way to do that would be able to keep a counter k of how far we got through the list jobs, and then take a slice of the next j elements starting at k. Like this:

    k = 0
    for host, slots in sorted(hosts.iteritems(), key=operator.itemgetter(1)):
        j = min(n // m, slots)
        n -= j
        m -= 1
        yield host, jobs[k:k+j]
        k += j

There's nothing wrong with doing it like this, except that it's a bit of a pain keeping the counter k up to date. We don't really care about the value of k, we just want the next j elements from jobs, whatver they are. That's where itertools.islice comes in. The call islice(iterator, j) returns an iterator that takes j elements from iterator. Which is almost exactly what we need, except that it's an iterator, but we need a list. So we convert it to a list by calling the built-in function list.

Here's an example showing islice in action:

>>> from itertools import count, islice
>>> c = count(1) # an iterator that counts upwards from 1
>>> a = islice(c, 5) # an iterator that gets 5 elements from c
>>> list(a)
[1, 2, 3, 4, 5]
>>> list(islice(c, 3)) # get another 3 elements from c
[6, 7, 8]

The only remaining problem with using islice to split up jobs is that this relies upon jobs being an iterator (a list won't work). So we use the built-in function iter to ensure that jobs is an iterator.

You should try out all these functions in the interactive interpreter to get a feel for what they do and how they work.

You also asked about assert. An assertion is a statement that tests a value and raises an exception if it's not true. It declares a condition that must be true at this point in the program. This is useful for programmers who want to read and understand the code, and it also catches implementation errors if these lead to the condition being violated. See Wikipedia on assertions.

In this case, I want to declare that the program has generated an assignment for every host (that is, m == 0 since m starts at the number of hosts and counts down for each one) and that every job has been assigned to some host (that is, n == 0, since n starts at the number of jobs, and gets reduced by j when we assign j jobs to some host).


Read file into list when class is instantiated in Python 2.7

I agree with Caridorc about not needing a class, in addition ReadFile isn't a very good class name, it sounds like a function. Unless, you meant read as an adjective (this file has been read), but you can see how that could be confusing.

Keeping filename and your hardcoded path seems redundant at the moment

    self.localdir = 'C:\\Users\\User\\Documents'
    self.filename = filename
    self.filepath = os.path.join(self.localdir, self.filename)

Also you could use r''to write your filepath without the double backslash. r before a string will tell Python to interpret it literally, ie. Don't consider anything an escape character. That means that a backslash will always just be a backslash.

You store all 3 of these but only every use filepath, why not go directly to creating the filepath? The point of init should be taking the passed parameters and turning them into the form needed for your class, and your class only needs filepath. Particularly if you do convert this to a function, it'll become less useful to keep the redundant values.

Also, since init is about getting the data you need, why even have getData as a separate function? Collapse that back into init since it's being called there anyway and will never be called again. In fact if you call get_data() twice you've accidentally doubled up on the info, which you surely never want.

Since you're not changing the data at all, you can pass the csv reader directly to list() to create a list. In fact, you could just return list(rows) if you turned this all into one function.

You should add a docstring to your class/function. ReadFile seems pretty clear until you find out that you've passed a filepath and gotten an error that it doesn't exist (since you read from a specific directory) or you might be puzzled when you pass a text file and get back a csv formatted file.

Here's how I might refactor your code:

def read_csv_file(filename):
    """Returns a list of data from a csv file passed to it.

    Only reads files from 'C:\Users\User\Documents\' + filename
    Prints any exceptions from reading the file."""

    filepath = os.path.join(r'C:\Users\User\Documents', filename)

    try:
        with open(filepath, 'rU') as c:
            rows = csv.reader(c)
            return list(rows)
    except Exception as ex:
        print(ex)

def main():
    new_data = read_csv_file('myfile.csv')
    for i in new_data:
        print(i)        # etc... more code will follow

if __name__ == '__main__':
    main()

If you were sticking with keeping it a class then I'd still keep the above in one function and make minor other changes. I'd add a docstring about the class's general use.

Also I would no longer catch and print the error. Errors shouldn't be ignored, and failing to read your file will actually mean that the class hasn't been correctly created as it's missing crucial data and likely has an invalid path. You can either let it be normally raised without intervention, or add a custom error message with raise ErrorType("Message about the error"). In your case IOError is likely, so you might raise IOError with a message about how the passed filename isn't in your hardcoded directory. But exactly how you'll handle that is up to you.

Like this:

class ReadFile(object):
    """Docstring"""

    def __init__(self, filename):
        self.localdir = r'C:\Users\User\Documents'
        self.filename = filename
        self.filepath = os.path.join(self.localdir, self.filename)

        try:
            with open(self.filepath, 'rU') as c:
                rows = csv.reader(c)
                self._data = list(rows)
        except IOError:
            raise IOError("{} not found in {}".format(
                          self.filename, self.directory)
    def get_data(self):
        return self._data


Return early, there's no need to touch files if the current file is <5mb.
DRY your code, move the "{}{}.{}".format into it's own function.
Don't use comprehensions for mutations. Use an explicit for loop for that.
As you want idiomatic code, you should be aware that some people discourage the use of __ as it performs name mangling.

If the function is intended to be private, not protected, then it should be ok.
You can use the pairwise recipe to make the reversed pairwise loop. I think it's more readable, however you may not.
It's unidiomatic to put brackets on if statements. Unless the statement spans multiple lines.
It's idiomatic to put two newlines around top level classes and functions.
I'm a bit confused why you want to touch everything.
You may want to split all the different aspects of rotate into smaller functions to follow SRP.

Your code's pretty idiomatic otherwise, your naming conventions are good, you've used a main guard and you've got white space where it should be.

from os import listdir
from os.path import getsize, exists
from shutil import copyfile
from argparse import ArgumentParser
import itertools

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

SIZE_5MB = 5e6
MAX_LOG_FILES_COUNT = 5

class LogRotator(object):
    def __init__(self, prefix, suffix):
        self.prefix = prefix
        self.suffix = suffix

    def __str__(self):
        return  "{}[x].{}".format(self.suffix, self.prefix)

    def __touch(self, file_name):
        open(file_name, 'w').close()

    def _gen_file_name(self, name):
        return "{}{}.{}".format(self.prefix, name, self.suffix)

    def rotate(self):
        current_log = self._gen_file_name('')
        if getsize(current_log) < SIZE_5MB:
            return

        files = [
            self._gen_file_name(i)
            for i in range(1, MAX_LOG_FILES_COUNT + 1)
        ]

        for file in files:
            if not exests(file):
                self.__touch(f)

        for older, newer in pairwise(reversed([current_log] + files)):
            copyfile(newer, older)

        self.__touch(current_log)

if __name__ == '__main__':
    parser = ArgumentParser(description="Rotate log files")
    parser.add_argument("-prefix", help="log file prefix")
    parser.add_argument("-suffix", help="log file suffix")

    args = parser.parse_args()

    log_rotator = LogRotator(args.prefix, args.suffix)
    log_rotator.rotate()


Checking arrays

Since you are in Java 8, you can use IntStream to help you out:

public static boolean isArrayZero(int[] arr){
    return Arrays.stream(arr).allMatch(i -> i <= 0);
}

What that means is to ensure all matches the IntPredicate (lambda) i <= 0.

Input validation

Your input validation can probably be better done as a method:

private static int getPile(Scanner scanner) {
    int result = -1;
    while (result = -1) {
        result = getPile(Character.toUpperCase(input.next().charAt(0)));
    }
    return result;
}

And the same goes for asking the number to remove from the pile. These can be done to eliminate the need to continue from the loop.

Modeling

Using an int[] array is perfectly fine, but you may also want to explore other forms of modeling, such as using an enum:

enum Pile {
    A, B, C;

    public static Pile getPile(char input) {
        try {
            return valueOf(String.valueOf(input));
        } catch (IllegalArgumentException e) {
            return null;
        }
    }
}

Instead of dealing with array indices, you then deal with enum values, which depending on your perspective may look a little better.

try-with-resources

The usage of try-with-resources on the Scanner instance is recommended to manage its underlying I/O resource cleanly.

Potential bug

The screenshot you currently have does not agree with your code, since it looks like Mark managed to remove 8 from 7 in pile 'C'. The same prompts confused me here... Maybe use a prompt that indicates an invalid input was encountered will be a bit better.


Parsing a fixed-size message using variable length array in C

Overall Observations
The int main(void) function is correctly declared since no arguments are expected.
The code definitely follows the Single Responsibility Principle and this is good!
The use of portable include guards is good.
The program would be more flexible if it accepted the message as input from either the console or a file (would require an alternate declaration for main()).
Use System Defined Constants
The main() function could be made more readable if the system defined constants EXIT_SUCCESS and EXIT_FAILURE were used (only EXIT_SUCCESS in this case). These constants are included in the stdlib.h header file which is already included in the code.
#include <stdio.h>
#include <stdlib.h>
#include "decoder.h"

int main(void) {

    uint8_t input[8] = { 80, 75, 73, 71, 1, 1, 1, 1 };
    parse(input);

    char addr[get_size()];
    get_address(addr, get_size());
    printf("==== %s ==== ADDRESS\n", addr);

    return EXIT_SUCCESS;
}

Avoid Global Variables
It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The answers in this stackoverflow question provide a fuller explanation.
In C it is possible to have a variable that is global to a file, but does not impact the entire program by using the static keyword.
static uint8_t parsed_message[LENGTH];
static uint8_t len = 0;

In the current implementation this compiles properly.
If you are really going to use global variables throughout the program they should be declared as extern variables in the header file.
#ifndef DECODER_H_INCLUDED
#define DECODER_H_INCLUDED

#include <stdint.h>

#define LENGTH 100
extern uint8_t parsed_message[LENGTH];
extern uint8_t len;

void parse(uint8_t* message);
void get_address(char* addr, int size);
uint8_t get_size(void);

#endif // DECODER_H_INCLUDED

Header Files
Only include header files that are absolutely necessary to make the code compile in header files, it is better to include the necessary header files in the C source file. This makes the code clearer in the source file. In decoder.h the only necessary header file is stdint.h. This could affect compile time and cause link errors if include guards are missing. In most implementations of C a temporary source file is generated by the C pre-processor and all header files are copied into the temporary file.
Variable Types
It isn't clear from reviewing the program why the code is using uint8_t rather than unsigned char. The overall result would be the same and less header files would be necessary.


This looks very clean and simple, which is always* a good thing when programming.  First, you don't save state, nor do you have long functions--each function does what says in a couple lines.  One nitpick is your naming:

let isGreen currentTime switchItme

switchItme should probably be switchTime.

You indented the conditions of your match statement too far.  That should be indented as:

match (isGreen currentTime switchTime) with
| false -> if (currentTime % switchTime) < 0.01 then switchTime else currentTime % switchTime
| _ -> 0.0

In F#, you typically don't use if statements, except for choosing a path based on the value of a boolean literal, and I only do that when I can use it like a C# ternary.  I would write the match in your second function as:

match (isGreen currentTime switchTime) with
| true -> 0.0
| false ->
    match (currentTime % switchTime) with
    | c when c < 0.01 -> switchTime
    | _ -> currentTime % switchTime

F# has a printfn function that is the same as printf, except it prints a newline at the end.  You should use this instead of manually specifying you want a newline with printf "...\n"

* Well, sometimes complicated, fast code is better in performance-critical environments.


How can I refactor this to use classes?

You don't. There is absolutely no need for that in this program as you don't share a common state between multiple functions. On the same subject, see also this PyCon talk.

Instead, we should focus on clearing the obvious mistakes made in this function:

Be sure to pass information to functions using parameters: global variable can be fine for constants, not so much for information to work on; besides if I import your code in an interactive session, I am greeted with a game but any other attempt to call guess_the_word() will reuse the same word to guess.
This also lead to how you call your code: running the program on the command line will play a game, but importing it will play it too; which may be undesirable. To avoid this side effect, get yourself familiar with the if __name__ == '__main__': construct.
secrets is a module designed for cryptographically secure sources of random numbers. You don't need such strong randomness here so you can avoid the associated overheads using the simpler random module.
You can join directly on lists: no need to write a list-comprehension which will just copy the underlying list before feeding it to join. In the same vein, striping whitespace and converting to str is superfluous here as the result of join already fulfill the two conditions.
Checking if a letter is in a string is an \$\mathcal{O}(n)\$ operation, so you can skip that and directly perform the iteration over each letter it won't cost more. You can use a flag to know if you have found a matching letter.
A message at the end of the while loop to conclude would be a great addition to the user experience.

All in all, this could yield the following code:

import random

def guess_the_word(secret_word):
    tries_left = 9
    output = ["_"] * len(secret_word)

    while tries_left >= 0 and secret_word != ''.join(output):
        print(' '.join(output))
        print("\nYou have", tries_left, "tries left")

        guessed_letter = input("Guess a letter from secret word: ")

        found = False
        for i, letter in enumerate(secret_word):
            if guessed_letter == letter:
                output[i] = guessed_letter
                found = True

        if found:
            print("You guessed correct")
        else:
            tries_left -= 1
            print("You guessed incorrect")

    if tries_left < 0:
        print("\nNo more tries, you lose")
    else:
        print("\nCongratz! You found the secret word:", secret_word)

def main(filename="words.txt"):
    print("\nWelcome to Hangman Game!\n")

    with open(filename) as words_file:
        words = words_file.read().split()

    guess_the_word(random.choice(words))

if __name__ == '__main__':
    main()

An other nice addition to have is the ability to repeat the games automatically. You could change your main part to:

def main(filename="words.txt", repeat=sys.maxsize):
    print("\nWelcome to Hangman Game!\n")

    with open(filename) as words_file:
        words = words_file.read().split()

    for _ in range(repeat):
        guess_the_word(random.choice(words))

if __name__ == '__main__':
    main(repeat=1)

to keep the current behaviour but allows importing the file to run main() the desired amount of time without having to reload the file each time.


Evaluating a dotted quad IP address has clumsy use of inject/fold

The correct Ruby-way (also Perl and others) is to use pack/unpack, since low-level bytes job is what they are implemented for.

def dotted_ip_to_num ip
    ip.split(".").map(&:to_i).pack("C*").unpack("N")[0]
end


Your code all looks clear and readable to me. This is basically all performance-related.

It's "divisor"

since you're not dealing with negatives, you can use the more efficient rem and quot instead of the more mathematically correct mod and div.
factorInt 1 should be [(1,1)].

In your prettyFactors method you're creating a bunch of left-nested ++'s. This leads to a quadratic complexity printing method. You can use foldr1 to switch them to right-nested ++'s and get linear time, or you could look into the showS trick. (this won't really matter since by the time your printing takes a noticeable amount of time the factorization will be taking ages.)
Addendum: In most cases foldl and foldl1 are not what you want. You usually use foldr or foldr1 when you want laziness and foldl' or foldl1' when you want strictness.

Every time you use factorInt you start takeDivizor at 2, despite the fact that you might have already tried 2,3,4.. on previous iterations. The simplest way to remedy this would be to just add a parameter to each of them telling them where to start looking for factors.

You check a lot of numbers you don't have to in your takeDivizor function, you really only need to look at a list of primes, not [2..]

You could modify maxPower to make it tail-recursive.

If I were to write this, I would probably leave out the headMaybe and takeDivizor and write factorInt something like this.

primes = 2 : [ p | p <- [3,5..], all (\x -> rem p x /= 0) (takeWhile (\x -> x^2 <= p) primes ]

factorInt :: Int -> [(Int,Int)]
factorInt 1 = [(1,1)]
factorInt n = f n primes where
  f n (p:ps) | n < x     = []
             | otherwise = let mp = maxPower n p in (p, mp) : f (quot n (p^mp)) ps

Note that my implementation of primes is far from optimal, you can find better implementations on the haskell wiki page for primes.


Checking if the whole number is prime, and if all its digits are too

The easiest improvement to make is to only go up to n**.5 inisprime This yields a quadratic speedup. The next obvious improvement is to not convert each digit to an int, but rather just use if j not in "2357":. This saves time in two ways: First, it skips an int conversion, and secondly, it uses one check instead of a for loop.


I think this is solid code. All I can think of is a repeat pointing to an array in the controller. I do this on some of our web apps that have high-freq of changes to menu items.

I don't know if this would really be a good refactor otherwise as it just abstracts away more of the template but it definitely DRY's it up.

BTW I'm not familiar with that templating lib so I apologize if there are any problems with the syntax.

template

 %ul.dropdown-menu(aria-labelledby="single-button" role="menu" uib-dropdown-menu)
        %li(role="menuitem" ng-repeat="item in doc_dropdown")
          %a(
             href={{ ( item.is_path ) ? item.pathLocation : true }}
             ng-click={{ item.clickTrigger }}
             ng-hide={{ ( item.can_hide ) ? "documentTemplate.parent_id" : "" }}
            )
                {{item.text}}

somewhere in the controller

doc_dropdown = [
    {
        is_path: true,
        pathLocation: "/legal-forms/admin/document_templates/{{ documentTemplate.id }}/edit",
        text: "Edit",
        click_trigger: null,
        can_hide: false
    },{
        is_path: true,
        pathLocation: "/legal-forms/admin/document_templates/{{ documentTemplate.id }}/open_in_wizard",
        text: "Create Document",
        click_trigger: null,
        can_hide: false
    },{
        is_path: true,
        pathLocation: "/legal-forms/admin/document_templates/{{ documentTemplate.id }}/preview",
        text: "Preview",
        click_trigger: null,
        can_hide: false
    },{
        is_path: false,
        pathLocation: null,
        text: "Copy",
        click_trigger: "copy(documentTemplate)",
        can_hide: true
    },{
        is_path: false,
        pathLocation: null,
        text: "Delete",
        click_trigger: "delete(documentTemplate)",
        can_hide: false
    },
];


From a mathematics and science genius:

"If I have seen further it is by standing on the shoulders of Giants." Isaac Newton
Wikipedia: Standing on the shoulders of giants

For Go giants, you might start with Rob Pike.

GitHub - robpike/filter: Simple apply/filter/reduce package.
I wanted to see how hard it was to implement this sort of thing in Go, with as nice an API as I could manage. It wasn't hard.
Having written it a couple of years ago, I haven't had occasion to use it once. Instead, I just use "for" loops.
You shouldn't use it either.

Take Rob Pike's advice and use "for" loops.


Extracting data from vue-chartjs into an array of datasets

False alarm! No callback hell here.

While this code can certainly be refactored a bit, I fail to see callback hell anywhere around. Callback hell is normally a term applied to the code that is executed asynchronously and with multiple nested callback functions. The nested structure is what causes a few issues:

cognitive complexity (which leads to bugs and maintenance complication);
refactoring difficulty;
more importantly, hard time expressing conditional ("branching") or cyclic ("loops") logic.

A related question on StackOverflow might be helpful (just don't focus on RxJs part of the answer there).

Your code does actively use arrow functions, but it is not equivalent to callback hell. The number one reason is because everything in getDatasets() is executed synchronously.

Refactoring

Nitpicking

Small details like line breaks are powerful. Splitting the function into paragraphs with empty line separators helps identifying logical steps you're making in code. It also can work help in extracting sub-functions later, if/when the function becomes too long.
Naming things: Spelling things out is always better than using names like el, e, arr. Abbreviated variable names like that suggest that these entities have no reason to exist or are unimportant. Even item is not a good name. Since it denotes a label, call it a label. I'm sure you got the idea.
Naming continued: Name your variables consistently. You iterate two times over the same object: Object.entries(obj).forEach(...) in one case you call the current entry as entry, while in the other – just el. That is confusing.
I like how you lock down the chart data in a locally scoped obj variable. Renaming it to chartData would make it more readable, though.
You could also avoid let in a few places and have const instead. For example, reduce(...) or map(...) are in many cases a better alternative to for (...) or .forEach(...).
Also, be careful when you deal with array deconstruction. While it's readable, it's also very inefficient because it creates a new array by iterating all the elements of the source arrays. It's only fine to use it for pieces of code that are not invoked frequently and/or operate on tiny arrays only.

Applying the suggestions to the code

I could only rewrite the first half of the function. The second half requires a broader context to make a meaningful change to it.

As you can see, I failed to rename e into something descriptive, because I'm unaware of the models you are using in your application. Hopefully, even this "mechanical" refactoring is able to give you some ideas on how the code can be improved.

getDatasets() {
  const chartData = this.getChartData;

  const datasetLabels = Object.values(chartData);

  // `datasets` could be a const, if only it wasn't modified further down the road...
  let datasets = [...new Set(datasetLabels)]
    .map((label, labelIndex, array) => ({ label, backgroundColor: this.getColor(array, labelIndex), data: [] }));

  // This is a subject to a few more changing, maybe...
  Object
    .entries(chartData)
    .forEach((entry) => {
      Object.entries(entry[1]).forEach((dataItem) => {
          datasets = datasets.map((e) => {
            if (e.label === dataItem[0]) {
              e.data.push(dataItem[1].median);
            }
            return e;
          });
        });
    });

  return datasets;
}

Update As @Gerrit0 suggested, Object.values(...) is a better option than Object.entities(...).map(...) (more concise and achieves exactly the same result).


Naming the classes and the design (at least as far as I can see from the code you pasted) suggests that you want to use the observer pattern. The main idea of this pattern is to use listeners which implement common listener interface and register them for the specific object which you want to make 'observable'. Then in the observable object you can call notifyAllListeners() method or notifyAllListenersOnError() or some similar which will do nothing else than for listener from registered listeners call listener.notify() (or listener.onError() etc.).

Methods notify(), onError() etc have to be declared in the common listener interface.

What I mean is described here.

The main idea is:

Create observable object.
Create as many listeners which implements common listener interface.
Register all created listeners for the observable object.
In the observable object call notifyAll code.

I also created a short article which explains the idea.


You have an awful lot of excess whitespace. Use one or two blank lines between functions, and one blank line to break up different parts of each function (especially, just below the end of a loop or if block). Don't put blank lines immediately between a line ending in : and the start of the indented block beneath it.

The while loop in info uses a class attribute as a loop counter, which actually seems to cause a potential bug here: the counter persists, so on subsequent calls you will skip the loop, never append to the outer list, and it will be returned empty. If page is a local variable instead, and it will work fine no matter how many calls you make.

Instead of keeping a loop counter like this, and incrementing it manually, preferred Python style is to use a for loop. The equivalent for loop to your current while loop would be:

for page in range(1, 2):
   ...

Although it would be good to store the maximum page in a variable. But in light of your clarification in the comments that this would normally be a while True: loop, which only breaks once it hits a page with no interesting links, then the equivalent is to use itertools from the stdlib:

for page in it.count(1):
    ...

You have a variable links to capture the links on each iteration of the loop, and linkz to accumulate them across all the pages you parse (which is only one at the moment anyway, but I'm assuming that could change later). Those names are quite confusing; it would be good to differentiate better - call them links for the one that gathers all the links, and page_links for the one that gets the links for just this page.

Your email function parses what I would call your 'main' data structure. Since that is a lot more than just email-related information, email isn't the best name for it.

The data structure that email creates seems awkward for your data. If you think of people as 'records', and the information you capture about them to be 'fields', then it would make more sense to have it as a list of namedtuples, or or even a pandas dataframe if you're working with a lot of data. That way, your code to parse it is a little bit simpler:

person = namedtuple(...)
people = []
for link in links:
   this_person = person()
   person.phone = #parse phone number
   etc.

return people

But this is the major data structure in your class. It contains all the information that this class is designed to parse. So, I think all of this should be done in __init__, with this structure - and only this structure - captured as an attribute.

The only other attribute you store is the filename that gets passed to __init__. I think it would make more sense as an argument to your csv method - the only method that uses it - because the filename to write it to is a decision that goes with "I want to write this data to disk" more than "I want to scrape some data from a website".

So, you're left with a class with one attribute, and two methods - one of which is __init__, and the other is fairly trivial. In fact, csv becomes even more trivial with a list of namedtuples, since you wouldn't need to zip it. Similarly if you use a pandas DataFrame, it has it's own CSV routines that you can use.

That means there is no need for a class. Instead, use what your __init__ has grown to as a standalone function - call it parse_yellowpages(url). Have it return the list or DataFrame. Then drop the csv function entirely and just put that in the main line of your program.

Your current code is a little schizophrenic about whether it allows multi-valued fields: eg, can a person have more than one phone number?

The code parsing it looks like it does. You parse out a list of data, then you extend it onto the accumulated list. But then when you write out your CSV, you assume (by your use of zip to regroup them) that all fields have exactly one value.

In the comments you clarified that you only want single-valued fields. That being the case, don't include a full list of every match you found in your data structure. If you get three phone numbers for a person when you're only expecting one, you want to either consider it an error and bail out, or forget all but one of them. Your current code would silently remember all of them, forget that it did that, and end up with corrupt data.

To take the 'signal an error' path, do something like this:

phone_numbers = soup2.findall(...)
if len(phone_numbers) != 1:
    raise RuntimeError('Empty or multivalued field: ' + url)
else:
   this_person.phone = phone_numbers[0]

If you prefer to instead ignore any surplus values, use find instead of find_all - they take the same arguments, but find will just return one result instead of a list of them.