Process a list of instructions and output the max value reached Inputs looks like this

b inc 5 if a > 1
a inc 1 if b < 5
c dec -10 if a >= 1
c inc -20 if c == 10

I am concerned that I need to declare __max__ as global (but not __registers__). Any other recommendation on this Python script for a beginner ?

import sys
import re

steps = 0

__registers__ = []
__max__ = None

class Instruction:
    def __init__(self, string):
        # Group 1 is the register name,
        # Group 2 is inc or dec,
        # Group 3 is the amount to increase or decrease,
        # Group 4 is the full condition
        # Group 5 is the name of register against which the condition is tested,
        # Group 6 is the operand of the condition,
        # Group 7 is the numerical value of the second term of the condition
        regex = "(\w+)\s(inc|dec)\s(-*\d+)\sif\s((\w+)\s([^\w\s]+)\s(-*\d+))"
        regex_string = re.search(regex, string)
        if regex_string:
            self.name = regex_string.group(1)
            __registers__.append(Register(self.name, 0))
            self.oper = regex_string.group(2)
            self.amount = int(regex_string.group(3))
            self.condition = regex_string.group(4)
            self.tested_register = regex_string.group(5)
            self.test_operand = regex_string.group(6)
            self.test_value = int(regex_string.group(7))

    def process_instruction(self):
        # We do the test :
        p =  str(find(self.tested_register).value)
        condition = self.condition.replace(self.tested_register, p)
        if eval(condition):
            # We apply the inc / dec amount :
            reg = find(self.name)
            # print(reg.value)
            if self.oper == "inc":
                reg.value = reg.value + self.amount
            else:
                reg.value = reg.value - self.amount
            # print(reg.value)
            global __max__
            if __max__ is None or reg.value > __max__:
                __max__ = reg.value

class Register:
    def __init__(self, name, value):
        self.name = name
        self.value = value

def find(register_name):
    for register in __registers__:
        if register.name == register_name:
            return register

def get_max():
    max = None
    for regi in __registers__:
        if max is None or regi.value > max:
            max = regi.value
    return max

def main(arguments):
    fileName = sys.argv[1]
    global instructions
    instructions = [Instruction(line.rstrip('\n')) for line in open(fileName)]
    # print(__registers__)
    # print(len(__registers__))
    global __max__
    for instru in instructions:
        instru.process_instruction()
    print(get_max())
    print(__max__)

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

As the comment threads make clear, the mystery about global goes away when you recognize the difference between accessing a variable from an outer scope (like your did with __registers___ and assigning to a variable whose name happens to also exist in an outer scope (what happened with __max__)

You can simplify a good bit of this by exploiting exactly this behavior.  If you store your registers in a module-level dictionary, you can access that dictionary in any part of the code without having to pass it around. Since you don't assign the dictionary -- you just access it -- you don't need to declare it global.  So in you case you could eliminate the find() function because you'd just grab a register value out of the dictionary.

 REGISTERS = {'a': 0, 'b': 1}

 def increment(reg, val):
     REGISTERS[reg] += val

would be an example.  In this case we can be a bit lazy and use a dictionary comprehension -- a shorthand way to fill out a dictionary with keys from 'a' to 'z' and values of all zeros:

import string  # the string module has a builtin for the ascii alphabet
REGISTERS = {char: 0 for char in string.ascii_lowercase}

So you don't need a register class -- you just manipulate the values in the dictionary for each register.

To do the instruction parsing, you can simplify things a good bit by eliminating the regex and simply using Python's builtin string split() function, which will take a string like  'b inc 5 if a > 1' and turn it into ['b', 'inc', '5', 'if', 'a', '>', '1'] without any extra work (this would not be appropriate if any of your directives had spaces in them -- but they don't seem to in this example).  That gives you 7 tokens -- your comment here was very useful -- 3 describing the tests you want to apply and three describing the operation to perform in the test passes (#3, the if, is basically ignorable).

With everything already parsed out, you really don't need to use classes.  The Instruction class does only two things: it applies the test in the last three tokens, and if that test is true it uses the instructions in the first three tokens to change the register.  Python has a handy built-in way to do what you're trying to do -- capturing common operations like addition or comparison.  The operator module has a bunch of functions which correspond to the basic operations. For example 'inc' corresponds to operator.iadd which is basically a += b expressed as a function.  '>' becomes operator.gt, a function that returns true if the first of its arguments is greater than the second.

That would get rid of much of the logic in your Instruction class.  Another module level 'global' dictionary is an easy way to map the strings to the operator,  simplifying both the process of parsing -- no conditional checks, just dictionary lookups -- and of running the tests.  So, first a dictionary to do the mapping:

# match operator functions to string identifiers
OPERANDS = {
    'inc': operator.iadd,
    'dec': operator.isub,
    '>': operator.gt,
    '>=': operator.ge,
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne
}

and with that in place the functions to use these operators are very simple. If you want to apply some operation to a register, you get the value from the REGISTERS dictionary, the operator from the OPERANDS dictionary, then call the operator with your value:

def apply_value(register, opstring, valstring):
    operator = OPERANDS[opstring]
    value = float(valstring)
    orig = REGISTERS[register]
    REGISTERS[register] = operator(orig, value)

doing the test ('is this larger than 5' or whatever) is equally simple:

def condition(register, teststring, testval):
    check = OPERANDS[teststring]
    value = float(testval)
    existing = REGISTERS[register]
    return check(existing, value)

So as you parse a line of instructions, you just run condition function on the last three tokens ("a > 5") and if it's true, run the apply_value function on the first three:

    with open(filename, 'rt') as fileread:
        for directive in fileread:
            tokens = directive.split()  # [3] is always 'if', so ignored
            if condition(tokens[4], tokens[5], tokens[6]):
                apply_value(tokens[0], tokens[1], tokens[2])

If you run that on all your directives you'll see the register values going up and down.  Python also has an easy built-in way to find the maximum value in a series -- so to get the largest register value it's just

    max_value = max(REGISTERS.values())

with no need for you to track the max value manually.

Putting it all together it might look like this:

import sys
import operator
import string

# match operator functions to string identifiers
OPERANDS = {
    'inc': operator.iadd,
    'dec': operator.isub,
    '>': operator.gt,
    '>=': operator.ge,
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne
}

# REGISTERS is a dictionary with names as keys, initialized to 0's
REGISTERS = {char: 0 for char in string.ascii_lowercase}

def apply_value(register, opstring, valstring):
    operator = OPERANDS[opstring]
    value = float(valstring)
    orig = REGISTERS[register]
    REGISTERS[register] = operator(orig, value)

def check_condition(register, teststring, testval):
    check = OPERANDS[teststring]
    value = float(testval)
    existing = REGISTERS[register]
    return check(existing, value)

if __name__ == '__main__':
    filename = sys.argv[-1]
    with open(filename, 'rt') as fileread:
        for directive in fileread:
            tokens = directive.split()  # [3] is always 'if', so ignored
            if check_condition(tokens[4], tokens[5], tokens[6]):
                apply_value(tokens[0], tokens[1], tokens[2])

    max_value = max(REGISTERS.values())
    for name, value in REGISTERS.items():
        if value == max_value:
            print ("highest register:", name, value)

As with many problems in Python, the rich offerings in the standard library often let you get away with just simple functions instead of lots of custom classes.


Stack allocator and C11's alignment features I am trying to write a custom stack allocator for a game I am working on. To deal with memory alignment, I am using C11's stdalign.h header; however, since I do not have prior experience with alignment issues, I'd like a expert opinion on whether I am doing it right.

The majority of the alignment stuff happens in alignup and aligndown macros. Specifically, in alignup, I try to go up to the nearest multiple of alignof(max_align_t) (unless we were already a multiple) by shooting past it by adding alignof(max_align_t) - 1 and then coming back using the bitwise AND. In aligndown, I first go below the last multiple of alignof(max_align_t) and then come up using alignup.

NOTE: The stack is in a memory arena and it grows down in memory instead of going up.

#define alignup(p) ((void*)((((char*)(p)) + (alignof(max_align_t) - 1)) & (~ (alignof(max_align_t) - 1))))

#define aligndown(p) ((void*)(alignup((((char*)(p)) - (alignof(max_align_t) - 1)))))

struct Mem_Stack_Header {
    size_t allocation_size;
    size_t total_size;
};

// This contains the "head" of the stack. The stack grows down, instead of up.
extern void *stack_head;

void* memPush (size_t s)
{
    void *head = stack_head;

    void *mem = (char*)head - s;
    mem = aligndown(mem);

    struct Mem_Stack_Header *h = (struct Mem_Stack_Header*)((char*)mem - sizeof(*h));
    h =  aligndown(h);
    h->allocation_size = s;
    h->total_size = (uintptr_t)((char*)head - (char*)h);

    stack_head = h;

    return mem;
}

void memPop (void)
{
    struct Mem_Stack_Header *h = stack_head;

    stack_head = (char*)stack_head + h->total_size;

    return;
}

Is this the correct way of doing this kind of stuff? Any improvements I can make?

Is this the correct way of doing this kind of stuff? Any improvements I can make?

The role of member allocation_size is unclear.  It appears to represent the  raw alignment with h->allocation_size = s;.  Later use with stack_head = (char*)stack_head + h->total_size; could then result in an unaligned stack_head.  I recommend that void* memPush (size_t s) first take s and increment it as needed to an aligned size and then save that value in  allocation_size.  This will simplify subsequent code too especially the macro aligndown()

s = (s + alignof(max_align_t) - 1) & ~(alignof(max_align_t) - 1u);

There is no protection against pushing too much.  I'd expect the size of memory available with stack_head to be provided and memPush() to code against overflow.  In any case, OP should provide documentation concerning what happens when too much memory is requested.
There is no clear functionality against popping too much.  I'd expect either an error return or a perhaps the equivalent of the top allocation having size 0.
Some compilers will warn about mixed signed/unsigned math.
As the return type from alignof() is some unsigned type, use unsigned constants throughout.

//alignof(max_align_t) - 1
alignof(max_align_t) - 1u

The name stack_head is a global object that could easily collide with other code.  Its name does not suggest that is is part of the memPop(), memPush() functions.  Recommend a name aligned with the funcitons like mem_stack_head.
A use of memPush(0) needs special consideration.  I recommend that such usage returns the same as memPush(alignof(max_align_t)) to provide unique allocations.  In any case, OP should provide documentation concerning the special case.
uintptr_t is an optional type and not the best to use here.  (char*)head - (char*)h results in type ptrdiff_t, simply cast it to the destination type.
Alternative:

//h->total_size = (uintptr_t)((char*)head - (char*)h);
h->total_size = (size_t)((char*)head - (char*)h);

Code could reduce explicit coding of cast (char *) by using char *head = stack_head;
Alternative idea to this line of code:

// struct Mem_Stack_Header *h = (struct Mem_Stack_Header*)((char*)mem - sizeof(*h));
struct Mem_Stack_Header *h = (struct Mem_Stack_Header*)mem - 1;

A simple test harness would help in evaluation of this code.
alignof is not valid without #include <stdalign.h>.  Other include files missing too.


Massive Number Of Scripts With Angular I've recently started switching from JQuery to Angular and it's awesome at making my HTML expressive and easy to read but every reusable module I make has its own script which leads to a massive script loading area. I suppose I could closure compile them or something but is there a better way?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Control Page</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/bootstrap-switch.min.css">
    <link rel="stylesheet" href="assets/css/bootstrap-theme.css">
    <link rel="stylesheet" href="assets/css/navbar.css">
    <link rel="stylesheet" href="assets/css/popup.css">

    <extension-navbar></extension-navbar>

        <status-monitor-area></status-monitor-area>

                    <state-message></state-message>

                    <enable-switch></enable-switch>

            <state-progress-bar></state-progress-bar>

                <review-request></review-request>

For starters, they will take all your files based on a pattern and "compile" them down to a single file - no more adding lots of script references.  That's just the tip of iceberg.

I happen to prefer Gulp.  Take a look at the npm packages for gulp.  For what you're trying to achieve, start with gulp-concat and gulp-livereload.

Follow the instructions here to get you started.

Here's an example that uses a watch to keep an eye on file changes, and, when detected, initiates a 'build' tasks, which will the livereload your page (requires the livereload plugin in chrome/firefox/whatever).

You will then only need a reference to the ./public/js/app.js file in your index.html file.

Note the build task uses two different globs, this is to ensure, in the case of AngularJS, that the module definition file is always the first thing in the concatenated file.

var gulp = require('gulp');
var concat = require('gulp-concat');
var livereload = require('gulp-livereload');

gulp.task('build', function() {
 return gulp.src(['src/**/*.module.js', 'src/**/*.js'])
  .pipe(concat('app.js'))
  .pipe(gulp.dest('./public/js'))
  .pipe(livereload());
});

gulp.task('default', ['build'], function() {
 livereload.listen({
    start: true
  });

  gulp.watch('src/**/*.js', ['build']);
});

Like a said, this is just the tip of the iceberg.  There are tons of examples of very powerful workflows using Gulp and Grunt out there.


Reading input fast in Java for competitive programming I have been solving problems on Timus Online Judge. In the beginning, I didn't worry much about I/O operations, so I just took some code from the internet and focused more on the logic. But after going through the helper class that I was using, I created my own class.

This is the original stuff:

import java.io.InputStream;

public class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() throws Exception {
        if (curChar >= numChars) {
            curChar = 0;
            numChars = stream.read(buf);
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() throws Exception {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString() throws Exception {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    public boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }
}

This is what I have written now:

import java.io.IOException;

public class IOUtils {

    public static String readString() throws Exception {
        int c = System.in.read();
        while (isSpaceChar(c))
            c = System.in.read();
        StringBuilder res = new StringBuilder();
        do {
            res.appendCodePoint(c);
            c = System.in.read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    public static int readInt() throws IOException {
        int i = 0;
        int c = System.in.read();
        while (isSpaceChar(c))
            c = System.in.read();
        int sign = 1;
        if (c == '-') {
            sign = -1;
            c = System.in.read();
        }
        do {
            i = i * 10 + c - '0';
            c = System.in.read();
        } while (!isSpaceChar(c));
        return i * sign;
    }

    public static int readPositiveInt() throws IOException {
        int i = 0;
        int c = System.in.read();
        while (isSpaceChar(c))
            c = System.in.read();
        do {
            i = i * 10 + c - '0';
            c = System.in.read();
        } while (!isSpaceChar(c));
        return i;
    }

    private static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == -1;
    }
}

Is my code any better than the original? Could someone look into it and let me know about the performance and the pitfalls?

In my experience, non-buffered I/O based on plain System.in and System.out are not fast enough for some competitive programming problems. I wrote a template based on BufferedReader and BufferedWriter, which are much faster. They aren't necessary for every problem, but I haven't found any downside to using them by default.

Some example code:

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in);
while (stdin.ready())
    String line = stdin.readLine();

BufferedWriter stdout = new BufferedWriter(new OutputStreamWriter(System.out));
stdout.write("test");
stdout.flush();
stdout.close();

I wrote a couple of blog posts with more details and some benchmark numbers:

Solving UVa 11340 in Java
Why is Java I/O Slow?


Automating the installation and configuration of Vim I am writing a script to automate the install and configuration of vim, zsh, ohmyzsh and tmux, on a Linux/Mac. I'd like to perform all operations in Python, rather than using subprocess to streamline some of the operations (e.g. git clone).

I would also like to use this script as an example to myself of good Python coding practice for file system operations. Code clarity, reuse and pythonic style are my primary objectives. Before I write the remainder of the script I'd like some input on the methods I've chosen for low level operations,  but all areas of the script are open for scrutiny.

from urllib.request import urlretrieve
from urllib.error import URLError
from zipfile import ZipFile
import sys
import os
import errno
import shutil

vim = ".vimtest"
vim_directories = [vim, (vim + "/bundle"), (vim + "/autoload"), (vim + "/colors")]
vim_files = [".vimrctest", vim + "/vimrc"]
flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY

def vim_install():

    # Create directories and files

    for sub in vim_directories:
        try:
            os.mkdir(os.path.expanduser('~/' + sub))
            print("mkkdir " + os.path.expanduser('~/' + sub))
        except OSError as e:
            if e.errno == errno.EEXIST:
                print("Directory " + vim + sub + " already exists.")
                sys.exit(1)
            else:
                raise

    try:
        file_handle = os.open(os.path.expanduser('~/' + vim_files[1]), flags)
    except OSError as e:
        if e.errno == errno.EEXIST:
            print("File " + vim_files[1] + " already exists")
            sys.exit(1)
        else:
            raise
    with os.fdopen(file_handle, 'w') as file_obj:
        file_obj.write("")
    print("Created file " + os.path.expanduser('~/') + vim_files[1])

    try:
        os.symlink(os.path.expanduser('~/') + vim_files[1],
        os.path.expanduser('~/') + vim_files[0])
        print("ln -s " + os.path.expanduser('~/') + vim_files[0] + " -> " +
        os.path.expanduser('~/') + vim_files[1])

    except OSError:
        print("Failed to make symbolic link.")
        print("ln -s " + os.path.expanduser('~/') +
        vim_files[0] + " -> " + os.path.expanduser('~/') +
        vim_files[1])
        sys.exit(1)

    # Download Pathogen, NerdTree, unpack

    try:
        urlretrieve("https://tpo.pe/pathogen.vim",
                        os.path.expanduser('~/' + vim + "/autoload/pathogen.vim"))
        print("Downloaded Pathogen")

        urlretrieve("https://github.com/scrooloose/nerdtree/archive/master.zip",
                        os.path.expanduser('~/' + vim + "/bundle/master.zip"))
        print("Downloaded NerdTree")

    except URLError as e:
        if hasattr(e, 'reason'):
            print('Scrip failed to reach a server.')
            print('Reason: ', e.reason)
        elif hasattr(e, 'code'):
            print('The server couldn\'t fulfill the request.')
            print('Error code: ', e.code)
       else:
            raise

    try:
        zip_ref = ZipFile(os.path.expanduser('~/') + vim +
        "/bundle/master.zip", 'r')
        zip_ref.extractall(os.path.expanduser('~/') + vim + "/bundle/")
        zip_ref.close()
        print("Unziped NerdTree")

    except OSError as e:
        print("Could not unzip: {0}".format(e))

    try:
        os.rename(os.path.expanduser('~/' + vim + "/bundle/nerdtree-master"),
        os.path.expanduser('~/' + vim + "/bundle/nerdtree"))
        print("Renamed " + os.path.expanduser('~/') + vim +
        "/bundle/nerdtree-master \n"
          + os.path.expanduser('~/') + vim + "/bundle/nerdtree")

    except OSError as e:
        print("OS error {0}".format(e))

vim, vim_directories, vim_files and flags seem to be constants, so you should apply the naming conventions on them by capitalizing their names.

Reviewing the very first part of your function code

About the serious things, I would talk for the moment only about the very first part of your code, later I may come back (no promise though):

Within the try block, you should test only the code that is actually prone to raising an exception, nothing else. If you apply this rule, you will end up by coding short try blocks.
What may raise an exception here is rather the attempt to create a directory: os.mkdir(os.path.expanduser('~/' + sub)), the print() would not execute anyway if the attempt fails. If the directory creation succeeds, the else block should take care of the printing task. The try block should be concise and clean
I do not see the necessity of sys.exit(1) here. To be honest, in most cases it is useless, and in your typical case, I do not see how it could be useful, and you already print a message about execution failure.
As a reader of your code, I was curious to know why are you particularly interested errno.EEXIST but not other error codes? I was expecting that you are too meticulous and you decided to track down all the symbols of errno module, but I was mistaken. I think it is fair enough to write this instead:

except OSError as e:
     print('Error code: {}'.format(e.errno))
     print('Error message: {}'.format(e.strerror))

Besides, note that this code:

e.errno == errno.EEXIST:
    print('...')

is the same as:

e.errno == 17:
    print('...')

What I mean here, do you really want to include such fine grain details in a function which is rather more generic/high level?
If for some mysterious reason of your own, you find errno.EEXIST too sexy and attractive, I would still opt for a less brain nagging syntax: FileExistsError instead of errno.EEXIST (note that the later corresponds exactly to FileExistsError but, as you can see, it is more readable)
Given the elements mentioned so far, I would write the very first part of your code as follows:

for sub in vim_directories:
    try:
        os.mkdir(os.path.expanduser('~/' + sub))
    except FileExistsError:
        print("Directory " + vim + sub + " already exists.")
    except OSError as e:
        print('Error code: {}'.format(e.errno))
        print('Error message: {}'.format(e.strerror))
    else:
        print("mkkdir " + os.path.expanduser('~/' + sub))


15 line Rust program, which writes the numbers 1 to N to a file I have this simple Rust program, which creates a file called numbers.txt and writes the numbers 1 to N (N is here 10000000) to it, separated with newlines:

use std::fs::File;
use std::io::Write;

const N: i32 = 1e7 as i32;

fn main() {
    let mut data = String::new();

    for i in 1..=N  {
        data.push_str(&format!("{0}\n", i));
    }

    let mut f = File::create("numbers.txt").expect("Unable to create file");
    f.write_all(data.as_bytes()).expect("Unable to write data");
}

I've been running and timing the program with:

$ time cargo run --release

numbers.txt after running:

1
2
3
4
...
9999999
10000000

I've timed the execution of the program, and it takes around 4.8 seconds to run on my machine. I tried timing just the string building, by commenting out the last two lines, and the time taken stayed pretty much the same. We can conclude that the bottleneck is the data string building and not writing to the file.

How could I make building data faster? Should I use something else than a String?

I improved the performances (and simplicity) like this:

use std::fs::File;
use std::io::Write;
use std::io::BufWriter;

const N: i32 = 1e7 as i32;

fn main() {
    let mut f = BufWriter::new(File::create("numbers.txt").expect("Unable to create file"));
    for i in 1..=N  {
        write!(f, "{0}\n", i);
    }

}

I just don't store the strings in a gigantic buffer but asks the BufWriter to manage the buffering. As a side effect, it's now possible to write bigger files without holding too much RAM.


C# easier ways to filter values in data-grid by month Goal:
My goal is to filter datagrid by selected month from dropdown options.
January, February, March etc...
I'd like to know if there are easier methods to my current method..
Code:
public Schedule()
{
    InitializeComponent();
    RefreshGrid();

    Dictionary<string, string> allOptions = new Dictionary<string, string>();
    allOptions.Add("1", "All");
    allOptions.Add("2", "January");
    allOptions.Add("3", "February");
    allOptions.Add("4", "March");
    allOptions.Add("5", "April");
    allOptions.Add("6", "May");
    allOptions.Add("7", "June");
    allOptions.Add("8", "July");
    allOptions.Add("9", "August");
    allOptions.Add("10", "September");
    allOptions.Add("11", "October");
    allOptions.Add("12", "November");
    allOptions.Add("13", "December");

    Months.DataSource = new BindingSource(allOptions, null);
    Months.DisplayMember = "Value";
    Months.ValueMember = "Key";

}

public void RefreshGrid()
{
    string value = "";

    // Select All
    if(Months.SelectedIndex == 0)
    {
        value = "";
    }
    // Select * from January
    if(Months.SelectedIndex == 1)
    {
        value = " where month(date_purchased) = 1;";
    }
    // Select * from February
    if (Months.SelectedIndex == 2)
    {
        value = " where month(date_purchased) = 2;";
    }
    //... and son on...

    // MySQL connection string
    using (var conn = new MySqlConnection(ConnectionString.ConnString))
    {
        //Select query
        using (var mySqlDataAdapter = new MySqlDataAdapter("select * from table "+ value +";", conn))
        {
            using (var dataSet = new DataSet())
            {
                DataSet DS = new DataSet();
                mySqlDataAdapter.Fill(DS);

                //Assign headers to Data Grid View
                scheduleData.DataSource = DS.Tables[0];
                scheduleData.Columns[0].HeaderText = "ID";
                scheduleData.Columns[1].HeaderText = "Equipment Name";
                scheduleData.Columns[2].HeaderText = "Date Purchased";

                //Set visibility to false for the columns to work in the background
                scheduleData.Columns[0].Visible = false;
            }
        }
    }
}

private void Months_SelectedIndexChanged(object sender, EventArgs e)
{
    RefreshGrid();
}

This idea does work - but Seems like there is too much unnecessarily code. But I cannot think of an alternative.

Why not something simple like this:
var filter = Months.SelectedIndex == 0 ? null :
    $" where month(date_purchased) = {Months.SelectedIndex};"

Also that dictionary initialization code is a lot of copy & paste, you could easily write it like this:
var allOptions = new Dictionary<string, string>()
{
    ["0"] = "All"
};

int idx = 1;
foreach(var month in DateTimeFormatInfo.CurrentInfo.MonthNames)
    allOptions.Add((idx++).ToString(), month);

Edit: also don't use data sets if you're only returning one data table, use the table versions of the database API instead.


Test if Excel is open without relying on catching an error Getting a hook on an open instance of Excel is something I do all the time. I'm now questioning if I'm doing this the best way. I'm particularly concerned with the fact that I rely on the GetObject method to throw an error. I'd like to avoid it if possible.

I have a Utils module that contains a function that returns a brand new instance of excel and one that tries to get an open instance of excel. When I encounter Err.Number 429 in the GetExcelApp function, I call the CreateExcelApp function. Something I've done routinely for years suddenly feels dirty. There has to be a better way to do this.

Public Function GetExcelApp() As Excel.Application
' Returns open excel instance.
'   If it doesn't exist, creates one to return
On Error GoTo ErrHandler
Const ERR_APP_NOTRUNNING As Long = 429

    Set GetExcelApp = GetObject(, "Excel.Application")

CleanExit:
    Exit Function
ErrHandler:
    If Err.number = ERR_APP_NOTRUNNING Then
        Set GetExcelApp = CreateExcelApp
    Else
        ShowErrorMessageBox
    End If
End Function

Private Function CreateExcelApp() As Excel.Application
' Returns New instance of Excel
On Error GoTo ErrHandler

    Set CreateExcelApp = CreateObject("Excel.Application")

CleanExit:
    Exit Function
ErrHandler:
    ShowErrorMessageBox
End Function

Private Sub ShowErrorMessageBox()
    ErrHandler.messageBox "Utils", "GetExcelApp", vbCritical, "Unable to get an instance of Excel."
End Sub

This code does also rely on this subroutine in an external module named ErrHandler.

Public Sub messageBox(moduleName As String, procName As String, Optional style As VbMsgBoxStyle = vbCritical, Optional OptionalText As String = vbNullString)
    Dim messageText As String
    messageText = "Module: " & moduleName & vbCrLf & _
                "Procedure: " & procName & vbCrLf & _
                Err.Description

    If Not OptionalText = vbNullString Then
        messageText = messageText & vbCrLf & OptionalText
    End If

    MsgBox messageText, style, "Runtime Error: " & Err.number

End Sub

And here is a quick example of how the GetExcelApp function is used.

Public Sub Test()
    Dim xl As Excel.Application
    Set xl = GetExcelApp
    xl.Visible = True
End Sub

I also read the MSDN documentation, but they're using On Error Resume Next... That's not even remotely acceptable.

As was pointed out in chat earlier, a module called Utils might as well be called Helpers or DumpAnythingYouWantHere.

You should prefer using vbNewLine over vbCrLf: vbNewLine will produce a platform-specific new line, while code that uses vbCrLf might only produce correct results under Windows, which means your comment about it being platform-independent is a false assumption.

I get the GetObject(, "Excel.Application") call to tap into the current instance (what happens when there are 2 or more instances already opened?), but the CreateExcelApp function could be much, much more straightforward than this:

Private Function CreateExcelApp() As Excel.Application
' Returns New instance of Excel
On Error GoTo ErrHandler

    Set CreateExcelApp = CreateObject("Excel.Application")

CleanExit:
    Exit Function
ErrHandler:
    ShowErrorMessageBox
End Function

Consider:

Private Function CreateExcelApp() As Excel.Application
    Set CreateExcelApp = New Excel.Application
End Function

At which point I'd question the need for this CreateExcelApp function! Why not simply handle that in GetExcelApp? Like the comments say, if it doesn't exist, creates one to return:

Public Function GetExcelApp() As Excel.Application
' Returns open excel instance.
'   If it doesn't exist, creates one to return
On Error GoTo ErrHandler
Const ERR_APP_NOTRUNNING As Long = 429

    Set GetExcelApp = GetObject(, "Excel.Application")

CleanExit:
    Exit Function
ErrHandler:
    If Err.number = ERR_APP_NOTRUNNING Then
        Set GetExcelApp = New Excel.Application
        Resume CleanExit
    Else
        ShowErrorMessageBox
    End If
End Function

I don't like ShowErrorMessageBox. It's Private and single-use, with a hard-coded message that's only relevant for an error occurring in GetExcelApp. I'd get rid of that method.


Inserting data in the database through POST My code here is completely working, but I feel like I destroyed or didn't follow the DRY rule, what suggestions can you give to me for this code??

<?php require_once("./includes/Utilities.php") ;?>
<?php require_once("./includes/Db_Resources/db_connection.php");?>
<?php require_once("./includes/Db/DatabaseUtilities.php"); ?>
<?php
    if(isset($_POST['submit'])){
        require_once("./includes/process_form.inc.php");
        require_once('./includes/Db/CheckPassword.php');
        require_once('./includes/Db/CheckUsername.php');
        $check_pwd = new Db_CheckPassword($password);
        $check_user = new Db_CheckUsername($username,$conn);
        $passwordOK = $check_pwd->check();//Checks if Password is valid
        $userOK = $check_user->check();//Checks if Username is valid
        //Checks if Password is the same with the retyped password
        $password_match = Db_CheckPassword::confirmPassword($password,$conf_pass);

        //if everything is okay! we'll finally add the muthafucking users account
        if($userOK && $passwordOK && $password_match){

            if(Db_DatabaseUtilities::registerAccount($conn,$username,$password,$email)){
                header("Location: login.php");
                exit;
            }

        }else{
            $pass_error =  $check_pwd -> getErrors();
            $user_error  = $check_user->getErrors();
        }
    }
?>

Here are some things that I would recommend:

PHP tags. There's no point in closing and reopening PHP tags if there is no non-PHP code in between. For this file, a single opening PHP tag is all you need for the entire thing. Closing PHP tags (anywhere in the file) can bring potential issues such as unnoticed white space, which will throw errors if you try to use header() or similar later on.
header() - When using header('Location: xxxxx');, you should use a full URL, not a relative URL, since it is making an HTTP request. Sure, it probably works most of the time, but let's follow the spec and not take chances.
isset($_POST['submit']) - Some versions of Internet Explorer (not sure when this was fixed) will ignore the name/value of the submit button if it is being used as an image (example: <input type="image" src="login.png" name="submit" value="Login" />). I would check for a different form element (or even the $_POST array itself) to eliminate that potential bug.
Required files - Since I don't know how the rest of your application is structured, this one is more speculation. But if you find yourself repeating these required lines often in different files, you should consider consolidating the require_once() lines to a single appropriate file. For instance, all of your database connections can be done in once place. All of the form validation files can be consolidated, also. This leaves you with only needing to do a single require_once() in your app's files, and only needing to maintain and update a single file elsewhere if you want to change or add functionality.
registerAccount() failure? - You perform a redirect if the registerAccount() method is successful, but don't do anything if it fails. Always have an action for when things fail, because they probably will at some point. Logging error messages, even sending yourself an email when it happens is a good way to notice a major error quickly in the event that it happens.

This one is more personal preference, but might be worth it to you:

I would rename the check() method in your user and password classes to isValid(), since that's what you're specifically looking for (even says so in the comments). I always try to name methods based on context. You could even use the methods directly in your if statement - no real point in assigning those variables, since you only use them once and they don't really save much typing later on.

I hope that helps. :)


Python Prime Testing This code seems surprisingly fast at checking if a number is prime.

def is_prime(number: int) -> bool:
    """Checks if a number is prime or not"""
    # number must be integer
    if type(number) != int:
        raise TypeError("Non-integers cannot be tested for primality.")
    # negatives aren't prime, 0 and 1 aren't prime either
    if number <= 1:
        return False
    # 2 and 3 are prime
    elif number <= 3:
        return True
    # multiples of 2 and 3 aren't prime
    elif number % 2 == 0 or number % 3 == 0:
        return False
    # only need to check if divisible by potential prime numbers
    # all prime numbers are of form 6k +/- 1
    # only need to check up to square root of number
    for i in range(5, int(number**0.5) + 1, 6):
        if number % i == 0 or number % (i + 2) == 0:
            return False

    return True

However, is there any way to speed this prime testing up?

Congratulations, you just came up with a prime sieve! And indeed, it's faster than always considering all the multiples of 2 of 3. But why do you stop at multiples of 2 and 3? What about 5? And 7? But why stop somewhere?

Let's be more ambitious. What about skipping all the multiples of all the primes encountered so far? This is called the sieve of Eratosthenes. It uses more memory (if you double the maximum number you're interested in, you need twice the memory), but it will be faster and will tell you if any number below your maximum number is prime.

If you want more improvements, note that other prime sieves exist: both the sieve of Sundaram and the sieve of Atkin improve over the sieve of Eratosthenes. And of course, if you're interested in raw speed, use numpy or even a language like C.


List of previous and upcoming months to a given date (year and month) I need a menu with buttons of months previous and after a given month,
something like this:

| month | month | month | current month | month | month | month |

Can this function further be improved?

/**
* Generates array of months previous and after given date
* @param $p_base_data       - array of base year and months,
         if not provided current date is used ['year'=>false, 'month'=>0]
* @param $p_nr_prev_months - number of previous mounts to calculate
* @param $p_nr_post_months - number of upcoming mounts to calculate
* @return populated array
*/

function buildListOfMonths( array $p_base_date = ['year'=>false, 'month'=>0],
                            int $p_nr_prev_months = 5,
                            int $p_nr_post_months = 6) : array
{
    // init var
    $months_list    = [];
    // setting base year and date if parameter not passed
    $base_year  = $p_base_date['year'] ? $p_base_date['year'] : date('Y');
    $base_month     = $p_base_date['month'] > 0
        ? (int)$p_base_date['month']
        : date('n');

    // looping through prev to post number of months
    for ($i = -$p_nr_prev_months; $i <= $p_nr_post_months; $i++) {
        // creating date object of actual date
        $date_obj       = strtotime(date($base_year.'-'.$base_month.'-01')." +$i months");
        // building array of months
        $months_list[]  = [ 'year'       => date('Y', $date_obj),
                               'nr_month'   => date('n', $date_obj),
                               'month_name' => date("M", $date_obj),
                               'current'    => (date('n', $date_obj) == $base_month) ? true : false ];
    } // end for

    return $months_list;
} // end func.

Be aware that in some scenarios, strtotime() may have a limitation.  Furthermore using property DateTime objects will provide greater utility if you decide to extend functionality in the future.

This task is well-suited for DatePeriod.  It will serve you up a collection of date objects that you can format however you wish.

Code: (Demo)

function rangeOfMonths($prior, $ahead, $baseYear = null, $baseMonth = null) {
    $baseYear = $baseYear ?: date('Y');
    $baseMonth = $baseMonth ?: date('m');

    $rangeStart = new DateTime($baseYear . '-' . $baseMonth . '-01 23:59:59');
    $rangeEnd = clone($rangeStart);

    $rangeStart->modify("-{$prior} month");
    $rangeEnd->modify("+{$ahead} month +1 day");

    $period = new DatePeriod($rangeStart, new DateInterval('P1M'), $rangeEnd);
    $monthsList = [];
    foreach ($period as $i => $dateObject) {
        $monthsList[] = [
            'year'       => $dateObject->format('Y'),
            'nr_month'   => $dateObject->format('n'),
            'month_name' => $dateObject->format('M'),
            'current'    => $i == $prior
        ];
    }
    return $monthsList;
}

var_export(rangeOfMonths(5, 6));

Instead of bloating the function declaration syntax with an array type argument which has two elements (with potentially falsey / non-date-oriented values), write these optional values as individually served arguments and write them as the final arguments.  This will allow you to call this function without needing to pass the array structure.  If your incoming data is already an indexed array with upto two elements, just ... (splat operator) the array when calling the function.
Either way, using any falsey default values will benefit your script by allowing you to leverage the brief ?: (elvis operator).

+1 day is to make the date range inclusive of the final month.

*Timezone impact was not included in my review, you may want to investigate fringe cases and set the timezone per your application's requirements.


Splitting a list in Racket I am working my way into learning a bit of Scheme (actually, Racket) with the help of a few practical problems to solve. In this case, I want to split a flat list of symbols at a certain delimiter symbol, discarding it and returning the list of split chunks.

#! /usr/bin/racket

#lang racket

(define (split lst del)
    (define (split-one lst)
        (if (or (empty? lst) (equal? (car lst) del))
            '()
            (cons (car lst) (split-one (cdr lst)))))
    (let loop ((next lst))
        (if (empty? next)
            '()
            (let ((cur (split-one next)))
                (cons
                    cur
                    (loop (let ((nextpos (+ 1 (length cur))))
                        (if (< nextpos (length next))
                            (list-tail next nextpos)
                            '()))))))))

(split '(a b c x d x e x f) 'x) ; '((a b c) (d) (e) (f))
(split '(0 1 2 0 2 0 3 0) 0) ; '(() (1 2) (2) (3))

It does work, but I feel it's not the best way to accomplish the task, for a couple of reasons:

The (loop (let (... part seems a bit clunky, maybe even unnecessary.
The (list-tail ... clause entails rescanning the list for nextpos elements, which obviously is not optimal. In Python, I would have split-one return the current chunk and a reference to the head of the following, i.e. the cdr of the last element considered, and keep iterating from that. Here I'm uncertain at what to do.

In addition to that, I've start using the (if (cond) '() (...)) pattern quite a lot for recurring, so I would be grateful if any seasoned LISPer could comment on how much this is idiomatic and if there are better ways of expressing the same.

Also, the whole point of this exercise is learning, so please don't tell me I should use string-split or regex-split or the like. I am aware of their existence.

tl;dr: See the bottom of the post for my implementation of the function.

As mentioned in Ben Rudgers's answer, lists should not be treated as vectors, as they are not random-access. That means you should not be using numeric indices, list lengths, etc.

Lists are recursive data structures

Lists are recursive data structures: a list is either an empty list, or else it's a non-empty list which conceptually has a first element and a rest of the list. For example:

() is an empty list
(1) is a non-empty list with a first of 1 and a rest of ()
(1 2) is a non-empty list with a first of 1 and a rest of (2)

To perform an operation across all elements of a list, you make use of this recursive structure:

You check whether the list is empty. If so, do the base case.
Otherwise, do something with the first element, then call the same function with the rest of the list. This is the recursive case.

Examples of list-processing functions

Here's a simple example, that calculates the sum of a list of numbers:

(define (sum lst)
  (if (empty? lst)
      0
      (+ (first lst) (sum (rest lst)))))

Base case: if the list is empty, the sum is 0.
Recursive case: if the list is not empty, the sum is the first element plus the sum of the rest of the list. (Recursive case.)

Another example. Suppose you want to write a function that takes a list of numbers, and returns the square of all of the numbers:

(define (square-all lst)
  (if (empty? lst)
      empty
      (cons (expt (first lst) 2) (square-all (rest lst)))))

Base case: If the list is empty, return an empty list.
Recursive case: If the list is not empty, return a new list where:

the first element of the new list is the square of the first element of the old list, and
the rest of the new list is the "square of all the numbers" of the rest of the old list.

As a third example, consider a function where you want to take a list and return all the elements that are numbers:

(define (only-numbers lst)
  (if (empty? lst)
      empty
      (if (number? (first lst))
          (cons (first lst) (only-numbers (rest lst)))
          (only-numbers (rest lst)))))

Base case: If the list is empty, return an empty list.
Recursive case: If the list is not empty, then:

If the first element of the old list is a number, return a new list where:

the first element of the new list is the first element of the old list, and
the rest of the new list is only the numbers from the rest of the old list.

If the first element of the old list is not a number, discard it and return only the numbers from the rest of the old list.

Generalising the above examples

Do you see a pattern? You always check the list for empty, and handle the base case if so, and otherwise handle the first element along with calling itself with the rest of the list. In fact, all three of the functions above fit this pattern:

(define (FUNCTION lst)
  (if (empty? lst)
      BASE-CASE
      (SOMETHING (first lst) (FUNCTION (rest lst)))))

This pattern is called a right-fold, or foldr as it's called in Racket. All three of the functions above can be written using foldr (I use the parameter name next to refer to the result of the recursive call, (FUNCTION (rest lst))):

(define (sum lst)
  (foldr (lambda (element next)
           (+ element next))
         0 lst))

(define (square-all lst)
  (foldr (lambda (element next)
           (cons (expt element 2) next))
         empty lst))

(define (only-numbers lst)
  (foldr (lambda (element next)
           (if (number? element)
               (cons element next)
               next))
         empty lst))

This pattern can be used whenever you are writing a function that processes all the elements of a list, one by one. Usually, you would use the element's value to compute the result, but it's not always necessary; for example, you can implement length like this:

(define (length lst)
  (foldr (lambda (element next)
           (+ next 1))
         0 lst))

Putting all this together

All the above is a very roundabout way to say that the splitting function you're trying to write is also a right-fold operation. It looks like this:

(define (split-by lst x)
  (foldr (lambda (element next)
           (if (eqv? element x)
               (cons empty next)
               (cons (cons element (first next)) (rest next))))
         (list empty) lst))

Let's break this down:

Base case: If the incoming list is empty, return a list with an empty sublist inside.
Recursive case: If the incoming list is not empty, consider the first element:

If that element is equivalent (eqv?) to the splitter, then prepend an empty sublist to the next result.
Otherwise, prepend the element to the frontmost sublist of the next result.

The code is quite dense, but I intentionally wrote it the way a seasoned Schemer would write it (except that it's more common to write car, cdr, null?, and '() instead of first, rest, empty?, and empty). It may take you a while to unpack all this information, if you're new to Scheme. Please feel free to ask for any clarifications.


Parse data from Input file and print results I have written a script which does parsing to the input file and take out some values from them with respect to the node and print the data accordingly.
Below is my script, and it works as expected:
#!/usr/bin/perl

use strict;
use warnings;

use Time::Local 'timelocal';
use List::Util qw(reduce);
use POSIX qw( strftime );

my $i = 0;

print "*"x20; print "\n";

while(<DATA>){
    chomp;

    next unless ($_);

    my @data = split / /, $_;

    $i++;
    my ($node, $time, $date, $time1, $unit);
    my %hash;
    if (scalar @data == 3){
        if( $data[0] =~ /FileName=([^_]+(?=_))_(\S+)_file.csv:(\S+),/gm ){
            ($node, $time, $unit) = ($2, $1, $3);
            if( $time =~ /[a-zA-Z](\d+).(\d+)/gm ){
                $date = $1; $time1 = $2;
            }
        }
        print "Node_$i:$node\n";
        my $datetime = $date.$time1;
        my ($second,$minute,$hour,$day,$month,$year);
        my $unix_time;

       if ($datetime =~ /(....)(..)(..)(..)(..)/){
            ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);
            $unix_time = timelocal($second,$minute,$hour,$day,$month-1,$year);
        }
       my @vol = split /,/, $data[2];
       foreach my $element (@vol){
            $hash{$unix_time} = $element;
            $unix_time += 6;
        }

        my $key = reduce { $hash{$a} <= $hash{$b} ? $a : $b } keys %hash;
        my $val = $hash{$key};

        my $dt = strftime("%Y-%m-%d %H:%M:%S", localtime($key));

        print "Text_$i:First occured on $dt on the Unit:$unit and the value is $val\n";
    }
}
print "*"x20; print "\n";
print "TotalCount=$i\n";

__DATA__
Node=01:FileName=A20200804.1815+0530-1816+0530_Network=NODE01_file.csv:Unit=R1,Meter=1 Vol 19,12,17,20,23,15,16,11,13,17
Node=02:FileName=A20200804.1830+0530-1831+0530_Network=NODE02_file.csv:Unit=R5,Meter=3 Vol 12,13,15,16,10,15,15,13,14,11

So, here we have 2 lines of data in input file which is giving output something like below:
********************
Node_1:Network=NODE01
Text_1:First occured on 2020-08-04 18:15:42 on the Unit:Unit=R1 and the value is 11
Node_2:Network=NODE02
Text_2:First occured on 2020-08-04 18:30:24 on the Unit:Unit=R5 and the value is 10
********************
TotalCount=2

So, logic in parser is each line data belongs to each node (node will be unique in the input file). Here you can see the Volume data which is generated based on the time. For example, NODE01 volume data it shows for 18:15 to 18:16 (10 volume values, that means each value is been generated in 6secs interval and its fixed through out all the node volume data).
From the list of volumes I should take the least number and its respective time with seconds. I am able to fetch as per the logic explained.
Here I need experts feedback on regex (which I am using) also there are couple of if conditions which looks really odd to me.
Is there any possiblity to simply the script?

The code looks fine and it is working for the given input
data. However, it can be difficult to
assess which inputs will be regarded as valid, and how it will behave
in case of unexpected input. One approach to uncertainty about code
(will it work?) is to let it pass through a testing framework. This
requires splitting your code into smaller units that can easily be
tested.
At the end of this post, I will present an example of how the code can
be adapted to a testing framework, but before that there are some
minor issues I would like to mention.
Unecessary g and m flag
Consider this line:
if( $data[0] =~ /FileName=([^_]+(?=_))_(\S+)_file.csv:(\S+),/gm ){

Since the code is only processing a single line at a time and there is only one
node on each line, global matching is not necessary. Also the m is
not needed. It allows ^ and $ to match internal the start and end of
internal lines for a multiline string.
Unnecessary use of lookahead regex
Consider this line:
if( $data[0] =~ /FileName=([^_]+(?=_))_(\S+)_file.csv:(\S+),/gm ){

First, as commented above we can remove the g and m flags. Then
/[^_]+(?=_)_/

is simpler written as
/[^_]+_/

Make code easier to read
This code:
($node, $time, $unit) = ($2, $1, $3);

is easier to read (my opinion) if written as:
($time, $node, $unit) = ($1, $2, $3);

such that the capture variables are sorted in numerical order. Similar
for this line:
my ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);

it can be written as:
my ($year, $month, $day, $hour, $minute, $second ) = ( $1, $2, $3, $4, $5, 0);

Shebang
See this blog for more information.
I usually use #!/usr/bin/env perl instead of #!/usr/bin/perl.
Most systems have /usr/bin/env, and it allows your script to run if you e.g.have multiple perls on your system. For example if you are using perlbrew.
say vs print
I prefer to use say instead of print to avoid typing a final
newline character for print statements.
The say function was introduced in
perl 5.10, and is mad available by adding use v5.10 or use use feature qw(say) to the top of your script.
Declare variable as close to their definition as possible
By declaring variable in the same scope as they are used and as close
the their first usage point as possible will help a reader to quickly
reason about the code, which will help producing correct code. For example,
in this code
my ($second,$minute,$hour,$day,$month,$year);
if ($datetime =~ /(....)(..)(..)(..)(..)/){
    ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);

the variables are only used within the if clause, so we can write it as:
if ($datetime =~ /(....)(..)(..)(..)(..)/){
    my ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);

Easier parsing of dates using Time::Piece
In the program below, I show how you can use Time::Piece instead of
timelocal to simplify the parsing of dates.
Example code with unit tests
Main script p.pl:
 #! /usr/bin/env perl

package Main;
use feature qw(say);
use strict;
use warnings;

use Carp;
use Data::Dumper qw(Dumper);

# Written as a modulino: See Chapter 17 in "Mastering Perl". Executes main() if
#   run as script, otherwise, if the file is imported from the test scripts,
#   main() is not run.
main() unless caller;

sub main {
    my $self = Main->new();
    $self->run_program();
}

# ---------------------------------------------
# Methods and subroutines in alphabetical order
# ---------------------------------------------

sub bad_arguments { die "Bad arguments\n" }

sub init_process_line {
    my ( $self ) = @_;

    $self->{lineno} = 1;
}

sub new {
    my ( $class, %args ) = @_;

    my $self = bless \%args, $class;
}

sub process_line {
    my ($self, $line) = @_;

    my $proc = ProcessLine->new( $line, $self->{lineno} );
    $self->{lineno}++;
    return $proc->process();
}

sub read_data {
    my ( $self ) = @_;

    # TODO: Read the data from file instead!
    my $data = [
'Node=01:FileName=A20200804.1815+0530-1816+0530_Network=NODE01_file.csv:Unit=R1,Meter=1 Vol 19,12,17,20,23,15,16,11,13,17',
'Node=02:FileName=A20200804.1830+0530-1831+0530_Network=NODE02_file.csv:Unit=R5,Meter=3 Vol 12,13,15,16,10,15,15,13,14,11'
   ];

    $self->{data} = $data;
}

sub run_program {
    my ( $self ) = @_;
    $self->read_data();
    $self->init_process_line();
    for my $line ( @{$self->{data}} ) {
        my ($node, $dt, $unit, $val) = $self->process_line($line);
        my $res = {
            node => $node,
            dt   => $dt,
            unit => $unit,
            val  => $val,
        };
        # TODO: write the data to STDOUT or to file in correct format
        print Dumper($res);
    }
}

package ProcessLine;
use feature qw(say);
use strict;
use warnings;

use Carp;
use POSIX qw( strftime );
use Time::Piece;

sub convert_date_to_epoch {
    my ( $self,  $date ) = @_;

    my $unix_time = Time::Piece->strptime( $date, "%Y%m%d.%H%M%z" )->epoch();
    return $unix_time;
}

# INPUT:
#  - $time_piece : initialized Time::Piece object
#
#
sub convert_epoch_to_date {
    my ( $self,  $time_piece ) = @_;

    my $dt = $time_piece->strftime("%Y-%m-%d %H:%M:%S");

    return $dt;
}

sub get_volumes {
    my ( $self,  $data ) = @_;

    $self->parse_error("No volumes") if !defined $data;
    my @vols = split /,/, $data;
    $self->parse_error("No volumes") if @vols == 0;
    for my $vol ( @vols ) {
        if ( $vol !~ /^\d+$/ ) {
            $self->parse_error("Volume not positive integer");
        }
    }
    return \@vols;
}

# INPUT:
#  - $volumes : list of volumes (integers).
#
# RETURNS: - index of smallest item (if there are multiple minimal, the index of
#  the first is returned.
#
# ASSUMES:
#  - Length of list >= 1
#  - Each item is a positive integer.
#  - NOTE: The items do not need to be unique.
#
sub find_min_vol {
    my ( $self, $volumes) = @_;

    my $min = $volumes->[0];
    my $idx = 0;
    for my $i (1..$#$volumes) {
        my $value = $volumes->[$i];
        if ( $value < $min) {
            $min = $value;
            $idx = $i;
        }
    }
    return $idx;
}

sub new {
    my ( $class, $line, $lineno ) = @_;

    my $self = bless {line => $line, lineno => $lineno}, $class;
}

sub parse_error {
    my ( $self, $msg ) = @_;

    croak ( sprintf( "Line %d: %s : '%s'\n", $self->{lineno}, $msg,
                 $self->{line} // "[undef]" ) );
}

sub process {
    my ($self) = @_;

    my $line = $self->{line};
    chomp $line;
    $self->parse_error("Empty line") if !$line;

    my ($field1, $field3) = $self->split_line( $line );
    my $date = $field1->get_date();
    my $node = $field1->get_node();
    my $unit = $field1->get_unit();
    my $unix_time = $self->convert_date_to_epoch( $date );
    my $volumes = $self->get_volumes( $field3 );
    my $idx = $self->find_min_vol($volumes);
    my $vol = $volumes->[$idx];
    my $vol_epoch = $unix_time + $idx*6;
    my $time_piece = localtime($vol_epoch);  # convert to local time zone
    my $dt = $self->convert_epoch_to_date( $time_piece );
    return ($node, $dt, $unit, $vol);
}

# INPUT:
#  - $line: defined string
#
sub split_line {
    my ( $self, $line ) = @_;

    my @data = split / /, $line;
    my $N = scalar @data;
    $self->parse_error( "Expected 3 fields (space-separated). Got $N fields.") if $N !=3;
    return (Field0->new($self, $data[0]), $data[2]);
}

package Field0;
use feature qw(say);
use strict;
use warnings;

sub get_date {
    my ( $self ) = @_;
    my $data = $self->{data};
    my $date;
    if( $data =~ s/FileName=([^_]+)_// ) {
        my $time = $1;
        if( $time =~ /[a-zA-Z](\d{8}\.\d{4}[+-]\d{4})-\d{4}[+-]/ ) {
            $date = $1;
        }
        else {
            $self->{parent}->parse_error("Could not parse time info");
        }
    }
    else {
        $self->{parent}->parse_error("Could not parse time info");
    }
    $self->{data} = $data;
    return $date;
}

sub get_node {
    my ( $self ) = @_;
    my $data = $self->{data};
    my $node;
    if( $data =~ s/(\S+)_// ) {
        $node = $1;
    }
    else {
        $self->{parent}->parse_error("Could not parse node info");
    }
    $self->{data} = $data;
    return $node;
}

sub get_unit {
    my ( $self ) = @_;
    my $data = $self->{data};
    my $unit;
    if( $data =~ s/file\.csv:(\S+),// ) {
        $unit = $1;
    }
    else {
        $self->{parent}->parse_error("Could not parse unit info");
    }
    $self->{data} = $data;
    return $unit;
}

sub new {
    my ( $class, $parent, $data ) = @_;
    return bless {parent => $parent, data => $data}, $class;
}

Unit test script t/main.t:
use strict;
use warnings;
use Test2::Tools::Basic qw(diag done_testing note ok);
use Test2::Tools::Compare qw(is like);
use Test2::Tools::Exception qw(dies lives);
use Test2::Tools::Subtest qw(subtest_buffered);
use lib '.';
require "p.pl";

{
    subtest_buffered "split line" => \&split_line;
    subtest_buffered "get_date" => \&get_date;
    subtest_buffered "get_node" => \&get_node;
    # TODO: Complete the test suite..
    done_testing;
}

sub get_date {
    my $proc = ProcessLine->new( "", 1 );
    my $fld = Field0->new($proc, "Node=01:FileName=A20200804.1815+0530-1816+0530_N");
    is($fld->get_date(), '20200804.1815+0530', 'correct');
    $fld = Field0->new($proc, "ileName=A20200804.1815+0530-1816+0530_N");
    like(dies { $fld->get_date() }, qr/Could not parse/, "bad input");
    $fld = Field0->new($proc, "FileName=A20200804.1815-1816+0530_N");
    like(dies { $fld->get_date() }, qr/Could not parse/, "bad input2");
}

sub get_node {
    my $proc = ProcessLine->new( "", 1 );
    my $fld = Field0->new($proc, "Node=01:FileName=A20200804.1815+0530-1816+0530_N");
    # TODO: complete this sub test..
}

sub split_line {
    my $proc = ProcessLine->new( "", 1 );
    like(dies { $proc->split_line( "" ) }, qr/Got 0 fields/, "zero fields");
    like(dies { $proc->split_line( " " ) }, qr/Got 0 fields/, "zero fields");
    like(dies { $proc->split_line( "1" ) }, qr/Got 1 fields/, "one field");
    like(dies { $proc->split_line( "1 2" ) }, qr/Got 2 fields/, "two fields");
    my ($f1, $f3);
    ok(lives { ($f1, $f3) = $proc->split_line( "1 2 3" ) }, "three fields");
    is($f1->{data}, "1", "correct value");
    is($f3, "3", "correct value");
}


Removing elements on a List while iterating through it I needed a way to remove elements on a List while iterating through it.

Supposedly something like this (illegal code):

List<Integer> nums = new ArrayList();
nums.add(1);
nums.add(2);
nums.add(3);
...
nums.add(10);

System.out.println("BEFORE REMOVE: " + nums);

for (Integer integer : nums) {
    if (integer < 3) {
        //not allowed
        nums.remove(integer);
    }
}

But we all know that the above code is not allowed.

So what I'm doing right now is that I create another List, where I'm putting every element that meets a given condition, then iterate through that List to get the elements that I need to remove on the first List.

List<Integer> toRemove = new ArrayList();
for (Integer integer : nums) {
    if (integer < 3) {
        toRemove.add(integer);
    }
}

for (Integer integer : toRemove) {
    nums.remove(integer);
}

System.out.println("AFTER REMOVE: " + nums);

I know it's not really long, but is there a better way to do this?

Is there some API that I can use?

There are several ways to do this. Let's look at the alternatives:

Iterating over a copy, removing from original

This is a simple solution for the underlying problem of your first code: A ConcurrentModificationException is thrown because you iterate through the list and removing from it at the same time.

Easy solution is to create a copy of the list and iterate through that.

for (Integer integer : new ArrayList<>(nums)) {
    if (integer < 3) {
        nums.remove(integer);
    }
}

Down-sides of this approach:

Creates a copy of the original list, which requires memory and an operation which performance depends on the type of the list (ArrayList, LinkedList, etc.)
Additionally, nums.remove(value) is a \$O(n)\$ operation. Making this loop overall \$O(n^2)\$

Java 8 Streams

List<Integer> filteredList = nums.stream().filter(i -> i >= 3).collect(Collectors.toList());

Down-sides:

Does not actually modify the existing list, so if references to the list are spread around various variables, you still have some old elements that just shouldn't be in that list.
Creates various stream-related objects which might not be the most effective option.

On the up-side, this is among the fastest for bigger lists.

If you're not using Java 8:

List<Object> originalList;
List<Object> newList = new YourFavoriteListType<>();
for (Object obj : originalList) {
    if (shouldKeep(obj)) {
        newList.add(obj);
    }
}

Java 8 method

nums.removeIf(i -> i < 3);

Java 8 introduced the default method removeIf on the Collection interface. This allows different implementations to have implementation-specific performance-optimized implementations of this method.

Iterator.remove()

Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
    Integer integer = it.next();
    if (integer < 3) {
        it.remove();
    }
}

The only down-side of this approach is that you need to switch your for-each to a while. However, this approach is the most efficient one, especially for LinkedList where it is \$O(n)\$ (it's \$O(n^2)\$ for ArrayList because it has to copy array data on each remove(index) call). This is the approach I would recommend in most cases.

Note: Instead of using a while-loop it can also be written as:

for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
    Integer integer = it.next();
    ...

Conclusion

If you want to mutate the existing list, removeIf is the solution I would go with. If you like functional programming and prefer a new list instead of mutating the existing one, then go with the list.stream().filter(...).collect(Collectors.toList()) approach.

See also

"When to use LinkedList over ArrayList?" on Stack Overflow


Calculator for any number of inputs The "nasty implementation" I mentioned is within the void calculator() inside of calculator.cpp. Everything goes well as long as user don't type in the erroneous syntax. But I think this isn't the good idea to implement it this way.
Can I do it the other way around with more reasonable implementation without losing the functionality of being able to calculate infinitely(not really,I know).

main.cpp:

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

int main()
{
    calculator();
    return 0;
}

calculator.cpp:

#include <iostream>
#include <cassert>
#include "calculator.h"

int getIntInput()
{
    int x{};
    std::cin >> x;
    assert("Syntax Error!!" && !std::cin.fail());
    return x;
}

char getOperatorInput()
{
    char x{};
    std::cin >> x;
    bool b{x == '+' || x == '-' || x == '*' || x == '/' || x == '^'};
    assert("Syntax Error!!" && b);
    return x;
}

int calculate(int x)
{
    char op{getOperatorInput()};
    int tmp{getIntInput()};
    if(op == '+')
    {
        return x + tmp;
    }
    else if(op == '-')
    {
        return x - tmp;
    }
    else if(op == '*')
    {
        return x * tmp;
    }
    else if(op == '/')
    {
        return x / tmp;
    }
    return 0;
}

void calculator()
{
    std::cout << "Enter your expression : ";
    int64_t result{};
    int loopCount{0};
    do{
            if(loopCount == 0)
                result = getIntInput();
            result = calculate(result);
            loopCount++;
    }
    while(std::cin.peek() != '\n');
    std::cout << "Your result is : " << result << '\n';
}

calculator.h:

#ifndef CALCULATOR_H
#define CALCULATOR_H

int getIntInput();
char getOperatorInput();
void calculator();

#endif // CALCULATOR_H
```

Some general comments:

I think your program is small enough not to warrant any functions. Of course, this can be a matter of taste. It's also reasonable to do input parsing, for instance, in a separate function.
To avoid hardcoding the possible binary operators, I suggest taking a more data-driven approach and storing all possibilities in a suitable container (like a map).
You use integers as your operands, but you support division. Because you truncate the result into an integer type, 1/2 will equal 0 in your calculator. For this reason, you might want to use a floating point type.

We could rewrite your program into the following 50 lines or so:

#include <iostream>
#include <limits>
#include <map>
#include <functional>
#include <cassert>

int main()
{
    typedef std::function<float(float, float)> binary_op;
    const std::map<char, binary_op> binary_ops =
    {
        { '+', std::plus<float>() },
        { '-', std::minus<float>() },
        { '*', std::multiplies<float>() },
        { '/', std::divides<float>() },
        // NOTE: see how easy adding new functionality is.
        { '#', [](float x, float y) { return x * x * x + y; } }
    };

    std::cout << "Enter your expression: ";
    float result = 0.0;

    float x;
    float y;
    char op;

    if (!(std::cin >> x >> op >> y))
    {
        std::cout << "ERROR!\n";
        return 0;
    }

    const auto op_iter = binary_ops.find(op);
    // Handle errors as you wish.
    assert(op_iter != binary_ops.end());
    result = op_iter->second(x, y);

    while (std::cin.peek() != '\n')
    {
        if (!(std::cin >> op >> y))
        {
            std::cout << "ERROR!\n";
            return 0;
        }

        const auto op_iter = binary_ops.find(op);
        // Handle errors as you wish.
        assert(op_iter != binary_ops.end());

        result = op_iter->second(result, y);
    }

    std::cout << "Result: " << result << "\n";
}

Comments about this solution:

We do not correctly handle operator precedence. If you want to do this, I suggest looking at something like the Reverse Polish notation.
The std::map now implements the data-driven approach as suggested: you easily add more binary operators as long as they satisfy the required interface. That is, any operator will do as long as it takes two operands (castable to floats) and returns a float. For example, you could add in a fifth line for operator '#' (or whatever you want to call it), and parsing etc. is done automagically for you.


Tidy up number counting code I am hoping someone can help me tidy up my code (for a practical for university). The practical is to use the random number generator to produce 100 integers (all between 1 and 10) and store them in an array. We then need to scan the array and print out how often each number appears. Following this, we needed to create a horizontal bar chart using asterisks to show how often each number appears, before finally printing out which number appeared the most.

My code works and produces the correct results:

import java.util.Random;

public class Practical4_Assessed
{

public static void main(String[] args)
{

    Random numberGenerator = new Random ();
    int[] arrayOfGenerator = new int[100];
    int[] countOfArray     = new int[10];
    int count;

    for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
    {
        count = numberGenerator.nextInt(10);
        countOfArray[count]++;
        arrayOfGenerator[countOfGenerator] = count + 1;
    }

    int countOfNumbersOnLine = 0;
    for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
    {
        if (countOfNumbersOnLine == 10)
        {
            System.out.println("");
            countOfNumbersOnLine = 0;
            countOfOutput--;
        }
        else
        {
            if (arrayOfGenerator[countOfOutput] == 10)
            {
                System.out.print(arrayOfGenerator[countOfOutput] + "  ");
                countOfNumbersOnLine++;
            }
            else
            {
                System.out.print(arrayOfGenerator[countOfOutput] + "   ");
                countOfNumbersOnLine++;
            }
        }
    }

    System.out.println("");
    System.out.println("");

// This section

    for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
        System.out.println("The number " + (countOfNumbers + 1) + " occurs " + countOfArray[countOfNumbers] + " times.");

    System.out.println("");

    for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
    {
        if (countOfNumbers != 9)
                System.out.print((countOfNumbers + 1) + "   ");
        else
                System.out.print((countOfNumbers + 1) + "  ");

        for (int a = 0; a < countOfArray[countOfNumbers]; a++)
        {
            System.out.print("*");
        }
        System.out.println("");
    }

 // To this section

    System.out.println("");

    int max = 0;
    int test = 0;
    for (int counter = 0; counter < countOfArray.length; counter++)
    {
        if (countOfArray[counter] > max)
        {
            max = countOfArray[counter];
            test = counter + 1;
        }
    }

    System.out.println("The number that appears the most is " + test);

}
}

However, I know that the section that tells how often a number occurs and the section that prints out the asterisks both start with the same for statement (I have marked them off in the code with comments). Can anyone advise me how I could do this using just one for statement? It seems quite straightforward, and yet I just can't get it to work!

Additionally, I am sure there are plenty of other areas that the code could be improved on. Feel free to suggest any improvements!

There is much to say about this piece of code. I'll just focus on some parts of it.

One long method

There is one long main method. It makes it hard to get an overview of what is happening. Consider breaking the main method into several methods that each does its piece. Something like.

public static void main(String...args){
    int[] randomNumbers = generateNumbers();
    String result = format(randomNumbers);
    result += formatNumberOfOccurences(randomNumbers);
    result += formatGraph(randomNumber);
    System.out.println(result);
}

// 4 methods omitted....

In this way you will get smaller chunks that is easier to understand. Each of these methods except the number generator is also easy to unit test since the outcome is the same for each argument. The code you have now is hard to unit test.

Printing with System.out

This is handy in many ways. But this is the main reason you need two loops for the code you have highlighted. Since you want to print the occurrence count first and then the graph you ned to do it in separate loops. If you instead store the intermediate result in a local variable then you can do it in one loop. Something like:

String occurrencesReport = "";
String graph = "";

for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
{
    occurrencesReport += "The number " + (countOfNumbers + 1) +
        " occurs " + countOfArray[countOfNumbers] + " times.";

    if (countOfNumbers != 9)
        graph += (countOfNumbers + 1) + "   ";
    else
        graph += (countOfNumbers + 1) + "  ";

    for (int a = 0; a < countOfArray[countOfNumbers]; a++)
    {
        graph += "*";
    }
    graph += "\n";
}

System.out.println(occurrencesReport);
System.out.println(graph);

Readability example

This little piece:

if (countOfNumbers != 9)
    graph += (countOfNumbers + 1) + "   ";
else
    graph += (countOfNumbers + 1) + "  ";

can be simplified like so:

graph += (countOfNumbers + 1) + "  ";
if (countOfNumbers != 9) graph += " ";

this makes it easier to understand what is going on. (On a side note - most people dislike the absence of curly braces in this code snippet. If you add a statement yo your if-block it will actually be outside if curly braces are omitted. I tend to do ifs on one line when they are short. But people don't like that either....) This example can be applied to at least one more piece of the code where there is unnecessary repetition.

Better stop now - just some bits and pieces I hope you can use to improve!


How to write a simple script to read text from a file and compute the number of sentences, number of unique words and punctuation/symbols? (NodeJS) I just finished a challenge (noted above) and I was wondering how good is this approach or is there some simpler solution that I am not aware of?
If you have a different solution, try to explain the code for people less experienced than myself rather just than pasting a solution.
Here is an example text file to be read from:
This file has eight words in this sentence.
There are two sentences. In this paragraph.

And two paragraphs in total.
Lorem ispsum.
Lorem ispsum.
Lorem ispsum.
Lorem ispsum.

/**
 * Write a simple script to read text from a file and compute (approximately) the number of sentences, number of unique words and punctuation/symbols.
 * Run the code with node ./problem-2.js test.txt
 */

 // Use Node's builtin api to read a file
const fs = require('fs');

//#1 count the number of words
const wordCount = (string) => string.split(" ").length;

//#2 count the number of unique words
const uniqueWords = txt => new Set(txt.toLowerCase().match(/\w+/g)).size;

//#3 count the number of paragraphs
const paragraphCount = (paragraphString) =>{
  //seperate each sentence into a seperate string
  paragraphString = paragraphString.split("\n\n");
  // console.table(paragraphString) // show as a table for better visual
  let paragraphArray = paragraphString.length; // length of paragraph array

  let paragraphCount = 0;
  let strip_whitespace = /\s+/gi;
  while (paragraphArray >=0) {
    paragraphArray--;
    let tmp = paragraphString[paragraphArray];
    tmp = tmp ? tmp .replace(strip_whitespace,"") : tmp;

    if( tmp && tmp.length > 1 ) paragraphCount++;
  }
  return paragraphCount;
}

function countPunctuations(punctuationsStrings) {
  let punctuationsCount = 0;
  const punctuations = [".", ",", "!", "?"];
  // const symbols = ["~","`","!","@","#","$","%","^","&","*","(",")","_","+","-","=","{","}","|","[","]","\",":",";","'","<",">","?","/",]
  for (const ch of punctuationsStrings) {
    if (punctuations.includes(ch)) punctuationsCount++;
  }
  return punctuationsCount;
}

fs.readFile("test-2.txt", 'utf8', function(err, data) {
  if (err) throw err;
  console.log("The text in the file:\n\n", data,"\n")
  // store results in an object to present the log better
  let result={
    "word count": wordCount(data),
    "unique words": uniqueWords(data),
    "paragraph count": paragraphCount(data),
    "punctuation count": countPunctuations(data),
  }
  console.table(result)
});
```

Word count bug This line here:
const wordCount = (string) => string.split(" ").length;

will overcount the number of words if the input text happens to have multiple spaces in a row. For example:

const wordCount = (string) => string.split(" ").length;

console.log(wordCount(`
  foo        bar baz
`));

I'd use .match instead, and match contiguous non-space characters. (Can't use \w+, since that'd result in they're and similar being counted as 2 words, and since \w only works with English letters - matching non-spaces is easier than figuring out all the possibilities, and will work for any romance language)

const wordCount = (string) => (string.match(/\S+/g) || []).length;

console.log(wordCount(`
  foo        bar baz
`));

The .match(..) || [] is needed because .match will return null (and not the empty array) if no matches are found.
uniqueWords bug As noted above, \w+ won't be accurate given apostrophes and other punctuation marks that may be around or inside single words. (You also need to alternate the .match with [] as described above too)
paragraphCount issues
You have:
paragraphString = paragraphString.split("\n\n");

There are a few problems here:

The paragraphString is initially not the string of a paragraph, but a string containing the entire input text - better to call it something like inputText.
Then, the paragraphString becomes an array - but its name is paragraphString? Easy source of confusion.
You're unnecesarily reassigning the paragraphString variable - it may refer to one thing, or it may refer to another, depending on what point in the program you're examining it. Code is generally easiest to reason about when the contents of a given variable name doesn't change. Occasionally it's necessary (like with a counter), but often it isn't - better to put a new expression into a different variable rather than reassigning the old one, if possible.

Similarly:
let paragraphArray = paragraphString.length; // length of paragraph array

But the .length is a number, not an array. Giving variables understandable, precise variable names makes code easier to read and helps prevent bugs. I'd either call it paragraphIndex - or, even better, avoid manually iterating over the array entirely and use an array method instead, eg:
paragraphArray.forEach((paragraphString) => {
  // check paragraphString

Empty strings can have .replace called on them just fine, and it makes the code easier to read, so you can simplify the assignment of tmp to:
const paragraphString = paragraphStrings[paragraphIndex].replace(strip_whitespace,"");

Or you could simplify the whole function here by filtering the array of paragraphs by those with a trimmed length:
const paragraphCount = inputText => inputText
  .split('\n\n')
  .filter(paragraphText => paragraphText.trim())
  .length;

You could also use .reduce to count up, instead of constructing an intermediate array that gets used only for its length, but the intent of this .reduce is probably a bit harder to recognize at a glance for some:
const paragraphCount = inputText => inputText
  .split('\n\n')
  .reduce((a, paragraphText) => a + paragraphText.trim() ? 1 : 0, 0)

\n\n might not be good enough, though - can you count on the file encoding using \ns only for newlines? Some files/OSs use \r\n. I'd use /\n\r?\n/ instead.
Punctuation count idea Rather than:
const punctuations = [".", ",", "!", "?"];
// const symbols = ["~","`","!","@","#","$","%","^","&","*","(",")","_","+","-","=","{","}","|","[","]","\",":",";","'","<",">","?","/",]

With a lot of punctuation, the above can be both hard to read and easy to make typos on. If you have more than a few, consider using a string that gets parsed into an array later:
const symbols = `\`~!@#$%^`.split(''); // and so on

You could even make it multiline or put it in a separate file if you wanted, then parse it as needed.
To reduce the computational complexity of the algorithm, make a Set of the punctuations in advance; Set.has is O(1), but Array.includes is O(n). With large files, this could make a big difference, especially if you wree using the large symbols array instead of the smaller punctuations array.
Constructing a regular expression that alternates between all punctuation characters might be even faster.


Simple string joiner in modern C++ - follow-up (See the previous iteration.)

Now, I have defined an iterator for dumping contents of a sequence such that the last element is not followed by the separator string.

main.cpp:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::for_each;
using std::vector;

using namespace std;

template <typename T, typename charT=char, typename traits=char_traits<charT>>
class my_ostream_iterator :
public iterator<output_iterator_tag, void, void, void, void>
{
    std::ostringstream* oss;
    std::string* separator;
    bool first_value_appended;

public:

    my_ostream_iterator(std::ostringstream* oss_, std::string* separator_)
    :
    oss{oss_},
    separator{separator_},
    first_value_appended{false}
    {}

    my_ostream_iterator<T,charT,traits>& operator= (const T& value) {
        if (!first_value_appended)
        {
            *oss << value;
            first_value_appended = true;
        }
        else
        {
            *oss << *separator << value;
        }

        return *this;
    }

    my_ostream_iterator<T,charT,traits>& operator*()     { return *this; }
    my_ostream_iterator<T,charT,traits>& operator++()    { return *this; }
    my_ostream_iterator<T,charT,traits>& operator++(int) { return *this; }
};

template<typename InputIt>
std::string join(InputIt begin,
                 InputIt end,
                 const std::string& separator =", ",
                 const std::string& concluder ="")
{
    std::ostringstream ss;
    std::string sep = separator;
    using value_type = typename std::iterator_traits<InputIt>::value_type;

    std::copy(begin,
              end,
              my_ostream_iterator<value_type>(&ss, &sep));

    ss << concluder;
    return ss.str();
}

int main() {
    vector<vector<int>> matrix = {
        { 1, 2, 3 },
        { 4, 5 },
        { },
        { 10, 26, 29 }
    };

    for_each(matrix.cbegin(),
             matrix.cend(),
             [](std::vector<int> a) {
                 cout << join(a.cbegin(), a.cend()) << endl;
             });
}

As always, any critique is much appreciated.

using declarations

Don't do this at top level:

using namespace std;

and certainly not in a header file, where it can can bring unexpected names into user code.

using std::cout;
using std::endl;
using std::for_each;
using std::vector;

These are less dangerous, but should still be avoided in headers.  Reduce their scope and visibility as much as you can, or use fully-qualified names.

Pointers and ownership

std::ostringstream* oss;
std::string* separator;

Who owns these objects?  Can they be null?  oss is used without checking for null, and it does not appear to be owned by this, so it should probably be a reference.  separator should probably be an owned value, so you can initialize from an rvalue.

Type of separator

Why is separator a std::string?  If the output stream can handle wide strings, we should be able to separate our values with wide strings.

Usual operator types

g++ -Weffc++ recommends that you return the result of postincrement by value, rather then by reference.  That's arguably moot in this case, as incrementing is a no-op, but I like to avoid warnings!

Code duplication

It's a small duplication, but I think it's clearer to separate out the emitting of separator and value:

my_ostream_iterator<T,charT,traits>& operator= (const T& value) {
    if (first_value_appended)
        oss << separator;
    else
        first_value_appended = true;

    oss << value;
    return *this;
}

Generality

Your iterator is templated on the character type, but you don't seem to make use of that type (see "type of separator" above).  I prefer to make the output stream a std::basic_ostringstream<CharT, Traits> so that your code will produce the correct kind of string as output.

Efficiency

In your std::for_each in main(), you pass a vector by value.  It should probably be a reference to const vector.

Modified code

#include <iterator>
#include <sstream>
#include <string>

template<typename T, typename CharT=char, typename Traits=std::char_traits<CharT>>
class my_ostream_iterator
    : public std::iterator<std::output_iterator_tag, void, void, void, void>
{
    using string_t = std::basic_string<CharT, Traits>;
    using stream_t = std::basic_ostringstream<CharT, Traits>;

    stream_t& oss;
    const string_t separator;
    bool first_value_appended;

public:

    my_ostream_iterator(stream_t& oss, const string_t& separator)
        : oss{oss},
          separator{separator},
          first_value_appended{false}
    {
    }

    my_ostream_iterator<T,CharT,Traits>& operator= (const T& value) {
        if (first_value_appended)
            oss << separator;
        else
            first_value_appended = true;

        oss << value;
        return *this;
    }

    my_ostream_iterator<T,CharT,Traits>& operator*()     { return *this; }
    my_ostream_iterator<T,CharT,Traits>& operator++()    { return *this; }
    my_ostream_iterator<T,CharT,Traits> operator++(int)  { return *this; }
};

template<typename InputIt, typename StringT = std::string>
StringT join(InputIt begin,
             InputIt end,
             const StringT& separator = ", ",
             const StringT& concluder = {})
{
    using value_type = typename std::iterator_traits<InputIt>::value_type;
    using char_type = typename StringT::value_type;

    std::basic_ostringstream<char_type> ss;
    std::copy(begin, end,
              my_ostream_iterator<value_type, char_type>(ss, separator));

    ss << concluder;
    return ss.str();
}

// test program
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    // Bring in names needed for argument-dependent lookup
    using std::begin;
    using std::end;

    const std::vector<std::vector<int>> matrix = {
        { 1, 2, 3 },
        { 4, 5 },
        { },
        { 10, 26, 29 }
    };

    std::for_each(begin(matrix), end(matrix),
                  [](const auto& a) {
                      std::cout << join(begin(a), end(a)) << std::endl;
                  });
    std::cout << " ---" << std::endl;

    std::for_each(begin(matrix), end(matrix),
                  [](const auto& a) {
                      std::wcout << join(begin(a), end(a), std::wstring(L", ")) << std::endl;
                  });
    std::wcout << " ---" << std::endl;
}


Taking flight with JavaFX Just another step in my educational Trek. I didn't know when/why I would use the transparent feature and in experimenting with it, I made this.

This one was fun to behold once done. It's an animated flying gif and you can move it around the screen and press keys to alter its speed or add effects to the image itself.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.effect.Bloom;
import javafx.scene.effect.Glow;
import javafx.scene.effect.MotionBlur;
import javafx.scene.effect.Reflection;
import javafx.scene.effect.Shadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class AnimatedFun extends Application {
    int animationSpeed = 5;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        ImageView view = new ImageView(new Image("https://d2aao99y1mip6n.cloudfront.net/images/runes/idols/eJ8HJ8Ge9Ae9Be9Ae9Bj9Fj9Geigtzillnuhymn.gif"));
        view.setEffect(new Glow());
        view.setOnMouseClicked(e -> stage.close());
        view.setFocusTraversable(true);
        view.setOnKeyPressed(e -> {
            if (e.getCode() == KeyCode.ESCAPE) {
                stage.close();
            } else if (e.getCode() == KeyCode.SPACE) {
                view.setEffect(new Reflection());
            } else if (e.getCode() == KeyCode.DELETE) {
                view.setEffect(null);
            } else if (e.getCode() == KeyCode.ENTER) {
                view.setEffect(new Bloom());
            } else if (e.getCode() == KeyCode.SHIFT) {
                view.setEffect(new Shadow());
            } else if (e.getCode() == KeyCode.RIGHT) {
                stage.setX(stage.getX() + animationSpeed);
            } else if (e.getCode() == KeyCode.LEFT) {
                stage.setX(stage.getX() - animationSpeed);
            } else if (e.getCode() == KeyCode.UP) {
                stage.setY(stage.getY() - animationSpeed);
            } else if (e.getCode() == KeyCode.DOWN) {
                stage.setY(stage.getY() + animationSpeed);
            } else if (e.getCode() == KeyCode.CONTROL) {
                animationSpeed += 3;
                if (animationSpeed >= 15) {
                    view.setEffect(new MotionBlur());
                }
            } else if (e.getCode() == KeyCode.ALT) {
                if (animationSpeed >= 15 && animationSpeed < 18){
                    view.setEffect(new Glow());
                }
                animationSpeed = (Math.max(5, animationSpeed - 2));
            }
        });

        Group root = new Group();
        root.getChildren().add(view);

        stage.setScene(new Scene(root, Color.TRANSPARENT));
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.getIcons().add(new Image("https://d2aao99y1mip6n.cloudfront.net/images/runes/lg/eJ8HJ8Ge9Ae9Be9Ae9Bj9Fj9Geigtzillnuhymn.jpg"));
        stage.show();
    }
}

Feel free download the runnable jar.

I'd like a general review of its current state as well as any befitting improvements, be it concerning JavaFX convention, or just the general structure.

Pardon the horizontally unkempt-ness, side-effect of porting over a usable version using online links for the images.

I'd pull out that huge if/else block into a switch block.

This will make your code more readable.  (Also slightly better performance.)  Right now it's difficult to see the logic because it is hidden behind code duplication.  See how a switch block makes it very easy to see the possible keycodes and their corresponding behaviors.

switch(e.getCode()) {
    case(KeyCode.ESCAPE) :  stage.close(); break;
    case(KeyCode.DELETE) :  view.setEffect(null); break;
    case(KeyCode.SPACE)  :  view.setEffect(new Reflection()); break;
    ...


Angular UI-Router Repetitive templateProvider Using $rootScope I am developing an application that has different configurable versions - "a1" and "a2". The version name is initially being set from the database as "a1" in the $rootScope.

I reference the version name in every templateProvider in UI-Router, which ends up being over 30 times:

.state('app.auto.public.inventory.list', {
    url: '/',
    views: {
        'auto-one@app.auto': {
            templateProvider: ['$rootScope', '$templateCache', function($rootScope, $templateCache) {
            return $templateCache.get($rootScope.autoVersion + '/html/inventory/list/index.html');
        }],
        controller: 'InventoryList'
        }
    }
})

There must be a better way to access the value of "a1", instead of referencing $rootScope.autoVersion so many times?

A better solution is to resolve the data in a parent route, then inject the resolved data ("identityResolve") from a service ("identity") into each child instance.

.state('app.auto', {
    abstract: true,
    url: '',
    resolve: {
        identityResolve: ['identity', function(identity) {
            return identity.initialize().$promise;
        }]
    }
})

Which then is used like this

.state('app.auto.public.inventory.list', {
    url: '/',
    views: {
        'auto-one@app.auto': {
            templateProvider: ['$templateCache', 'identityResolve', function($templateCache, identityResolve) {
                return $templateCache.get(identityResolve.version + '/html/inventory/list/index.html');
        }],
        controller: 'InventoryList'
    }
});


Elegant solution to find a pair of Strings in a List I'm new to Java8 and I must find an elegant solution to a problem. The problem goes I have a List of letters (of any size) that could contain any letter such as "A", "B", "C", "D", etc. I must check if I have an pair of "A" and "B". So, if I have something like ["A", "A", "C", "Z"], since I don't have both "A" and "B" the code should throw an error. I need to refactor something like this in java8...

import java.util.Arrays;
import java.util.List;

public class atest {

    public static void checkForABPair(List<String> letters) {
        int iA = 0;
        int iB = 0;
        for (String letter : letters) {
            if (letter.equals("A")) {
                iA = 1;
            }
            if (letter.equals("B")) {
                iB = 1;
            }
        }
        if ((1 == iA || 1 == iB) && (1 != iA || 1 != iB)) {
            System.out.println(letters + " - ERROR! The pair of letters [A - B] must be present at least once, or not at all!");
        } else {
            System.out.println(letters + " - Everything fine!");
        }
    }

    public static void main(String[] args) {

        List<String> letters = Arrays.asList("B", "A", "C");
        checkForABPair(letters);

        letters = Arrays.asList("A", "A", "C");
        checkForABPair(letters);

        letters = Arrays.asList("M", "S", "C");
        checkForABPair(letters);
    }
}

This must return the following:

[B, A, C] - Everything fine!
[A, A, C] - ERROR! The pair of letters [A - B] must be present at least once, or not at all!
[M, S, C] - Everything fine!

I need it done in a more elegant way. Anyone have a more elegant solution? Thanks!

iA and iB can only take the values 0 and 1, so that

if ((1 == iA || 1 == iB) && (1 != iA || 1 != iB)) { ... }

can be simplified to

if (iA != iB) { ... }

Boolean variables would be more appropriate for this purpose, and the variable names can be improved, e.g.

boolean containsA = false;
boolean containsB = false;