Using as few queries as possible for many table associations

When I see long lists of if/elsif, I look to see whether case/when is a good alternate:

tmp_string_text = case col_num
                  when 0
                    finding_phase
                  when 1, 2
                    ""
                  when 3
                    finding.vuln_finding.severity
                  when 4
                    finding.node.ip
                  when 5
                    finding.node.host_name
                  when 6
                    finding.node.dns_name
                  when 7
                    finding.port
                  when 8
                    finding.pentest_finding.name
                  when 9
                    finding.vuln_finding.name
                  when 10
                    finding.vuln_finding.description
                  when 11
                    finding.vuln_finding.solution
                  when 12
                    finding.additional_output
                  when 13
                    finding.cve
                  when 14
                    finding.node.os
                  when 15
                    finding.node.device_type
                  when 16
                    finding.node.scan_time
                  end

In this case I think it's a reasonable solution. If you were only returning strings then a hash would be even more compact:

tmp_string_text = {
  0 => 'finding_phase',
  1 => "",
  2 => "",
  3 => 'finding.vuln_finding.severity',
}[col_num]

That's obviously truncated, but you get the idea.

But, again, you're executing code for your return value once your condition matches. Trying to use a hash will cause all that code to execute when the hash is initialized, which is likely to not be what you want.

As an exercise, I tried clarifying what's going on by using nested case statements:

tmp_string_text = case col_num
                  when 0
                    finding_phase
                  when 1 .. 2
                    ""
                  when 3
                    finding.vuln_finding.severity
                  when 4 .. 6
                    meth = case col_num
                          when 4
                            :ip
                          when 5
                            :host_name
                          when 6
                            :dns_name
                          end
                    finding.node.send(meth)
                  when 7
                    finding.port
                  when 8
                    finding.pentest_finding.name
                  when 9 .. 11
                    meth = case col_num
                          when 9
                            :name
                          when 10
                            :description
                          when 11
                            :solution
                          end
                    finding.vuln_finding.send(meth)
                  when 12
                    finding.additional_output
                  when 13
                    finding.cve
                  when 14 .. 16
                    meth = case col_num
                          when 14
                            :os
                          when 15
                            :device_type
                          when 16
                            :scan_time
                          end
                    finding.node.send(meth)
                  end

Obviously that's untested. It's a bit longer, but the nesting does help reveal  the logic.

Then, as a DRY exercise, took that and tried to reduce the repetition a bit:

case col_num
when 0
  finding_phase
when 1 .. 2
  ""
when 3 .. 16

  result = finding

  methods = case col_num
            when 3
              [:vuln_finding, :severity]
            when 4 .. 6
              [:node] << case col_num
              when 4
                :ip
              when 5
                :host_name
              when 6
                :dns_name
              end
            when 7
              [:port]
            when 8
              [:pentest_finding, :name]
            when 9 .. 11
              [:vuln_finding] << case col_num
              when 9
                :name
              when 10
                :description
              when 11
                :solution
              end
            when 12
              [:additional_output]
            when 13
              [:cve]
            when 14 .. 16
              [:node] << case col_num
              when 14
                :os
              when 15
                :device_type
              when 16
                :scan_time
              end
            end
  methods.each do |m|
    result = result.send(m)
  end
  result
end

Again that's not tested. It loses some readability at that point but it's pretty easy to figure out what's going on.


NodeJS Module Exports: Export multiple functions vs Exporting a single function

Which one is a better approach to setting up variables in NodeJS? (faster, easier to maintain, not an antipattern)

Evaluating the merit of different options depends upon these factors:

How many total options are there now?
How likely are you to add more options as time goes?
Does the caller always set all the options at once? Or is there value to being able to set just some options
Does the caller usually just set one option?

Evaluating each of these:

Total number of options

First off, if you have lots of variables, then neither A or B are particularly practical.  A is not very practical because you have to make a separate API for every variable when they're all really just doing the same thing, but for a slightly different property.  That's generally not a good thing in an API design.

For lots of variables, option B ends up having to list out a lot of different values all in some precise order and that's not easy to use without having the doc page open every time you want to use it and it's not all that easy to read code that's written to use it either because the reader won't remember which position every single parameter is.

Extending to add more options in the future

Both A and B require modifying the API to extend and add more options.  Option A requires adding and documenting a new API entry point.  Option B requires adding and documenting a parameter and then making sure that prior code that doesn't include the new parameter isn't broken (by detecting the missing parameter on the receiving end of things).  Neither is ideal.

Does the caller always set all options at once

If so, option A is a pain.

Does the caller usually set just one option or a small number of options

If so, option B is a pain.

Do, what you find is that neither option A or option B is entirely flexible for different types of calling usage or extensibility or use with lots of options.

Option C

So, I'll propose using a single options object to be a lot more flexible for different types of calling usage and infinite extensibility without changing the API surface itself.  This is also trivial to maintain.  Let's call this option C.

// default values for options
let defaultOptions = {
    optionA: defaultValA,
    optionB: defaultValB,
    optionC: defaultValC,
    optionD: defaultValD,
    optionE: defaultValE
};

module.exports.setOptions = function(options) {
    // copy any properties from the options object to the default options
    //   overwriting default values with new values
    Object.assign(defaultOptions, options)
}

Or, in some cases, you want to prevent adding anything to defaultOptions that isn't already there (no additional properties allowed):

module.exports.setOptions = function(options) {
    // Copy any properties from the options object to the default options
    //   overwriting default values with new values
    // Only allow copying of properties that are already in defaultOptions
    for (let prop of Object.keys(options)) {
       if (Object.hasOwnProperty(defaultOptions, prop)) {
           defaultOptions[prop] = options[prop];
       }
    }
}

And, the caller would do something like this:

m.setOptions({
    optionC: "someNewValue",
    optionE: "anotherNewValue"
});

Where they can include only whatever options they want to set and they are named options so even if there were 1000 options and you just wanted to set 2 of them, it works quite cleanly.

For extensibility, option C wins every time because it can be extended by simply documenting that you now accept another property name without changing the surface of the API at all.

Option D

A fourth option which I will call option D, is to just have one "setter" function that takes a property name and a value.

// default values for options
let defaultOptions = {
    optionA: defaultValA,
    optionB: defaultValB,
    optionC: defaultValC,
    optionD: defaultValD,
    optionE: defaultValE
};

module.exports.setProp = function(propName, value) {
    defaultOptions[propName] = value;
    return this;
}

This allows you to have one single function that could even be chainable that can set any property.

m.setProp("optionC", "someNewValue").setProp("optionE", "anotherNewValue");

This is probably better than option A if everything is just property name and value because it's more extensible without modifying the API, but it's a pain to use if you're trying to set a lot of properties (where option C excels).

Review

For option A, it's really only practical or best if you have a small number of options (say less than 5) and the caller is typically not setting multiple options (typically only setting one option).  Even then, I probably still prefer option C as its infinitely extensible without adding more entry points to the API.

For option B, it's really only practical or best if you have a small number of options (say less than 5) and the caller is always setting all the options (or at most leaving off the last one or two).  Option B is complicated to use and read if there are lots of options (because you have to remember the right position in the parameter list for each option) and it's complicated to overload to only pass some options.  The best part of option B is that with a small number of options, it's probably the least typing for the caller, but that lesser typing means it's less self documenting than the object with named properties in option C.

For option C, it's infinitely extensible and flexible for any type of caller use from setting one property to setting hundreds of properties.  And, it's trivial to maintain, even as you add more options.  This is generally my preferred choice anytime I have 3 or more options or value extensibility or flexibility in how it's used by the caller.

For option D, I don't personally find it cleaner than option C, but it is flexible and extensible, though inefficient for setting a bunch of options.


That's a beautiful excuse for writing code, and the final product is quite nice as well.

★ First of all, congrats to your Java-ridden mind for not forcing classes into Python where they aren't needed.

★ You import but do not use OrderedDict and operator. Remove unused imports.

★ It is customary to write your code in a way that allows it to be used as either a module, or a script. For this, the if __name__ == '__main__' trick is used:

if __name__ == '__main__':
    # executed only if used as a script

★ You declare a few variables like room, url, and pages up front. This hinders code reuse:

The room variable should not be declared up front as a global variable, but in your main section. From there, it can be passed down through all functions.
The url specifically but unnecessarily mentions the-2nd-monitor. This isn't harmful, but unnecessary as only the ID is relevant. Furthermore, url is an awfully short name for such a large scope. Something like star_url_pattern would be better – except that global “constants” should be named all-uppercase:

STAR_URL_PATTERN = 'http://chat.stackexchange.com/rooms/info/{0}/?tab=stars&page={1}'

Reserve plural names for collections. pages should rather be page_count. But wait – why are we hardcoding this rather than fetching it from the page itself? Just follow the rel="next" links until you reach the end.

★ That last idea could be implemented with a generator function. A Python generator function is similar to a simple iterator. It can yield elements, or return when exhausted. We could build such a generator function that yields a beautiful soup object for each page, and takes care of fetching the next one. As a sketch:

from urllib.parse import urljoin

def walk_pages(start_url):
    current_page = start_url
    while True:
        content = ... # fetch the current_page
        soup = BeautifulSoup(content)
        yield soup
        # find the next page
        next_link = soup.find('a', {'rel': 'next'})
        if next_link is None:
            return
        # urljoin takes care of resolving the relative URL
        current_page = urljoin(current_page, next_link.['href'])

★ Please don't use urllib.request. That library has a horrible interface and is more or less broken by design. You might notice that the .read() method returns raw bytes, rather than using the charset from the Content-Type header to automatically decode the content. This is useful when handling binary data, but a HTML page is text. Instead of hardcoding the encoding utf-8 (which isn't even the default encoding for HTML), we could use a better library like requests. Then:

import requests
response = requests.get(current_page)
response.raise_for_status()  # throw an error (only for 4xx or 5xx responses)
content = response.text  # transparently decodes the content

★ Your allstars variable should not only be named something like all_stars (notice the separation of words via an underscore), but also not be a global variable. Consider passing it in as a parameter to add_stars, or wrapping this dictionary in an object where add_stars would be a method.

★ I don't quite understand why you write each page to a file. I suspect this was intended as a debugging help, but it doesn't add any value to a user of that script. Instead of cluttering the current working directory, make this behavior optional.

★ Do not compare to None via the == operator – this is for general comparison. To test for identity, use the is operator: if stars is None. Sometimes, it is preferable to rely on the boolean overload of an object. For example, arrays are considered falsey if they are empty.

Talking is easy,
coding is hard.
Is this refactoring
equally bad?

import time
from bs4 import BeautifulSoup
import requests
from urllib.parse import urljoin

STAR_URL_TEMPLATE = 'http://chat.{0}/rooms/info/{1}/?tab=stars'

def star_pages(start_url):
    current_page = start_url
    while True:
        print("GET {}".format(current_page))
        response = requests.get(current_page)
        response.raise_for_status()
        soup = BeautifulSoup(response.text)
        yield soup
        # find the next page
        next_link = soup.find('a', {'rel': 'next'})
        if next_link is None:
            return
        # urljoin takes care of resolving the relative URL
        current_page = urljoin(current_page, next_link['href'])

def star_count(room_id, site='stackexchange.com'):
    stars = {}
    for page in star_pages(STAR_URL_TEMPLATE.format(site, room_id)):
        for message in page.find_all(attrs={'class': 'monologue'}):
            author = message.find(attrs={'class': 'username'}).string

            star_count = message.find(attrs={'class': 'times'}).string
            if star_count is None:
                star_count = 1

            if author not in stars:
                stars[author] = 0
            stars[author] += int(star_count)

        # be nice to the server, and wait after each page
        time.sleep(1)
    return stars

if __name__ == '__main__':
    the_2nd_monitor_id = 8595
    stars = star_count(the_2nd_monitor_id)
    # print out the stars in descending order
    for author, count in sorted(stars.items(), key=lambda pair: pair[1], reverse=True):
        print("{}: {}".format(author, count))


UnitOfWork without repository and transaction

Ef already implements unit of work in itself, as does it the repository pattern.

Since you open the connection yourself I take it you use EF6, which also automatically wraps SaveChanges in a transaction if there isn't one already, so you have little use of your UnitOfWork.

Read more at Microsoft.

If you DO need to open a transaction manually, and you don't care to use the TransactionScope class, the transaction must be opened before the connection opens and should be disposed before you close the connection again.


Java client that consumes a RESTful web service created using Jersey 2

Realistically these are about the same.  WebTarget is a standard part of JAX-RS so if you were to move to another provider like RestEasy you wouldn't have to port it.  If you like standards then this would be the way to go.

HttpClient is common though not a standard in the JSR way.  It is very powerful and sometimes easier to use when you've got specialized requirements like custom SSL processing.  It is, however, a pain to keep up with.  Every release seems to deprecate something I'm using.

The security of either will depend on you - the libraries will not be significantly different in this area and it will be up to you to implement the code well.

Performance is also likely to be similar.  It's highly likely that the performance of your system will be dependent on something that takes significantly more time than any differences in these libraries.

I would always vote for code that is more readable and I'd argue the WebTarget way is easier to read.


Data structure for inserting and replacing data in list

A hashtable sounds like a better fit for your problem than using a linked list like this, giving you O(1) lookup time in the average case (O(n) for worst case).

You can find a popular hashing algorithm here: djb2

Also are you sure of your use of const?

struct _kvp *const item;
const struct _kvp *item;


Laravel model and controller interaction

PHP is not my area of expertise, so just some generic notes:

4 is a magic number here:

$post = $this->paginate(4);

Why is it 4? What the purpose if this number? A named constant or local variable would be readable with a descriptive name.

public function getMonth($post)
{
    $post->month = date('M', strtotime($this->created_at));
    $post->month = strtoupper($post->month);
    return $post->month;
}

Using a local variable with a proper name, like lowercase_month, in the first line would be readable and more descriptive.
These methods violates Command Query Separation since they return some data and modify the $post too.

  Functions should either do something or answer something, but not both.

Source: Clean Code by Robert C. Martin, Chapter 3: Functions, Command Query Separation p45

$post->month = date('M', strtotime($this->created_at));
$post->month = strtoupper($post->month);

I'd consider moving these calls to the Post class since it seems data envy. (Pseudocode.)

class Post {
    ...
    public void setMonth($created_at) {
        $lowercase_month = date('M', strtotime($created_at));
        $post->month = strtoupper($lowercase_month);
    }
    ...
}


Using shims to turn my integration tests into unit tests

There was no need to delete the post on Stack Overflow, it belonged there just fine; perhaps even better than here.

You don't have to shim anything. Integration tests are tests that use an external dependency (system time, external API, filesystem, etc). In your case all your "dependencies" are simply method calls in your own project.

Here in your case this can simply be seen as a unit test: you're testing a single public method (~ unit) which encapsulates smaller unit tests. This is a perfectly valid unit.

Integration testing refers to a bigger set of components that and testing how these major interfaces work together.

Now, on to the bigger question: how do you test this [void method]? As is tradition: a link to an answer of mine.

void methods change the state of your program (adjusting values of variables) or they interact with an external dependency (printing to the console, logging to a file). So in order to assert against any expectations you'll have to either interpret the results or intercept them along the way.

Interpreting results

In the first case (adjusting of a variable) the answer is obvious: look at the variables that got changed and see if they now have the values you want.

In the latter case you get a "problem": you're now reading the result of an external dependency so you're entering the realm of integration testing. This is why we have the alternative solution..

Intercepting results

This is done with shims, mocks, stubs, seams, you name it. You're already aware how this works: a DI framework intercepts the call and you can provide your own values around the actual call, or you inject the unit under test with a specific implementation for testing purposes.


Reading a text file, manipulating it and saving it to a mongo database

Style

Comments are just noise and thus reduce readability if they state what is obvious in the code. EG the comment //Read from each line is followed by the line
lineReader.eachLine(filePath, (line)=> {

Do not mix styles. You use semicolons randomly in the code. Use them or not, do not mix them

Do not add empty blocks or as your comment describes  "do nothing"  . Example if (line.includes('ATTACK LOG')) { } else  should be if (!line.includes('ATTACK LOG')) {

Do not add magic numbers or string in the code. Define them as constants in one place

Always delimite statement blocks with {}. EG for(let i of attackData) i && tempAttackData.push(i); should be  for(const i of attackData) { i && tempAttackData.push(i) }

Use constants for variables that do not change

Single argument arrow functions do not need the () around the argument. EG (line)=> { can be line => {

Spaces between commas

Undeclared variable are dangerouse. The variables finalResults, attackData, tempAttackData, cleanedAttackData and removedDateTime are all undecalared and thus are part of the top level scope and may clash creating very hard to debug problems

Avoid single use variables. EG  finalResults = new Results(result); finalResults.save(); can be new Results(result).save();

i is used as a loop counter and should not be used to represent a value or item of an array. The loop for (let i of ... should be for (const item of...

Do not add arguments to a function if that argument is not used. EG tempAttackData.forEach((data, index) => You do not use index so there is no need to define it

Logic
The whole thing feels clumsy as you move data from array to array, variable to variable, and step over and into nested and superfluous statements blocks.
It can be greatly simplified by creating a few helper functions to separate the various tasks. See example.
There also seams to be a bug as you do not check if the line is the second header line (contains "---- LOOT -----").
Example
The example breaks the task into smaller functions reducing the overall source code (and executional) complexity.
The additional item at the end of the data line is just ignored (rather than popped from the array) by the function Attack which creates the attack object you save.
const LOGS = "/retrieve-logs";
const message = "Results successfully loaded";
const FILE_PATH = "AttackLog-2019-10.log";
const FIELDS = "accountNumber,timeOfAttack,trophies,searches,ds,gold,elixir,darkElixir,trophyChange,victory,damagePercentage,bonusGold,bonusElixir,bonusDarkElixir";
const Attack = new Function(...FIELDS.split(","), "return {" + FIELDS + "};");

const valid = line => ! ["ATTACK LOG", "GOLD", "LOOT"].some(mark => line.includes(mark));
const clean = line => line.slice(22).replace("||", "|");
const parse = line => Attack(...clean(line).split("|").map(item => item.trim()));

router.get(LOGS, (req, res) => {
    lineReader.eachLine(FILE_PATH, line => { valid(line) && new Results(parse(line)).save() });
    Results.find({}, (err, success) => { res.status(200).send({message, success}) });
});


I think it is just a matter of taste. Here is one approach:

do
{
    var ftdiStatus = FtdiDevice.FtdiDevice.Instance.GetRxBytesWaiting(ref rxBytes);

    if (ftdiStatus != FTDI.FT_STATUS.FT_OK)
        return null;

    if(rxBytes >= dataBlockSize)
        break;

    Thread.Sleep(10);
}
while (true); // Perhaps a check for timeout?


Generation of all numbers of arbitrary length and base

It turns out that this is exactly what replicateM does in the [] monad. For the sake of completeness, let's look at exactly how replicateM works.

replicateM :: Monad m => Int -> m a -> m [a]
replicateM n x = sequence (replicate n x)

replicate :: Int -> a -> [a]
replicate n x = [ x | _ <- [1..n] ]

replicateM turns out to just pass off the heavy lifting to replicate and sequence. replicate is pretty simple, so the interesting part happens in sequence:

sequence :: Monad m => [m a] -> m [a]
sequence [] = return []
sequence (x:xs) = do
    x'  <- x
    xs' <- sequence xs
    return (x' : xs')

And in fact, that's exactly what leaning on the [] monad instance for iteration looks like. A couple of binds and a return.


Script to download sequentially named files, rename them, and delete smaller files

sh is not bash. This shouldn't be a problem for your script though, because I don't think there are any bashisms in there.
Use More Quotes™. If there had been another parameter in the URL you would have needed an ampersand (&) in there, and that's the special character to run a command in the background. That's one of many ways to trip up if you don't comment basically any non-trivial string.
You don't need to sleep, because the wget commands are synchronous.
That said, you might get a result much faster if you run them in parallel, by doing several wget […] & commands followed by a wait.
You don't need to exit at the end of a shell script. That's only useful if you want to exit prematurely or with a different exit code from the previous command.
If you use Bash you can use read -p "Start file #: " start etc. to avoid most of the echoing.
However, it is much more common to make shell scripts take parameters instead of being interactive, making the script even simpler:

start="$1"
end="$2"

Use set -o errexit -o nounset (and -o pipefail if you're really in Bash) to make sure you catch any common bugs early.
I'm not sure what progressfilt does, but you can suppress the wget progress bar by using --quiet.
To be done slightly faster you should swap around the deleting and the renaming.
Rather than find * you should use find . to avoid exceeding the maximum argument length. This is a good practice in general, but will only really break with lots of files.
One very common feature of *nix scripts is that they are silent unless there's something important to report. Therefore, I'd remove the last echo.

Your script should now be 9 SLOC, and clean as a whistle!


Update machine settings at various moments over time period

To be honest: Not a very elegant approach.

Let's have a look at a different hypothetical sample data to see where it breaks:

module.exports = {
  temperature : {
    "00:00" : 100,
    "01:05" : 110,
  },
  ventilation : {
    "00:00" : 0,
    "00:30" : 25,
  },
  end : "01:35"
}

And the machine did not stop. Why?

Because you are only handling multiples of 10 seconds, and everything in between is never matched by your string comparisons.

Specifying the times as strings for readability in the config module is reasonable, so let's keep this as a requirement for now.

This leaves us with either increasing the sample rate on the timer, or with refactoring the logic which handles the state at any given point in time. Since the sample rate can't be increased arbitrarily, let's go with refactoring the logic.

Tracking the machines state is the key here. Right now, your state only contains machineTimer. However, it should also contain some information which allows to decide which instructions have been executed yet, and which don't.

For simplicity, let's just call that one machineLastUpdate, and assume that everything up to the time stamp recorded in that variable has already run.

With that, simply reverse the logic. Instead of converting machineTimer to string, instead convert the times from the configuration into seconds. For every converted time stamp, execute the correlating command exactly when timestamp > machineLastUpdate && timestamp <= machineTimer.

This approach ensures that all defined commands are executed exactly once - regardless of whether your timer can provide that resolution.

  // machineTimer is in deciseconds

This is somewhat pointless in Javascript, it's a double precision float anyway.

Unless you have a good reason to specifically use deciseconds, just stick with the established standard of using seconds as the unit for all time stamps.

machineTimer += 10;

Beware that setInterval can have a drift, or may even skip invocations when missing the time window. If you need accuracy for longer runs, instead better sample the system time at every invocation instead to determine the real time offset since the machine was started.


Trim() every string in a JavaScript object?

I see a bug for a null property case as typeof null == "object". You should check if it's not null or an object :)

Another less important? bug is you can't use the key hasOwnProeprty on any of your objects. You can get around this by using Object.prototype.hasOwnProperty.call(obj, key)

Only obvious optimization I see is to move the hasOwnProperty check after the typeof check. hasOwnProperty is a relatively expensive function so you will probably see some gains off that. I expect this should be even faster than doing Object.keys which is known to be faster than your for in has loop...

I assume you're polyfilling trim for older browsers right?

function DeepTrim(obj) {
    for (var prop in obj) {
        var value = obj[prop], type = typeof value;
        if (value != null && (type == "string" || type == "object") && obj.hasOwnProperty(prop)) {
            if (type == "object") {
                DeepTrim(obj[prop]);
            } else {
                obj[prop] = obj[prop].trim();
            }
        }
    }
}


Simple bcrypt Register User and User Login using PHP - is this approach acceptable?

Yes, your approach to hashing and storing passwords is acceptable.

Misc

== true is not needed, and should never be used. Either directly write if (password_verify(...)) {...}, or use === (if you don't trust ==, which you shouldn't in many situations[*]).
you should generally try to be consistent with your variable naming schemes. Either use camelCase or snake_case, don't mix them.
I appreciate that you are mostly consistent with your naming overall, as it really helps readability. :email is the exception here, so you should change it.
fld_pwd_form also does not fit your general naming scheme. Either append _form to all values that are input, or to none (and think about changing it to _input).
Is there a reason for the fld_ prefix? It reduces readability, so if you can still change your database names, I would remove it.
hash is enough as a name, you don't need ToStoreInDb.

[*] == should be ok for password_verify, as it is very unlikely that the function will be changed to return anything else than true or false in the future. On the other hand, it is PHP, so who knows. And "1", 1, -1, ["error"], "error" are all true.


IsolateMessages()
You are creating a lot of strings here. Each time you call Substring(), or .Remove() on a string you are creating a new string. In addition the readability of

messages.Add(data.Substring
    (0, terminatorIndex + m_TerminatorLength)
        .Remove(terminatorIndex, m_TerminatorLength));

is very very bad.

By returning an IEnumerable<string> instead of string[] the execution of that method can be deffered by using yield.
By using the overloaded IndexOf(int, int) you could omit the terminatorCount and replace the for loop by a while loop.

Applying these two points would lead to this beautyful code
internal IEnumerable<string> IsolateMessages(string data)
{
    if (string.IsNullOrWhiteSpace(data)) { yield break; }

    var currentIndex = 0;
    var terminatorIndex = -1;

    while ((terminatorIndex = data.IndexOf(m_MessageTerminator, currentIndex)) > 0)
    {
        var messageLength = terminatorIndex - currentIndex;

        yield return data.Substring(currentIndex, messageLength);

        currentIndex = terminatorIndex + m_TerminatorLength;
    }
}

the only difference to your code is that if there is no message or the passed string data is empty my message isn't returning null so you could change the ProcessMessages() like
internal void ProcessMessages(IEnumerable<string> messages)
{
    foreach(var message in messages)
    {
        Console.WriteLine(message);
    }
}


Refactoring multiple boolean conditions?

What especially jumps at me is, that you take your real data object (the Employee), convert it to a string representation and do your checks on the string.

Why? Can't you check your data object?

Apart from that, I don't see a problem with 5 and-conditions. This is clearer to read than some clever stream-through-predicates-and-reduce code. Clear. Simple. Leave it like that.

What I'd recommend is rethinking your naming:

getPredicate(): yes, it returns a predicate, we see that from the method signature. But what does this predicate test?
filter(): does some filtering, but according to which criteria?

(Sorry to pepijno, I typed this without seeing your answer... no offense meant ;-))


static inline bool fillBuffer(FILE *, char [], size_t *, size_t *);

It'd be nice to provide names for these function parameters, especially since two of them have the same type (size_t *).

It's fairly unusual to see a pointer parameter declared with [] instead of * — I infer your rationale, something like "This pointer is expected to point to an array of contiguous objects, not just one object," but the inconsistency (and risk of some maintainer forgetting and writing sizeof buffer just once) is too costly IMHO. The fact that char *buffer is immediately followed by size_t bufferlen should be a dead giveaway that buffer points to an array.

...Oh, what do you mean char *buffer isn't followed by size_t bufferlen?!

static inline bool fillBuffer(FILE *file, char buffer[], size_t *numBytesRead, size_t *numBytesUsed) {
    *numBytesRead = fread(buffer, 1, BUFFER_SIZE, file);

Yep, that's a buffer overflow waiting to happen. Your fillBuffer function takes a pointer (buffer) and unconditionally writes up to BUFFER_SIZE (4096) bytes into it. If the caller passes in a smaller buffer... boom.
So what we want to see here is more like the API to fread itself:

static inline bool fillBuffer(FILE *file, char *buffer, size_t bufferlen, size_t *numBytesRead, size_t *numBytesUsed) {
    *numBytesRead = fread(buffer, 1, bufferlen, file);
    *numBytesUsed = 0;

    return (0 < *numBytesRead);
}

I know that fread returns numBytesRead as its return value, so I'm suspicious of the way fillBuffer returns numBytesRead via an out-parameter. Out-parameters are a code smell. So I look at what we're using our return value for.

    return (0 < *numBytesRead);

Comparing a size_t against 0 should generally be done with !=, not <, since the only value of type size_t that is not > 0 is 0 itself.

    return (0 != *numBytesRead);

But this function returns bool, and size_t converts to bool in the obvious way, so:

    return *numBytesRead;

Oh look! We just eliminated that out-parameter!

static inline size_t fillBuffer(FILE *fp, char *buffer, size_t bufferlen, size_t *numBytesUsed) {
    size_t numBytesRead = fread(buffer, 1, bufferlen, fp);
    *numBytesUsed = 0;
    return numBytesRead;
}

Now simplify:

static inline size_t fillBuffer(FILE *fp, char *buffer, size_t bufferlen, size_t *numBytesUsed) {
    *numBytesUsed = 0;
    return fread(buffer, 1, bufferlen, fp);
}

Now pause. Notice that numBytesUsed is not actually used by this function at all, except to unconditionally set it to 0. The Single Responsibility Principle suggests that perhaps setting this arbitrary size_t to 0 could be done by the caller, so as not to bother us with an essentially unrelated task. But then our whole function becomes a tail-call to fread(...), which seems ridiculous. Let's eliminate this function. Find its caller...

static inline bool nextCharEquals(FILE *file, char buffer[], size_t *numBytesRead, size_t *numBytesUsed, char value) {
    return (((*numBytesUsed < *numBytesRead) || fillBuffer(file, buffer, numBytesRead, numBytesUsed)) && (buffer[*numBytesUsed] == value));
}

Oh dear me. Let's rewrite this mess using if and else:

static inline bool nextCharEquals(FILE *file, char buffer[], size_t *numBytesRead, size_t *numBytesUsed, char value) {
    if (*numBytesUsed >= *numBytesRead) {
        if (fillBuffer(file, buffer, numBytesRead, numBytesUsed) == 0) {
            return false;
        }
    }
    return buffer[*numBytesUsed] == value;
}

Okay, now for the inlining step!

static inline bool nextCharEquals(FILE *fp, char *buffer, size_t bufferlen, size_t *numBytesUsed, char value) {
    if (*numBytesUsed >= *numBytesRead) {
        *numBytesRead = fread(buffer, 1, bufferlen, fp);
        *numBytesUsed = 0;
        if (*numBytesRead == 0) {
            return false;
        }
    }
    return buffer[*numBytesUsed] == value;
}

Now we can start to make out where the real problems lie. For example, it is tempting to observe that if (*numBytesRead == 0) is equivalent to if (*numBytesUsed >= *numBytesRead) (since we just set *numBytesUsed to 0 on the previous line). So we are tempted to rewrite this function as

static inline bool nextCharEquals(FILE *fp, char *buffer, size_t bufferlen, size_t *numBytesUsed, char value) {
    while (*numBytesUsed >= *numBytesRead) {
        *numBytesRead = fread(buffer, 1, bufferlen, fp);
        *numBytesUsed = 0;
        // TODO: check errno? check feof(fp)?
    }
    return buffer[*numBytesUsed] == value;
}

Of course as written that would be an infinite loop on EOF; but it makes us ponder in what situations we expect to see fread(...) == 0... which starts us thinking about error handling.

Meanwhile, we can apply the Single Responsibility Principle again to figure out that perhaps char value doesn't belong in this function. Why would our caller want to write

nextCharEquals(dataFile, buffer, &numBytesRead, &numBytesUsed, '\n')

when they could write

nextChar(dataFile, buffer, &numBytesRead, &numBytesUsed) == '\n'

instead?

Any time you're spelling out the name of a built-in operator (==) in your function name, it's a good sign that your function is doing more than it should be. Let the built-in operator pull its own weight!

One more random tip: Instead of hard-coding BUFFER_SIZE all over your program, try to use sizeof buffer.

char buffer[BUFFER_SIZE];
foo(buffer, BUFFER_SIZE);  // bad, repetitive, easy to typo

char buffer[4096];
foo(buffer, sizeof buffer);  // good, clean, hard to typo

It'll also train you to pass your buffer sizes around properly, since you won't have all your buffers' sizes so promiscuously available in "global variables." And that will help you prepare for the world of multi-source-file programs.


at least I would extract a variable:

var address = (Adress)((OwnerIDList)owner.Adresses.Value)[0].Adress.Value;
data.Add(address.FirstName.Value.ToString());
data.Add(address.LastName.Value.ToString());

All these cast operations make me believe that your code is not that strongly typed. If it so then there is not that much you can do with readability in this code.

P.S.: Address in English has two d.


Parsing an array of comma-numbers obtained from an input dialog

I suggest next way:

    String x = (JOptionPane.showInputDialog(". Each patamater should be separated with a ',' and without spaces. (eg. 1,2,3)") + ",");
    String[] split = x.split(",");
    Double[] z = new Double[split.length];
    int i = 0;
    for (String s : split) {
        if(s.trim().isEmpty()){
            continue;
        }
        try {
            z[i++] = Double.valueOf(s.trim());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

1)split() instead of loop for ','

2)validate spaces

read more about String class and it's functions.


This seems fine.

This should give you a key-space of 64^10.

If you have only a few thousand links then you're more likely to win the lottery jackpot than get a collision.


Obligatory PEP 8 reminder:

Whitespace is important.
Whitespace is important too.
Recommendations state that you should:

Design exception hierarchies based on the distinctions that code catching the exceptions is likely to need, rather than the locations where the exceptions are raised. Aim to answer the question "What went wrong?" programmatically, rather than only stating that "A problem occurred" (see PEP 3151 for an example of this lesson being learned for the builtin exception hierarchy);
Not compare boolean values to True or False using == .

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:

Applying that to your code gives the more readable:

class NoBadVersion(Exception):
    pass

def isBadVersion(number):
    """Mocked external API. Obligatory camelCaseName for consistency."""
    return number > 0

def find_bad_version(numbers):
    """Return the index of the first bad version.
    Tries to perform as few external API calls as possible.
    """

    start = 0
    end = len(numbers) - 1

    if isBadVersion(numbers[start]):
        return start

    if not isBadVersion(numbers[end]):
        raise NoBadVersion('all good')

    while start <= end:
        mid = start + (end-start) / 2
        if isBadVersion(numbers[mid]):
            if start == end:
                return end
            end = mid
        else:
            start = mid + 1

if __name__ == "__main__":
    print find_bad_version([0, 0, 0, 1, 1, 1, 1, 1])
    print find_bad_version([0, 0, 0, 0, 0, 0, 0, 1])


HackerRank: Friend Circles (DFS in Java)

Welcome to Code Review. Your code is good and easy to read, you can iterate over only half of the matrix (in my case the elements of the matrix a[i,j] with i < j) because from the test matrices always results a[i, j] = a[j, i] so friendship in symmetric .
I'm using a TreeMap<Integer, Set<Integer>> to store initial situation to guarantee natural order of the keys so it will always the lower index the index where friends will be added : everybody is friend of himself (reflexive property) so map[i]={ i }.

int n = friends.length;
Map<Integer, Set<Integer>> map = new TreeMap<>();
for (int i = 0; i < n; ++i) {
    Set<Integer> set = new TreeSet<>();
    set.add(i);
    map.put(i, set);
}

Now I check all elements a[i, j] with i < j and see if i appears as key in the map: if yes I add j to map[j], otherwise it means that i appears in another set and I will add j to this set. At the end in any case I will remove the key j:

for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
        if (i < j && friends[i][j] == 'Y') {
            if (map.containsKey(i)) {
                map.get(i).add(j);
            } else {
                for (Integer key : map.keySet()) {
                    Set<Integer> set = map.get(key);
                    if (set.contains(i)) {
                        set.add(j);
                    }
                }
            }
            map.remove(j);
        }
    }
}

The number of circles will coincide with the number of keys present in the map at the end:

public static int CountFriendsCircles(char[][] friends) {
    int n = friends.length;
    Map<Integer, Set<Integer>> map = new TreeMap<>();
    for (int i = 0; i < n; ++i) {
        Set<Integer> set = new TreeSet<>();
        set.add(i);
        map.put(i, set);
    }

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (i < j && friends[i][j] == 'Y') {
                if (map.containsKey(i)) {
                    map.get(i).add(j);
                } else {
                    for (Integer key : map.keySet()) {
                        Set<Integer> set = map.get(key);
                        if (set.contains(i)) {
                            set.add(j);
                        }
                    }
                }
                map.remove(j);
            }
        }
    }

    return map.size();
}


Trigger breakpoint when string is not a Google-owned domain

One thing you could look at is Regex. If you're willing to assume that strLink is in fact a valid URL you could try something like

Dim googleDomains = {"google.com", "blogger.com", "youtube.com"}
Dim regexp = "^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+\.com)"
Dim match = Regex.Match(strLink, regexp)
If match.Length <> 0 Then
    Dim domain As String = match.Groups(1).Value
    If Not googleDomains.Contains(domain) Then
        Dim hello2 = 1 'set breakpoint here.
    End If
End If

If you wanted to expand to include ".org" or ".net" you could do something like this:

Dim regexp = "^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+\.(com|org|net|gov))"

Modified Example Regex Demo

In general, I'd say Regex is a very useful tool to have in your arsenal and would be good to learn. Comes in handy when you need to scan large code files or restructure something in a lot of places (as Regex can do replacements as well)

In this example the main benefit is that you can actually extract out the domain from a well-formed URL rather than just see if "google.com" is anywhere in the string

If you want the actual check to truly be String.Contains You could do something with LINQ

Dim domain = googleDomains.FirstOrDefault(Function(d) strLink.Contains(d))
If domain = Nothing Then
    Dim hello2 = 1 'set breakpoint here.
End If

A little bit less verbose, but it doesn't necessarily mean the string is a valid URL to google.com


Calling strlen() twice on each string is wasteful in time.

Current code make 3 trips down each string, once for length, once for copying, once to determine new length.

    l += strlen(va_arg(ap, char*));
    ...
    memcpy(joined + total_length, s, sizeof_char * (length = strlen(s)));
    total_length += length;

The following runs down each string twice, once for length determination and a second for copying.  It "parses" the variable arguments only once, but then does need to save those results somewhere.

char* concat_n(size_t n, ...) {
  va_list ap;
  size_t size = 1;

  // Allocate memory or for small `n`, use VLA or fixed array.
  struct {
    size_t len;
    const char *ptr;
  } str[n];

  va_start(ap, n);
  for (size_t i = 0; i < n; i++) {
    str[i].ptr = va_arg(ap, const char *);
    str[i].len = strlen(str[i].ptr);
    if (str[i].len > SIZE_MAX - size) {  // Detect overflow in length
      va_end(ap);
      return NULL;
    }
    size += str[i].len;
  }
  va_end(ap);

  char *dest = malloc(size);
  if (dest) {
    char *p = dest;
    for (size_t i = 0; i < n; i++) {
      memcpy(p, str[i].ptr, str[i].len);
      p += str[i].len;
    }
    *p = '\0';
  }
  return dest;
}

An alternative to saving the lengths and recomputing strlen() is to use some non-standard function like char *strpcpy() which copies and returns the pointer to the null character.  As if this is faster than other approaches, YMMV.  IMO, memcpy() is the best to speed code along and since the length was  compute prior, take advantage of that even if managing the saving of those prior results is a minor extra burden.

int is not the best type for array index nor size math.  size_t is the Goldilocks type, neither too wide, nor too narrow.

sizeof_char appears artificial.  Alternatives:

// char *joined = malloc(sizeof_char * (l + 1));
char *joined = malloc(l + 1);
// or
char *joined = malloc(sizeof *joined * (l + 1));

Defensive programming.  What happens if user passed a negative value for argc?   (Answer: a very long loop).

// Problem code when `argc < 0`
char *concat_strings(int argc, ...) {
  ...
  int n = argc;
  while(n--) {

Suggest either size_t or > 0

char *concat_strings(size_t argc, ...) {
  ...
  size_t n = argc;
  while(n--) {

or

char *concat_strings(int argc, ...) {
  ...
  int n = argc;
  while(n-- > 0) {

Check allocation

char *joined = malloc(l + 1);
if (joined == NULL) return NULL;

argc, though not a reserved name, has special meaning.  Suggest a different variable name like string_count


Universally unique 64 bit long generator

I would just use SecureRandom#nextLong(). SecureRandom will seed itself and shouldn't be the same between two similar computers at the same time. Also, it uses more bits of state than Random (128 vs 48).

I don't know exactly what computers you'll be running this on, but if it's something like a cluster of servers they'll probably have the exact same s1/s2/s3/s4. If they happen to start at the same time (plausible if two processes on two cores are launched by a parents at the same time), then that only leaves the 48 bits of random state.

If you use SecureRandom, you can just call it and immediately get a 64 bit UUID that will have as few collisions as you can possibly guarantee with two offline computers.


Since we assume GCC or Clang, we can easily make the code adapt to the target's endianness:

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    constexpr auto hton(std::uint64_t x){
        return __builtin_bswap64(x);
    }

    constexpr auto hton(std::uint32_t x){
        return __builtin_bswap32(x);
    }
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    constexpr auto hton(std::uint64_t x){
        return x;
    }

    constexpr auto hton(std::uint32_t x){
        return x;
    }
#else
#error Unsupported byte order
#endif

I've used the conventional "host to net" name for the function, to be clearer.

Some identifiers are misspelt: std::uint32_t, std::uint64_t, std::strncpy, std::strncmp, std::printf.

This function is unnecessary:

template<typename T>
auto sscmp(T a, T b){
    return sshhash_implementation::sscmp(a, b);
}

Much simpler to write

using sshhash_implementation::sscmp;

No need for the immediately-executed lambda in testC():

bool const ok = [=](){
    if (overflow)
        return x == 0 && y == std::numeric_limits<int>::max();
    else
        return x == y;
}();

That can be written as a simple expression:

bool const ok = overflow
    ? x == 0 && y == std::numeric_limits<int>::max()
    : x == y;

In mask(), I think the constant 8 was intended to be CHAR_BIT, since it's converting a count of char to number of bits.


Python bot to answer mathematical questions for a remote server

My main concern is the use of eval() without proper validation (well, the regular expression extraction puts some limits onto the possible expression values, but still it can be exploitable). I would either switch to tools like numexpr (there are some other options at this topic), or, taking into account the simplicity of the possible expressions, map the operator strings into actual operators, something like:

import operator

OPERATIONS = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv  # // operator
}
match = re.search(r'(\d+)\s*([-+*/])\s*(\d+)', data.decode('utf-8'))
if not match:
    raise ValueError("Invalid expression string")

operand1, operation, operand2 = match.groups()

if operation not in OPERATIONS:
    raise ValueError("Invalid operation '%s'" % operation)

result = OPERATIONS[operation](float(operand1), float(operand2))

I'm not sure about converting to floats, may be you need Decimals.

Some other notes:

it is recommended to use raw strings for regular expression strings
you can pre-compile the regular expression before going into the loop (even though the Python's regex engine is smart enough to cache the compiled patterns implicitly, see this topic for more information)
error handling - check if the "match" is not None before calling .group() on it (see how I've done it above)
fix the typo - "recevied" vs "received"
comments style - according to PEP8, there has to be a single whitespace after the # character


C - A function that calculates the integral of a polynomial

buff is not a meaningful name. Call it integral perhaps?
I'd use a more mathematical degree rather than number_of_terms.
In your approach (going from lowest to highest degree) polynomial and buff may never overlap. restrict them:

void integrate(double * restrict polynomial, double * restrict buff, int number_of_terms)

I see no other way to deal with the integration constant but passing it as a separate parameter.


Attempt at Abstracted YAML Configuration Loader

Sorry to say this is not good practice. Exactly why is a bit more technical of an explanation than I like to give off the cuff, Google for "Haskell typeclass interface" and you'll find a bunch of threads comparing and contrasting and recommending you use an ADT. Here's one from Reddit with a game programming example that I think is particularly practical.

In your case, I imagine you intend to provide different configuration methods (XML, command line flags, &c) which would also be instances of Config. You've already realized that you want to work with some abstract Config thing elsewhere in your program and not a YamlConfig, because whatever is using a configuration value doesn't care where that value came from. The next logical step is that by making Config a class, you actually are still passing a YamlConfig around everywhere, you're just relying on callers to never look more closely at it than as a generic Config instance. You've got implementation leaking all over the place.

Instead, making Config a datatype.

data Config = Config { outputPath :: FilePath
                     , template   :: String -> FilePath
                     }

Now populate it from a YAML source.

makeConfig :: Yaml.Value -> Config
makeConfig yaml = Config { outputPath = stringYamlLookup ["output", "path"] yaml
                         , template   = \name -> stringYamlLookup ["templates", name] yaml
                         }

It's easy to make arbitrary Configs now. Maybe you want a default Config.

defaultConfig :: Config
defaultConfig = Config { outputPath = "output/"
                       , template   = ("template/" ++)
                       }

You can even make lists of Configs from different sources ([defaultConfig, makeConfig yaml]).


No, that's not a good design. Catching NullPointerException is almost never the correct thing to do. Effectively ignoring it is worse. You're hiding possible programming errors by using it in this way.

jsonBuilder() should be throwing a known, checked exception up to fetchPushDriver(), which should either handle the exception, rethrow it, or wrap it in a new exception and throw that.


Isolate URLs from other text around it and put each on own line (with sed)

What about this?

cat input | tr ' ' '\n' | grep -i "^http"

Put every string on new line.
Filter urls.


Breadth First Search using adjacency list

Will be fixed soon

Advice 1

In BFS, you don't really need colors. (See alternative implementation.)

Advice 2 (Exposing internals)

public:

  std::vector<Vertex> vertices;
  std::vector< std::list<int> > adjList;

I suggest you put the two fields under private:.

Advice 3

Since an undirected graph is a special case of a directed graph (in which each edge \$\{u, v\}\$ can be simulated by two directed arcs \$(u, v), (v, u)\$), I suggest you implement it as a directed graph, but add a method that inserts an undirected edge by two directed arcs.

Advice 4

I would rip off the actual BFS from the Graph. This is, however, a matter of taste.

Advice 5

Graph::Graph(int v)
{
   vertex_count = v;
   adjList.resize(vertex_count);
   for (int i = 0; i < vertex_count; i++)
   {
       vertices.push_back( Vertex(i) );
   }
}

Why not name int v int vertex_count in the first place? Also, I would go for, for example, std::unordered_map<int, list<int>> since it is not restricted to non-negative integers.

Alternative implementation

This is by no means a best possible implementation, but it demonstrates the overall structure I had in mind:

#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#include <iterator>

class Graph
{
public:
    void addEdge(int node1, int node2);
    void addArc(int tailNode, int headNode);
    std::unordered_set<int>& getChildNodesOf(int node);

private:
    std::unordered_map<int, std::unordered_set<int>> m_adjacency_list;
};

void Graph::addArc(int tail, int head)
{
    m_adjacency_list[tail].insert(head);
}

void Graph::addEdge(int tail, int head)
{
    // Simulate an undirected edge via two bidirectional arcs:
    addArc(tail, head);
    addArc(head, tail);
}

std::unordered_set<int>& Graph::getChildNodesOf(int node)
{
    return m_adjacency_list[node];
}

std::unordered_map<int, int*>
computeUnweightedShortestPathTree(Graph& graph, int sourceNode)
{
    std::unordered_map<int, int*> parentMap = { { sourceNode, nullptr }};
    std::queue<int> open;
    open.push(sourceNode);

    while (!open.empty())
    {
        int currentNode = open.front();
        open.pop();
        int* parentNode = new int{currentNode};

        for (int childNode : graph.getChildNodesOf(currentNode))
        {
            if (parentMap.find(childNode) == parentMap.end())
            {
                parentMap[childNode] = parentNode;
                open.push(childNode);
            }
        }
    }

    return parentMap;
}

std::vector<int> tracebackPath(int targetNode,
                               std::unordered_map<int, int*>& shortestPathTree)
{
    std::vector<int> path;
    int currentNode = targetNode;
    int* nextNode = shortestPathTree[currentNode];

    while (true) {
        path.push_back(currentNode);
        nextNode = shortestPathTree[currentNode];

        if (nextNode == nullptr)
        {
            break;
        }

        currentNode = *nextNode;
    }

    std::reverse(path.begin(), path.end());
    return path;
}

int main()
{
    Graph graph;
    graph.addEdge(0, 1);
    graph.addEdge(0, 4);
    graph.addEdge(1, 3);
    graph.addEdge(1, 4);
    graph.addEdge(1, 2);
    graph.addEdge(2, 3);
    graph.addEdge(3, 4);

    for (int sourceNode : { 0, 1, 2, 3, 4 })
    {
        std::unordered_map<int, int*> shortestPathTree =
            computeUnweightedShortestPathTree(graph, sourceNode);

        for (int targetNode : { 0, 1, 2, 3, 4 })
        {
            std::cout << "Shortest path from " << sourceNode << " to " << targetNode << ": ";
            std::vector<int> path = tracebackPath(targetNode, shortestPathTree);

            std::copy(path.cbegin(),
                      path.cend(),
                      std::ostream_iterator<int>(std::cout, " "));

            std::cout << "\n";

        }
    }
}


Are there any memory issues with this Eigen QR wrapper?

First check that there are the enough command line parameters

// If there are not enough parameters
//
// If there are no parameters passed then
// Then argv[1] is NULL
//      argv[2] is random
    int m   =       atoi(argv[1]);
    int n   =       atoi(argv[2]);

If not enough parameters are passed then this can get you funny number in m and n which will affect how much memory you allocate.

Don't use malloc in C++ code.
You can not mix malloc/free with new/delete. So by only using one system of memory management you will not mix up the two different types of memory.

    double* A       =       (double*)malloc(m*n*sizeof(double));

   // Also the C++ interface is simpler.

    double* A       =       new double[m*n];

Secondly don't use pointer.
In modern C++ it is very rare to see RAW pointers (as they have no concept of ownership). And they are prone to leaking. you should be using either smart pointers or containers to hold your dynamically allocated memory.

In this case a container would have been better.

   std::vector<double> A(m*n);

All memory management now handled correctly.
This can then be used in your C code with

   double* Ap = &A[0];  // get the address of the first element.

This is not going to go well:

    Q       =       (double*)realloc(Q_E.data(), m*minmn*sizeof(double));

  // Q_E.data() better not only return you a pointer allocated with malloc.
  //            But it better set the internal pointers to NULL or some
  //            other safe value. As soon as the realloc() finishes the
  //            old pointer is no longer valid.

Also this is not the correct way to use realloc.

  size_t    size = /* Calc Size */;
  double*   data = (double*)malloc(size);
  ...
  size_t    newSiz = /* New Space needed */;
  double*   resize = (double*)realloc(data, newSize);
  if (resize != NULL)
  {
      data = resize;  // if realloc() returns NULL the original array
      size = newSiz;  // is unaffected. You should check this after
  }                   // the call and only reassign the original
                      // value if the resize worked correctly.

Major Points:

I don't know what is happening inside MatrixXd but it looks like it is exposing its memory management outside the class. That is not a good idea. An object should know how to handle its memory in all situation (and do its own resizing as appropriate).

Two don't use RAW pointers (use C++ ownership symantics).

Learn the Rule of Three/Five so that objects manage their own memory.

Don't write C code and definately don't write C memory management code.


Skiena's Programming Challenges: The Trip problem

return (double)((int)(n*100.0)) / 100.0; fails for values of n greater than 2.147483648E7 as product n*100.0 would be larger than the maximum value of a 32-bit signed int. Use floor() instead. But that's probably not the reason the online judge fails it. **EDIT**problem size is restricted so this isn't an issue.
your mean() function is theoretically numerically instable, but that's probably not it either. EDIT definitely not it due to the problem description.
double expenses[n_students]; is not supported in C89 as it is a variable-length array. This feature was required in C99, but in the newer C11 it is an optional feature that compilers are not required to support. I suspect that your compiler supports variable-length arrays a la C99 but the online judge's compiler doesn't. Try using double * expenses = malloc(sizeof(double)*n_students); and changing other types as appropriate. Don't forget to free() your memory too. EDIT Checked the website and they say it supports "ANSI C". My guess is they mean C89.


Function to find midpoint of two floats where one of the floats might be an empty string

def get_new_position(prev_seq, next_seq):

    if next_seq == "":
        new_position = float(prev_seq) + 1
    elif prev_seq == "":
        new_position = float(next_seq) - 1
    else:
        new_position = (float(prev_seq) + float(next_seq)) / 2

    return new_position


I'll only address C programming issues in this answer, not the algorithm itself.

Program design and programming practice

As a rule of thumb, there is never a reason to use more than two levels of indirection in C programming. More levels than that always originates from flawed program design. In your case, you are allocating an array of pointers to char. So it should be char* destinations[].
Because of the above reason, the function should be changed to

static void parse (char **destinations, const char **fields, const char *source)

or if you would prefer:

static void parse (char**       destinations,
                   const char** fields,
                   const char*  source)

It is bad practice to allocate memory in a different module than the one doing the allocation. If parse() does memory allocation, then a function located in the same module should handle the cleanup, not the caller. I would advise to create a function called parse_cleanup() or similar, which does this.
The function parse is performing a parsing algorithm. The function shouldn't concern itself with anything else but that. Dynamic memory allocation is completely unrelated to the task "parsing". Consider splitting the code in two sub-functions: one which handles the algorithm and one for the memory allocation.
Your loop control is made needlessly complex. You control the iteration from no less than 5 places: outer while loop, first for loop, continue statement, goto statement. This is spaghetti code and needs to be rewritten from scratch.

You don't need nested loops at all. Throughout the iteration, you will have to constantly check for \0, as any string can end anywhere. You can merge the while and for into a single while. That will also mean that you can remove the goto.
Instead of having one big super loop that does a lot of things, consider writing a simple loop that calls upon various functions. Try to avoid break if possible, and always avoid continue and goto, as the latter two are completely superfluous language features that many programmers consider hard to read.

Consider to add some error handling to the function. Parsers in particular usually have many things that can go wrong. Then it is nice for the caller to have detailed error information.
Investigate if you can't use the standard functions isblank(), isspace() and toupper() from ctype.h, rather than your own custom ones.

Coding style
(these remarks are more subjective and not everyone will agree)

Always write statements on a line of their own and always use braces. This makes the code easier to read and prevent bugs during code maintenance. For example:

while(*source == ' ' || *source == '\t')
{
  ++source;
}

The above is especially important in the case of while(*++source && *source != '\n');, because there you can't tell whether the programmer intentionally wrote an empty loop, or if they accidentally wrote a ; at the end of the line, which is a very common, classic bug. It is far better to write:

while(x)
{} // this means: "yes, I did intend this loop to be empty"

Never use the ++ operator in the same expression as other operators, it can easily lead to undefined behavior bugs such as the classic i = i + i++; bug. But it is also harder to read. Mixing ++ with other operators is pointless anyhow, since it doesn't affect performance or the final machine code in any way. One example of how to rewrite it:

do
{
  source++;
} while (*source != '\0' && *source != '\n');

(And of course the check for \0 should be explicit like in this example - that is good practice and you do it everywhere else in your code.)
Avoid assignment inside conditions. Just as with the ++ operator, it can lead to bugs, and there is never a reason to have assignment inside conditions, it is another 100% superfluous feature of the language.

Most compilers will warn against assignment inside conditions, so it is annoying to have it there. You should not disable such warnings, because they will find the bug x=y where you intended to have x==y.

Furthermore, in the case of if((*destinations[i] = malloc(buffer_position + 1)) != 0), did you actually intend to set the contents to NULL if allocation fails? It may or may not be better to leave the pointer alone in that case. Your function call documentation must mention which applies.
It is good practice to compare against NULL rather than 0 when dealing with pointers, to show the reader that you did intend to compare a pointer and not an integer value.
If you heed my advice to never use ++ together with other operators, then the need for either prefix ++ or postfix ++ is gone: they turn completely equivalent. Ask yourself if you are using prefix ++ for a particular reason. Because people who do think they have a reason, tend to either name something based on superstition or something about how compilers were designed in the 80s.


Locating a PID based on an IP address and port

First off, a couple of quick tips:

Follow the PEP8 style guide
Instead of x == False, use not x, for example in if (is_legal_ip(args.ip_port[0]) == False)
Omit unnecessary imports (import socket in this example)
Use spaces around operators, for example all(0 <= int(p) < 256 for p in pieces)
Break lines after colons, for example in if __name__ == "__main__": main()

Leave the job of argument parsing to argparse

No need to work with sys.args yourself.
For example you can simply remove these lines:

if len(sys.argv) > 2 or len(sys.argv) == 1:
    print("Please provide a single argument.")
    exit(1)

The way you specified the ip-port arguments with nargs=1,
argparse will take care of validating the number of command line arguments.

Simplify the argument parsing

You can omit nargs=1.
But in that case,
the value of args.ip_port will not be a list,
but a simple string.

You can also omit the type=str, as that's the default.

Your usage would become simpler:

parser.add_argument('ip_port', metavar='IP:PORT', help='local address')
args = parser.parse_args()

if not is_legal_ip(args.ip_port):
    parser.error("Invalid IP address.")

return args.ip_port

Use two arguments instead of one

It's awkward that use ip:port,
the splitting at multiple places is just noise.
It will be simpler and cleaner to use two arguments instead of one:

parser.add_argument('ip', help='local address')
parser.add_argument('port', type=int, help='local port')
args = parser.parse_args()

if not is_legal_ip(args.ip):
    parser.error("Invalid IP address.")

return args.ip, args.port

Notice that this way argparse can take care of validating the port number.

Then in your main function, you can get the ip address and port pair like this:

ip, port = parse_arguments()

Benefit from the error reporting features of argparse

Instead of this:

if not is_legal_ip(args.ip_port):
    print("Invalid IP address.")
    exit(1)

I suggest to use this way:

if not is_legal_ip(args.ip_port):
    parser.error("Invalid IP address.")

argparse will print a usage help along with the error message,
and also exit.

A subtlety here is that argparse will exit with code 2 in this case,
which is common in case of invalid parameters of UNIX commands.

Working with file handles

When working with files, use with:

with open(os.devnull, 'w') as devnull:
    output = subprocess.check_output("netstat -nl".split(), stderr=devnull).splitlines()

This makes devnull.close() unnecessary, Python will call it when exiting the block.


Keep the global scope clean and data/code segregation

First I will say your code is good for a beginner but you are missing some concepts and techniques that will help you improve your code and improve the client experience.

Some important concepts

Use requestAnimationFrame for animations, and know the difference between animation and one off content changes.
Data belongs in the page. Be it the text, images, or the instructions/values for the javascript, the place for data is on the page.
Keep the global namespace clean. With a little effort you can completely avoid adding any variables to the window namespace / global scope.
Don't put code in the HTML It is tempting to put code in the page to start an animation <button onclick="startAnim()" value="start">. All good when it's a simple page but a source of headache, bugs, and unhappy clients when its get complicated
When parts of your code starts to look repetitive it's a good sign that there is a better way.
Remove event handlers when you are done. Event handlers use up resources.
Always keep in mind your page shares the computer with dozens of others on the client's machine. Do your best to reduce the total load on their device.

The javascript

Always start your code with "use strict" it helps you avoid some very common bugs and bad coding styles and runs your code significantly faster.

"use strict"; // is valid as the first line of a script tag or the first
              // line inside a function. Put anywhere else and it has no effect
window.addEventListener("load",function(){  // starting your code on the load
                                           // event ensures that all the DOM
                                           // tree is populated and ready

try to define your event handlers as named functions because you need a function referance to remove the event if you need to.

    function startButtonClick(){  // the start button event

We only want this to play once. So remove the event from the button. When events are called this references the element that triggered the event

        this.removeEventListener("click",startButtonClick); // remove event

The spread operator is a short cut way of turning a array like list into an array. Be wary as IE 11 is still popular and does not support many ES6 features. If you use things like the spread operator you should consider using babel.js so that your code can run on legacy browsers.

        var numberEl = [...document.getElementsByClassName('number')];

The numbers moving up is an animation. It will be control by requestAnimationFrame that will call the animate function at 60fps if possible, but that is not a guarantee. To ensure you get consistent animation on all devices use the supplied time the requestAnimationFrame callback supplies to time your animation.

You were using a interval of 1ms.The rule of thumb is 60fps or 16ms between display frames, updating content any higher than that rate will simply not be seen and thus will just waste resources.

        var startTime;  // holds that animation start time
        function animateNumbers(time){ // time is the first argument of the
                                       // requestAnimationFrame callback

This countSpeed controls how fast the numbers will increase per second. The animation will play at the same speed on all devices.

            const countSpeed = 120; // count speed in increments per second
            if(startTime === undefined){// if there is no start time then this must
                                        // be first frame so make it the start time
                startTime = time;
            }
            var seconds = (time - startTime) / 1000; //seconds from animation start
            var count = countSpeed * seconds; // get the current count
            done = true; // flag to indicate the animation is complete
            numberEl.forEach(element => {
                var max = Number(element.dataset.maxValue); // properties that you
                                                // get from the  page are strings.
                                                // If you know it's a  number let
                                                // Javascript know

If the count is below max for any element flag the animation as not done.

                if(count < max){
                    done = false;
                }

Try to avoid setting text content with innerHTML as it can cause all sorts of problems that are avoided by telling the DOM it is only text you are adding

                element.textContent = Math.min(max,Math.floor(count));
            }
            if(!done){  // continue animation until done
                requestAnimationFrame(animateNumbers);
            }
        }

When ever you are animating anything on the page were you define every frame use requestAnimationFrame it ensures that the animation is in sync with the hardware and any other page rendering. It also prevents updated content from being presented to early or quicker than can actualy be seen. Smooth animation is not about speed, but about being in sync and limiting the amount of work the computer must do.

        requestAnimationFrame(animateNumbers);
    }

Get the button element and add the event listener

    document.querySelector("#startButton").addEventListener("click", startButtonClick);
})

The HTML, data lives here

Placing the values for the counters inside the javascript code makes it hard to manage. The javascript is a constant, the page contains the data and is unique per view/client

The formal way to add data/attributes to elements is via the data- prefix though this is not enforced and any named value pair you add to an element can be accessed, data- ensures your data is safe from conflict or misinterpreted by the DOM.

data-max-value is not a valid javascript variable name so you can not easily acces the data using that name you need to use the javascript version created by the DOM. In HTML5 the DOM creates an attribute called dataset that you use to access the variable with. Replace data- with dataset. (that's a dot not a full stop)  then the max, then replacing any subsequent '-' by removing the - and capitalising the first letter following, thus data-max-value becomes dataset.maxValue see the code above as an example.

   0

Styles Created

   0

Awards Won

   0

Stores Worldwide

   0

Varities Desinged

Avoid placing javascrpt inside the HTML content. It makes it much harder to manage your code. Use an unquie Id to identify elements for direct or queried access from within your javascript.

<button id = "startButton" >START</button>

Put it all together

"use strict";
window.addEventListener("load",function(){
    function startButtonClick(){
        this.removeEventListener("click",startButtonClick); // remove event
        var numberEl = [...document.getElementsByClassName('number')];
        var startTime;
        function animateNumbers(time){
            const countSpeed = 120;
            if(startTime === undefined){
                startTime = time;
            }
            var seconds = (time - startTime) / 1000; // get the seconds since the animation start
            var count = countSpeed * seconds; // get the current count
            var done = true;
            numberEl.forEach(element => {
                var max = Number(element.dataset.maxValue);
                if(count < max) {
                    done = false;
                }
                element.textContent = Math.min(max,Math.floor(count));
            });
            if(!done){
                requestAnimationFrame(animateNumbers);
            }
        }
        requestAnimationFrame(animateNumbers);
    }
    document.querySelector("#startButton").addEventListener("click", startButtonClick);
});
button {
   position: absolute;
   top: 30px;
   left: auto;
   right: 30px;
   border: none;
   background-color: black;
   color: white;
   padding: 10px;
   cursor: pointer;
}
button:hover {
   background-color: crimson;
}

   0

Styles Created

   0

Awards Won

   0

Stores Worldwide

   0

Varities Desinged

<button id = "startButton" >START</button>


Checking if a text contains N consecutive repeating characters

Edit - there is a bug with this: see my other answer

This is very easy with Regular Expressions:

public static bool HasConsecutiveChars(string source, int sequenceLength)
{
    // should check sequence length

    // just repeating letters
    return Regex.IsMatch(source,"([a-zA-Z])\\1{"+ (sequenceLength - 1) + "}");

    // any character version
    // return Regex.IsMatch(source,"(.)\\1{"+ (sequenceLength - 1) + "}");
}

The regular expression simply captures each letter into a group and then checks if it is repeated the number of times minus one. I've omitted range checking.

Talking about your code for a moment:

Great method name - would be perfect as an extension method in my opinion.

These two checks can be merged:

if (string.IsNullOrEmpty(source))
{
    return false;
}

if (source.Length == 1)
{
    return false;
}


Find height of a tree without using recursion

The code is basically sound.

It's not a helper function, so don't name it as such.  (Helper functions would usually be private.)

Comments would be good.  In particular, a JavaDoc explaining how to interpret the height of a degenerate tree would be helpful.

Your currentLevelNodeCount and nextLevelNodeCount are basically segmenting the queue into two queues the hard way.  Why not reduce the bookkeeping by using two queues?  (I've named them thisLevel and nextLevel because variable names that have the same length make the code look pretty.)

A few tweaks here and there make the code slightly more compact.

/**
 * Returns the maximum depth of a tree.
 *
 * @param node The root of the tree
 *
 * @return -1 if node is null, 0 if node has no children,
 *         a positive number otherwise.
 */
public int height(TreeNode node) {
    int height = -1;
    if (node != null) {
        // Breadth-first traversal, keeping track of the number of levels
        Queue<TreeNode> thisLevel = new LinkedList<TreeNode>(),
                        nextLevel = new LinkedList<TreeNode>();

        thisLevel.add(node);
        while (null != (node = thisLevel.poll())) {
            if (node.left  != null) nextLevel.add(node.left);
            if (node.right != null) nextLevel.add(node.right);

            if (thisLevel.isEmpty()) {
                height++;

                Queue<TreeNode> swapTemp = thisLevel;
                thisLevel = nextLevel;
                // We could create a new nextLevel queue, but reusing the
                // newly emptied thisLevel queue is more efficient.
                nextLevel = swapTemp;
            }
        }
    }
    return height;
}


Temperature converter in Rust with input error handling

Is my code idiomatic Rust? Does it follow its coding conventions, style, etc.?

It's pretty close. There are a couple of things I would recommend changing:

Use match whenever multiple branches in your flow are based upon a single value.

This means that you should replace the if ... else if ... else with a match statement:

match choice {
    1 => { ... },
    2 => { ... },
    _ => { ... },
}

I'd also use match instead of if value == 1 || value == 2 but in that case you aren't gaining as much:

match value {
    1 | 2 => break value,
    _ => (),
}

read_value_from_input should probably return a Result<T, Error> or Option<T>. This provides you with a couple of benefits.

First, by returning a Result you can use the new "try" operator (?) in the body (which is essentially just a way of automatically return an error in the case that they fail):

print!("{}", prompt);
io::stdout().flush()?;

let mut input_value = String::new();
io::stdin().read_line(&mut input_value)?;

return input_value.trim().parse()?;

Second, this way you can handle how to control failures higher up in the program flow.

One problem with this approach is that all Errors may not have the same type (parse errors and io Errors are different) but you should be able to use Result<T, impl Error> as your return type which should work with all of them. Or, maybe you want the program to immediately exit on those conditions, in which case expect is fitting.
Reduce the number of loops you have.

Right now you have two loops. One in read_value_from_input which gets any value from stdin, and one in your main function which validates that integer or tries again. I'd try to just handle all of that logic in one or the other, but since you only want the value 1 or 2 that could be difficult.
Use return in the read value loop.

If you didn't remove that loop, you should at least be returning directly instead of breaking out of the loop and then finishing with that value. Also, the continue in there isn't doing anything as far as I can tell.

fn read_value_from_input<T: FromStr>(prompt: &str, error_message: &str) -> T {
    loop {
        print!("{}", prompt);
        io::stdout().flush().expect("Unable to flush STDOUT!");

        let mut input_value = String::new();

        io::stdin().read_line(&mut input_value)
            .expect(error_message);

        match input_value.trim().parse() {
            Ok(value) => return value,
            Err(_) => {
                println!("{}", error_message);
            }
        }
    }
}

  Does my code handle all erroneous inputs properly?

Your code currently panics when it can't flush or read from stdin. This may be what you want. Beyond that, your code does seem to handle inputs correctly.

  Can the code be shortened or optimized in any way?

I've given a few ways it can be shortened and optimized. One more thing I would suggest is passing around the string or character instead of an integer. This would save that parsing step.

You could even create an enum with the possible modes of your program and impl FromStr for it, then pass that around (which is what I did in my working example).

Here's my complete example. It has essentially the same behavior as yours.

use std::io;
use std::io::Write;
use std::str::FromStr;

struct ParseModeError {}

enum Mode {
    F2C,
    C2F,
}
impl FromStr for Mode {
    type Err = ParseModeError;

    fn from_str(s: &str) -> Result<Mode, ParseModeError> {
        match s {
            "1" => Ok(Mode::F2C),
            "2" => Ok(Mode::C2F),
            _ => Err(ParseModeError {}),
        }
    }
}

fn main() {
    println!("Welcome to the temperature converter!");

    println!("Pick a conversion:");
    println!("[1] Fahrenheit to Celsius");
    println!("[2] Celsius to Fahrenheit");

    let choice: Mode = read_value_from_input(
        "> ",
        "Please enter a valid choice (0 or 1)!"
    );

    match choice {
        Mode::F2C => {
            let temperature: f64 = read_value_from_input(
                "Enter the temperature to convert: ",
                "Please enter a valid floating point variable!"
            );

            println!(
                "{:.2} °F is {:.2} °C.",
                temperature,
                (temperature - 32f64) * 5f64 / 9f64
            );
        },
        Mode::C2F => {
            let temperature: f64 = read_value_from_input(
                "Enter the temperature to convert: ",
                "Please enter a valid floating point variable!"
            );

            println!(
                "{:.2} °C is {:.2} °F.",
                temperature,
                temperature * 9f64 / 5f64 + 32f64
            );
        },
    }
}

fn read_value_from_input<T: FromStr>(prompt: &str, error_message: &str) -> T {
    loop {
        print!("{}", prompt);
        io::stdout().flush()
            .expect("Unable to flush STDOUT!");

        let mut input_value = String::new();
        io::stdin().read_line(&mut input_value)
            .expect("Unable to read STDIN!");

        match input_value.trim().parse() {
            Ok(value) => return value,
            Err(_) => println!("{}", error_message),
        }
    }
}


Automate the Boring Stuff – Chess Dictionary Validator – Optimal Solution

As you may know already, your validation rules are both incomplete and too strict. For example, a black bishop must be on a black square, and there can be more-than-expected numbers of the pieces after a pawn is advanced and promoted (usually, but not always, to a queen). I'll ignore those issues and focus on the code.
Get the so-called magic strings and numbers out of the code and into named
constants and/or data structures. Here's a draft of some constants that might
be handy for your task. As you add more validation checks, you might need to
augment or adjust these.
import sys
from collections import namedtuple

BLACK = 'b'
WHITE = 'w'

KING = 'king'
QUEEN = 'queen'
ROOK = 'rook'
BISHOP = 'bishop'
KNIGHT = 'knight'
PAWN = 'pawn'

COLORS = {BLACK, WHITE}
PIECES = {KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN}

RANKS = set('12345678')
COLUMNS = set('abcdefgh')

VALID_COUNTS = {
    PAWN:   range(0, 9),
    KNIGHT: range(0, 3),
    BISHOP: range(0, 3),
    ROOK:   range(0, 3),
    QUEEN:  range(0, 2),
    KNIGHT: range(1, 2),
}

Set up a simple data structure to facilitate testing and debugging
as you write the script. For example, we have the board you gave us
and an invalid board I added.
INPUT_BOARDS = {
    'orig': {
        '1h': 'bking',
        '6c': 'wqueen',
        '2g': 'bbishop',
        '5h': 'bqueen',
        '3e': 'wking',
    },
    'bad1': {
        '9h': 'bking',
        '9x': 'wking',
    },
}

The input format for a board is not convenient for validation because it
glues together rank-plus-column and color-plus-piece. Do parsing first, validation
second. There are various ways to arrange the parsing, but an easy, low-tech
way is with a namedtuple -- an immutable container that behaves like a tuple
but also allows one to access the attributes via their names.
By parsing the input board immediately, you can simplify the rest of the code.
The validation function should take and return data (e.g. the first
error or, even better, all errors). It should not print.
Print only in the simple, outer-shell of the program (e.g. a main() function), not it
its more complex, algorithmic center (where you are doing validation).
ParsedCell = namedtuple('ParsedCell', 'cell color_piece rank column color piece')

def main(args):
    board = parse_input_board(INPUT_BOARDS[args[0]])
    errors = check_board(board)
    if errors:
        for e in errors:
            print(e)
    else:
        print('OK')

def parse_input_board(input_board):
    return tuple(
        ParsedCell(
            cell,
            color_piece,
            cell[0:1],       # A safe technique even if cell is an empty string.
            cell[1:],
            color_piece[0:1],
            color_piece[1:],
        )
        for cell, color_piece in input_board.items()
    )

Now sitting on a more solid foundation, the program's validation
code becomes (1) simpler to write and (2) easier to read
because it is more declarative or self-documenting.
def check_board(board):
    errors = []
    for pcell in board:
        if pcell.rank not in RANKS:
            msg = emsg('Invalid rank', pcell.cell)
            errors.append(msg)

        if pcell.color not in COLORS:
            msg = emsg('Invalid color', pcell.cell)
            errors.append(msg)

        # Etc.

    return errors

def emsg(msg, item):
    return f'{msg}: {item}'

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


While this code works as intended, there is room for improvement.

Use small functions that do one thing

The main method does too many things:

Read input from the console
Sort the array
Print the array

These steps are distinct features, their implementations are independent from each other.
It would be better if they were in separate functions.
That will make the responsibilities of each function clear,
and easy to test and verify the correct behavior.

Declare and initialize variables right before you need them

Instead of this:

int size, temp = 0;
System.out.println("Enter the size of the array");
Scanner sc = new Scanner(System.in);
size = sc.nextInt();

You could declare and initialize size where needed:

System.out.println("Enter the size of the array");
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();

Notice that I completely dropped temp.
It's not needed here.
You can declare it later when needed.

Unnecessary throws

The main method declares to throw IOException but it's unnecessary.

Style

Although this is a valid way to declare an array in Java, it's unusual:

int arr[] = new int[size];

This is the recommended writing style:

int[] arr = new int[size];

The reasoning is that [] is part of the type.
In int arr[] the type and the variable name are mixed,
in int[] arr the type is cleanly at the left,
and the variable name is cleanly at the right.

The same goes for String args[] in the arguments of main.


Copying data from an Excel sheet to Word

Things you could try:

Set shorter wait times. This shows you how. This is likely the main source of delay. You can assess if this is true by timing the total time, and calculating the time taken with each vfile.
Avoid Selecting unless mandatory. For instance, replace

ActiveSheet.Columns("C").Select
ActiveSheet.Paste

with

ActiveSheet.Columns("C").PasteSpecial


My first approach is to map the arguments to a list of IO actions and then execute them:

import Control.Monad
import System.Environment

lastLines :: Int -> String -> [String]
lastLines n = reverse.take n.reverse.lines

printLines :: [String] -> IO ()
printLines = flip forM_ $ putStrLn

readLastLines :: Int -> FilePath -> IO [String]
readLastLines n f = readFile f >>= return . (++) ["==>" ++ f ++ "<=="] . lastLines n

argsToActions :: [String] -> [IO ()]
argsToActions ("-h":_) = [print "Usage"]
argsToActions ("-v":_) = [print "V 1.0"]
argsToActions ("-n":n:f:_) = [readLastLines (read n) f >>= printLines]
argsToActions (f:fs) = [readLastLines 10 f >>= printLines] ++ argsToActions fs
argsToActions [] = []

main :: IO ()
main = getArgs >>= sequence_ . argsToActions


Echoing the comments from the question, the usual design for these sort of things, often called a scope guard, is to have a function that is called when it no longer needs to be run (frequenlty called dismiss or release.

int existing_func()
{
    int res = FAILURE;

    auto_logger logger([](){
        print_to_log();
    });

    do_some_stuff_that_may_throw();

    res = perform_operation();

    dismiss_logger(logger, res);

    return res;
}

void dismiss_logger(auto_logger& logger, int result) {
    if (res != SUCCESS) {
        logger.dont_log();
    }
}

  virtual ~auto_logger()

Is the expectation that there will be derived classes destroyed via base pointers or via base references? If not, a non-virtual destructor is a common way to signal that a class is not designed to be inherited from.

  } catch (...) {

Note that Visual C++ (at least) can be configured via the /EHa switch (this is usually a misguided configuration, IMHO) to catch structured exceptions (things like access violations/segmentation faults) in a catch (...) handler.

A common technique to hedge against this configuration is to catch std::exception& under the assumption that all sensible exceptions will derive from it. Anything else being caught (e.g, an int, a structured exception) is likely indicative of a bug in the program so egregious that termination is the only safe recourse, as there's likely some corrupt state somewhere that prevents any further cleanup.

This assumption may or may not be valid. Say this code needs to work in an environment where it is normal and okay to throw and catch things that don't derive from std::exception. (E.g., a framework that has its own base exception class is being used.) If Visual C++ isn't being used of /EHa will never be used, this recommendation may come off as paranoid. :-)


Recursive and iterative Euclidean algorithms

I don't like the multiple different assignments inside the operator.
They currently all assign to gcd but you need to study it in detail to work that out.
I would make the assignment explicit and the ternary operator return the correct value.

The other thing with ternary operator is that they are not trivial to read. So use white space to try and make it obvious that it's happening. Also I prefer to explicitly use '{' '}' to make sure that things don't accidentally become associated with the a different statement. I would lay it out like this:

int recursive_euclidean( int num1, int num2 )
{
    int gcd;

    if( num1 == num2 || num1 < 0 || num2 < 0 )
    {
        gcd = (num1 == num2)
                 ? num1
                 : (num1 < 0)
                      ? num2
                      : num1;
    }
    else
    {
        gcd = (num1 > num2)
                 ? recursive_euclidean( num1-num2, num2 )
                 : recursive_euclidean( num1, num2-num1 );
    }
    return gcd;
}

Actually reading this again I would refactor more to this:

int recursive_euclidean( int num1, int num2 )
{
    int gcd;

    if ( num1 == num2)
    {    gcd = num1;
    }
    else if (num1 < 0)
    {    gcd = num2;
    }
    else if (num2 < 0)
    {    gcd = num1;
    }
    else
    {
        gcd = (num1 > num2)
                 ? recursive_euclidean( num1-num2, num2 )
                 : recursive_euclidean( num1, num2-num1 );
    }
    return gcd;
}

Then here, I would not personally not use the ternary operator.

int iterative_euclidean( int num1, int num2 )
{
    while( num1 != num2 && num1 > 0 && num2 > 0 )
    {
       if (num1 > num2 )
           { num1-=num2;}
       else{ num2-=num1;}
    }
    return (num1>0) ? num1 : num2;
}


Splitting URL query string to key-value pairs

To decode the query string correctly, you must take care of percent-encoding, like %25 for a literal percent, or %C3%A4 for an ä (encoded as UTF-8). The canonical code for doing this is:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;

public class QueryStringDecoder {

    public static Map<String, String> decodeQueryString(String query) {
        try {
            Map<String, String> params = new LinkedHashMap<>();
            for (String param : query.split("&")) {
                String[] keyValue = param.split("=", 2);
                String key = URLDecoder.decode(keyValue[0], "UTF-8");
                String value = keyValue.length > 1 ? URLDecoder.decode(keyValue[1], "UTF-8") : "";
                if (!key.isEmpty()) {
                    params.put(key, value);
                }
            }
            return params;
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e); // Cannot happen with UTF-8 encoding.
        }
    }

    public static void main(String[] args) {
        System.out.println(decodeQueryString("&&&"));
        System.out.println(decodeQueryString("&&&a=b"));
        System.out.println(decodeQueryString("a=b&c=%26%25==&utf8=%E2%9C%93"));
        System.out.println(decodeQueryString("latin1=%FC"));
    }
}

I don't know why you prefer to do the parsing in a single pass. That would be possible, but the single-pass code must then behave exactly like the above code.
Furthermore, since this part of the code is probably not the bottleneck, there is no point in optimizing it for execution speed instead of readability.